text stringlengths 8 4.13M |
|---|
use std::rc::Rc;
use std::collections::HashMap;
use {Value, Procedure, AresResult, AresError, ParamBinding, LoadedContext, State, Environment};
use super::util::expect_arity;
use intern::Symbol;
pub fn equals(args: &[Value]) -> AresResult<Value> {
try!(expect_arity(args, |l| l >= 2, "at least 2"));
let first = &args[0];
for next in args.iter().skip(1) {
if *next != *first {
return Ok(Value::Bool(false));
}
}
Ok(Value::Bool(true))
}
pub fn lett<S: State + ?Sized>(args: &[Value], ctx: &mut LoadedContext<S>) -> AresResult<Value> {
try!(expect_arity(args, |l| l >= 2, "at least 2"));
let bindings = &args[0];
let bodies = &args[1..];
let bindings = match bindings {
&Value::List(ref inner) => inner,
other => return Err(AresError::UnexpectedType {
value: other.clone(),
expected: "List".into(),
}),
};
try!(expect_arity(&**bindings, |l| l % 2 == 0, "an even number"));
let mut new_env = Environment::new_with_data(ctx.env().clone(), HashMap::new());
for pair in bindings.chunks(2) {
let (name, value) = (&pair[0], &pair[1]);
let name = match name {
&Value::Symbol(s) => s,
other => return Err(AresError::UnexpectedType {
value: other.clone(),
expected: "Symbol".into(),
}),
};
let (env, evaluated) = ctx.with_other_env(new_env, move |new_ctx| new_ctx.eval(value));
new_env = env;
let evaluated = try!(evaluated);
new_env.borrow_mut().insert_here(name, evaluated.clone());
}
let mut last = None;
let (_, bodies_execution) = ctx.with_other_env(new_env, |new_ctx| -> AresResult<()> {
for body in bodies {
last = Some(try!(new_ctx.eval(body)));
}
Ok(())
});
try!(bodies_execution);
Ok(last.unwrap())
}
pub fn eval<S: State + ?Sized>(args: &[Value], ctx: &mut LoadedContext<S>) -> AresResult<Value> {
try!(expect_arity(args, |l| l == 1, "exactly 1"));
ctx.eval(&args[0])
}
pub fn apply<S: State + ?Sized>(args: &[Value], ctx: &mut LoadedContext<S>) -> AresResult<Value> {
try!(expect_arity(args, |l| l == 2, "exactly 2"));
let func = &args[0];
let arguments = &args[1];
match arguments {
&Value::List(ref lst) => ctx.call(func, lst),
other => Err(AresError::UnexpectedType {
value: other.clone(),
expected: "List".into(),
}),
}
}
pub fn lambda<S: State + ?Sized>(args: &[Value], ctx: &mut LoadedContext<S>) -> AresResult<Value> {
try!(expect_arity(args, |l| l >= 2, "at least 2"));
let dot = ctx.interner_mut().intern(".");
let param_names = match &args[0] {
&Value::List(ref v) => {
let mut params = vec![];
let mut rest = None;
let mut seen_dot = false;
try!(v.iter()
.map(|n| {
match n {
&Value::Symbol(s) if s == dot => {
if seen_dot {
Err(AresError::UnexpectedArgsList(args[0].clone()))
} else {
seen_dot = true;
Ok(())
}
}
&Value::Symbol(s) => {
if seen_dot {
match rest {
None => {
rest = Some(s);
Ok(())
}
Some(_) =>
Err(AresError::UnexpectedArgsList(args[0].clone())),
}
} else {
params.push(s);
Ok(())
}
}
&ref other => Err(AresError::UnexpectedType {
value: other.clone(),
expected: "Symbol".into(),
}),
}
})
.collect::<AresResult<Vec<()>>>());
ParamBinding {
params: params,
rest: rest,
}
}
&Value::Symbol(s) => {
ParamBinding {
params: vec![],
rest: Some(s),
}
}
x => {
return Err(AresError::UnexpectedArgsList(x.clone()));
}
};
let bodies: Vec<_> = args.iter().skip(1).cloned().collect();
Ok(Value::Lambda(Procedure::new(None, Rc::new(bodies), param_names, ctx.env().clone()),
false))
}
fn define_helper<S: State + ?Sized>(args: &[Value],
ctx: &mut LoadedContext<S>)
-> AresResult<(Symbol, Value)> {
try!(expect_arity(args, |l| l == 2, "exactly 2"));
let name = match &args[0] {
&Value::Symbol(s) => s,
&ref other => return Err(AresError::UnexpectedType {
value: other.clone(),
expected: "Symbol".into(),
}),
};
if ctx.env().borrow().is_defined_at_this_level(name) {
return Err(AresError::AlreadyDefined(ctx.interner().lookup_or_anon(name)));
}
let value = &args[1];
let result = try!(ctx.eval(value));
Ok((name, result))
}
pub fn define<S: State + ?Sized>(args: &[Value], ctx: &mut LoadedContext<S>) -> AresResult<Value> {
let (name, value) = try!(define_helper(args, ctx));
ctx.env().borrow_mut().insert_here(name, value.clone());
Ok(value)
}
pub fn define_macro<S: State + ?Sized>(args: &[Value],
ctx: &mut LoadedContext<S>)
-> AresResult<Value> {
let (name, value) = try!(define_helper(args, ctx));
let procedure = match value {
Value::Lambda(p, _) => p.clone(),
other => {
return Err(AresError::UnexpectedType {
value: other,
expected: "Lambda".into(),
});
}
};
let mac = Value::Lambda(procedure, true);
ctx.env().borrow_mut().insert_here(name, mac.clone());
Ok(mac)
}
pub fn walk<F>(value: &Value, f: &mut F) -> AresResult<Value>
where F: FnMut(&Value) -> AresResult<(Value, bool)>
{
let (v, recurse) = try!(f(value));
if recurse {
match v {
Value::List(v) => {
let result = try!(v.iter()
.map(|value| Ok(try!(walk(value, f))))
.collect::<AresResult<Vec<Value>>>());
Ok(Value::list(result))
}
Value::Map(m) => {
let mut result = HashMap::with_capacity(m.len());
for (k, v) in m.iter() {
let new_k = try!(walk(k, f));
let new_v = try!(walk(v, f));
result.insert(new_k, new_v);
}
Ok(Value::Map(Rc::new(result)))
}
v => Ok(v),
}
} else {
Ok(v)
}
}
pub fn macroexpand<S: State + ?Sized>(args: &[Value],
ctx: &mut LoadedContext<S>)
-> AresResult<Value> {
try!(expect_arity(args, |l| l == 1, "exactly 1"));
let quote = ctx.interner_mut().intern("quote"); // this should really be handled better...
let mut walk_f = |value: &Value| {
match value {
&Value::List(ref lst) => {
if lst.len() == 0 {
return Ok((Value::List(lst.clone()), false));
}
match &lst[0] {
&Value::Symbol(s) if s == quote => Ok((value.clone(), false)),
&Value::Symbol(s) => {
let v = ctx.env().borrow().get(s);
match v {
Some(v@Value::Lambda(_, true)) => {
let macro_out = try!(ctx.call(&v, &lst[1..lst.len()]));
let finished = try!(macroexpand(&[macro_out], ctx));
Ok((finished, true))
}
_ => Ok((value.clone(), true)),
}
}
_ => Ok((value.clone(), true)),
}
}
other => Ok((other.clone(), false)),
}
};
walk(&args[0], &mut walk_f)
}
pub fn set<S: State + ?Sized>(args: &[Value], ctx: &mut LoadedContext<S>) -> AresResult<Value> {
try!(expect_arity(args, |l| l == 2, "exactly 2"));
let name = match &args[0] {
&Value::Symbol(s) => s,
&ref v => return Err(AresError::UnexpectedType {
value: v.clone(),
expected: "Symbol".into(),
}),
};
let value = &args[1];
if !ctx.env().borrow().is_defined(name) {
return Err(AresError::UndefinedName(ctx.interner().lookup_or_anon(name)));
}
let result = try!(ctx.eval(value));
ctx.env().borrow_mut().with_value_mut(name, |v| *v = result.clone());
Ok(result)
}
pub fn quote<S: State + ?Sized>(args: &[Value], _ctx: &mut LoadedContext<S>) -> AresResult<Value> {
try!(expect_arity(args, |l| l == 1, "exactly 1"));
Ok(args[0].clone())
}
pub fn cond<S: State + ?Sized>(args: &[Value], ctx: &mut LoadedContext<S>) -> AresResult<Value> {
try!(expect_arity(args, |l| l == 3, "exactly 3"));
let (cond, true_branch, false_branch) = (&args[0], &args[1], &args[2]);
match try!(ctx.eval(cond)) {
Value::Bool(true) => ctx.eval(true_branch),
Value::Bool(false) => ctx.eval(false_branch),
other => Err(AresError::UnexpectedType {
value: other,
expected: "Bool".into(),
}),
}
}
pub fn gensym<S: State + ?Sized>(args: &[Value], ctx: &mut LoadedContext<S>) -> AresResult<Value> {
try!(expect_arity(args, |l| l == 0 || l == 1, "either 0 or 1"));
let symbol = if args.len() == 0 {
ctx.interner_mut().gen_sym()
} else {
match &args[0] {
&Value::String(ref s) => ctx.interner_mut().gen_sym_prefix(&s[..]),
other => return Err(AresError::UnexpectedType {
value: other.clone(),
expected: "String".into(),
}),
}
};
Ok(Value::Symbol(symbol))
}
pub fn quasiquote<S: State + ?Sized>(args: &[Value],
ctx: &mut LoadedContext<S>)
-> AresResult<Value> {
try!(expect_arity(args, |l| l == 1, "exactly 1"));
let unquote = Value::Symbol(ctx.interner_mut().intern("unquote"));
let unquote_splicing = Value::Symbol(ctx.interner_mut().intern("unquote-splicing"));
let mut walk_f = |v: &Value| {
match v {
&Value::List(ref lst) => {
if lst.len() >= 1 && lst[0] == unquote_splicing {
return Err(AresError::InvalidUnquotation);
} else if lst.len() == 2 && lst[0] == unquote {
return Ok(try!(ctx.eval(&lst[1])));
}
let mut new_v = vec![];
for elem in lst.iter() {
match elem {
&Value::List(ref inner) => {
if inner.len() == 2 && inner[0] == unquote {
new_v.push(try!(ctx.eval(&inner[1])));
} else if inner.len() == 2 && inner[0] == unquote_splicing {
let evald = try!(ctx.eval(&inner[1]));
match evald {
Value::List(ref evald) => new_v.extend(evald.iter().cloned()),
_ => return Err(AresError::UnexpectedType {
value: evald,
expected: "list".into(),
}),
}
} else {
let r = try!(quasiquote(&[elem.clone()], ctx));
new_v.push(r);
}
}
elem => new_v.push(elem.clone()),
}
}
Ok(Value::list(new_v))
}
_ => Ok(v.clone()),
}
};
walk_f(&args[0])
}
pub fn unquote_error<S: State + ?Sized>(_args: &[Value],
_ctx: &mut LoadedContext<S>)
-> AresResult<Value> {
Err(AresError::InvalidUnquotation)
}
|
use std::path::PathBuf;
use clap::ArgMatches;
use cli;
pub fn load_config() -> UpdaterConfig {
let cli_app = cli::create_cli_app();
let matches = cli_app.get_matches();
UpdaterConfig {
target_directory: get_string_value(&matches, "target-directory").map(|d| PathBuf::from(d)),
exclude_asn: matches.is_present("exclude_asn"),
exclude_ip2asn: matches.is_present("exclude_ip2asn"),
exclude_maxmind: matches.is_present("exclude_maxmind"),
skip_optimize: matches.is_present("skip_optimize"),
}
}
fn get_string_value(matches: &ArgMatches, key: &str) -> Option<String> {
matches.value_of(key).map(|m| m.to_string())
}
#[derive(Debug)]
pub struct UpdaterConfig {
pub target_directory: Option<PathBuf>,
pub exclude_asn: bool,
pub exclude_ip2asn: bool,
pub exclude_maxmind: bool,
pub skip_optimize: bool,
}
|
#[doc = "Register `ETH_MTLRxQ0MPOCR` reader"]
pub type R = crate::R<ETH_MTLRX_Q0MPOCR_SPEC>;
#[doc = "Field `OVFPKTCNT` reader - OVFPKTCNT"]
pub type OVFPKTCNT_R = crate::FieldReader<u16>;
#[doc = "Field `OVFCNTOVF` reader - OVFCNTOVF"]
pub type OVFCNTOVF_R = crate::BitReader;
#[doc = "Field `MISPKTCNT` reader - MISPKTCNT"]
pub type MISPKTCNT_R = crate::FieldReader<u16>;
#[doc = "Field `MISCNTOVF` reader - MISCNTOVF"]
pub type MISCNTOVF_R = crate::BitReader;
impl R {
#[doc = "Bits 0:10 - OVFPKTCNT"]
#[inline(always)]
pub fn ovfpktcnt(&self) -> OVFPKTCNT_R {
OVFPKTCNT_R::new((self.bits & 0x07ff) as u16)
}
#[doc = "Bit 11 - OVFCNTOVF"]
#[inline(always)]
pub fn ovfcntovf(&self) -> OVFCNTOVF_R {
OVFCNTOVF_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bits 16:26 - MISPKTCNT"]
#[inline(always)]
pub fn mispktcnt(&self) -> MISPKTCNT_R {
MISPKTCNT_R::new(((self.bits >> 16) & 0x07ff) as u16)
}
#[doc = "Bit 27 - MISCNTOVF"]
#[inline(always)]
pub fn miscntovf(&self) -> MISCNTOVF_R {
MISCNTOVF_R::new(((self.bits >> 27) & 1) != 0)
}
}
#[doc = "Rx queue 0 missed packet and overflow counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_mtlrx_q0mpocr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ETH_MTLRX_Q0MPOCR_SPEC;
impl crate::RegisterSpec for ETH_MTLRX_Q0MPOCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`eth_mtlrx_q0mpocr::R`](R) reader structure"]
impl crate::Readable for ETH_MTLRX_Q0MPOCR_SPEC {}
#[doc = "`reset()` method sets ETH_MTLRxQ0MPOCR to value 0"]
impl crate::Resettable for ETH_MTLRX_Q0MPOCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use super::*;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_const() {
println!("1");
let mut graph = Graph::new();
println!("2");
let a = ops::Const::<f32>::new(Box::new(Tensor::<f32>::new(&vec![1,2]))).finish();
println!("3");
let options = SessionOptions::new();
println!("4");
let sess = Session::new(&options, &graph).unwrap();
println!("5");
let result = sess.fetch(&mut graph, &a.output()).unwrap();
// println!("6");
// assert_eq!(result, 2_f32.into());
// println!("7");
}
} |
//! Providing auxiliary information for signals.
use std::io::Error;
use std::mem;
use std::ptr;
use libc::{c_int, EINVAL};
#[cfg(not(windows))]
use libc::{sigset_t, SIG_UNBLOCK};
use crate::consts::signal::*;
use crate::low_level;
#[derive(Clone, Copy, Debug)]
enum DefaultKind {
Ignore,
#[cfg(not(windows))]
Stop,
Term,
}
struct Details {
signal: c_int,
name: &'static str,
default_kind: DefaultKind,
}
macro_rules! s {
($name: expr, $kind: ident) => {
Details {
signal: $name,
name: stringify!($name),
default_kind: DefaultKind::$kind,
}
};
}
#[cfg(not(windows))]
const DETAILS: &[Details] = &[
s!(SIGABRT, Term),
s!(SIGALRM, Term),
s!(SIGBUS, Term),
s!(SIGCHLD, Ignore),
// Technically, continue the process... but this is not done *by* the process.
s!(SIGCONT, Ignore),
s!(SIGFPE, Term),
s!(SIGHUP, Term),
s!(SIGILL, Term),
s!(SIGINT, Term),
#[cfg(any(
target_os = "freebsd",
target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd",
target_os = "macos"
))]
s!(SIGINFO, Ignore),
#[cfg(not(target_os = "haiku"))]
s!(SIGIO, Ignore),
// Can't override anyway, but...
s!(SIGKILL, Term),
s!(SIGPIPE, Term),
s!(SIGPROF, Term),
s!(SIGQUIT, Term),
s!(SIGSEGV, Term),
// Can't override anyway, but...
s!(SIGSTOP, Stop),
s!(SIGSYS, Term),
s!(SIGTERM, Term),
s!(SIGTRAP, Term),
s!(SIGTSTP, Stop),
s!(SIGTTIN, Stop),
s!(SIGTTOU, Stop),
s!(SIGURG, Ignore),
s!(SIGUSR1, Term),
s!(SIGUSR2, Term),
s!(SIGVTALRM, Term),
s!(SIGWINCH, Ignore),
s!(SIGXCPU, Term),
s!(SIGXFSZ, Term),
];
#[cfg(windows)]
const DETAILS: &[Details] = &[
s!(SIGABRT, Term),
s!(SIGFPE, Term),
s!(SIGILL, Term),
s!(SIGINT, Term),
s!(SIGSEGV, Term),
s!(SIGTERM, Term),
];
/// Provides a human-readable name of a signal.
///
/// Note that the name does not have to be known (in case it is some less common, or non-standard
/// signal).
///
/// # Examples
///
/// ```
/// # use signal_hook::low_level::signal_name;
/// assert_eq!("SIGKILL", signal_name(9).unwrap());
/// assert!(signal_name(142).is_none());
/// ```
pub fn signal_name(signal: c_int) -> Option<&'static str> {
DETAILS.iter().find(|d| d.signal == signal).map(|d| d.name)
}
#[cfg(not(windows))]
fn restore_default(signal: c_int) -> Result<(), Error> {
unsafe {
// A C structure, supposed to be memset to 0 before use.
let mut action: libc::sigaction = mem::zeroed();
#[cfg(target_os = "aix")]
{
action.sa_union.__su_sigaction = mem::transmute::<
usize,
extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void),
>(libc::SIG_DFL);
}
#[cfg(not(target_os = "aix"))]
{ action.sa_sigaction = libc::SIG_DFL as _; }
if libc::sigaction(signal, &action, ptr::null_mut()) == 0 {
Ok(())
} else {
Err(Error::last_os_error())
}
}
}
#[cfg(windows)]
fn restore_default(signal: c_int) -> Result<(), Error> {
unsafe {
// SIG_DFL = 0, but not in libc :-(
if libc::signal(signal, 0) == 0 {
Ok(())
} else {
Err(Error::last_os_error())
}
}
}
/// Emulates the behaviour of a default handler for the provided signal.
///
/// This function does its best to provide the same action as the default handler would do, without
/// disrupting the rest of the handling of such signal in the application. It is also
/// async-signal-safe.
///
/// This function necessarily looks up the appropriate action in a table. That means it is possible
/// your system has a signal that is not known to this function. In such case an error is returned
/// (equivalent of `EINVAL`).
///
/// See also the [`register_conditional_default`][crate::flag::register_conditional_default].
///
/// # Warning
///
/// There's a short race condition in case of signals that terminate (either with or without a core
/// dump). The emulation first resets the signal handler back to default (as the application is
/// going to end, it's not a problem) and invokes it. But if some other thread installs a signal
/// handler in the meantime (without assistance from `signal-hook`), it can happen this will be
/// invoked by the re-raised signal.
///
/// This function will still terminate the application (there's a fallback on `abort`), the risk is
/// invoking the newly installed signal handler. Note that manipulating the low-level signals is
/// always racy in a multi-threaded program, therefore the described situation is already
/// discouraged.
///
/// If you are uneasy about such race condition, the recommendation is to run relevant termination
/// routine manually ([`exit`][super::exit] or [`abort`][super::abort]); they always do what they
/// say, but slightly differ in externally observable behaviour from termination by a signal (the
/// exit code will specify that the application exited, not that it terminated with a signal in the
/// first case, and `abort` terminates on `SIGABRT`, so the detected termination signal may be
/// different).
pub fn emulate_default_handler(signal: c_int) -> Result<(), Error> {
#[cfg(not(windows))]
{
if signal == SIGSTOP || signal == SIGKILL {
return low_level::raise(signal);
}
}
let kind = DETAILS
.iter()
.find(|d| d.signal == signal)
.map(|d| d.default_kind)
.ok_or_else(|| Error::from_raw_os_error(EINVAL))?;
match kind {
DefaultKind::Ignore => Ok(()),
#[cfg(not(windows))]
DefaultKind::Stop => low_level::raise(SIGSTOP),
DefaultKind::Term => {
if let Ok(()) = restore_default(signal) {
#[cfg(not(windows))]
unsafe {
#[allow(deprecated)]
let mut newsigs: sigset_t = mem::zeroed();
// Some android versions don't have the sigemptyset and sigaddset.
// Unfortunately, we don't have an access to the android _version_. We just
// know that 64bit versions are all OK, so this is a best-effort guess.
//
// For the affected/guessed versions, we provide our own implementation. We
// hope it to be correct (it's inspired by a libc implementation and we assume
// the kernel uses the same format ‒ it's unlikely to be different both because
// of compatibility and because there's really nothing to invent about a
// bitarray).
//
// We use the proper way for other systems.
#[cfg(all(target_os = "android", target_pointer_width = "32"))]
unsafe fn prepare_sigset(set: *mut sigset_t, mut signal: c_int) {
signal -= 1;
let set_raw: *mut libc::c_ulong = set.cast();
let size = mem::size_of::<libc::c_ulong>();
assert_eq!(set_raw as usize % mem::align_of::<libc::c_ulong>(), 0);
let pos = signal as usize / size;
assert!(pos < mem::size_of::<sigset_t>() / size);
let bit = 1 << (signal as usize % size);
set_raw.add(pos).write(bit);
}
#[cfg(not(all(target_os = "android", target_pointer_width = "32")))]
unsafe fn prepare_sigset(set: *mut sigset_t, signal: c_int) {
libc::sigemptyset(set);
libc::sigaddset(set, signal);
}
prepare_sigset(&mut newsigs, signal);
// Ignore the result, if it doesn't work, we try anyway
// Also, sigprocmask is unspecified, but available on more systems. And we want
// to just enable _something_. And if it doesn't work, we'll terminate
// anyway... It's not UB, so we are good.
libc::sigprocmask(SIG_UNBLOCK, &newsigs, ptr::null_mut());
}
let _ = low_level::raise(signal);
}
// Fallback if anything failed or someone managed to put some other action in in
// between.
unsafe { libc::abort() }
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn existing() {
assert_eq!("SIGTERM", signal_name(SIGTERM).unwrap());
}
#[test]
fn unknown() {
assert!(signal_name(128).is_none());
}
}
|
// ======================================
// nanomsg.rs : nanomsg bindings for rust
//
// This aims to be a rust version of the
// full public API of nanomsg. But parts
// are probably still missing, since the
// safe API only does nn_send and nn_recv
// currently.
// ======================================
#![crate_name = "nanomsg"]
#![crate_type = "lib"]
#![license = "MIT/ASL2"]
#![feature(globs, unsafe_destructor)]
#![allow(dead_code, non_camel_case_types)]
#![feature(phase)]
#[phase(plugin, link)] extern crate log;
extern crate libc;
extern crate debug;
use std::ptr;
use std::ptr::RawPtr;
use libc::{c_void,size_t,c_int,c_short,malloc,free};
use std::intrinsics;
use std::mem::transmute;
use std::io;
use std::io::{Reader,Writer};
use std::io::IoResult;
use std::cmp::min;
use std::os::last_os_error;
use std::os::errno;
use std::slice;
use std::num::FromPrimitive;
use std::slice::raw::buf_as_slice;
pub static AF_SP: c_int = 1;
pub static AF_SP_RAW: c_int = 2;
pub static NN_CHUNKREF_MAX: c_int = 32;
pub static NN_DOMAIN: c_int = 12;
pub static NN_DONTWAIT: c_int = 1;
pub static NN_FSM_ACTION: c_int = -2;
pub static NN_FSM_START: c_int = -2;
pub static NN_FSM_STOP: c_int = -3;
pub static NN_HAUSNUMERO: int = 156384712;
pub static NN_INPROC: c_int = -1;
pub static NN_IPC: c_int = -2;
pub static NN_IPV4ONLY: c_int = 14;
pub static NN_LINGER: c_int = 1;
pub static NN_PIPEBASE_PARSED: c_int = 2;
pub static NN_PIPEBASE_RELEASE: c_int = 1;
pub static NN_PIPE_IN: c_int = 33987;
pub static NN_PIPE_OUT: c_int = 33988;
pub static NN_PIPE_PARSED: c_int = 2;
pub static NN_PIPE_RELEASE: c_int = 1;
pub static NN_PROTO_BUS: c_int = 7;
pub static NN_PROTOCOL: c_int = 13;
pub static NN_PROTO_PAIR: c_int = 1;
pub static NN_PROTO_PIPELINE: c_int = 5;
pub static NN_PROTO_PUBSUB: c_int = 2;
pub static NN_PROTO_REQREP: c_int = 3;
pub static NN_PROTO_SURVEY: c_int = 6;
pub static NN_RCVBUF: c_int = 3;
pub static NN_RCVFD: c_int = 11;
pub static NN_RCVTIMEO: c_int = 5;
pub static NN_RECONNECT_IVL: c_int = 6;
pub static NN_RECONNECT_IVL_MAX: c_int = 7;
pub static NN_REQ_RESEND_IVL: c_int = 1;
pub static NN_SNDBUF: c_int = 2;
pub static NN_SNDFD: c_int = 10;
pub static NN_SNDPRIO: c_int = 8;
pub static NN_SNDTIMEO: c_int = 4;
pub static NN_SOCKADDR_MAX: c_int = 128;
pub static NN_SOCKBASE_EVENT_IN: c_int = 1;
pub static NN_SOCKBASE_EVENT_OUT: c_int = 2;
pub static NN_SOCKTYPE_FLAG_NORECV: c_int = 1;
pub static NN_SOCKTYPE_FLAG_NOSEND: c_int = 2;
pub static NN_SOL_SOCKET: c_int = 0;
pub static NN_SUB_SUBSCRIBE: c_int = 1;
pub static NN_SUB_UNSUBSCRIBE: c_int = 2;
pub static NN_SURVEYOR_DEADLINE: c_int = 1;
pub static NN_TCP: c_int = -3;
pub static NN_TCP_NODELAY: c_int = 1;
pub static NN_VERSION_AGE: c_int = 0;
pub static NN_VERSION_CURRENT: c_int = 0;
pub static NN_VERSION_REVISION: c_int = 0;
pub static NN_POLLIN: c_short = 1;
pub static NN_POLLOUT: c_short = 2;
pub static NN_BUS: c_int = (NN_PROTO_BUS * 16 + 0);
pub static NN_MSG: u64 = -1;
pub static NN_PAIR: c_int = (NN_PROTO_PAIR * 16 + 0);
pub static NN_PUSH: c_int = (NN_PROTO_PIPELINE * 16 + 0);
pub static NN_PULL: c_int = (NN_PROTO_PIPELINE * 16 + 1);
pub static NN_PUB: c_int = (NN_PROTO_PUBSUB * 16 + 0);
pub static NN_SUB: c_int = (NN_PROTO_PUBSUB * 16 + 1);
pub static NN_REQ: c_int = (NN_PROTO_REQREP * 16 + 0);
pub static NN_REP: c_int = (NN_PROTO_REQREP * 16 + 1);
pub static NN_SURVEYOR: c_int = (NN_PROTO_SURVEY * 16 + 0);
pub static NN_RESPONDENT: c_int = (NN_PROTO_SURVEY * 16 + 1);
pub static NN_QUEUE_NOTINQUEUE: c_int = -1;
pub static NN_LIST_NOTINLIST: c_int = -1;
pub type c_schar = i8;
pub struct IoVec {
iov_base: *mut c_void,
iov_len: size_t,
}
//MsgHdr
pub struct MsgHdr {
msg_iov: *mut IoVec,
msg_iovlen: c_int,
msg_control: *mut c_void,
msg_controllen: size_t,
}
#[deriving(Show)]
pub struct PollFd {
fd: c_int,
events: c_short,
revents: c_short
}
#[link(name = "nanomsg")]
extern "C" {
pub static mut program_invocation_name: *mut c_schar;
pub static mut program_invocation_short_name: *mut c_schar;
pub fn __errno_location() -> *mut c_int;
pub fn nn_errno() -> c_int;
pub fn nn_strerror(errnum: c_int) -> *const c_schar;
pub fn nn_symbol(i: c_int,
value: *mut c_int) -> *const c_schar;
pub fn nn_term();
pub fn nn_allocmsg(size: size_t,
_type: c_int) -> *mut c_void;
pub fn nn_freemsg(msg: *mut c_void) -> c_int;
pub fn nn_socket(domain: c_int, protocol: c_int) -> c_int;
pub fn nn_close(s: c_int) -> c_int;
pub fn nn_setsockopt(s: c_int,
level: c_int,
option: c_int,
optval: *const c_void,
optvallen: size_t) -> c_int;
pub fn nn_getsockopt(s: c_int, level: c_int,
option: c_int,
optval: *mut c_void,
optvallen: *mut size_t) -> c_int;
pub fn nn_bind(s: c_int, addr: *const c_schar) -> c_int;
pub fn nn_connect(s: c_int, addr: *const c_schar) -> c_int;
pub fn nn_shutdown(s: c_int, how: c_int) -> c_int;
pub fn nn_send(s: c_int,
buf: *const c_void,
len: size_t,
flags: c_int) -> c_int;
pub fn nn_recv(s: c_int,
buf: *mut c_void,
len: size_t,
flags: c_int) -> c_int;
pub fn nn_sendmsg(s: c_int,
msghdr: *const MsgHdr,
flags: c_int) -> c_int;
pub fn nn_recvmsg(s: c_int,
msghdr: *mut MsgHdr,
flags: c_int) -> c_int;
pub fn nn_device(s1: c_int,
s2: c_int) -> c_int;
pub fn nn_poll(fds: *mut PollFd, nfds: c_int, timeout: c_int) -> c_int;
}
// ======================================================
// NanoErr
// ======================================================
pub struct NanoErr {
pub rc: c_int,
pub errstr: String,
}
// Rust-idiomatic memory safe wrappers for nanomsg objects:
// ======================================================
// NanoSocket
// ======================================================
pub struct NanoSocket {
sock: c_int,
}
#[deriving(PartialEq, FromPrimitive, Show)]
pub enum NanoError {
ENOTSUP = NN_HAUSNUMERO + 1,
EPROTONOSUPPORT = NN_HAUSNUMERO + 2,
ENOBUFS = NN_HAUSNUMERO + 3,
ENETDOWN = NN_HAUSNUMERO + 4,
EADDRINUSE = NN_HAUSNUMERO + 5,
EADDRNOTAVAIL = NN_HAUSNUMERO + 6,
ECONNREFUSED = NN_HAUSNUMERO + 7,
EINPROGRESS = NN_HAUSNUMERO + 8,
ENOTSOCK = NN_HAUSNUMERO + 9,
EAFNOSUPPORT = NN_HAUSNUMERO + 10,
EPROTO = NN_HAUSNUMERO + 11,
EAGAIN = NN_HAUSNUMERO + 12,
EBADF = NN_HAUSNUMERO + 13,
EINVAL = NN_HAUSNUMERO + 14,
EMFILE = NN_HAUSNUMERO + 15,
EFAULT = NN_HAUSNUMERO + 16,
EACCESS = NN_HAUSNUMERO + 17,
ENETRESET = NN_HAUSNUMERO + 18,
ENETUNREACH = NN_HAUSNUMERO + 19,
EHOSTUNREACH = NN_HAUSNUMERO + 20,
ENOTCONN = NN_HAUSNUMERO + 21,
EMSGSIZE = NN_HAUSNUMERO + 22,
ETIMEDOUT = NN_HAUSNUMERO + 23,
ECONNABORTED = NN_HAUSNUMERO + 24,
ECONNRESET = NN_HAUSNUMERO + 25,
ENOPROTOOPT = NN_HAUSNUMERO + 26,
EISCONN = NN_HAUSNUMERO + 27,
ETIMEOUT = NN_HAUSNUMERO + 100, // Added by library for timeouts
EUNKNOWN = NN_HAUSNUMERO + 101 // Added by library for unknown problems
}
impl NanoSocket {
// example: let sock = NanoSocket::new(AF_SP, NN_PAIR);
#[inline(never)]
pub fn new(domain: c_int, protocol: c_int) -> Result<NanoSocket, NanoErr> {
let rc: c_int = unsafe { nn_socket(domain, protocol) };
if rc < 0 {
Err(NanoErr{ rc: rc, errstr: last_os_error() })
} else {
Ok(NanoSocket{ sock: rc })
}
}
// connect
#[inline(never)]
pub fn connect(&self, addr: &str) -> Result<(), NanoErr> {
let rc = unsafe { nn_connect(self.sock, addr.to_c_str().as_ptr()) };
if rc < 0 {
Err(NanoErr{ rc: rc, errstr: last_os_error() })
} else {
Ok(())
}
}
// bind(listen)
#[inline(never)]
pub fn bind(&self, addr: &str) -> Result<(), NanoErr>{
// bind
let rc = unsafe { nn_bind(self.sock, addr.to_c_str().as_ptr()) };
if rc < 0 {
Err(NanoErr{rc: rc, errstr: last_os_error() })
} else {
Ok(())
}
}
// subscribe, with prefix-filter
#[inline(never)]
pub fn subscribe(&self, prefix: &[u8]) -> Result<(), NanoErr>{
let rc = unsafe {
nn_setsockopt(self.sock,
NN_SUB,
NN_SUB_SUBSCRIBE,
prefix.as_ptr() as *const c_void,
prefix.len() as u64)
};
if rc < 0 {
Err( NanoErr{ rc: rc, errstr: last_os_error() })
} else {
Ok(())
}
}
/*
pub fn getFd(&self, FdType) -> Result<fd_t, NanoErr>{
}
*/
// send
#[inline(never)]
pub fn send(&self, buf: &[u8]) -> Result<(), NanoErr> {
let len : i64 = buf.len() as i64;
if 0 == len { return Ok(()); }
let rc : i64 = unsafe { nn_send(self.sock, buf.as_ptr() as *const c_void, len as u64, 0) } as i64;
if rc < 0 {
Err(NanoErr{rc: rc as i32, errstr: last_os_error() })
} else {
Ok(())
}
}
// send a string
#[inline(never)]
pub fn sendstr(&self, b: &str) -> Result<(), NanoErr> {
let len = b.len();
if 0 == len { return Ok(()); }
let rc = unsafe { nn_send(self.sock, b.to_c_str().as_ptr() as *const libc::c_void, len as u64, 0) };
if rc < 0 {
Err(NanoErr{rc: rc as i32, errstr: last_os_error() })
} else {
Ok(())
}
}
// buffer receive
#[inline(never)]
pub fn recv(&self) -> Result<Vec<u8>, NanoErr> {
let mut mem : *mut u8 = ptr::mut_null();
let recvd = unsafe { nn_recv(self.sock, transmute(&mut mem), NN_MSG, 0) };
if recvd < 0 {
Err(NanoErr{rc: recvd as i32, errstr: last_os_error() })
} else {
unsafe {
let buf = std::slice::raw::buf_as_slice(mem as *const u8, recvd as uint, |buf| {
buf.to_vec()
});
nn_freemsg(mem as *mut c_void);
Ok(buf)
}
}
}
#[inline(never)]
pub fn getsockopt(&self, level: i32, option: i32) -> Result<u32, NanoErr> {
let mut optval: u32 = 0;
let optval_ptr: *mut u32 = &mut optval;
let mut optvallen: u64 = 4;
let optvallen_ptr: *mut u64 = &mut optvallen;
let recvd = unsafe {
nn_getsockopt(self.sock,
level,
option,
optval_ptr as *mut c_void,
optvallen_ptr) as i64
};
match recvd {
0 => Ok(optval),
_ => Err(NanoErr{ rc: recvd as i32, errstr: last_os_error() })
}
}
#[inline(never)]
pub fn can_send(&self, timeout: int) -> bool {
match self.poll(true, false, timeout) {
Ok((s, _)) => s,
Err(_) => false
}
}
#[inline(never)]
pub fn can_receive(&self, timeout: int) -> bool {
match self.poll(false, true, timeout) {
Ok((_, r)) => r,
Err(_) => false
}
}
#[inline(never)]
pub fn poll(&self, send: bool, receive: bool, timeout: int) -> Result<(bool, bool), NanoError> {
let events: i16 = match (send, receive) {
(false, false) => return Ok((false,false)), // If you don't want to poll either, exit early
(true, false) => NN_POLLOUT,
(false, true) => NN_POLLIN,
(true, true) => NN_POLLIN | NN_POLLOUT
};
let mut pollfd = PollFd { fd: self.sock, events: events, revents: 0 };
let pollfds_ptr: *mut PollFd = &mut pollfd;
let ret = unsafe { nn_poll(pollfds_ptr, 1 as c_int, timeout as i32) };
drop(pollfds_ptr);
match ret {
0 => Err(ETIMEOUT),
-1 => {
match self.errno() {
Some(s) => Err(s),
None => Err(EUNKNOWN)
}
},
_ => {
let can_send = pollfd.revents & NN_POLLOUT > 0;
let can_recv = pollfd.revents & NN_POLLIN > 0;
Ok((can_send, can_recv))
}
}
}
#[inline(never)]
pub fn errno(&self) -> Option<NanoError> {
let error: Option<NanoError> = FromPrimitive::from_i32( unsafe { nn_errno() });
error
}
}
impl std::io::Reader for NanoSocket {
#[inline(never)]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.recv() {
Err(e) => {
warn!("recv failed: {:?} {:?}",e.rc, e.errstr);
// [TODO]: Return specific error based on the failure.
Err(io::standard_error(io::OtherIoError))
},
Ok(b) => {
let copylen = min(b.len(), buf.len());
slice::bytes::copy_memory(buf, b.slice(0, copylen));
Ok(copylen)
}
}
}
}
impl io::Seek for NanoSocket {
fn seek(&mut self, _offset: i64, _whence: io::SeekStyle) -> IoResult<()> {
Err(io::standard_error(io::OtherIoError))
}
fn tell(&self) -> IoResult<u64> {fail!();}
}
impl std::io::Writer for NanoSocket {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
// [TODO]: Return specific error based on the failure.
self.send(buf).map_err(|_| io::standard_error(io::OtherIoError))
}
fn flush(&mut self) -> IoResult<()> {
Ok(())
}
}
#[unsafe_destructor]
impl Drop for NanoSocket {
#[inline(never)]
fn drop(&mut self) {
// close
let rc = unsafe { nn_close(self.sock) };
if rc != 0 {
let msg = format!("nn_close({:?}) failed with errno: {:?} '{:?}'", self.sock, std::os::errno(), std::os::last_os_error());
error!("{:s}", msg);
fail!("{:s}", msg);
}
}
}
// ======================================================
// NanoMsg
//
// It is not necessary to restrict the lifetime of the
// NanoMsg to be a subset of the lifetime of the
// NanoSocket. But if you wanted to do that, you would
// write:
// struct Msg<'self> { socket: &'self Socket, ... }
// which would put a borrowed pointer to the socket in
// the msg and restrict the messages' lifetime.
// ======================================================
enum HowToCleanup {
/// depending on whether recv_any_size() or recv_no_more_than_maxlen()
/// was used to get the message, the cleanup code is different.
/// If recv_any_size (zero-copy enabled), then we call nn_freemsg().
/// if recv_no_more_than_maxlen(), the we call ::free() to release the malloc.
/// Lastly if we have no message to cleanup, then DoNothing.
Free,
FreeMsg,
DoNothing
}
/// a wrapper around the message returned by nn_recv
pub struct NanoMsg {
buf: *mut u8,
bytes_stored_in_buf: u64,
bytes_available: u64,
cleanup: HowToCleanup,
}
impl NanoMsg {
pub fn new() -> NanoMsg {
let buf : *mut u8 = ptr::mut_null();
NanoMsg{buf: buf, bytes_stored_in_buf: 0, bytes_available: 0, cleanup: DoNothing }
}
pub fn len(&self) -> u64 {
self.bytes_stored_in_buf
}
pub fn actual_msg_bytes_avail(&self) -> u64 {
self.bytes_available
}
pub fn printbuf(&self) {
println!("NanoMsg contains message of length {:?}: '{:s}'", self.bytes_stored_in_buf, self.copy_to_string());
}
/// Unwraps the NanoMsg.
/// Any ownership of the message pointed to by buf is forgotten.
/// Since we take self by value, no further access is possible.
pub unsafe fn unwrap(self) -> *mut u8 {
let mut msg = self;
msg.cleanup = DoNothing;
msg.buf
}
/// recv_any_size allows nanomsg to do zero-copy optimizations
#[inline(never)]
pub fn recv_any_size(&mut self, sock: c_int, flags: c_int) -> Result<u64, NanoErr>{
match self.cleanup {
DoNothing => (),
Free => self.cleanup(),
FreeMsg => self.cleanup()
}
let len = unsafe { nn_recv(sock, transmute(&mut self.buf), NN_MSG, flags) };
self.bytes_stored_in_buf = len as u64;
self.bytes_available = self.bytes_stored_in_buf;
if len < 0 {
debug!("nn_recv failed with errno: {:?} '{:?}'", std::os::errno(), std::os::last_os_error());
Err(NanoErr{ rc: std::os::errno() as i32, errstr: last_os_error() })
} else {
self.cleanup = FreeMsg;
Ok(self.bytes_stored_in_buf)
}
}
/// Use recv_no_more_than_maxlen() if we need our own copy anyway, but don't want to overflow our
/// heap. The function will truncate any part of the message over maxlen. In general, prefer recv_any_size() above.
#[inline(never)]
pub fn recv_no_more_than_maxlen(&mut self, sock: c_int, maxlen: u64, flags: c_int) -> Result<u64, NanoErr> {
match self.cleanup {
DoNothing => (),
Free => self.cleanup(),
FreeMsg => self.cleanup()
}
let ptr = unsafe { malloc(maxlen as size_t) as *mut u8 };
assert!(!ptr.is_null());
self.cleanup = Free;
self.buf = ptr;
let len = unsafe { nn_recv(sock, transmute(self.buf), maxlen, flags) };
self.bytes_available = len as u64;
if len < 0 {
let errmsg = format!("recv_no_more_than_maxlen: nn_recv failed with errno: {:?} '{:?}'", std::os::errno(), std::os::last_os_error());
warn!("{:s}", errmsg);
return Err(NanoErr{rc: std::os::errno() as i32, errstr: last_os_error() });
}
if self.bytes_available > maxlen {
let errmsg = format!("recv_no_more_than_maxlen: message was longer ({:?} bytes) than we allocated space for ({:?} bytes)", self.bytes_available, maxlen);
warn!("{:s}", errmsg);
}
self.bytes_stored_in_buf = min(maxlen, self.bytes_available);
Ok(self.bytes_stored_in_buf)
}
pub fn copy_to_string(&self) -> String {
unsafe { std::string::raw::from_buf_len(self.buf as *const u8, self.bytes_stored_in_buf as uint) }
}
#[inline(never)]
pub fn cleanup(&self) {
if self.buf.is_null() { return; }
match self.cleanup {
DoNothing => (),
Free => {
unsafe {
// see example code: http://static.rust-lang.org/doc/tutorial-ffi.html
let x = intrinsics::init(); // dummy value to swap in
// moving the object out is needed to call the destructor
ptr::replace(self.buf, x);
free(self.buf as *mut c_void)
}
},
FreeMsg => {
unsafe {
// println!("*** FreeMsg Drop running.");
let x = intrinsics::init(); // dummy value to swap in
// moving the object out is needed to call the destructor
ptr::replace(self.buf, x);
let rc = nn_freemsg(self.buf as *mut c_void);
assert! (rc == 0);
}
}
}
}
}
#[unsafe_destructor]
impl Drop for NanoMsg {
#[inline(never)]
fn drop(&mut self) {
//println!("starting Drop for NanoMsg, with style: {:?}", self.cleanup);
self.cleanup();
}
}
#[cfg(test)]
mod test {
#![allow(unused_must_use)]
extern crate debug;
use super::*;
use std::io::timer::sleep;
use std::comm;
#[test]
fn smoke_test_msg_client_msg_server() {
spawn(proc() {
msgserver_test();
});
msgclient_test();
}
#[test]
fn smoke_test_readerwriter() {
let addr="tcp://127.0.0.1:1234";
// server end:
spawn(proc() {
let mut sock = NanoSocket::new(AF_SP, NN_PAIR).ok().expect("asdf");
sock.bind(addr);
let mut buf = [0,0,0,0,0];
sock.read(buf);
assert!(buf[2] == 3);
});
// client end:
let mut sock = NanoSocket::new(AF_SP, NN_PAIR).ok().expect("asdf");
sock.connect(addr);
sock.write([1,2,3,4]);
}
// basic test that NanoMsg and NanoSocket are working
fn msgclient_test() {
// make a NanoMsg to hold a received message
let mut msg = NanoMsg::new();
let address = "tcp://127.0.0.1:5439";
{ // sock lifetime
// create and connect
let sock = match NanoSocket::new(AF_SP, NN_PAIR) {
Ok(s) => s,
Err(e) => fail!("Failed with err:{:?} {:?}", e.rc, e.errstr)
};
sock.connect(address);
// send
let b = "WHY";
sock.sendstr(b);
// demonstrate NanoMsg::recv_any_size()
match msg.recv_any_size(sock.sock, 0) {
Ok(_) => {
let m = msg.copy_to_string();
assert!(m.as_slice() == "LUV");
},
Err(e) => fail!("recv_any_size -> nn_recv failed with errno: {:?} '{:?}'", e.rc, e.errstr)
}
// it is okay to reuse msg (e.g. as below, or in a loop). NanoMsg will free any previous message before
// receiving a new one.
// demonstrate NanoMsg::recv_no_more_than_maxlen()
match msg.recv_no_more_than_maxlen(sock.sock, 2, 0) {
Ok(_) => {
let m = msg.copy_to_string();
assert!(m.as_slice() == "CA");
},
Err(e) => fail!("recv_no_more_than_maxlen -> nn_recv failed with errno: {:?} '{:?}'", e.rc, e.errstr)
}
} // end of socket lifetime
}
fn msgserver_test() {
let mut msg = NanoMsg::new();
let address = "tcp://127.0.0.1:5439";
// create and connect
let sock = match NanoSocket::new(AF_SP, NN_PAIR) {
Ok(s) => s,
Err(e) => fail!("Failed with err:{:?} {:?}", e.rc, e.errstr)
};
match sock.bind(address) {
Ok(_) => {},
Err(e) => fail!("Bind failed with err:{:?} {:?}", e.rc, e.errstr)
}
// receive
match msg.recv_any_size(sock.sock, 0) {
Ok(_) => {
let m = msg.copy_to_string();
assert!(m.as_slice() == "WHY");
},
Err(e) => fail!("recv_any_size -> nn_recv failed with errno: {:?} '{:?}'", e.rc, e.errstr)
}
// send
let b = "LUV";
match sock.sendstr(b) {
Ok(_) => {},
Err(e) => fail!("send failed with err:{:?} {:?}", e.rc, e.errstr)
}
// send 2
let b = "CAT";
match sock.sendstr(b) {
Ok(_) => {},
Err(e) =>{
fail!("send failed with err:{:?} {:?}", e.rc, e.errstr);
}
}
}
#[test]
fn test_getsockopt() {
let addr="tcp://127.0.0.1:8898";
let sock = NanoSocket::new(AF_SP, NN_PAIR).ok().expect("asdf");
sock.bind(addr);
// Linger default is 1000ms
let ret = match sock.getsockopt(NN_SOL_SOCKET, NN_LINGER) {
Ok(s) => s,
Err(e) => fail!("failed getsockopt(NN_SOL_SOCKET, NN_LINGER) with err:{:?} {:?}", e.rc, e.errstr)
};
assert!(ret == 1000);
// SendBuffer default is 128kb (131072 bytes)
let ret = match sock.getsockopt(NN_SOL_SOCKET, NN_SNDBUF) {
Ok(s) => s,
Err(e) => fail!("failed getsockopt(NN_SOL_SOCKET, NN_SNDBUF) with err:{:?} {:?}", e.rc, e.errstr)
};
assert!(ret == 131072);
// ReceiveBuffer default is 128kb (131072 bytes)
let ret = match sock.getsockopt(NN_SOL_SOCKET, NN_RCVBUF) {
Ok(s) => s,
Err(e) => fail!("failed getsockopt(NN_SOL_SOCKET, NN_RCVBUF) with err:{:?} {:?}", e.rc, e.errstr)
};
assert!(ret == 131072);
// Send timeout default is -1 (unlimited)
let ret = match sock.getsockopt(NN_SOL_SOCKET, NN_SNDTIMEO) {
Ok(s) => s,
Err(e) => fail!("failed getsockopt(NN_SOL_SOCKET, NN_SNDTIMEO) with err:{:?} {:?}", e.rc, e.errstr)
};
assert!(ret == -1);
}
#[test]
fn test_poll() {
let addr="tcp://127.0.0.1:8899";
let mut sock = NanoSocket::new(AF_SP, NN_PAIR).ok().expect("asdf");
sock.bind(addr);
let (parent_send, child_recv) = comm::channel::<int>();
let (child_send, parent_recv) = comm::channel::<int>();
spawn(proc() {
let addr="tcp://127.0.0.1:8899";
let sock = NanoSocket::new(AF_SP, NN_PAIR).ok().expect("asdf");
sock.connect(addr);
parent_send.send(0);
parent_recv.recv();
let (can_send, can_recv) = match sock.poll(true, true, 1000) {
Ok((s, r)) => (s,r),
Err(e) => fail!(format!("Failed: {}", e))
};
assert!(can_send == true); // Can send since we are connected
assert!(can_recv == false); // Cannot read, since no messages are pending
sock.send([0,0,0,0,0]); // Send two batches of messages
sock.send([0,0,0,0,0]);
parent_send.send(0);
parent_recv.recv(); //signal to shutdown
});
// ----- Binding has completed ------//
child_recv.recv();
let (can_send, can_recv) = match sock.poll(true, true, 1000) {
Ok((s, r)) => (s,r),
Err(e) => fail!(format!("Failed: {}", e))
};
assert!(can_send == true); // Can send since we are connected
assert!(can_recv == false); // Cannot read, since no messages are pending
child_send.send(0);
// ----- Two messages pending ------//
child_recv.recv();
sleep(100); //hacky, but sometimes the socket send doesnt finish before the chan send
let (can_send, can_recv) = match sock.poll(true, true, 1000) {
Ok((s, r)) => (s,r),
Err(e) => fail!(format!("Failed: {}", e))
};
assert!(can_send == true);
assert!(can_recv == true); // Can now read since two messages are pending
let mut buf = [0,0,0,0,0]; // Read the first batch
sock.read(buf);
let (can_send, can_recv) = match sock.poll(true, true, 1000) {
Ok((s, r)) => (s,r),
Err(e) => fail!(format!("Failed: {}", e))
};
assert!(can_send == true);
assert!(can_recv == true); // should still be true, one message pending
// ----- One message pending ------//
sock.read(buf); // Read second message
let (can_send, can_recv) = match sock.poll(true, true, 1000) {
Ok((s, r)) => (s,r),
Err(e) => fail!(format!("Failed: {}", e))
};
assert!(can_send == true);
assert!(can_recv == false); // Can no longer read since all messages have been received
child_send.send(0); // shutdown
}
}
|
use action::Action;
use bluetooth::Bluetooth;
use core::marker::Unsize;
use debug::UnwrapLog;
use hidreport::HidReport;
use keycodes::KeyCode;
use keymatrix::KeyState;
use layout::LAYERS;
use layout::LAYER_BT;
use led::Led;
use stm32l151::SCB;
use stm32l151::SYST;
use usb::Usb;
pub struct Keyboard {
layers: Layers,
previous_state: KeyState, // TODO: use packed state here
}
fn eq(sa: &KeyState, sb: &KeyState) -> bool {
sa.iter().zip(sb.iter()).all(|(a, b)| a == b)
}
impl Keyboard {
pub const fn new() -> Keyboard {
Keyboard {
layers: Layers::new(),
previous_state: [false; 70],
}
}
fn get_action(&self, key: usize) -> Action {
let mut action = Action::Transparent;
for i in (0..LAYERS.len()).rev() {
if self.layers.current & (1 << i) != 0 {
action = LAYERS[i][key];
}
if action != Action::Transparent {
break;
}
}
action
}
pub fn process<BUFFER>(
&mut self,
state: &KeyState,
bluetooth: &mut Bluetooth<BUFFER>,
led: &mut Led<BUFFER>,
scb: &mut SCB,
syst: &SYST,
usb: &mut Usb,
) where
BUFFER: Unsize<[u8]>,
{
// TODO: might not even need this check after switching to wakeup only handling?
if !eq(&self.previous_state, state) {
let mut hid = HidProcessor::new();
for (key, pressed) in state.iter().enumerate() {
let changed = self.previous_state[key] != *pressed;
// Only handle currently pressed and changed keys to
// cut down on processing time.
if *pressed || changed {
let action = self.get_action(key);
if let Action::Reset = action {
unsafe {
// write unlock: 0x05fa << 16
// SYSRESETREQ: 0b100
scb.aircr.write((0x05fa << 16) | 0b100);
let current_tick = syst.cvr.read();
let wait_until_tick = current_tick - 300;
while syst.cvr.read() > wait_until_tick {}
// Should be unreachable
}
}
hid.process(&action, *pressed, changed);
led.process(&action, *pressed, changed);
bluetooth.process(&action, *pressed, changed);
self.layers.process(&action, *pressed, changed);
}
}
let bt_layer_current: bool = self.layers.current & (1 << LAYER_BT) != 0;
let bt_layer_next: bool = self.layers.next & (1 << LAYER_BT) != 0;
if bt_layer_next && !bt_layer_current {
bluetooth.update_led(led).log_error();
} else if bt_layer_current && !bt_layer_next {
led.theme_mode().log_error();
}
self.layers.finish();
bluetooth.send_report(&hid.report).log_error();
led.send_keys(state).log_error();
usb.update_report(&hid.report);
self.previous_state = *state;
}
}
pub fn bluetooth_mode_enabled(&self) -> bool {
self.layers.current & (1 << LAYER_BT) != 0
}
pub fn disable_bluetooth_mode(&mut self) {
self.layers.current &= !(1 << LAYER_BT);
}
}
trait EventProcessor {
fn process(&mut self, action: &Action, pressed: bool, changed: bool);
fn finish(&mut self) {}
}
struct Layers {
current: u8,
next: u8,
}
impl Layers {
const fn new() -> Layers {
Layers {
current: 0b1,
next: 0b1,
}
}
}
impl EventProcessor for Layers {
fn process(&mut self, action: &Action, pressed: bool, changed: bool) {
if changed {
match (*action, pressed) {
(Action::LayerMomentary(layer), true) => self.next |= 1 << layer,
(Action::LayerMomentary(layer), false) => self.next &= !(1 << layer),
(Action::LayerToggle(layer), true) => self.next ^= 1 << layer,
(Action::LayerOn(layer), true) => self.next |= 1 << layer,
(Action::LayerOff(layer), true) => self.next &= !(1 << layer),
_ => {}
}
}
}
fn finish(&mut self) {
self.current = self.next;
}
}
struct HidProcessor {
pub report: HidReport,
i: usize,
}
impl HidProcessor {
fn new() -> HidProcessor {
HidProcessor {
report: HidReport::new(),
i: 0,
}
}
}
impl EventProcessor for HidProcessor {
fn process(&mut self, action: &Action, pressed: bool, _changed: bool) {
if pressed {
match *action {
Action::Key(code) => {
if code.is_modifier() {
self.report.modifiers |= 1 << (code as u8 - KeyCode::LCtrl as u8);
} else if code.is_normal_key() && self.i < self.report.keys.len() {
self.report.keys[self.i] = code as u8;
self.i += 1;
}
}
_ => {}
}
}
}
}
impl<BUFFER> EventProcessor for Led<BUFFER>
where
BUFFER: Unsize<[u8]>,
{
fn process(&mut self, action: &Action, pressed: bool, changed: bool) {
if changed && pressed {
let result = match *action {
Action::LedOn => self.on(),
Action::LedOff => self.off(),
Action::LedToggle => self.toggle(),
Action::LedNextTheme => self.next_theme(),
Action::LedNextBrightness => self.next_brightness(),
Action::LedNextAnimationSpeed => self.next_animation_speed(),
Action::LedTheme(theme_id) => self.set_theme(theme_id),
_ => Ok(()),
};
result.log_error()
}
}
}
impl<BUFFER> EventProcessor for Bluetooth<BUFFER>
where
BUFFER: Unsize<[u8]>,
{
fn process(&mut self, action: &Action, pressed: bool, changed: bool) {
if changed && pressed {
let result = match *action {
Action::BtOn => self.on(),
Action::BtOff => self.off(),
Action::BtSaveHost(host) => self.save_host(host),
Action::BtConnectHost(host) => self.connect_host(host),
Action::BtDeleteHost(host) => self.delete_host(host),
Action::BtBroadcast => self.broadcast(),
Action::BtCompatibilityMode(on) => self.enable_compatibility_mode(on),
Action::BtToggleCompatibilityMode => self.toggle_compatibility_mode(),
Action::BtHostListQuery => self.host_list_query(),
_ => Ok(()),
};
result.log_error()
}
}
}
|
//
// sprocketnes/rom.rs
//
// Author: Patrick Walton
//
use std::io::File;
use std::vec::Vec;
pub struct Rom {
pub header: INesHeader,
pub prg: Vec<u8>, // PRG-ROM
pub chr: Vec<u8>, // CHR-ROM
}
impl Rom {
fn from_file(file: &mut File) -> Rom {
let mut buffer = [ 0, ..16 ];
file.fill(buffer).unwrap();
let header = INesHeader {
magic: [
buffer[0],
buffer[1],
buffer[2],
buffer[3],
],
prg_rom_size: buffer[4],
chr_rom_size: buffer[5],
flags_6: buffer[6],
flags_7: buffer[7],
prg_ram_size: buffer[8],
flags_9: buffer[9],
flags_10: buffer[10],
zero: [ 0, ..5 ]
};
assert!(header.magic == [
'N' as u8,
'E' as u8,
'S' as u8,
0x1a,
]);
let mut prg_rom = Vec::from_elem(header.prg_rom_size as uint * 16384, 0u8);
file.fill(prg_rom.as_mut_slice()).unwrap();
let mut chr_rom = Vec::from_elem(header.chr_rom_size as uint * 8192, 0u8);
file.fill(chr_rom.as_mut_slice()).unwrap();
Rom {
header: header,
prg: prg_rom,
chr: chr_rom,
}
}
pub fn from_path(path: &Path) -> Rom {
Rom::from_file(&mut File::open(path).unwrap())
}
}
pub struct INesHeader {
pub magic: [u8, ..4], // 'N' 'E' 'S' '\x1a'
pub prg_rom_size: u8, // number of 16K units of PRG-ROM
pub chr_rom_size: u8, // number of 8K units of CHR-ROM
pub flags_6: u8,
pub flags_7: u8,
pub prg_ram_size: u8, // number of 8K units of PRG-RAM
pub flags_9: u8,
pub flags_10: u8,
pub zero: [u8, ..5], // always zero
}
impl INesHeader {
pub fn mapper(&self) -> u8 {
(self.flags_7 & 0xf0) | (self.flags_6 >> 4)
}
pub fn ines_mapper(&self) -> u8 {
self.flags_6 >> 4
}
pub fn trainer(&self) -> bool {
(self.flags_6 & 0x04) != 0
}
pub fn to_str(&self) -> ~str {
format!("PRG-ROM size: {}\nCHR-ROM size: {}\nMapper: {}/{}\nTrainer: {}",
self.prg_rom_size as int,
self.chr_rom_size as int,
self.mapper() as int,
self.ines_mapper() as int,
if self.trainer() {
"Yes"
} else {
"No"
})
}
}
|
pub mod docker;
mod ssl_tcp_docker;
mod tcp_docker;
mod unix_docker;
pub mod util;
pub mod container;
pub mod image;
pub mod images;
pub mod containers;
pub mod network;
pub mod networks;
pub use container::Container;
pub use image::Image;
pub use images::Images;
pub use network::Network;
pub use docker::{DockerApi, new_docker}; |
use crate::nes::{Nes, NesIo};
use bitflags::bitflags;
use std::cell::Cell;
use std::fmt;
use std::ops::Generator;
use std::u8;
#[derive(Debug, Clone)]
pub struct Cpu {
pub pc: Cell<u16>,
pub a: Cell<u8>,
pub x: Cell<u8>,
pub y: Cell<u8>,
pub s: Cell<u8>,
pub p: Cell<CpuFlags>,
pub nmi: Cell<bool>,
}
impl Cpu {
pub fn new() -> Self {
Cpu {
pc: Cell::new(0),
a: Cell::new(0),
x: Cell::new(0),
y: Cell::new(0),
s: Cell::new(0xFD),
p: Cell::new(CpuFlags::from_bits_truncate(0x34)),
nmi: Cell::new(false),
}
}
fn contains_flags(&self, flags: CpuFlags) -> bool {
self.p.get().contains(flags)
}
fn set_flags(&self, flags: CpuFlags, value: bool) {
// TODO: Prevent the break (`B`) and unused (`U`) flags
// from being changed!
let mut p = self.p.get();
p.set(flags, value);
self.p.set(p);
}
fn pc_inc(&self) -> u16 {
let pc = self.pc.get();
// TODO: Should this be using `wrapping_add`?
self.pc.set(pc.wrapping_add(1));
pc
}
fn pc_fetch(nes: &Nes<impl NesIo>) -> u8 {
let pc = nes.cpu.pc.get();
nes.read_u8(pc)
}
fn pc_fetch_inc(nes: &Nes<impl NesIo>) -> u8 {
let pc = nes.cpu.pc_inc();
nes.read_u8(pc)
}
fn stack_addr(&self) -> u16 {
0x0100 | self.s.get() as u16
}
fn inc_s(&self) {
self.s.update(|s| s.wrapping_add(1));
}
fn dec_s(&self) {
self.s.update(|s| s.wrapping_sub(1));
}
pub fn run<'a>(nes: &'a Nes<impl NesIo>) -> impl Generator<Yield = CpuStep, Return = !> + 'a {
move || loop {
// TODO: Does this properly account for CPU cycles for handling NMI?
let nmi = nes.cpu.nmi.get();
if nmi {
nes.cpu.nmi.set(false);
nes.push_u16(nes.cpu.pc.get());
nes.push_u8(nes.cpu.p.get().bits);
let nmi_vector = nes.read_u16(0xFFFA);
nes.cpu.pc.set(nmi_vector);
}
let pc = nes.cpu.pc.get();
let opcode = nes.read_u8(pc);
let instruction_with_mode = opcode_to_instruction_with_mode(opcode);
let op = match instruction_with_mode {
(Instruction::Adc, OpMode::Abs) => {
yield_all! { abs_read(nes, AdcOperation) }
}
(Instruction::Adc, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, AdcOperation) }
}
(Instruction::Adc, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, AdcOperation) }
}
(Instruction::Adc, OpMode::Imm) => {
yield_all! { imm_read(nes, AdcOperation) }
}
(Instruction::Adc, OpMode::IndX) => {
yield_all! { ind_x_read(nes, AdcOperation) }
}
(Instruction::Adc, OpMode::IndY) => {
yield_all! { ind_y_read(nes, AdcOperation) }
}
(Instruction::Adc, OpMode::Zero) => {
yield_all! { zero_read(nes, AdcOperation) }
}
(Instruction::Adc, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, AdcOperation) }
}
(Instruction::And, OpMode::Abs) => {
yield_all! { abs_read(nes, AndOperation) }
}
(Instruction::And, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, AndOperation) }
}
(Instruction::And, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, AndOperation) }
}
(Instruction::And, OpMode::Imm) => {
yield_all! { imm_read(nes, AndOperation) }
}
(Instruction::And, OpMode::IndX) => {
yield_all! { ind_x_read(nes, AndOperation) }
}
(Instruction::And, OpMode::IndY) => {
yield_all! { ind_y_read(nes, AndOperation) }
}
(Instruction::And, OpMode::Zero) => {
yield_all! { zero_read(nes, AndOperation) }
}
(Instruction::And, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, AndOperation) }
}
(Instruction::Asl, OpMode::Accum) => {
yield_all! { accum_modify(nes, AslOperation) }
}
(Instruction::Asl, OpMode::Abs) => {
yield_all! { abs_modify(nes, AslOperation) }
}
(Instruction::Asl, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, AslOperation) }
}
(Instruction::Asl, OpMode::Zero) => {
yield_all! { zero_modify(nes, AslOperation) }
}
(Instruction::Asl, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, AslOperation) }
}
(Instruction::Bcc, OpMode::Branch) => {
yield_all! { branch(&nes, BccOperation) }
}
(Instruction::Bcs, OpMode::Branch) => {
yield_all! { branch(&nes, BcsOperation) }
}
(Instruction::Beq, OpMode::Branch) => {
yield_all! { branch(&nes, BeqOperation) }
}
(Instruction::Bit, OpMode::Zero) => {
yield_all! { zero_read(&nes, BitOperation) }
}
(Instruction::Bit, OpMode::Abs) => {
yield_all! { abs_read(&nes, BitOperation) }
}
(Instruction::Bmi, OpMode::Branch) => {
yield_all! { branch(&nes, BmiOperation) }
}
(Instruction::Bne, OpMode::Branch) => {
yield_all! { branch(&nes, BneOperation) }
}
(Instruction::Bpl, OpMode::Branch) => {
yield_all! { branch(&nes, BplOperation) }
}
(Instruction::Brk, OpMode::Implied) => {
yield_all! { brk(&nes) }
}
(Instruction::Bvc, OpMode::Branch) => {
yield_all! { branch(&nes, BvcOperation) }
}
(Instruction::Bvs, OpMode::Branch) => {
yield_all! { branch(&nes, BvsOperation) }
}
(Instruction::Clc, OpMode::Implied) => {
yield_all! { implied(nes, ClcOperation) }
}
(Instruction::Cld, OpMode::Implied) => {
yield_all! { implied(nes, CldOperation) }
}
(Instruction::Cli, OpMode::Implied) => {
yield_all! { implied(nes, CliOperation) }
}
(Instruction::Clv, OpMode::Implied) => {
yield_all! { implied(nes, ClvOperation) }
}
(Instruction::Cmp, OpMode::Abs) => {
yield_all! { abs_read(nes, CmpOperation) }
}
(Instruction::Cmp, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, CmpOperation) }
}
(Instruction::Cmp, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, CmpOperation) }
}
(Instruction::Cmp, OpMode::Imm) => {
yield_all! { imm_read(nes, CmpOperation) }
}
(Instruction::Cmp, OpMode::IndX) => {
yield_all! { ind_x_read(nes, CmpOperation) }
}
(Instruction::Cmp, OpMode::IndY) => {
yield_all! { ind_y_read(nes, CmpOperation) }
}
(Instruction::Cmp, OpMode::Zero) => {
yield_all! { zero_read(nes, CmpOperation) }
}
(Instruction::Cmp, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, CmpOperation) }
}
(Instruction::Cpx, OpMode::Abs) => {
yield_all! { abs_read(nes, CpxOperation) }
}
(Instruction::Cpx, OpMode::Imm) => {
yield_all! { imm_read(nes, CpxOperation) }
}
(Instruction::Cpx, OpMode::Zero) => {
yield_all! { zero_read(nes, CpxOperation) }
}
(Instruction::Cpy, OpMode::Abs) => {
yield_all! { abs_read(nes, CpyOperation) }
}
(Instruction::Cpy, OpMode::Imm) => {
yield_all! { imm_read(nes, CpyOperation) }
}
(Instruction::Cpy, OpMode::Zero) => {
yield_all! { zero_read(nes, CpyOperation) }
}
(Instruction::Dec, OpMode::Abs) => {
yield_all! { abs_modify(nes, DecOperation) }
}
(Instruction::Dec, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, DecOperation) }
}
(Instruction::Dec, OpMode::Zero) => {
yield_all! { zero_modify(nes, DecOperation) }
}
(Instruction::Dec, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, DecOperation) }
}
(Instruction::Dex, OpMode::Implied) => {
yield_all! { implied(nes, DexOperation) }
}
(Instruction::Dey, OpMode::Implied) => {
yield_all! { implied(nes, DeyOperation) }
}
(Instruction::Eor, OpMode::Abs) => {
yield_all! { abs_read(nes, EorOperation) }
}
(Instruction::Eor, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, EorOperation) }
}
(Instruction::Eor, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, EorOperation) }
}
(Instruction::Eor, OpMode::Imm) => {
yield_all! { imm_read(nes, EorOperation) }
}
(Instruction::Eor, OpMode::IndX) => {
yield_all! { ind_x_read(nes, EorOperation) }
}
(Instruction::Eor, OpMode::IndY) => {
yield_all! { ind_y_read(nes, EorOperation) }
}
(Instruction::Eor, OpMode::Zero) => {
yield_all! { zero_read(nes, EorOperation) }
}
(Instruction::Eor, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, EorOperation) }
}
(Instruction::Inc, OpMode::Abs) => {
yield_all! { abs_modify(nes, IncOperation) }
}
(Instruction::Inc, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, IncOperation) }
}
(Instruction::Inc, OpMode::Zero) => {
yield_all! { zero_modify(nes, IncOperation) }
}
(Instruction::Inc, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, IncOperation) }
}
(Instruction::Inx, OpMode::Implied) => {
yield_all! { implied(nes, InxOperation) }
}
(Instruction::Iny, OpMode::Implied) => {
yield_all! { implied(nes, InyOperation) }
}
(Instruction::Jmp, OpMode::Abs) => {
yield_all! { abs_jmp(nes) }
}
(Instruction::Jmp, OpMode::Ind) => {
yield_all! { ind_jmp(nes) }
}
(Instruction::Jsr, OpMode::Abs) => {
yield_all! { jsr(nes) }
}
(Instruction::Lda, OpMode::Abs) => {
yield_all! { abs_read(nes, LdaOperation) }
}
(Instruction::Lda, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, LdaOperation) }
}
(Instruction::Lda, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, LdaOperation) }
}
(Instruction::Lda, OpMode::Imm) => {
yield_all! { imm_read(nes, LdaOperation) }
}
(Instruction::Lda, OpMode::IndX) => {
yield_all! { ind_x_read(nes, LdaOperation) }
}
(Instruction::Lda, OpMode::IndY) => {
yield_all! { ind_y_read(nes, LdaOperation) }
}
(Instruction::Lda, OpMode::Zero) => {
yield_all! { zero_read(nes, LdaOperation) }
}
(Instruction::Lda, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, LdaOperation) }
}
(Instruction::Ldx, OpMode::Abs) => {
yield_all! { abs_read(nes, LdxOperation) }
}
(Instruction::Ldx, OpMode::Imm) => {
yield_all! { imm_read(nes, LdxOperation) }
}
(Instruction::Ldx, OpMode::Zero) => {
yield_all! { zero_read(nes, LdxOperation) }
}
(Instruction::Ldx, OpMode::ZeroY) => {
yield_all! { zero_y_read(nes, LdxOperation) }
}
(Instruction::Ldy, OpMode::Abs) => {
yield_all! { abs_read(nes, LdyOperation) }
}
(Instruction::Ldy, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, LdyOperation) }
}
(Instruction::Ldx, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, LdxOperation) }
}
(Instruction::Ldy, OpMode::Imm) => {
yield_all! { imm_read(nes, LdyOperation) }
}
(Instruction::Ldy, OpMode::Zero) => {
yield_all! { zero_read(nes, LdyOperation) }
}
(Instruction::Ldy, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, LdyOperation) }
}
(Instruction::Lsr, OpMode::Accum) => {
yield_all! { accum_modify(nes, LsrOperation) }
}
(Instruction::Lsr, OpMode::Abs) => {
yield_all! { abs_modify(nes, LsrOperation) }
}
(Instruction::Lsr, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, LsrOperation) }
}
(Instruction::Lsr, OpMode::Zero) => {
yield_all! { zero_modify(nes, LsrOperation) }
}
(Instruction::Lsr, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, LsrOperation) }
}
(Instruction::Nop, OpMode::Implied) => {
yield_all! { implied(nes, NopOperation) }
}
(Instruction::Ora, OpMode::Abs) => {
yield_all! { abs_read(nes, OraOperation) }
}
(Instruction::Ora, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, OraOperation) }
}
(Instruction::Ora, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, OraOperation) }
}
(Instruction::Ora, OpMode::Imm) => {
yield_all! { imm_read(nes, OraOperation) }
}
(Instruction::Ora, OpMode::IndX) => {
yield_all! { ind_x_read(nes, OraOperation) }
}
(Instruction::Ora, OpMode::IndY) => {
yield_all! { ind_y_read(nes, OraOperation) }
}
(Instruction::Ora, OpMode::Zero) => {
yield_all! { zero_read(nes, OraOperation) }
}
(Instruction::Ora, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, OraOperation) }
}
(Instruction::Pha, OpMode::Implied) => {
yield_all! { stack_push(nes, PhaOperation) }
}
(Instruction::Php, OpMode::Implied) => {
yield_all! { stack_push(nes, PhpOperation) }
}
(Instruction::Pla, OpMode::Implied) => {
yield_all! { stack_pull(nes, PlaOperation) }
}
(Instruction::Plp, OpMode::Implied) => {
yield_all! { stack_pull(nes, PlpOperation) }
}
(Instruction::Rol, OpMode::Accum) => {
yield_all! { accum_modify(nes, RolOperation) }
}
(Instruction::Rol, OpMode::Abs) => {
yield_all! { abs_modify(nes, RolOperation) }
}
(Instruction::Rol, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, RolOperation) }
}
(Instruction::Rol, OpMode::Zero) => {
yield_all! { zero_modify(nes, RolOperation) }
}
(Instruction::Rol, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, RolOperation) }
}
(Instruction::Ror, OpMode::Accum) => {
yield_all! { accum_modify(nes, RorOperation) }
}
(Instruction::Ror, OpMode::Abs) => {
yield_all! { abs_modify(nes, RorOperation) }
}
(Instruction::Ror, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, RorOperation) }
}
(Instruction::Ror, OpMode::Zero) => {
yield_all! { zero_modify(nes, RorOperation) }
}
(Instruction::Ror, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, RorOperation) }
}
(Instruction::Rti, OpMode::Implied) => {
yield_all! { rti(nes) }
}
(Instruction::Rts, OpMode::Implied) => {
yield_all! { rts(nes) }
}
(Instruction::Sbc, OpMode::Abs) => {
yield_all! { abs_read(nes, SbcOperation) }
}
(Instruction::Sbc, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, SbcOperation) }
}
(Instruction::Sbc, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, SbcOperation) }
}
(Instruction::Sbc, OpMode::Imm) => {
yield_all! { imm_read(nes, SbcOperation) }
}
(Instruction::Sbc, OpMode::IndX) => {
yield_all! { ind_x_read(nes, SbcOperation) }
}
(Instruction::Sbc, OpMode::IndY) => {
yield_all! { ind_y_read(nes, SbcOperation) }
}
(Instruction::Sbc, OpMode::Zero) => {
yield_all! { zero_read(nes, SbcOperation) }
}
(Instruction::Sbc, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, SbcOperation) }
}
(Instruction::Sec, OpMode::Implied) => {
yield_all! { implied(nes, SecOperation) }
}
(Instruction::Sed, OpMode::Implied) => {
yield_all! { implied(nes, SedOperation) }
}
(Instruction::Sei, OpMode::Implied) => {
yield_all! { implied(nes, SeiOperation) }
}
(Instruction::Sta, OpMode::Abs) => {
yield_all! { abs_write(nes, StaOperation) }
}
(Instruction::Sta, OpMode::AbsX) => {
yield_all! { abs_x_write(nes, StaOperation) }
}
(Instruction::Sta, OpMode::AbsY) => {
yield_all! { abs_y_write(nes, StaOperation) }
}
(Instruction::Sta, OpMode::IndX) => {
yield_all! { ind_x_write(nes, StaOperation) }
}
(Instruction::Sta, OpMode::IndY) => {
yield_all! { ind_y_write(nes, StaOperation) }
}
(Instruction::Sta, OpMode::Zero) => {
yield_all! { zero_write(nes, StaOperation) }
}
(Instruction::Sta, OpMode::ZeroX) => {
yield_all! { zero_x_write(nes, StaOperation) }
}
(Instruction::Stx, OpMode::Abs) => {
yield_all! { abs_write(nes, StxOperation) }
}
(Instruction::Stx, OpMode::Zero) => {
yield_all! { zero_write(nes, StxOperation) }
}
(Instruction::Stx, OpMode::ZeroY) => {
yield_all! { zero_y_write(nes, StxOperation) }
}
(Instruction::Sty, OpMode::Abs) => {
yield_all! { abs_write(nes, StyOperation) }
}
(Instruction::Sty, OpMode::Zero) => {
yield_all! { zero_write(nes, StyOperation) }
}
(Instruction::Sty, OpMode::ZeroX) => {
yield_all! { zero_x_write(nes, StyOperation) }
}
(Instruction::Tax, OpMode::Implied) => {
yield_all! { implied(nes, TaxOperation) }
}
(Instruction::Tay, OpMode::Implied) => {
yield_all! { implied(nes, TayOperation) }
}
(Instruction::Tsx, OpMode::Implied) => {
yield_all! { implied(nes, TsxOperation) }
}
(Instruction::Txa, OpMode::Implied) => {
yield_all! { implied(nes, TxaOperation) }
}
(Instruction::Txs, OpMode::Implied) => {
yield_all! { implied(nes, TxsOperation) }
}
(Instruction::Tya, OpMode::Implied) => {
yield_all! { implied(nes, TyaOperation) }
}
(Instruction::UnofficialAnc, OpMode::Imm) => {
yield_all! { imm_read(nes, UnofficialAncOperation) }
}
(Instruction::UnofficialAlr, OpMode::Imm) => {
yield_all! { imm_read(nes, UnofficialAlrOperation) }
}
(Instruction::UnofficialArr, OpMode::Imm) => {
yield_all! { imm_read(nes, UnofficialArrOperation) }
}
(Instruction::UnofficialAxs, OpMode::Imm) => {
yield_all! { imm_read(nes, UnofficialAxsOperation) }
}
(Instruction::UnofficialDcp, OpMode::Abs) => {
yield_all! { abs_modify(nes, UnofficialDcpOperation) }
}
(Instruction::UnofficialDcp, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, UnofficialDcpOperation) }
}
(Instruction::UnofficialDcp, OpMode::AbsY) => {
yield_all! { abs_y_modify(nes, UnofficialDcpOperation) }
}
(Instruction::UnofficialDcp, OpMode::IndX) => {
yield_all! { ind_x_modify(nes, UnofficialDcpOperation) }
}
(Instruction::UnofficialDcp, OpMode::IndY) => {
yield_all! { ind_y_modify(nes, UnofficialDcpOperation) }
}
(Instruction::UnofficialDcp, OpMode::Zero) => {
yield_all! { zero_modify(nes, UnofficialDcpOperation) }
}
(Instruction::UnofficialDcp, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, UnofficialDcpOperation) }
}
(Instruction::UnofficialIsc, OpMode::Abs) => {
yield_all! { abs_modify(nes, UnofficialIscOperation) }
}
(Instruction::UnofficialIsc, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, UnofficialIscOperation) }
}
(Instruction::UnofficialIsc, OpMode::AbsY) => {
yield_all! { abs_y_modify(nes, UnofficialIscOperation) }
}
(Instruction::UnofficialIsc, OpMode::IndX) => {
yield_all! { ind_x_modify(nes, UnofficialIscOperation) }
}
(Instruction::UnofficialIsc, OpMode::IndY) => {
yield_all! { ind_y_modify(nes, UnofficialIscOperation) }
}
(Instruction::UnofficialIsc, OpMode::Zero) => {
yield_all! { zero_modify(nes, UnofficialIscOperation) }
}
(Instruction::UnofficialIsc, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, UnofficialIscOperation) }
}
(Instruction::UnofficialLax, OpMode::Abs) => {
yield_all! { abs_read(nes, UnofficialLaxOperation) }
}
(Instruction::UnofficialLax, OpMode::AbsY) => {
yield_all! { abs_y_read(nes, UnofficialLaxOperation) }
}
(Instruction::UnofficialLax, OpMode::Imm) => {
yield_all! { imm_read(nes, UnofficialLaxOperation) }
}
(Instruction::UnofficialLax, OpMode::IndX) => {
yield_all! { ind_x_read(nes, UnofficialLaxOperation) }
}
(Instruction::UnofficialLax, OpMode::IndY) => {
yield_all! { ind_y_read(nes, UnofficialLaxOperation) }
}
(Instruction::UnofficialLax, OpMode::Zero) => {
yield_all! { zero_read(nes, UnofficialLaxOperation) }
}
(Instruction::UnofficialLax, OpMode::ZeroY) => {
yield_all! { zero_y_read(nes, UnofficialLaxOperation) }
}
(Instruction::UnofficialNop, OpMode::Abs) => {
yield_all! { abs_read(nes, UnofficialNopOperation) }
}
(Instruction::UnofficialNop, OpMode::AbsX) => {
yield_all! { abs_x_read(nes, UnofficialNopOperation) }
}
(Instruction::UnofficialNop, OpMode::Imm) => {
yield_all! { imm_read(nes, UnofficialNopOperation) }
}
(Instruction::UnofficialNop, OpMode::Implied) => {
yield_all! { implied(nes, UnofficialNopOperation) }
}
(Instruction::UnofficialNop, OpMode::Zero) => {
yield_all! { zero_read(nes, UnofficialNopOperation) }
}
(Instruction::UnofficialNop, OpMode::ZeroX) => {
yield_all! { zero_x_read(nes, UnofficialNopOperation) }
}
(Instruction::UnofficialRla, OpMode::Abs) => {
yield_all! { abs_modify(nes, UnofficialRlaOperation) }
}
(Instruction::UnofficialRla, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, UnofficialRlaOperation) }
}
(Instruction::UnofficialRla, OpMode::AbsY) => {
yield_all! { abs_y_modify(nes, UnofficialRlaOperation) }
}
(Instruction::UnofficialRla, OpMode::IndX) => {
yield_all! { ind_x_modify(nes, UnofficialRlaOperation) }
}
(Instruction::UnofficialRla, OpMode::IndY) => {
yield_all! { ind_y_modify(nes, UnofficialRlaOperation) }
}
(Instruction::UnofficialRla, OpMode::Zero) => {
yield_all! { zero_modify(nes, UnofficialRlaOperation) }
}
(Instruction::UnofficialRla, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, UnofficialRlaOperation) }
}
(Instruction::UnofficialRra, OpMode::Abs) => {
yield_all! { abs_modify(nes, UnofficialRraOperation) }
}
(Instruction::UnofficialRra, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, UnofficialRraOperation) }
}
(Instruction::UnofficialRra, OpMode::IndX) => {
yield_all! { ind_x_modify(nes, UnofficialRraOperation) }
}
(Instruction::UnofficialRra, OpMode::IndY) => {
yield_all! { ind_y_modify(nes, UnofficialRraOperation) }
}
(Instruction::UnofficialRra, OpMode::AbsY) => {
yield_all! { abs_y_modify(nes, UnofficialRraOperation) }
}
(Instruction::UnofficialRra, OpMode::Zero) => {
yield_all! { zero_modify(nes, UnofficialRraOperation) }
}
(Instruction::UnofficialRra, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, UnofficialRraOperation) }
}
(Instruction::UnofficialSax, OpMode::Abs) => {
yield_all! { abs_write(nes, UnofficialSaxOperation) }
}
(Instruction::UnofficialSax, OpMode::IndX) => {
yield_all! { ind_x_write(nes, UnofficialSaxOperation) }
}
(Instruction::UnofficialSax, OpMode::Zero) => {
yield_all! { zero_write(nes, UnofficialSaxOperation) }
}
(Instruction::UnofficialSax, OpMode::ZeroY) => {
yield_all! { zero_y_write(nes, UnofficialSaxOperation) }
}
(Instruction::UnofficialSbc, OpMode::Imm) => {
yield_all! { imm_read(nes, UnofficialSbcOperation) }
}
(Instruction::UnofficialShx, OpMode::AbsY) => {
yield_all! { abs_y_modify(nes, UnofficialShxOperation) }
}
(Instruction::UnofficialShy, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, UnofficialShyOperation) }
}
(Instruction::UnofficialSlo, OpMode::Abs) => {
yield_all! { abs_modify(nes, UnofficialSloOperation) }
}
(Instruction::UnofficialSlo, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, UnofficialSloOperation) }
}
(Instruction::UnofficialSlo, OpMode::AbsY) => {
yield_all! { abs_y_modify(nes, UnofficialSloOperation) }
}
(Instruction::UnofficialSlo, OpMode::IndX) => {
yield_all! { ind_x_modify(nes, UnofficialSloOperation) }
}
(Instruction::UnofficialSlo, OpMode::IndY) => {
yield_all! { ind_y_modify(nes, UnofficialSloOperation) }
}
(Instruction::UnofficialSlo, OpMode::Zero) => {
yield_all! { zero_modify(nes, UnofficialSloOperation) }
}
(Instruction::UnofficialSlo, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, UnofficialSloOperation) }
}
(Instruction::UnofficialSre, OpMode::Abs) => {
yield_all! { abs_modify(nes, UnofficialSreOperation) }
}
(Instruction::UnofficialSre, OpMode::AbsX) => {
yield_all! { abs_x_modify(nes, UnofficialSreOperation) }
}
(Instruction::UnofficialSre, OpMode::AbsY) => {
yield_all! { abs_y_modify(nes, UnofficialSreOperation) }
}
(Instruction::UnofficialSre, OpMode::IndX) => {
yield_all! { ind_x_modify(nes, UnofficialSreOperation) }
}
(Instruction::UnofficialSre, OpMode::IndY) => {
yield_all! { ind_y_modify(nes, UnofficialSreOperation) }
}
(Instruction::UnofficialSre, OpMode::Zero) => {
yield_all! { zero_modify(nes, UnofficialSreOperation) }
}
(Instruction::UnofficialSre, OpMode::ZeroX) => {
yield_all! { zero_x_modify(nes, UnofficialSreOperation) }
}
insn_with_mode => {
unimplemented!("Unhandled instruction/mode: {:?}", insn_with_mode);
}
};
debug_assert_eq!(instruction_with_mode, op.instruction_with_mode());
yield CpuStep::Op(CpuStepOp { pc, op });
}
}
}
bitflags! {
pub struct CpuFlags: u8 {
/// Carry flag: set when an arithmetic operation resulted in a carry.
const C = 1 << 0;
/// Zero flag: set when an operation results in 0.
const Z = 1 << 1;
/// Interrupt disable flag: set to disable CPU interrupts.
const I = 1 << 2;
/// Decimal mode flag: exists for compatibility with the 6502 (which
/// used it for decimal arithmetic), but ignored by the
/// Rioch 2A03/2A07 processors used in the NES/Famicom.
const D = 1 << 3;
/// Break flag: set when BRK or PHP are called, cleared when
/// the /IRQ or /NMI interrupts are called. When PLP or RTI are called,
/// this flag is unaffected.
///
/// In other words, this flag isn't exactly "set" or "cleared"-- when an
/// interrupt happens, the status register is pushed to the stack. If
/// the interrupt was an /IRQ or /NMI interrupt, the value pushed to the
/// stack will have this bit cleared; if the interrupt was caused by
/// BRK (or if the PHP instruction is used), then the value pushed to
/// the stack will have this bit set.
const B = 1 << 4;
/// Unused: this flag is always set to 1
const U = 1 << 5;
/// Overflow flag: set when an operation resulted in a signed overflow.
const V = 1 << 6;
/// Negative flag: set when an operation resulted in a negative value,
/// i.e. when the most significant bit (bit 7) is set.
const N = 1 << 7;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Instruction {
Adc,
And,
Asl,
Bcc,
Bcs,
Beq,
Bit,
Bmi,
Bne,
Bpl,
Brk,
Bvc,
Bvs,
Clc,
Cld,
Cli,
Clv,
Cmp,
Cpx,
Cpy,
Dec,
Dex,
Dey,
Eor,
Inc,
Inx,
Iny,
Jmp,
Jsr,
Lda,
Ldx,
Ldy,
Lsr,
Nop,
Ora,
Pha,
Php,
Pla,
Plp,
Rol,
Ror,
Rti,
Rts,
Sbc,
Sec,
Sed,
Sei,
Sta,
Stx,
Sty,
Tax,
Tay,
Tsx,
Txa,
Txs,
Tya,
UnofficialAnc,
UnofficialAlr,
UnofficialArr,
UnofficialAxs,
UnofficialDcp,
UnofficialIsc,
UnofficialLax,
UnofficialNop,
UnofficialRla,
UnofficialRra,
UnofficialSax,
UnofficialSbc,
UnofficialShx,
UnofficialShy,
UnofficialSlo,
UnofficialSre,
}
impl fmt::Display for Instruction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mnemonic = match self {
Instruction::Adc => "ADC",
Instruction::And => "AND",
Instruction::Asl => "ASL",
Instruction::Bcc => "BCC",
Instruction::Bcs => "BCS",
Instruction::Beq => "BEQ",
Instruction::Bit => "BIT",
Instruction::Bmi => "BMI",
Instruction::Bne => "BNE",
Instruction::Bpl => "BPL",
Instruction::Brk => "BRK",
Instruction::Bvc => "BVC",
Instruction::Bvs => "BVS",
Instruction::Clc => "CLC",
Instruction::Cld => "CLD",
Instruction::Cli => "CLI",
Instruction::Clv => "CLV",
Instruction::Cmp => "CMP",
Instruction::Cpx => "CPX",
Instruction::Cpy => "CPY",
Instruction::Dec => "DEC",
Instruction::Dex => "DEX",
Instruction::Dey => "DEY",
Instruction::Eor => "EOR",
Instruction::Inc => "INC",
Instruction::Inx => "INX",
Instruction::Iny => "INY",
Instruction::Jmp => "JMP",
Instruction::Jsr => "JSR",
Instruction::Lda => "LDA",
Instruction::Ldx => "LDX",
Instruction::Ldy => "LDY",
Instruction::Lsr => "LSR",
Instruction::Nop | Instruction::UnofficialNop => "NOP",
Instruction::Ora => "ORA",
Instruction::Pha => "PHA",
Instruction::Php => "PHP",
Instruction::Pla => "PLA",
Instruction::Plp => "PLP",
Instruction::Rol => "ROL",
Instruction::Ror => "ROR",
Instruction::Rti => "RTI",
Instruction::Rts => "RTS",
Instruction::Sbc | Instruction::UnofficialSbc => "SBC",
Instruction::Sec => "SEC",
Instruction::Sed => "SED",
Instruction::Sei => "SEI",
Instruction::Sta => "STA",
Instruction::Stx => "STX",
Instruction::Sty => "STY",
Instruction::Tax => "TAX",
Instruction::Tay => "TAY",
Instruction::Tsx => "TSX",
Instruction::Txa => "TXA",
Instruction::Txs => "TXS",
Instruction::Tya => "TYA",
Instruction::UnofficialAnc => "ANC",
Instruction::UnofficialAlr => "ALR",
Instruction::UnofficialArr => "ARR",
Instruction::UnofficialAxs => "AXS",
Instruction::UnofficialDcp => "DCP",
Instruction::UnofficialIsc => "ISC",
Instruction::UnofficialLax => "LAX",
Instruction::UnofficialRla => "RLA",
Instruction::UnofficialRra => "RRA",
Instruction::UnofficialSax => "SAX",
Instruction::UnofficialShx => "SHX",
Instruction::UnofficialShy => "SHY",
Instruction::UnofficialSlo => "SLO",
Instruction::UnofficialSre => "SRE",
};
write!(f, "{}", mnemonic)?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OpMode {
Implied,
Accum,
Abs,
AbsX,
AbsY,
Branch,
Imm,
Ind,
IndX,
IndY,
Zero,
ZeroX,
ZeroY,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OpArg {
Implied,
Accum,
Abs { addr: u16 },
AbsX { addr_base: u16 },
AbsY { addr_base: u16 },
Branch { addr_offset: i8 },
Ind { target_addr: u16 },
Imm { value: u8 },
IndX { target_addr_base: u8 },
IndY { target_addr_base: u8 },
Zero { zero_page: u8 },
ZeroX { zero_page_base: u8 },
ZeroY { zero_page_base: u8 },
}
impl From<OpArg> for OpMode {
fn from(arg: OpArg) -> Self {
match arg {
OpArg::Implied => OpMode::Implied,
OpArg::Accum => OpMode::Accum,
OpArg::Abs { .. } => OpMode::Abs,
OpArg::AbsX { .. } => OpMode::AbsX,
OpArg::AbsY { .. } => OpMode::AbsY,
OpArg::Branch { .. } => OpMode::Branch,
OpArg::Imm { .. } => OpMode::Imm,
OpArg::Ind { .. } => OpMode::Ind,
OpArg::IndX { .. } => OpMode::IndX,
OpArg::IndY { .. } => OpMode::IndY,
OpArg::Zero { .. } => OpMode::Zero,
OpArg::ZeroX { .. } => OpMode::ZeroX,
OpArg::ZeroY { .. } => OpMode::ZeroY,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Op {
instruction: Instruction,
arg: OpArg,
}
impl Op {
fn instruction_with_mode(&self) -> (Instruction, OpMode) {
(self.instruction, self.arg.into())
}
}
fn opcode_to_instruction_with_mode(opcode: u8) -> (Instruction, OpMode) {
match opcode {
0x00 => (Instruction::Brk, OpMode::Implied),
0x01 => (Instruction::Ora, OpMode::IndX),
0x03 => (Instruction::UnofficialSlo, OpMode::IndX),
0x04 => (Instruction::UnofficialNop, OpMode::Zero),
0x05 => (Instruction::Ora, OpMode::Zero),
0x06 => (Instruction::Asl, OpMode::Zero),
0x07 => (Instruction::UnofficialSlo, OpMode::Zero),
0x08 => (Instruction::Php, OpMode::Implied),
0x09 => (Instruction::Ora, OpMode::Imm),
0x0A => (Instruction::Asl, OpMode::Accum),
0x0B => (Instruction::UnofficialAnc, OpMode::Imm),
0x0C => (Instruction::UnofficialNop, OpMode::Abs),
0x0D => (Instruction::Ora, OpMode::Abs),
0x0E => (Instruction::Asl, OpMode::Abs),
0x0F => (Instruction::UnofficialSlo, OpMode::Abs),
0x10 => (Instruction::Bpl, OpMode::Branch),
0x11 => (Instruction::Ora, OpMode::IndY),
0x13 => (Instruction::UnofficialSlo, OpMode::IndY),
0x14 => (Instruction::UnofficialNop, OpMode::ZeroX),
0x15 => (Instruction::Ora, OpMode::ZeroX),
0x16 => (Instruction::Asl, OpMode::ZeroX),
0x17 => (Instruction::UnofficialSlo, OpMode::ZeroX),
0x18 => (Instruction::Clc, OpMode::Implied),
0x19 => (Instruction::Ora, OpMode::AbsY),
0x1A => (Instruction::UnofficialNop, OpMode::Implied),
0x1B => (Instruction::UnofficialSlo, OpMode::AbsY),
0x1C => (Instruction::UnofficialNop, OpMode::AbsX),
0x1D => (Instruction::Ora, OpMode::AbsX),
0x1E => (Instruction::Asl, OpMode::AbsX),
0x1F => (Instruction::UnofficialSlo, OpMode::AbsX),
0x20 => (Instruction::Jsr, OpMode::Abs),
0x21 => (Instruction::And, OpMode::IndX),
0x23 => (Instruction::UnofficialRla, OpMode::IndX),
0x24 => (Instruction::Bit, OpMode::Zero),
0x25 => (Instruction::And, OpMode::Zero),
0x26 => (Instruction::Rol, OpMode::Zero),
0x27 => (Instruction::UnofficialRla, OpMode::Zero),
0x28 => (Instruction::Plp, OpMode::Implied),
0x29 => (Instruction::And, OpMode::Imm),
0x2A => (Instruction::Rol, OpMode::Accum),
0x2B => (Instruction::UnofficialAnc, OpMode::Imm),
0x2C => (Instruction::Bit, OpMode::Abs),
0x2D => (Instruction::And, OpMode::Abs),
0x2E => (Instruction::Rol, OpMode::Abs),
0x2F => (Instruction::UnofficialRla, OpMode::Abs),
0x30 => (Instruction::Bmi, OpMode::Branch),
0x31 => (Instruction::And, OpMode::IndY),
0x33 => (Instruction::UnofficialRla, OpMode::IndY),
0x34 => (Instruction::UnofficialNop, OpMode::ZeroX),
0x35 => (Instruction::And, OpMode::ZeroX),
0x36 => (Instruction::Rol, OpMode::ZeroX),
0x37 => (Instruction::UnofficialRla, OpMode::ZeroX),
0x38 => (Instruction::Sec, OpMode::Implied),
0x39 => (Instruction::And, OpMode::AbsY),
0x3A => (Instruction::UnofficialNop, OpMode::Implied),
0x3B => (Instruction::UnofficialRla, OpMode::AbsY),
0x3C => (Instruction::UnofficialNop, OpMode::AbsX),
0x3D => (Instruction::And, OpMode::AbsX),
0x3E => (Instruction::Rol, OpMode::AbsX),
0x3F => (Instruction::UnofficialRla, OpMode::AbsX),
0x40 => (Instruction::Rti, OpMode::Implied),
0x41 => (Instruction::Eor, OpMode::IndX),
0x43 => (Instruction::UnofficialSre, OpMode::IndX),
0x44 => (Instruction::UnofficialNop, OpMode::Zero),
0x45 => (Instruction::Eor, OpMode::Zero),
0x46 => (Instruction::Lsr, OpMode::Zero),
0x47 => (Instruction::UnofficialSre, OpMode::Zero),
0x48 => (Instruction::Pha, OpMode::Implied),
0x49 => (Instruction::Eor, OpMode::Imm),
0x4A => (Instruction::Lsr, OpMode::Accum),
0x4B => (Instruction::UnofficialAlr, OpMode::Imm),
0x4C => (Instruction::Jmp, OpMode::Abs),
0x4D => (Instruction::Eor, OpMode::Abs),
0x4E => (Instruction::Lsr, OpMode::Abs),
0x4F => (Instruction::UnofficialSre, OpMode::Abs),
0x50 => (Instruction::Bvc, OpMode::Branch),
0x51 => (Instruction::Eor, OpMode::IndY),
0x53 => (Instruction::UnofficialSre, OpMode::IndY),
0x54 => (Instruction::UnofficialNop, OpMode::ZeroX),
0x55 => (Instruction::Eor, OpMode::ZeroX),
0x56 => (Instruction::Lsr, OpMode::ZeroX),
0x57 => (Instruction::UnofficialSre, OpMode::ZeroX),
0x58 => (Instruction::Cli, OpMode::Implied),
0x59 => (Instruction::Eor, OpMode::AbsY),
0x5A => (Instruction::UnofficialNop, OpMode::Implied),
0x5B => (Instruction::UnofficialSre, OpMode::AbsY),
0x5C => (Instruction::UnofficialNop, OpMode::AbsX),
0x5D => (Instruction::Eor, OpMode::AbsX),
0x5E => (Instruction::Lsr, OpMode::AbsX),
0x5F => (Instruction::UnofficialSre, OpMode::AbsX),
0x60 => (Instruction::Rts, OpMode::Implied),
0x61 => (Instruction::Adc, OpMode::IndX),
0x64 => (Instruction::UnofficialNop, OpMode::Zero),
0x63 => (Instruction::UnofficialRra, OpMode::IndX),
0x65 => (Instruction::Adc, OpMode::Zero),
0x66 => (Instruction::Ror, OpMode::Zero),
0x67 => (Instruction::UnofficialRra, OpMode::Zero),
0x68 => (Instruction::Pla, OpMode::Implied),
0x69 => (Instruction::Adc, OpMode::Imm),
0x6A => (Instruction::Ror, OpMode::Accum),
0x6B => (Instruction::UnofficialArr, OpMode::Imm),
0x6C => (Instruction::Jmp, OpMode::Ind),
0x6D => (Instruction::Adc, OpMode::Abs),
0x6E => (Instruction::Ror, OpMode::Abs),
0x6F => (Instruction::UnofficialRra, OpMode::Abs),
0x70 => (Instruction::Bvs, OpMode::Branch),
0x71 => (Instruction::Adc, OpMode::IndY),
0x73 => (Instruction::UnofficialRra, OpMode::IndY),
0x74 => (Instruction::UnofficialNop, OpMode::ZeroX),
0x75 => (Instruction::Adc, OpMode::ZeroX),
0x76 => (Instruction::Ror, OpMode::ZeroX),
0x77 => (Instruction::UnofficialRra, OpMode::ZeroX),
0x78 => (Instruction::Sei, OpMode::Implied),
0x79 => (Instruction::Adc, OpMode::AbsY),
0x7A => (Instruction::UnofficialNop, OpMode::Implied),
0x7B => (Instruction::UnofficialRra, OpMode::AbsY),
0x7C => (Instruction::UnofficialNop, OpMode::AbsX),
0x7D => (Instruction::Adc, OpMode::AbsX),
0x7E => (Instruction::Ror, OpMode::AbsX),
0x7F => (Instruction::UnofficialRra, OpMode::AbsX),
0x80 => (Instruction::UnofficialNop, OpMode::Imm),
0x81 => (Instruction::Sta, OpMode::IndX),
0x82 => (Instruction::UnofficialNop, OpMode::Imm),
0x83 => (Instruction::UnofficialSax, OpMode::IndX),
0x84 => (Instruction::Sty, OpMode::Zero),
0x85 => (Instruction::Sta, OpMode::Zero),
0x86 => (Instruction::Stx, OpMode::Zero),
0x87 => (Instruction::UnofficialSax, OpMode::Zero),
0x88 => (Instruction::Dey, OpMode::Implied),
0x89 => (Instruction::UnofficialNop, OpMode::Imm),
0x8A => (Instruction::Txa, OpMode::Implied),
0x8C => (Instruction::Sty, OpMode::Abs),
0x8D => (Instruction::Sta, OpMode::Abs),
0x8E => (Instruction::Stx, OpMode::Abs),
0x8F => (Instruction::UnofficialSax, OpMode::Abs),
0x90 => (Instruction::Bcc, OpMode::Branch),
0x91 => (Instruction::Sta, OpMode::IndY),
0x94 => (Instruction::Sty, OpMode::ZeroX),
0x95 => (Instruction::Sta, OpMode::ZeroX),
0x96 => (Instruction::Stx, OpMode::ZeroY),
0x97 => (Instruction::UnofficialSax, OpMode::ZeroY),
0x98 => (Instruction::Tya, OpMode::Implied),
0x99 => (Instruction::Sta, OpMode::AbsY),
0x9A => (Instruction::Txs, OpMode::Implied),
0x9C => (Instruction::UnofficialShy, OpMode::AbsX),
0x9D => (Instruction::Sta, OpMode::AbsX),
0x9E => (Instruction::UnofficialShx, OpMode::AbsY),
0xA0 => (Instruction::Ldy, OpMode::Imm),
0xA1 => (Instruction::Lda, OpMode::IndX),
0xA2 => (Instruction::Ldx, OpMode::Imm),
0xA3 => (Instruction::UnofficialLax, OpMode::IndX),
0xA4 => (Instruction::Ldy, OpMode::Zero),
0xA5 => (Instruction::Lda, OpMode::Zero),
0xA6 => (Instruction::Ldx, OpMode::Zero),
0xA7 => (Instruction::UnofficialLax, OpMode::Zero),
0xA8 => (Instruction::Tay, OpMode::Implied),
0xA9 => (Instruction::Lda, OpMode::Imm),
0xAA => (Instruction::Tax, OpMode::Implied),
0xAB => (Instruction::UnofficialLax, OpMode::Imm),
0xAC => (Instruction::Ldy, OpMode::Abs),
0xAD => (Instruction::Lda, OpMode::Abs),
0xAE => (Instruction::Ldx, OpMode::Abs),
0xAF => (Instruction::UnofficialLax, OpMode::Abs),
0xB0 => (Instruction::Bcs, OpMode::Branch),
0xB1 => (Instruction::Lda, OpMode::IndY),
0xB3 => (Instruction::UnofficialLax, OpMode::IndY),
0xB4 => (Instruction::Ldy, OpMode::ZeroX),
0xB5 => (Instruction::Lda, OpMode::ZeroX),
0xB6 => (Instruction::Ldx, OpMode::ZeroY),
0xB7 => (Instruction::UnofficialLax, OpMode::ZeroY),
0xB8 => (Instruction::Clv, OpMode::Implied),
0xB9 => (Instruction::Lda, OpMode::AbsY),
0xBA => (Instruction::Tsx, OpMode::Implied),
0xBC => (Instruction::Ldy, OpMode::AbsX),
0xBD => (Instruction::Lda, OpMode::AbsX),
0xBE => (Instruction::Ldx, OpMode::AbsY),
0xBF => (Instruction::UnofficialLax, OpMode::AbsY),
0xC0 => (Instruction::Cpy, OpMode::Imm),
0xC1 => (Instruction::Cmp, OpMode::IndX),
0xC2 => (Instruction::UnofficialNop, OpMode::Imm),
0xC3 => (Instruction::UnofficialDcp, OpMode::IndX),
0xC4 => (Instruction::Cpy, OpMode::Zero),
0xC5 => (Instruction::Cmp, OpMode::Zero),
0xC6 => (Instruction::Dec, OpMode::Zero),
0xC7 => (Instruction::UnofficialDcp, OpMode::Zero),
0xC8 => (Instruction::Iny, OpMode::Implied),
0xC9 => (Instruction::Cmp, OpMode::Imm),
0xCA => (Instruction::Dex, OpMode::Implied),
0xCB => (Instruction::UnofficialAxs, OpMode::Imm),
0xCC => (Instruction::Cpy, OpMode::Abs),
0xCD => (Instruction::Cmp, OpMode::Abs),
0xCE => (Instruction::Dec, OpMode::Abs),
0xCF => (Instruction::UnofficialDcp, OpMode::Abs),
0xD0 => (Instruction::Bne, OpMode::Branch),
0xD1 => (Instruction::Cmp, OpMode::IndY),
0xD3 => (Instruction::UnofficialDcp, OpMode::IndY),
0xD4 => (Instruction::UnofficialNop, OpMode::ZeroX),
0xD5 => (Instruction::Cmp, OpMode::ZeroX),
0xD6 => (Instruction::Dec, OpMode::ZeroX),
0xD7 => (Instruction::UnofficialDcp, OpMode::ZeroX),
0xD8 => (Instruction::Cld, OpMode::Implied),
0xD9 => (Instruction::Cmp, OpMode::AbsY),
0xDA => (Instruction::UnofficialNop, OpMode::Implied),
0xDB => (Instruction::UnofficialDcp, OpMode::AbsY),
0xDC => (Instruction::UnofficialNop, OpMode::AbsX),
0xDD => (Instruction::Cmp, OpMode::AbsX),
0xDE => (Instruction::Dec, OpMode::AbsX),
0xDF => (Instruction::UnofficialDcp, OpMode::AbsX),
0xE0 => (Instruction::Cpx, OpMode::Imm),
0xE1 => (Instruction::Sbc, OpMode::IndX),
0xE2 => (Instruction::UnofficialNop, OpMode::Imm),
0xE3 => (Instruction::UnofficialIsc, OpMode::IndX),
0xE4 => (Instruction::Cpx, OpMode::Zero),
0xE5 => (Instruction::Sbc, OpMode::Zero),
0xE6 => (Instruction::Inc, OpMode::Zero),
0xE7 => (Instruction::UnofficialIsc, OpMode::Zero),
0xE8 => (Instruction::Inx, OpMode::Implied),
0xE9 => (Instruction::Sbc, OpMode::Imm),
0xEA => (Instruction::Nop, OpMode::Implied),
0xEB => (Instruction::UnofficialSbc, OpMode::Imm),
0xEC => (Instruction::Cpx, OpMode::Abs),
0xED => (Instruction::Sbc, OpMode::Abs),
0xEE => (Instruction::Inc, OpMode::Abs),
0xEF => (Instruction::UnofficialIsc, OpMode::Abs),
0xF0 => (Instruction::Beq, OpMode::Branch),
0xF1 => (Instruction::Sbc, OpMode::IndY),
0xF3 => (Instruction::UnofficialIsc, OpMode::IndY),
0xF4 => (Instruction::UnofficialNop, OpMode::ZeroX),
0xF5 => (Instruction::Sbc, OpMode::ZeroX),
0xF6 => (Instruction::Inc, OpMode::ZeroX),
0xF7 => (Instruction::UnofficialIsc, OpMode::ZeroX),
0xF8 => (Instruction::Sed, OpMode::Implied),
0xF9 => (Instruction::Sbc, OpMode::AbsY),
0xFA => (Instruction::UnofficialNop, OpMode::Implied),
0xFB => (Instruction::UnofficialIsc, OpMode::AbsY),
0xFC => (Instruction::UnofficialNop, OpMode::AbsX),
0xFD => (Instruction::Sbc, OpMode::AbsX),
0xFE => (Instruction::Inc, OpMode::AbsX),
0xFF => (Instruction::UnofficialIsc, OpMode::AbsX),
_ => {
unimplemented!("Unhandled opcode: 0x{:X}", opcode);
}
}
}
impl fmt::Display for Op {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.arg {
OpArg::Implied => {
write!(f, "{}", self.instruction)?;
}
OpArg::Accum => {
write!(f, "{} A", self.instruction)?;
}
OpArg::Abs { addr } => {
write!(f, "{} ${:04X}", self.instruction, addr)?;
}
OpArg::AbsX { addr_base } => {
write!(f, "{} ${:04X},X", self.instruction, addr_base)?;
}
OpArg::AbsY { addr_base } => {
write!(f, "{} ${:04X},Y", self.instruction, addr_base)?;
}
OpArg::Zero { zero_page } => {
write!(f, "{} ${:02X}", self.instruction, zero_page as u16)?;
}
OpArg::ZeroX { zero_page_base } => {
write!(f, "{} ${:02X},X", self.instruction, zero_page_base)?;
}
OpArg::ZeroY { zero_page_base } => {
write!(f, "{} ${:02X},Y", self.instruction, zero_page_base)?;
}
OpArg::Ind { target_addr } => {
write!(f, "{} (${:04X})", self.instruction, target_addr)?;
}
OpArg::IndX { target_addr_base } => {
write!(f, "{} (${:02X},X)", self.instruction, target_addr_base)?;
}
OpArg::IndY { target_addr_base } => {
write!(f, "{} (${:02X}),Y", self.instruction, target_addr_base)?;
}
OpArg::Imm { value } => {
write!(f, "{} #${:02X}", self.instruction, value)?;
}
OpArg::Branch { addr_offset } => {
if addr_offset >= 0 {
write!(f, "{} _ + #${:02X}", self.instruction, addr_offset)?;
} else {
let abs_offset = -(addr_offset as i16);
write!(f, "{} _ - #${:02X}", self.instruction, abs_offset)?;
}
}
}
Ok(())
}
}
pub enum CpuStep {
Cycle,
Op(CpuStepOp),
}
pub struct CpuStepOp {
pub pc: u16,
pub op: Op,
}
trait ImpliedOperation {
fn operate(&self, cpu: &Cpu);
fn instruction(&self) -> Instruction;
}
trait ReadOperation {
fn read(&self, cpu: &Cpu, value: u8);
fn instruction(&self) -> Instruction;
}
trait ModifyOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8;
fn instruction(&self) -> Instruction;
}
trait WriteOperation {
fn write(&self, cpu: &Cpu) -> u8;
fn instruction(&self) -> Instruction;
}
trait BranchOperation {
fn branch(&self, cpu: &Cpu) -> bool;
fn instruction(&self) -> Instruction;
}
trait StackPushOperation {
fn push(&self, cpu: &Cpu) -> u8;
fn instruction(&self) -> Instruction;
}
trait StackPullOperation {
fn pull(&self, cpu: &Cpu, value: u8);
fn instruction(&self) -> Instruction;
}
fn implied<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ImpliedOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = Cpu::pc_fetch(nes);
op.operate(&nes.cpu);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Implied,
}
}
}
fn brk<'a>(nes: &'a Nes<impl NesIo>) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let pc = nes.cpu.pc.get();
nes.push_u8(((pc & 0xFF00) >> 8) as u8);
yield CpuStep::Cycle;
nes.push_u8((pc & 0x00FF) as u8);
yield CpuStep::Cycle;
let p = nes.cpu.p.get().bits | 0b_0011_0000;
nes.push_u8(p);
yield CpuStep::Cycle;
let pc_hi = nes.read_u8(0xFFFE);
yield CpuStep::Cycle;
let pc_lo = nes.read_u8(0xFFFF);
let pc = u16_from(pc_hi, pc_lo);
nes.cpu.pc.set(pc);
yield CpuStep::Cycle;
Op {
instruction: Instruction::Brk,
arg: OpArg::Implied,
}
}
}
fn accum_modify<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ModifyOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = Cpu::pc_fetch(nes);
let value = nes.cpu.a.get();
let new_value = op.modify(&nes.cpu, value);
nes.cpu.a.set(new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Accum,
}
}
}
fn imm_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let value = Cpu::pc_fetch_inc(nes);
op.read(&nes.cpu, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Imm { value },
}
}
}
fn zero_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let zero_page = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr = zero_page as u16;
let value = nes.read_u8(addr);
op.read(&nes.cpu, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Zero { zero_page },
}
}
}
fn zero_modify<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ModifyOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let zero_page = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr = zero_page as u16;
let value = nes.read_u8(addr);
yield CpuStep::Cycle;
nes.write_u8(addr, value);
let new_value = op.modify(&nes.cpu, value);
yield CpuStep::Cycle;
nes.write_u8(addr, new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Zero { zero_page },
}
}
}
fn zero_write<'a>(
nes: &'a Nes<impl NesIo>,
op: impl WriteOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let zero_page = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr = zero_page as u16;
let value = op.write(&nes.cpu);
nes.write_u8(addr, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Zero { zero_page },
}
}
}
fn zero_x_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let zero_page_base = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(zero_page_base as u16);
let addr = zero_page_base.wrapping_add(nes.cpu.x.get()) as u16;
yield CpuStep::Cycle;
let value = nes.read_u8(addr);
op.read(&nes.cpu, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::ZeroX { zero_page_base },
}
}
}
fn zero_x_modify<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ModifyOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let zero_page_base = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(zero_page_base as u16);
let addr = zero_page_base.wrapping_add(nes.cpu.x.get()) as u16;
yield CpuStep::Cycle;
let value = nes.read_u8(addr);
yield CpuStep::Cycle;
nes.write_u8(addr, value);
let new_value = op.modify(&nes.cpu, value);
yield CpuStep::Cycle;
nes.write_u8(addr, new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::ZeroX { zero_page_base },
}
}
}
fn zero_x_write<'a>(
nes: &'a Nes<impl NesIo>,
op: impl WriteOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let zero_page_base = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(zero_page_base as u16);
let addr = zero_page_base.wrapping_add(nes.cpu.x.get()) as u16;
yield CpuStep::Cycle;
let value = op.write(&nes.cpu);
nes.write_u8(addr, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::ZeroX { zero_page_base },
}
}
}
fn zero_y_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let zero_page_base = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(zero_page_base as u16);
let addr = zero_page_base.wrapping_add(nes.cpu.y.get()) as u16;
yield CpuStep::Cycle;
let value = nes.read_u8(addr);
op.read(&nes.cpu, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::ZeroY { zero_page_base },
}
}
}
fn zero_y_write<'a>(
nes: &'a Nes<impl NesIo>,
op: impl WriteOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let zero_page_base = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(zero_page_base as u16);
let addr = zero_page_base.wrapping_add(nes.cpu.y.get()) as u16;
yield CpuStep::Cycle;
let value = op.write(&nes.cpu);
nes.write_u8(addr, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::ZeroY { zero_page_base },
}
}
}
fn abs_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr = u16_from(addr_lo, addr_hi);
let value = nes.read_u8(addr);
op.read(&nes.cpu, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Abs { addr },
}
}
}
fn abs_modify<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ModifyOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr = u16_from(addr_lo, addr_hi);
let value = nes.read_u8(addr);
yield CpuStep::Cycle;
nes.write_u8(addr, value);
let new_value = op.modify(&nes.cpu, value);
yield CpuStep::Cycle;
nes.write_u8(addr, new_value);
Op {
instruction: op.instruction(),
arg: OpArg::Abs { addr },
}
}
}
fn abs_write<'a>(
nes: &'a Nes<impl NesIo>,
op: impl WriteOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr = u16_from(addr_lo, addr_hi);
let value = op.write(&nes.cpu);
nes.write_u8(addr, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Abs { addr },
}
}
}
fn abs_jmp<'a>(nes: &'a Nes<impl NesIo>) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let pc_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let pc_hi = Cpu::pc_fetch(nes);
let addr = u16_from(pc_lo, pc_hi);
nes.cpu.pc.set(addr);
yield CpuStep::Cycle;
Op {
instruction: Instruction::Jmp,
arg: OpArg::Abs { addr },
}
}
}
fn ind_jmp<'a>(nes: &'a Nes<impl NesIo>) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let target_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let target_hi = Cpu::pc_fetch(nes);
let addr_lo = u16_from(target_lo, target_hi);
let addr_hi = u16_from(target_lo.wrapping_add(1), target_hi);
yield CpuStep::Cycle;
let pc_lo = nes.read_u8(addr_lo);
yield CpuStep::Cycle;
let pc_hi = nes.read_u8(addr_hi);
let addr = u16_from(pc_lo, pc_hi);
nes.cpu.pc.set(addr);
yield CpuStep::Cycle;
Op {
instruction: Instruction::Jmp,
arg: OpArg::Ind {
target_addr: addr_lo,
},
}
}
}
fn abs_x_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
let addr_base = u16_from(addr_lo, addr_hi);
let x = nes.cpu.x.get();
let addr_lo_x = addr_lo.wrapping_add(x);
yield CpuStep::Cycle;
// Speculatively load from memory based on the
// incomplete address calculation
let addr_unfixed = u16_from(addr_lo_x, addr_hi);
let value_unfixed = nes.read_u8(addr_unfixed);
// Calculate the actual address to use
let addr = addr_base.wrapping_add(x as u16);
let value = if addr == addr_unfixed {
value_unfixed
} else {
// If the speculative load was incorrect, read the from
// the correct address (at the cost of an extra cycle)
let fixed_value = nes.read_u8(addr);
yield CpuStep::Cycle;
fixed_value
};
op.read(&nes.cpu, value);
Op {
instruction: op.instruction(),
arg: OpArg::AbsX { addr_base },
}
}
}
fn abs_x_modify<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ModifyOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
let addr_base = u16_from(addr_lo, addr_hi);
let x = nes.cpu.x.get();
let addr_lo_x = addr_lo.wrapping_add(x);
yield CpuStep::Cycle;
let addr_unfixed = u16_from(addr_lo_x, addr_hi);
let _garbage = nes.read_u8(addr_unfixed);
yield CpuStep::Cycle;
let addr = addr_base.wrapping_add(x as u16);
let value = nes.read_u8(addr);
yield CpuStep::Cycle;
nes.write_u8(addr, value);
let new_value = op.modify(&nes.cpu, value);
yield CpuStep::Cycle;
nes.write_u8(addr, new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::AbsX { addr_base },
}
}
}
fn abs_x_write<'a>(
nes: &'a Nes<impl NesIo>,
op: impl WriteOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
let addr_base = u16_from(addr_lo, addr_hi);
let x = nes.cpu.x.get();
let addr_lo_x = addr_lo.wrapping_add(x);
yield CpuStep::Cycle;
let addr_unfixed = u16_from(addr_lo_x, addr_hi);
let _garbage = nes.read_u8(addr_unfixed);
yield CpuStep::Cycle;
let addr = addr_base.wrapping_add(x as u16);
let new_value = op.write(&nes.cpu);
nes.write_u8(addr, new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::AbsX { addr_base },
}
}
}
fn abs_y_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
let addr_base = u16_from(addr_lo, addr_hi);
let y = nes.cpu.y.get();
let addr_lo_y = addr_lo.wrapping_add(y);
yield CpuStep::Cycle;
// Speculatively load from memory based on the
// incomplete address calculation
let addr_unfixed = u16_from(addr_lo_y, addr_hi);
let value_unfixed = nes.read_u8(addr_unfixed);
// Calculate the actual address to use
let addr = addr_base.wrapping_add(y as u16);
let value = if addr == addr_unfixed {
value_unfixed
} else {
// If the speculative load was incorrect, read the from
// the correct address (at the cost of an extra cycle)
let fixed_value = nes.read_u8(addr);
yield CpuStep::Cycle;
fixed_value
};
op.read(&nes.cpu, value);
Op {
instruction: op.instruction(),
arg: OpArg::AbsY { addr_base },
}
}
}
fn abs_y_modify<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ModifyOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
let addr_base = u16_from(addr_lo, addr_hi);
let y = nes.cpu.y.get();
let addr_lo_y = addr_lo.wrapping_add(y);
yield CpuStep::Cycle;
let addr_unfixed = u16_from(addr_lo_y, addr_hi);
let _garbage = nes.read_u8(addr_unfixed);
yield CpuStep::Cycle;
let addr = addr_base.wrapping_add(y as u16);
let value = nes.read_u8(addr);
yield CpuStep::Cycle;
nes.write_u8(addr, value);
let new_value = op.modify(&nes.cpu, value);
yield CpuStep::Cycle;
nes.write_u8(addr, new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::AbsY { addr_base },
}
}
}
fn abs_y_write<'a>(
nes: &'a Nes<impl NesIo>,
op: impl WriteOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch_inc(nes);
let addr_base = u16_from(addr_lo, addr_hi);
let y = nes.cpu.y.get();
let addr_lo_y = addr_lo.wrapping_add(y);
yield CpuStep::Cycle;
let addr_unfixed = u16_from(addr_lo_y, addr_hi);
let _garbage = nes.read_u8(addr_unfixed);
yield CpuStep::Cycle;
let addr = addr_base.wrapping_add(y as u16);
let new_value = op.write(&nes.cpu);
nes.write_u8(addr, new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::AbsY { addr_base },
}
}
}
fn ind_x_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let target_addr_base = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(target_addr_base as u16);
let x = nes.cpu.x.get();
let target_addr = target_addr_base.wrapping_add(x);
yield CpuStep::Cycle;
let addr_lo = nes.read_u8(target_addr as u16);
yield CpuStep::Cycle;
let addr_hi = nes.read_u8(target_addr.wrapping_add(1) as u16);
yield CpuStep::Cycle;
let addr = u16_from(addr_lo, addr_hi);
let value = nes.read_u8(addr);
op.read(&nes.cpu, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::IndX { target_addr_base },
}
}
}
fn ind_x_modify<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ModifyOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let target_addr_base = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(target_addr_base as u16);
let x = nes.cpu.x.get();
let target_addr = target_addr_base.wrapping_add(x);
yield CpuStep::Cycle;
let addr_lo = nes.read_u8(target_addr as u16);
yield CpuStep::Cycle;
let addr_hi = nes.read_u8(target_addr.wrapping_add(1) as u16);
yield CpuStep::Cycle;
let addr = u16_from(addr_lo, addr_hi);
let value = nes.read_u8(addr);
yield CpuStep::Cycle;
nes.write_u8(addr, value);
yield CpuStep::Cycle;
let new_value = op.modify(&nes.cpu, value);
nes.write_u8(addr, new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::IndX { target_addr_base },
}
}
}
fn ind_x_write<'a>(
nes: &'a Nes<impl NesIo>,
op: impl WriteOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let target_addr_base = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(target_addr_base as u16);
let x = nes.cpu.x.get();
let target_addr = target_addr_base.wrapping_add(x);
yield CpuStep::Cycle;
let addr_lo = nes.read_u8(target_addr as u16);
yield CpuStep::Cycle;
let addr_hi = nes.read_u8(target_addr.wrapping_add(1) as u16);
yield CpuStep::Cycle;
let addr = u16_from(addr_lo, addr_hi);
let value = op.write(&nes.cpu);
nes.write_u8(addr, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::IndX { target_addr_base },
}
}
}
fn ind_y_read<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ReadOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(&nes);
yield CpuStep::Cycle;
let target_addr_base = Cpu::pc_fetch_inc(&nes);
let target_addr_base_lo = target_addr_base as u16;
let target_addr_base_hi = target_addr_base.wrapping_add(1) as u16;
yield CpuStep::Cycle;
let addr_base_lo = nes.read_u8(target_addr_base_lo);
yield CpuStep::Cycle;
let addr_base_hi = nes.read_u8(target_addr_base_hi);
let y = nes.cpu.y.get();
yield CpuStep::Cycle;
// Speculatively load from memory based on the
// incomplete address calculation
let addr_unfixed = u16_from(addr_base_lo.wrapping_add(y), addr_base_hi);
let value_unfixed = nes.read_u8(addr_unfixed);
yield CpuStep::Cycle;
// Calculate the actual address to use
let addr_base = u16_from(addr_base_lo, addr_base_hi);
let addr = addr_base.wrapping_add(y as u16);
let value = if addr == addr_unfixed {
value_unfixed
} else {
// If the speculative load was incorrect, read the from
// the correct address (at the cost of an extra cycle)
let fixed_value = nes.read_u8(addr);
yield CpuStep::Cycle;
fixed_value
};
op.read(&nes.cpu, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::IndY { target_addr_base },
}
}
}
fn ind_y_modify<'a>(
nes: &'a Nes<impl NesIo>,
op: impl ModifyOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(&nes);
yield CpuStep::Cycle;
let target_addr_base = Cpu::pc_fetch_inc(&nes);
let target_addr_base_lo = target_addr_base as u16;
let target_addr_base_hi = target_addr_base.wrapping_add(1) as u16;
yield CpuStep::Cycle;
let addr_base_lo = nes.read_u8(target_addr_base_lo);
yield CpuStep::Cycle;
let addr_base_hi = nes.read_u8(target_addr_base_hi);
let y = nes.cpu.y.get();
let addr_unfixed = u16_from(addr_base_lo.wrapping_add(y), addr_base_hi);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(addr_unfixed);
yield CpuStep::Cycle;
let addr_base = u16_from(addr_base_lo, addr_base_hi);
let addr = addr_base.wrapping_add(y as u16);
let value = nes.read_u8(addr);
yield CpuStep::Cycle;
nes.write_u8(addr, value);
let new_value = op.modify(&nes.cpu, value);
yield CpuStep::Cycle;
nes.write_u8(addr, new_value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::IndY { target_addr_base },
}
}
}
fn ind_y_write<'a>(
nes: &'a Nes<impl NesIo>,
op: impl WriteOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(&nes);
yield CpuStep::Cycle;
let target_addr_base = Cpu::pc_fetch_inc(&nes);
let target_addr_base_lo = target_addr_base as u16;
let target_addr_base_hi = target_addr_base.wrapping_add(1) as u16;
yield CpuStep::Cycle;
let addr_base_lo = nes.read_u8(target_addr_base_lo);
yield CpuStep::Cycle;
let addr_base_hi = nes.read_u8(target_addr_base_hi);
let y = nes.cpu.y.get();
let addr_unfixed = u16_from(addr_base_lo.wrapping_add(y), addr_base_hi);
yield CpuStep::Cycle;
let _garbage = nes.read_u8(addr_unfixed);
yield CpuStep::Cycle;
let addr_base = u16_from(addr_base_lo, addr_base_hi);
let addr = addr_base.wrapping_add(y as u16);
let value = op.write(&nes.cpu);
nes.write_u8(addr, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::IndY { target_addr_base },
}
}
}
fn branch<'a>(
nes: &'a Nes<impl NesIo>,
op: impl BranchOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(&nes);
yield CpuStep::Cycle;
let addr_offset = Cpu::pc_fetch_inc(&nes) as i8;
yield CpuStep::Cycle;
if op.branch(&nes.cpu) {
let pc = nes.cpu.pc.get();
let pc_hi = (pc >> 8) as u8;
let pc_lo = (pc & 0x00FF) as u8;
let pc_lo_offset = pc_lo.wrapping_add(addr_offset as u8);
let unfixed_addr = u16_from(pc_hi, pc_lo_offset);
let addr = pc.wrapping_add(addr_offset as u16);
nes.cpu.pc.set(addr);
if addr != unfixed_addr {
// yield CpuStep::Cycle;
}
yield CpuStep::Cycle;
}
Op {
instruction: op.instruction(),
arg: OpArg::Branch { addr_offset },
}
}
}
fn stack_push<'a>(
nes: &'a Nes<impl NesIo>,
op: impl StackPushOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = Cpu::pc_fetch(nes);
yield CpuStep::Cycle;
let value = op.push(&nes.cpu);
nes.write_u8(nes.cpu.stack_addr(), value);
nes.cpu.dec_s();
Op {
instruction: op.instruction(),
arg: OpArg::Implied,
}
}
}
fn stack_pull<'a>(
nes: &'a Nes<impl NesIo>,
op: impl StackPullOperation + 'a,
) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = Cpu::pc_fetch(nes);
yield CpuStep::Cycle;
nes.cpu.inc_s();
yield CpuStep::Cycle;
let value = nes.read_u8(nes.cpu.stack_addr());
op.pull(&nes.cpu, value);
yield CpuStep::Cycle;
Op {
instruction: op.instruction(),
arg: OpArg::Implied,
}
}
}
fn jsr<'a>(nes: &'a Nes<impl NesIo>) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let ret_pc = nes.cpu.pc.get().wrapping_add(3);
let push_pc = ret_pc.wrapping_sub(1);
let push_pc_hi = (push_pc >> 8) as u8;
let push_pc_lo = (push_pc & 0x00FF) as u8;
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let addr_lo = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
// No-op
yield CpuStep::Cycle;
nes.write_u8(nes.cpu.stack_addr(), push_pc_hi);
nes.cpu.dec_s();
yield CpuStep::Cycle;
nes.write_u8(nes.cpu.stack_addr(), push_pc_lo);
nes.cpu.dec_s();
yield CpuStep::Cycle;
let addr_hi = Cpu::pc_fetch(nes);
let addr = u16_from(addr_lo, addr_hi);
nes.cpu.pc.set(addr);
yield CpuStep::Cycle;
Op {
instruction: Instruction::Jsr,
arg: OpArg::Abs { addr },
}
}
}
fn rti<'a>(nes: &'a Nes<impl NesIo>) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = Cpu::pc_fetch(nes);
yield CpuStep::Cycle;
nes.cpu.inc_s();
yield CpuStep::Cycle;
let p = nes.read_u8(nes.cpu.stack_addr());
nes.cpu.p.set(CpuFlags::from_bits_truncate(p));
nes.cpu.inc_s();
yield CpuStep::Cycle;
let pc_lo = nes.read_u8(nes.cpu.stack_addr());
nes.cpu.inc_s();
yield CpuStep::Cycle;
let pc_hi = nes.read_u8(nes.cpu.stack_addr());
nes.cpu.pc.set(u16_from(pc_lo, pc_hi));
yield CpuStep::Cycle;
Op {
instruction: Instruction::Rti,
arg: OpArg::Implied,
}
}
}
fn rts<'a>(nes: &'a Nes<impl NesIo>) -> impl Generator<Yield = CpuStep, Return = Op> + 'a {
move || {
let _opcode = Cpu::pc_fetch_inc(nes);
yield CpuStep::Cycle;
let _garbage = Cpu::pc_fetch(nes);
yield CpuStep::Cycle;
nes.cpu.inc_s();
yield CpuStep::Cycle;
let pull_pc_lo = nes.read_u8(nes.cpu.stack_addr());
nes.cpu.inc_s();
yield CpuStep::Cycle;
let pull_pc_hi = nes.read_u8(nes.cpu.stack_addr());
nes.cpu.pc.set(u16_from(pull_pc_lo, pull_pc_hi));
yield CpuStep::Cycle;
nes.cpu.pc_inc();
yield CpuStep::Cycle;
Op {
instruction: Instruction::Rts,
arg: OpArg::Implied,
}
}
}
struct AdcOperation;
impl ReadOperation for AdcOperation {
fn read(&self, cpu: &Cpu, value: u8) {
let AdcResult { a, c, z, v, n } = adc(AdcArg {
a: cpu.a.get(),
c: cpu.contains_flags(CpuFlags::C),
value,
});
cpu.a.set(a);
cpu.set_flags(CpuFlags::C, c);
cpu.set_flags(CpuFlags::Z, z);
cpu.set_flags(CpuFlags::V, v);
cpu.set_flags(CpuFlags::N, n);
}
fn instruction(&self) -> Instruction {
Instruction::Adc
}
}
struct AndOperation;
impl ReadOperation for AndOperation {
fn read(&self, cpu: &Cpu, value: u8) {
let new_a = cpu.a.get() & value;
cpu.a.set(new_a);
cpu.set_flags(CpuFlags::Z, new_a == 0);
cpu.set_flags(CpuFlags::N, (new_a & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::And
}
}
struct AslOperation;
impl ModifyOperation for AslOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
let c = (value & 0b_1000_0000) != 0;
let new_value = value << 1;
cpu.set_flags(CpuFlags::C, c);
cpu.set_flags(CpuFlags::Z, new_value == 0);
cpu.set_flags(CpuFlags::N, (new_value & 0b_1000_0000) != 0);
new_value
}
fn instruction(&self) -> Instruction {
Instruction::Asl
}
}
struct BccOperation;
impl BranchOperation for BccOperation {
fn branch(&self, cpu: &Cpu) -> bool {
!cpu.contains_flags(CpuFlags::C)
}
fn instruction(&self) -> Instruction {
Instruction::Bcc
}
}
struct BcsOperation;
impl BranchOperation for BcsOperation {
fn branch(&self, cpu: &Cpu) -> bool {
cpu.contains_flags(CpuFlags::C)
}
fn instruction(&self) -> Instruction {
Instruction::Bcs
}
}
struct BeqOperation;
impl BranchOperation for BeqOperation {
fn branch(&self, cpu: &Cpu) -> bool {
cpu.contains_flags(CpuFlags::Z)
}
fn instruction(&self) -> Instruction {
Instruction::Beq
}
}
struct BitOperation;
impl ReadOperation for BitOperation {
fn read(&self, cpu: &Cpu, value: u8) {
cpu.set_flags(CpuFlags::Z, cpu.a.get() & value == 0);
cpu.set_flags(CpuFlags::N, value & 0b_1000_0000 != 0);
cpu.set_flags(CpuFlags::V, value & 0b_0100_0000 != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Bit
}
}
struct BmiOperation;
impl BranchOperation for BmiOperation {
fn branch(&self, cpu: &Cpu) -> bool {
cpu.contains_flags(CpuFlags::N)
}
fn instruction(&self) -> Instruction {
Instruction::Bmi
}
}
struct BneOperation;
impl BranchOperation for BneOperation {
fn branch(&self, cpu: &Cpu) -> bool {
!cpu.contains_flags(CpuFlags::Z)
}
fn instruction(&self) -> Instruction {
Instruction::Bne
}
}
struct BplOperation;
impl BranchOperation for BplOperation {
fn branch(&self, cpu: &Cpu) -> bool {
!cpu.contains_flags(CpuFlags::N)
}
fn instruction(&self) -> Instruction {
Instruction::Bpl
}
}
struct BvcOperation;
impl BranchOperation for BvcOperation {
fn branch(&self, cpu: &Cpu) -> bool {
!cpu.contains_flags(CpuFlags::V)
}
fn instruction(&self) -> Instruction {
Instruction::Bvc
}
}
struct BvsOperation;
impl BranchOperation for BvsOperation {
fn branch(&self, cpu: &Cpu) -> bool {
cpu.contains_flags(CpuFlags::V)
}
fn instruction(&self) -> Instruction {
Instruction::Bvs
}
}
struct ClcOperation;
impl ImpliedOperation for ClcOperation {
fn operate(&self, cpu: &Cpu) {
cpu.set_flags(CpuFlags::C, false);
}
fn instruction(&self) -> Instruction {
Instruction::Clc
}
}
struct CldOperation;
impl ImpliedOperation for CldOperation {
fn operate(&self, cpu: &Cpu) {
cpu.set_flags(CpuFlags::D, false);
}
fn instruction(&self) -> Instruction {
Instruction::Cld
}
}
struct CliOperation;
impl ImpliedOperation for CliOperation {
fn operate(&self, cpu: &Cpu) {
cpu.set_flags(CpuFlags::I, false);
}
fn instruction(&self) -> Instruction {
Instruction::Cli
}
}
struct ClvOperation;
impl ImpliedOperation for ClvOperation {
fn operate(&self, cpu: &Cpu) {
cpu.set_flags(CpuFlags::V, false);
}
fn instruction(&self) -> Instruction {
Instruction::Clv
}
}
struct CmpOperation;
impl ReadOperation for CmpOperation {
fn read(&self, cpu: &Cpu, value: u8) {
let a = cpu.a.get();
let result = a.wrapping_sub(value);
cpu.set_flags(CpuFlags::C, a >= value);
cpu.set_flags(CpuFlags::Z, a == value);
cpu.set_flags(CpuFlags::N, (result & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Cmp
}
}
struct CpxOperation;
impl ReadOperation for CpxOperation {
fn read(&self, cpu: &Cpu, value: u8) {
let x = cpu.x.get();
let result = x.wrapping_sub(value);
cpu.set_flags(CpuFlags::C, x >= value);
cpu.set_flags(CpuFlags::Z, x == value);
cpu.set_flags(CpuFlags::N, (result & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Cpx
}
}
struct CpyOperation;
impl ReadOperation for CpyOperation {
fn read(&self, cpu: &Cpu, value: u8) {
let y = cpu.y.get();
let result = y.wrapping_sub(value);
cpu.set_flags(CpuFlags::C, y >= value);
cpu.set_flags(CpuFlags::Z, y == value);
cpu.set_flags(CpuFlags::N, (result & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Cpy
}
}
struct DecOperation;
impl ModifyOperation for DecOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
let new_value = value.wrapping_sub(1);
cpu.set_flags(CpuFlags::Z, new_value == 0);
cpu.set_flags(CpuFlags::N, (new_value & 0b_1000_0000) != 0);
new_value
}
fn instruction(&self) -> Instruction {
Instruction::Dec
}
}
struct DexOperation;
impl ImpliedOperation for DexOperation {
fn operate(&self, cpu: &Cpu) {
let new_x = cpu.x.get().wrapping_sub(1);
cpu.x.set(new_x);
cpu.set_flags(CpuFlags::Z, new_x == 0);
cpu.set_flags(CpuFlags::N, (new_x & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Dex
}
}
struct DeyOperation;
impl ImpliedOperation for DeyOperation {
fn operate(&self, cpu: &Cpu) {
let new_y = cpu.y.get().wrapping_sub(1);
cpu.y.set(new_y);
cpu.set_flags(CpuFlags::Z, new_y == 0);
cpu.set_flags(CpuFlags::N, (new_y & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Dey
}
}
struct EorOperation;
impl ReadOperation for EorOperation {
fn read(&self, cpu: &Cpu, value: u8) {
let new_a = cpu.a.get() ^ value;
cpu.a.set(new_a);
cpu.set_flags(CpuFlags::Z, new_a == 0);
cpu.set_flags(CpuFlags::N, (new_a & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Eor
}
}
struct IncOperation;
impl ModifyOperation for IncOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
let new_value = value.wrapping_add(1);
cpu.set_flags(CpuFlags::Z, new_value == 0);
cpu.set_flags(CpuFlags::N, (new_value & 0b_1000_0000) != 0);
new_value
}
fn instruction(&self) -> Instruction {
Instruction::Inc
}
}
struct InxOperation;
impl ImpliedOperation for InxOperation {
fn operate(&self, cpu: &Cpu) {
let new_x = cpu.x.get().wrapping_add(1);
cpu.x.set(new_x);
cpu.set_flags(CpuFlags::Z, new_x == 0);
cpu.set_flags(CpuFlags::N, (new_x & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Inx
}
}
struct InyOperation;
impl ImpliedOperation for InyOperation {
fn operate(&self, cpu: &Cpu) {
let new_y = cpu.y.get().wrapping_add(1);
cpu.y.set(new_y);
cpu.set_flags(CpuFlags::Z, new_y == 0);
cpu.set_flags(CpuFlags::N, (new_y & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Iny
}
}
struct LdaOperation;
impl ReadOperation for LdaOperation {
fn read(&self, cpu: &Cpu, value: u8) {
cpu.a.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Lda
}
}
struct LdxOperation;
impl ReadOperation for LdxOperation {
fn read(&self, cpu: &Cpu, value: u8) {
cpu.x.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Ldx
}
}
struct LdyOperation;
impl ReadOperation for LdyOperation {
fn read(&self, cpu: &Cpu, value: u8) {
cpu.y.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Ldy
}
}
struct LsrOperation;
impl ModifyOperation for LsrOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
let new_value = value >> 1;
cpu.set_flags(CpuFlags::C, (value & 0b_0000_0001) != 0);
cpu.set_flags(CpuFlags::Z, new_value == 0);
cpu.set_flags(CpuFlags::N, (new_value & 0b_1000_0000) != 0);
new_value
}
fn instruction(&self) -> Instruction {
Instruction::Lsr
}
}
struct NopOperation;
impl ImpliedOperation for NopOperation {
fn operate(&self, _cpu: &Cpu) {}
fn instruction(&self) -> Instruction {
Instruction::Nop
}
}
struct OraOperation;
impl ReadOperation for OraOperation {
fn read(&self, cpu: &Cpu, value: u8) {
let new_a = cpu.a.get() | value;
cpu.a.set(new_a);
cpu.set_flags(CpuFlags::Z, new_a == 0);
cpu.set_flags(CpuFlags::N, (new_a & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Ora
}
}
struct PhaOperation;
impl StackPushOperation for PhaOperation {
fn push(&self, cpu: &Cpu) -> u8 {
cpu.a.get()
}
fn instruction(&self) -> Instruction {
Instruction::Pha
}
}
struct PhpOperation;
impl StackPushOperation for PhpOperation {
fn push(&self, cpu: &Cpu) -> u8 {
cpu.p.get().bits | 0b_0011_0000
}
fn instruction(&self) -> Instruction {
Instruction::Php
}
}
struct PlaOperation;
impl StackPullOperation for PlaOperation {
fn pull(&self, cpu: &Cpu, value: u8) {
cpu.a.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Pla
}
}
struct PlpOperation;
impl StackPullOperation for PlpOperation {
fn pull(&self, cpu: &Cpu, value: u8) {
cpu.p.set(CpuFlags::from_bits_truncate(value));
}
fn instruction(&self) -> Instruction {
Instruction::Plp
}
}
struct RolOperation;
impl ModifyOperation for RolOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
let prev_c = cpu.contains_flags(CpuFlags::C);
let carry_mask = match prev_c {
true => 0b_0000_0001,
false => 0b_0000_0000,
};
let new_value = (value << 1) | carry_mask;
cpu.set_flags(CpuFlags::C, (value & 0b_1000_0000) != 0);
cpu.set_flags(CpuFlags::Z, new_value == 0);
cpu.set_flags(CpuFlags::N, (new_value & 0b_1000_0000) != 0);
new_value
}
fn instruction(&self) -> Instruction {
Instruction::Rol
}
}
struct RorOperation;
impl ModifyOperation for RorOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
let prev_c = cpu.contains_flags(CpuFlags::C);
let carry_mask = match prev_c {
true => 0b_1000_0000,
false => 0b_0000_0000,
};
let new_value = (value >> 1) | carry_mask;
cpu.set_flags(CpuFlags::C, (value & 0b_0000_0001) != 0);
cpu.set_flags(CpuFlags::Z, new_value == 0);
cpu.set_flags(CpuFlags::N, (new_value & 0b_1000_0000) != 0);
new_value
}
fn instruction(&self) -> Instruction {
Instruction::Ror
}
}
struct SbcOperation;
impl ReadOperation for SbcOperation {
fn read(&self, cpu: &Cpu, value: u8) {
// Subtract-with-carry is the same as add-with-carry after
// performing a bitwise not on `value`
let AdcResult { a, c, z, v, n } = adc(AdcArg {
a: cpu.a.get(),
c: cpu.contains_flags(CpuFlags::C),
value: !value,
});
cpu.a.set(a);
cpu.set_flags(CpuFlags::C, c);
cpu.set_flags(CpuFlags::Z, z);
cpu.set_flags(CpuFlags::V, v);
cpu.set_flags(CpuFlags::N, n);
}
fn instruction(&self) -> Instruction {
Instruction::Sbc
}
}
struct SecOperation;
impl ImpliedOperation for SecOperation {
fn operate(&self, cpu: &Cpu) {
cpu.set_flags(CpuFlags::C, true);
}
fn instruction(&self) -> Instruction {
Instruction::Sec
}
}
struct SedOperation;
impl ImpliedOperation for SedOperation {
fn operate(&self, cpu: &Cpu) {
cpu.set_flags(CpuFlags::D, true);
}
fn instruction(&self) -> Instruction {
Instruction::Sed
}
}
struct SeiOperation;
impl ImpliedOperation for SeiOperation {
fn operate(&self, cpu: &Cpu) {
cpu.set_flags(CpuFlags::I, true);
}
fn instruction(&self) -> Instruction {
Instruction::Sei
}
}
struct StaOperation;
impl WriteOperation for StaOperation {
fn write(&self, cpu: &Cpu) -> u8 {
cpu.a.get()
}
fn instruction(&self) -> Instruction {
Instruction::Sta
}
}
struct StxOperation;
impl WriteOperation for StxOperation {
fn write(&self, cpu: &Cpu) -> u8 {
cpu.x.get()
}
fn instruction(&self) -> Instruction {
Instruction::Stx
}
}
struct StyOperation;
impl WriteOperation for StyOperation {
fn write(&self, cpu: &Cpu) -> u8 {
cpu.y.get()
}
fn instruction(&self) -> Instruction {
Instruction::Sty
}
}
struct TaxOperation;
impl ImpliedOperation for TaxOperation {
fn operate(&self, cpu: &Cpu) {
let value = cpu.a.get();
cpu.x.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Tax
}
}
struct TayOperation;
impl ImpliedOperation for TayOperation {
fn operate(&self, cpu: &Cpu) {
let value = cpu.a.get();
cpu.y.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Tay
}
}
struct TsxOperation;
impl ImpliedOperation for TsxOperation {
fn operate(&self, cpu: &Cpu) {
let value = cpu.s.get();
cpu.x.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Tsx
}
}
struct TxaOperation;
impl ImpliedOperation for TxaOperation {
fn operate(&self, cpu: &Cpu) {
let value = cpu.x.get();
cpu.a.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Txa
}
}
struct TxsOperation;
impl ImpliedOperation for TxsOperation {
fn operate(&self, cpu: &Cpu) {
let value = cpu.x.get();
cpu.s.set(value);
}
fn instruction(&self) -> Instruction {
Instruction::Txs
}
}
struct TyaOperation;
impl ImpliedOperation for TyaOperation {
fn operate(&self, cpu: &Cpu) {
let value = cpu.y.get();
cpu.a.set(value);
cpu.set_flags(CpuFlags::Z, value == 0);
cpu.set_flags(CpuFlags::N, (value & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::Tya
}
}
struct UnofficialAncOperation;
impl ReadOperation for UnofficialAncOperation {
fn read(&self, cpu: &Cpu, value: u8) {
// This operation is like AND, but the C flag is also set to
// bit 7 of the result
let new_a = cpu.a.get() & value;
cpu.a.set(new_a);
cpu.set_flags(CpuFlags::Z, new_a == 0);
cpu.set_flags(CpuFlags::N, (new_a & 0b_1000_0000) != 0);
cpu.set_flags(CpuFlags::C, (new_a & 0b_1000_0000) != 0);
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialAnc
}
}
struct UnofficialAlrOperation;
impl ReadOperation for UnofficialAlrOperation {
fn read(&self, cpu: &Cpu, value: u8) {
// This operation combines AND and LSR
AndOperation.read(cpu, value);
cpu.a.set(LsrOperation.modify(cpu, cpu.a.get()));
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialAlr
}
}
struct UnofficialArrOperation;
impl ReadOperation for UnofficialArrOperation {
fn read(&self, cpu: &Cpu, value: u8) {
// This operation is a combination of AND and ROR, except it
// sets the C and V flags differently
let prev_c = cpu.contains_flags(CpuFlags::C);
let carry_mask = match prev_c {
true => 0b_1000_0000,
false => 0b_0000_0000,
};
let and_a = cpu.a.get() & value;
let result = (and_a >> 1) | carry_mask;
let result_bit_7 = (result & 0b_1000_0000) != 0;
let result_bit_6 = (result & 0b_0100_0000) != 0;
let result_bit_5 = (result & 0b_0010_0000) != 0;
cpu.a.set(result);
cpu.set_flags(CpuFlags::C, result_bit_6);
cpu.set_flags(CpuFlags::Z, result == 0);
cpu.set_flags(CpuFlags::V, result_bit_6 != result_bit_5);
cpu.set_flags(CpuFlags::N, result_bit_7);
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialArr
}
}
struct UnofficialAxsOperation;
impl ReadOperation for UnofficialAxsOperation {
fn read(&self, cpu: &Cpu, value: u8) {
// This operation sets X to ((A & X) - value), and updates the
// C, Z, and N flags appropriately.
let a_and_x = cpu.a.get() & cpu.x.get();
let AdcResult {
a: result,
c,
z,
v: _,
n,
} = adc(AdcArg {
a: a_and_x,
c: true,
value: !value,
});
cpu.x.set(result);
cpu.set_flags(CpuFlags::C, c);
cpu.set_flags(CpuFlags::Z, z);
cpu.set_flags(CpuFlags::N, n);
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialAxs
}
}
struct UnofficialDcpOperation;
impl ModifyOperation for UnofficialDcpOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
// This operation combines DEC and CMP
let shift_value = DecOperation.modify(cpu, value);
CmpOperation.read(cpu, shift_value);
shift_value
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialDcp
}
}
struct UnofficialIscOperation;
impl ModifyOperation for UnofficialIscOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
// This operation combines INC and SBC
let shift_value = IncOperation.modify(cpu, value);
SbcOperation.read(cpu, shift_value);
shift_value
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialIsc
}
}
struct UnofficialLaxOperation;
impl ReadOperation for UnofficialLaxOperation {
fn read(&self, cpu: &Cpu, value: u8) {
// This operation combines LDA and LDX
LdaOperation.read(cpu, value);
LdxOperation.read(cpu, value);
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialLax
}
}
struct UnofficialNopOperation;
impl ImpliedOperation for UnofficialNopOperation {
fn operate(&self, _cpu: &Cpu) {}
fn instruction(&self) -> Instruction {
Instruction::UnofficialNop
}
}
// NOTE: Some undocumented opcodes do nothing, but still perform a memory read
impl ReadOperation for UnofficialNopOperation {
fn read(&self, _cpu: &Cpu, _value: u8) {}
fn instruction(&self) -> Instruction {
Instruction::UnofficialNop
}
}
struct UnofficialRlaOperation;
impl ModifyOperation for UnofficialRlaOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
// This operation combines ROL and AND
let shift_value = RolOperation.modify(cpu, value);
AndOperation.read(cpu, shift_value);
shift_value
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialRla
}
}
struct UnofficialRraOperation;
impl ModifyOperation for UnofficialRraOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
// This operation combines ROR and ADC
let shift_value = RorOperation.modify(cpu, value);
AdcOperation.read(cpu, shift_value);
shift_value
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialRra
}
}
struct UnofficialSaxOperation;
impl WriteOperation for UnofficialSaxOperation {
fn write(&self, cpu: &Cpu) -> u8 {
// This operation writes the bitwise-AND of A and X
cpu.a.get() & cpu.x.get()
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialSax
}
}
struct UnofficialSbcOperation;
impl ReadOperation for UnofficialSbcOperation {
fn read(&self, cpu: &Cpu, value: u8) {
SbcOperation.read(cpu, value);
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialSbc
}
}
struct UnofficialShxOperation;
impl ModifyOperation for UnofficialShxOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
// This operation writes (X & ((value << 7) + 1))
cpu.x.get() & ((value << 7) + 1)
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialShx
}
}
struct UnofficialShyOperation;
impl ModifyOperation for UnofficialShyOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
// This operation writes (Y & ((value << 7) + 1))
cpu.y.get() & ((value << 7) + 1)
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialShy
}
}
struct UnofficialSloOperation;
impl ModifyOperation for UnofficialSloOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
// This operation combines ASL and ORA
let shift_value = AslOperation.modify(cpu, value);
OraOperation.read(cpu, shift_value);
shift_value
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialSlo
}
}
struct UnofficialSreOperation;
impl ModifyOperation for UnofficialSreOperation {
fn modify(&self, cpu: &Cpu, value: u8) -> u8 {
// This operation combines LSR and EOR
let shift_value = LsrOperation.modify(cpu, value);
EorOperation.read(cpu, shift_value);
shift_value
}
fn instruction(&self) -> Instruction {
Instruction::UnofficialSre
}
}
struct AdcArg {
a: u8,
value: u8,
c: bool,
}
struct AdcResult {
a: u8,
c: bool,
z: bool,
v: bool,
n: bool,
}
fn adc(AdcArg { a, value, c }: AdcArg) -> AdcResult {
let result = (a as u16).wrapping_add(value as u16).wrapping_add(c as u16);
let out = result as u8;
// Get the "intended" sign of the result by performing the same calculation
// with signed integers
let signed_a = a as i8;
let signed_value = value as i8;
let signed_c = c as i8;
let signed_result = (signed_a as i16)
.wrapping_add(signed_value as i16)
.wrapping_add(signed_c as i16);
let out_negative = (out & 0b_1000_0000) != 0;
let signed_result_negative = signed_result < 0;
let c = result >= 256;
let z = out == 0;
let v = out_negative != signed_result_negative;
let n = (out & 0b_1000_0000) != 0;
AdcResult { a: out, c, z, v, n }
}
fn u16_from(lo: u8, hi: u8) -> u16 {
((hi as u16) << 8) | (lo as u16)
}
|
use libc;
use libnice_sys::{
nice_address_set_from_string, nice_address_set_port, nice_candidate_free, nice_candidate_new,
NiceCandidate, NiceCandidateTransport_NICE_CANDIDATE_TRANSPORT_UDP,
NiceCandidateType_NICE_CANDIDATE_TYPE_HOST,
NiceCandidateType_NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE,
};
use std::{ffi::CString, ptr::NonNull};
use crate::{candidate_type::CandidateType, mdns_resolve, transport::Transport};
#[derive(Debug)]
pub struct IceCandidate {
inner: NonNull<NiceCandidate>,
pub foundation: u8,
pub component: u32,
pub transport: Transport,
pub priority: u32,
pub ip: String,
pub port: u16,
pub typ: CandidateType,
}
impl IceCandidate {
pub fn new(
foundation: u8,
component: u32,
transport: Transport,
priority: u32,
ip: String,
port: u16,
typ: CandidateType,
) -> Result<Self, String> {
let inner;
unsafe {
let candidate_type = match &typ {
CandidateType::HostTcp(_) | CandidateType::HostUdp => {
NiceCandidateType_NICE_CANDIDATE_TYPE_HOST
}
CandidateType::ServerReflexive(_, _) => {
NiceCandidateType_NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE
}
};
inner = NonNull::new(nice_candidate_new(candidate_type))
.ok_or::<String>("candidate creation failed".into())?;
(*inner.as_ptr()).component_id = component;
(*inner.as_ptr()).transport = NiceCandidateTransport_NICE_CANDIDATE_TRANSPORT_UDP;
// g_strlcpy(c->foundation, rfoundation, NICE_CANDIDATE_MAX_FOUNDATION);
libc::strcpy(
(*inner.as_ptr()).foundation.as_mut_ptr(),
foundation.to_string().as_ptr() as *const _,
);
(*inner.as_ptr()).priority = priority;
if let Ok(resolved_ip) = mdns_resolve(&ip) {
let c_ip = CString::new(resolved_ip.clone()).unwrap();
let added = nice_address_set_from_string(
std::ptr::addr_of_mut!((*inner.as_ptr()).addr),
c_ip.as_c_str().as_ptr(),
);
if added != 1 {
// nice_candidate_free(c);
}
nice_address_set_port(std::ptr::addr_of_mut!((*inner.as_ptr()).addr), port as u32);
} else {
return Err("there was a problem resolving the candidate addr".into());
}
}
Ok(Self {
inner,
foundation,
component,
transport,
priority,
ip,
port,
typ,
})
}
pub fn set_stream_id(&self, stream_id: u32) {
unsafe {
(*self.inner.as_ptr()).stream_id = stream_id;
}
}
pub fn get_ptr(&self) -> *mut NiceCandidate {
self.inner.as_ptr()
}
}
impl Drop for IceCandidate {
fn drop(&mut self) {
unsafe {
nice_candidate_free(self.inner.as_ptr() as *mut _);
}
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - MCU Device ID Code Register"]
pub idcode: IDCODE,
#[doc = "0x04 - Debug MCU Configuration Register"]
pub cr: CR,
#[doc = "0x08 - APB Low Freeze Register 1"]
pub apb1l_fz: APB1L_FZ,
#[doc = "0x0c - APB Low Freeze Register 2"]
pub apb1h_fz: APB1H_FZ,
#[doc = "0x10 - APB High Freeze Register"]
pub apb2_fz: APB2_FZ,
}
#[doc = "IDCODE (r) register accessor: MCU Device ID Code Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`idcode::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`idcode`]
module"]
pub type IDCODE = crate::Reg<idcode::IDCODE_SPEC>;
#[doc = "MCU Device ID Code Register"]
pub mod idcode;
#[doc = "CR (rw) register accessor: Debug MCU Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`]
module"]
pub type CR = crate::Reg<cr::CR_SPEC>;
#[doc = "Debug MCU Configuration Register"]
pub mod cr;
#[doc = "APB1L_FZ (rw) register accessor: APB Low Freeze Register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1l_fz::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb1l_fz::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1l_fz`]
module"]
pub type APB1L_FZ = crate::Reg<apb1l_fz::APB1L_FZ_SPEC>;
#[doc = "APB Low Freeze Register 1"]
pub mod apb1l_fz;
#[doc = "APB1H_FZ (rw) register accessor: APB Low Freeze Register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1h_fz::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb1h_fz::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb1h_fz`]
module"]
pub type APB1H_FZ = crate::Reg<apb1h_fz::APB1H_FZ_SPEC>;
#[doc = "APB Low Freeze Register 2"]
pub mod apb1h_fz;
#[doc = "APB2_FZ (rw) register accessor: APB High Freeze Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2_fz::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb2_fz::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`apb2_fz`]
module"]
pub type APB2_FZ = crate::Reg<apb2_fz::APB2_FZ_SPEC>;
#[doc = "APB High Freeze Register"]
pub mod apb2_fz;
|
use sdl2::keyboard::Scancode;
use specs::prelude::*;
use crate::ecs::components::*;
use crate::ecs::resources::*;
use crate::ecs::weapon::*;
pub struct HealthSystem;
impl<'a> System<'a> for HealthSystem {
type SystemData = (Entities<'a>, WriteStorage<'a, Health>, Read<'a, LazyUpdate>);
fn run(&mut self, data: Self::SystemData) {
let (entities, mut health_storage, world) = data;
for (entity, health) in (&entities, &mut health_storage).join() {
for damage_event in health.damage_events.iter() {
let DamageEvent::DamageTaken(amount, pos) = damage_event;
if amount >= &health.health {
health.health = 0;
(health.on_death)(*pos, &entities, &world);
entities.delete(entity).expect("error deleeting entity")
// enemy died!
} else {
health.health -= amount;
}
}
health.damage_events.clear();
}
}
}
pub struct LifetimeKiller;
impl<'a> System<'a> for LifetimeKiller {
type SystemData = (
Entities<'a>,
WriteStorage<'a, Lifetime>,
Read<'a, DeltaTime>,
);
fn run(&mut self, data: Self::SystemData) {
let (entities, mut lifetime_storage, delta_time) = data;
let delta_time = delta_time.0;
for (entity, mut lifetime) in (&entities, &mut lifetime_storage).join() {
lifetime.time_left -= delta_time;
if lifetime.time_left < 0.0 {
entities
.delete(entity)
.expect("error deleting after lifetime ended")
}
}
}
}
pub struct PositionUpdateSystem;
impl<'a> System<'a> for PositionUpdateSystem {
type SystemData = (
Read<'a, DeltaTime>,
ReadStorage<'a, Velocity>,
WriteStorage<'a, Position>,
);
fn run(&mut self, data: Self::SystemData) {
let (delta_time, velocity_storage, mut position_storage) = data;
let delta_time = delta_time.0;
let update_position = |(velocity, position): (&Velocity, &mut Position)| {
position.position += velocity.velocity * delta_time;
};
(&velocity_storage, &mut position_storage)
.join()
.for_each(update_position);
}
}
pub struct InputSystem;
impl<'a> System<'a> for InputSystem {
type SystemData = (
Read<'a, InputResource>,
ReadStorage<'a, KeyboardControlled>,
WriteStorage<'a, Velocity>,
WriteStorage<'a, Weapon>,
);
fn run(&mut self, data: Self::SystemData) {
let (input, controlled, mut velocity_storage, mut weapon_storage) = data;
let input = &input.0;
for (velocity, _) in (&mut velocity_storage, &controlled).join() {
velocity.set_y(0.0);
velocity.set_x(0.0);
}
if input.get_key(Scancode::Up).held {
for (velocity, _) in (&mut velocity_storage, &controlled).join() {
velocity.set_y(-400.0);
}
}
if input.get_key(Scancode::Down).held {
for (velocity, _) in (&mut velocity_storage, &controlled).join() {
velocity.set_y(400.0);
}
}
if input.get_key(Scancode::Left).held {
for (velocity, _) in (&mut velocity_storage, &controlled).join() {
velocity.set_x(-400.0);
}
}
if input.get_key(Scancode::Right).held {
for (velocity, _) in (&mut velocity_storage, &controlled).join() {
velocity.set_x(400.0);
}
}
let should_fire = input.get_key(Scancode::Space).held;
if should_fire {
for (weapon, _) in (&mut weapon_storage, &controlled).join() {
weapon.command = WeaponFireCommand::FireOnce;
}
} else {
for (weapon, _) in (&mut weapon_storage, &controlled).join() {
weapon.command = WeaponFireCommand::Waiting;
}
}
}
}
|
extern crate advent_of_code_2017_day_4;
|
// SPDX-FileCopyrightText: 2020-2021 HH Partners
//
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Serialize};
use crate::Algorithm;
use super::{Checksum, FileType, SPDXExpression};
/// ## File Information
///
/// SPDX's [File Information](https://spdx.github.io/spdx-spec/4-file-information/)
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FileInformation {
/// https://spdx.github.io/spdx-spec/4-file-information/#41-file-name
pub file_name: String,
/// https://spdx.github.io/spdx-spec/4-file-information/#42-file-spdx-identifier
#[serde(rename = "SPDXID")]
pub file_spdx_identifier: String,
/// https://spdx.github.io/spdx-spec/4-file-information/#43-file-type
#[serde(rename = "fileTypes", skip_serializing_if = "Vec::is_empty", default)]
pub file_type: Vec<FileType>,
/// https://spdx.github.io/spdx-spec/4-file-information/#44-file-checksum
#[serde(rename = "checksums")]
pub file_checksum: Vec<Checksum>,
/// https://spdx.github.io/spdx-spec/4-file-information/#45-concluded-license
#[serde(rename = "licenseConcluded")]
pub concluded_license: SPDXExpression,
/// https://spdx.github.io/spdx-spec/4-file-information/#46-license-information-in-file
#[serde(rename = "licenseInfoInFiles")]
pub license_information_in_file: Vec<String>,
/// https://spdx.github.io/spdx-spec/4-file-information/#47-comments-on-license
#[serde(
rename = "licenseComments",
skip_serializing_if = "Option::is_none",
default
)]
pub comments_on_license: Option<String>,
/// https://spdx.github.io/spdx-spec/4-file-information/#48-copyright-text
pub copyright_text: String,
/// https://spdx.github.io/spdx-spec/4-file-information/#412-file-comment
#[serde(rename = "comment", skip_serializing_if = "Option::is_none", default)]
pub file_comment: Option<String>,
/// https://spdx.github.io/spdx-spec/4-file-information/#413-file-notice
#[serde(
rename = "noticeText",
skip_serializing_if = "Option::is_none",
default
)]
pub file_notice: Option<String>,
/// https://spdx.github.io/spdx-spec/4-file-information/#414-file-contributor
#[serde(
rename = "fileContributors",
skip_serializing_if = "Vec::is_empty",
default
)]
pub file_contributor: Vec<String>,
/// https://spdx.github.io/spdx-spec/4-file-information/#415-file-attribution-text
#[serde(skip_serializing_if = "Option::is_none", default)]
pub file_attribution_text: Option<Vec<String>>,
// TODO: Snippet Information.
}
impl Default for FileInformation {
fn default() -> Self {
Self {
file_name: "NOASSERTION".to_string(),
file_spdx_identifier: "NOASSERTION".to_string(),
file_type: Vec::new(),
file_checksum: Vec::new(),
concluded_license: SPDXExpression("NOASSERTION".to_string()),
license_information_in_file: Vec::new(),
comments_on_license: None,
copyright_text: "NOASSERTION".to_string(),
file_comment: None,
file_notice: None,
file_contributor: Vec::new(),
file_attribution_text: None,
}
}
}
impl FileInformation {
/// Create new file.
pub fn new(name: &str, id: &mut i32) -> Self {
*id += 1;
Self {
file_name: name.to_string(),
file_spdx_identifier: format!("SPDXRef-{}", id),
..Default::default()
}
}
/// Check if hash equals.
pub fn equal_by_hash(&self, algorithm: Algorithm, value: &str) -> bool {
let checksum = self
.file_checksum
.iter()
.find(|&checksum| checksum.algorithm == algorithm);
if let Some(checksum) = checksum {
checksum.value.to_ascii_lowercase() == value.to_ascii_lowercase()
} else {
false
}
}
/// Get checksum
pub fn checksum(&self, algorithm: Algorithm) -> Option<&str> {
let checksum = self
.file_checksum
.iter()
.find(|&checksum| checksum.algorithm == algorithm);
checksum.map(|checksum| checksum.value.as_str())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn checksum_equality() {
let mut id = 1;
let mut file_sha256 = FileInformation::new("sha256", &mut id);
file_sha256
.file_checksum
.push(Checksum::new(Algorithm::SHA256, "test"));
assert!(file_sha256.equal_by_hash(Algorithm::SHA256, "test"));
assert!(!file_sha256.equal_by_hash(Algorithm::SHA256, "no_test"));
let mut file_md5 = FileInformation::new("md5", &mut id);
file_md5
.file_checksum
.push(Checksum::new(Algorithm::MD5, "test"));
assert!(file_md5.equal_by_hash(Algorithm::MD5, "test"));
assert!(!file_md5.equal_by_hash(Algorithm::MD5, "no_test"));
assert!(!file_md5.equal_by_hash(Algorithm::SHA1, "test"));
}
#[test]
fn get_checksum() {
let mut id = 1;
let mut file_sha256 = FileInformation::new("sha256", &mut id);
file_sha256
.file_checksum
.push(Checksum::new(Algorithm::SHA256, "test"));
assert_eq!(file_sha256.checksum(Algorithm::SHA256), Some("test"));
assert_eq!(file_sha256.checksum(Algorithm::MD2), None);
let mut file_md5 = FileInformation::new("md5", &mut id);
file_md5
.file_checksum
.push(Checksum::new(Algorithm::MD5, "test"));
assert_eq!(file_md5.checksum(Algorithm::MD5), Some("test"));
}
}
|
//! Variable-width 64-bit little endian integers
use byteorder::{ByteOrder, LittleEndian};
/// Encode a 64-bit unsigned integer in zsuint64 form
pub fn encode(value: u64, out: &mut [u8]) -> usize {
let mut length = 1;
let mut result = (value << 1) | 1;
let mut max = 1 << 7;
while value >= max {
// 9-byte special case
if max == 1 << 63 {
out[0] = 0;
LittleEndian::write_u64(&mut out[1..9], value);
return 9;
}
result <<= 1;
max <<= 7;
length += 1;
}
LittleEndian::write_uint(out, result, length);
length
}
/// Decode a zsuint64-encoded unsigned 64-bit integer
pub fn decode(input: &mut &[u8]) -> Result<u64, ()> {
let bytes = *input;
let prefix = *bytes.first().ok_or(())?;
if prefix == 0 {
if bytes.len() >= 9 {
let result = LittleEndian::read_u64(&bytes[1..9]);
*input = &bytes[9..];
return Ok(result);
} else {
return Err(());
}
}
let count = prefix.trailing_zeros() as usize + 1;
if bytes.len() < count {
return Err(());
}
let result = LittleEndian::read_uint(bytes, count) >> count;
*input = &bytes[count..];
Ok(result)
}
#[cfg(test)]
mod tests {
#[cfg(feature = "bench")]
use leb128;
#[cfg(feature = "bench")]
use test::Bencher;
use varint;
#[test]
fn encode() {
let mut output = [0u8; 9];
// 0
assert_eq!(varint::encode(0, &mut output), 1);
assert_eq!(output, *b"\x01\0\0\0\0\0\0\0\0");
// 42
assert_eq!(varint::encode(42, &mut output), 1);
assert_eq!(output, *b"U\0\0\0\0\0\0\0\0");
// 127
assert_eq!(varint::encode(127, &mut output), 1);
assert_eq!(output, *b"\xFF\0\0\0\0\0\0\0\0");
// 128
assert_eq!(varint::encode(128, &mut output), 2);
assert_eq!(output, *b"\x02\x02\0\0\0\0\0\0\0");
// 2**42 - 1
assert_eq!(varint::encode(4398046511103, &mut output), 6);
assert_eq!(output, *b"\xE0\xFF\xFF\xFF\xFF\xFF\0\0\0");
// 2**42
assert_eq!(varint::encode(4398046511104, &mut output), 7);
assert_eq!(output, *b"@\x00\x00\x00\x00\x00\x02\0\0");
// 2**64-2
assert_eq!(varint::encode(18446744073709551614, &mut output), 9);
assert_eq!(output, *b"\x00\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF");
// 2**64-1
assert_eq!(varint::encode(18446744073709551615, &mut output), 9);
assert_eq!(output, *b"\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF");
}
#[test]
fn decode() {
let mut remaining;
// 0 with nothing trailing
let zero_nothing = b"\x01";
remaining = &zero_nothing[..];
assert_eq!(varint::decode(&mut remaining).unwrap(), 0);
assert_eq!(remaining, b"");
// 0 with trailing 0
let zero_trailing_zero = b"\x01\0";
remaining = &zero_trailing_zero[..];
assert_eq!(varint::decode(&mut remaining).unwrap(), 0);
assert_eq!(remaining, b"\0");
// 42 with trailing 0
let forty_two_trailing_zero = b"U\0";
remaining = &forty_two_trailing_zero[..];
assert_eq!(varint::decode(&mut remaining).unwrap(), 42);
assert_eq!(remaining, b"\0");
// 127 with trailing 0
let one_twenty_seven_trailing_zero = b"\xFF\0";
remaining = &one_twenty_seven_trailing_zero[..];
assert_eq!(varint::decode(&mut remaining).unwrap(), 127);
assert_eq!(remaining, b"\0");
// 128 with trailing 0
let one_twenty_eight_trailing_zero = b"\x02\x02\0";
remaining = &one_twenty_eight_trailing_zero[..];
assert_eq!(varint::decode(&mut remaining).unwrap(), 128);
assert_eq!(remaining, b"\0");
// 2**64-2 with trailing 0
let maxint_minus_one_trailing_zero = b"\x00\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\0";
remaining = &maxint_minus_one_trailing_zero[..];
assert_eq!(varint::decode(&mut remaining).unwrap(), 18446744073709551614);
assert_eq!(remaining, b"\0");
// 2**64-1 with trailing 0
let maxint_trailing_zero = b"\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\0";
remaining = &maxint_trailing_zero[..];
assert_eq!(varint::decode(&mut remaining).unwrap(), 18446744073709551615);
assert_eq!(remaining, b"\0");
}
#[cfg(feature = "bench")]
#[bench]
fn bench_encode(b: &mut Bencher) {
let mut output = [0u8; 9];
// 2**48 + 31337
b.iter(|| varint::encode(281474976741993, &mut output));
}
#[cfg(feature = "bench")]
#[bench]
fn bench_decode(b: &mut Bencher) {
let input = b"\xC04=\x00\x00\x00\x80";
// 2**48 + 31337
b.iter(|| {
let mut readable = &input[..];
varint::decode(&mut readable).unwrap()
});
}
#[cfg(feature = "bench")]
#[bench]
fn bench_leb128_encode(b: &mut Bencher) {
let mut output = [0u8; 9];
// 2**48 + 31337
b.iter(|| {
let mut writable = &mut output[..];
leb128::write::unsigned(&mut writable, 281474976741993).unwrap()
});
}
#[cfg(feature = "bench")]
#[bench]
fn bench_leb128_decode(b: &mut Bencher) {
let input = b"\xE9\xF4\x81\x80\x80\x80@";
// 2**48 + 31337
b.iter(|| {
let mut readable = &input[..];
leb128::read::unsigned(&mut readable).unwrap()
});
}
}
|
use graphics::tileset::TilesetDesc;
use tilemap::MapBuilder;
pub struct Tilesets {
pub tileset_descs: Vec<TilesetDesc>,
}
impl Tilesets {
pub fn empty() -> Self {
Tilesets {
tileset_descs: vec![],
}
}
pub fn build(builder: &mut MapBuilder) -> Self {
// Reborrow. `&mut *` can be removed if that's ever made implicit outside
// of function calls, or if closure captures of structs is ever made
// more fine-grained
let graphics = &mut *builder.graphics;
let tileset_descs = builder
.map
.tilesets
.iter()
.map(|tileset| TilesetDesc::load(graphics, tileset.clone()))
.collect();
Tilesets { tileset_descs }
}
}
|
mod errors;
mod hash_map;
mod taking_input;
mod traits;
mod triangle;
mod vectors;
use std::io::Write;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use crate::traits::GetInfo;
use anyhow::{Context, Result};
fn main() -> Result<()> {
let test_type: String = get_test_type();
if test_type == "1" {
let mut tri = triangle::Triangle::new(3, 4, 5);
println!(
"Sides are: {}, {}, and {}.",
tri.get_side_one(),
tri.get_side_two(),
tri.get_side_three()
);
println!("Is right: {}", tri.is_right());
println!("Is equilateral: {}", tri.is_equilateral());
println!("Is scalene: {}", tri.is_scalene());
println!("Is isosceles: {}", tri.is_isosceles());
tri.set_side_one(5);
tri.set_side_two(5);
tri.set_side_three(5);
println!(
"Sides are: {}, {}, and {}.",
tri.get_side_one(),
tri.get_side_two(),
tri.get_side_three()
);
} else if test_type == "2" {
// creates three new objects with the trait GetFullName
let man = traits::Person::new("Darren", "Capper", 27);
let canine = traits::Dog::new("Berk", "Bomber", 4);
let feline = traits::Cat::new("Vern", "MacCaster", 27);
// creates a vector of them and specifies that they share that trait,
// dynamically.
let group: Vec<&dyn GetInfo> = vec![&man, &canine, &feline];
// iterates over them and prints their names
for object in group.iter() {
println!("{}", object.get_full_name());
println!("{}", object.get_age());
}
} else if test_type == "3" {
// first two is the &str type, being immutable
let str_one = "Kitty";
let str_two = "Cat";
// last one is a String type and can be altered
let mut str_three = "".to_string();
// to add these together you must put the String type first
// then add the rest with the & in front of each one.
str_three = str_three + &str_one + &" " + &str_two;
println!("{}", str_three)
} else if test_type == "4" {
println!("What is your name?");
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("failed to real line");
// trim removes the newline on the players name.
println!("Hello, {}, what's your favorite number?", input.trim());
// gets the number from the player
let number: f64 = taking_input::get_number("Please enter a number.");
println!("I like, {} too.", number);
} else if test_type == "5" {
let number = errors::propagating_errors().context("Failed to convert to integer.")?;
println!("Converted number is {}", number);
} else if test_type == "6" {
let mut stdout = StandardStream::stdout(ColorChoice::Always);
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?;
//writeln!(&mut stdout,"{}", format!("{}", 5))?;
println!("color test");
stdout.reset()?;
println!("no color test")
} else if test_type == "7" {
let mut list: Vec<i32> = vec![12, 23, 4, 4, 1, 67, 78, 9, 91, 100];
let length = (list.len() -1) as i32;
//vectors::forward_dismantle_vec(list);
//vectors::selection_sort(list);
vectors::quick_sort(&mut list, 0, length);
vectors::print_vec(list);
} else {
println!("Not an Accepted Option.");
}
Ok(())
}
fn get_test_type() -> String {
// gets the second argument
let args = std::env::args().nth(1).unwrap_or_else(|| {
// if there is not a second one it defaults to 1
let val = "1".to_string();
val
});
args
}
|
pub mod scanner;
pub mod literal;
use literal::Literal;
#[derive(Debug, Clone)]
pub struct Token {
pub ttype: TokenType,
pub lexeme: String,
pub line: usize,
pub start: usize
}
impl Token {
pub fn new(ttype: TokenType, lexeme: String, line: usize, start: usize) -> Self {
Self {
ttype,
lexeme,
line,
start
}
}
pub fn to_string(&self) -> String {
match &self.ttype {
TokenType::Identifier => format!("{:?} {} ln{}", self.ttype, self.lexeme, self.line),
TokenType::Literal(lit) => format!("{:?} ln{}", lit, self.line),
_ => format!("{:?} ln{}", self.ttype, self.line),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum TokenType {
// Reserved symbols
Colon,
Period,
LeftBrace, RightBrace,
LeftParen, RightParen,
LeftSqBracket, RightSqBracket,
Carrot,
Pipe,
Semicolon,
// Reserved identifiers
// Symbolic
Equal,
RightArrow,
// Alphanumeric
Underscore,
Self_,
Asm,
// Literals
Literal(Literal),
// Index(u32),
Identifier,
// ScopedIdent,
End
} |
use serde::Serialize;
use serde_json::value::{to_value, Value as Json};
use serde_json::Map;
use crate::op::Op;
use crate::error::{Error, Result};
use crate::arg::Arg;
/// The Rule type, contains an `Expr`.
#[derive(Clone, Debug, PartialEq)]
pub struct Rule {
expr: Expr,
}
impl Rule {
/// Constructs a new `Rule` from a serde Json Value object.
pub fn new(val: Json) -> Result<Rule> {
Ok(Rule {
expr: Expr::new(val)?,
})
}
/// Constructs a new `Rule` from a rust object that implements the serde `Serialize` trait.
pub fn from_value<T: Serialize>(val: T) -> Result<Rule> {
Rule::new(to_value(val)?)
}
/// Constructs a new `Rule` from a json string.
pub fn from_str(s: &str) -> Result<Rule> {
Rule::new(serde_json::from_str(s)?)
}
/// Matches the rule with a context.
pub fn matches<T: Serialize>(&self, context: &T) -> Result<bool> {
self.expr.matches(context)?.as_bool().ok_or(Error::FinalResultNotBoolError)
}
}
/// The Expression type, contains a `Op` and a `Vec<Arg>`.
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct Expr {
op: Op,
args: Vec<Arg>,
}
impl Expr {
/// Constructs an new `Expr` from a serde Json Value object.
pub fn new(val: Json) -> Result<Expr> {
match val {
Json::Array(args) => {
Expr::from_vec(args)
},
_ => Err(Error::ExprIsNotArrayError),
}
}
/// Constructs an new `Expr` from a Vec of Json object.
pub fn from_vec(val: Vec<Json>) -> Result<Expr> {
let mut args: Vec<Arg> = val.into_iter().map(|x| Arg::from_json(x)).collect::<Result<Vec<_>>>()?;
let op_s = match args.remove(0) {
Arg::String(s) => s,
_ => return Err(Error::ExprOpIsNotStringError),
};
let op = match Op::get(&op_s) {
Some(v) => v,
None => return Err(Error::NoSuchOpError),
};
Ok(Expr { op: op.clone(), args: args })
}
/// Matches the expression with a Serialize context.
pub fn matches<T: Serialize>(&self, context: &T) -> Result<Arg> {
self.matches_json(&to_value(context)?)
}
/// Matches the expression with a Json context.
pub fn matches_json(&self, context: &Json) -> Result<Arg> {
self.matches_json_dict(context.as_object().ok_or(Error::ContextNotDictError)?)
}
/// Matches the expression with a Json Dict context.
pub fn matches_json_dict(&self, context: &Map<String, Json>) -> Result<Arg> {
let mut args = self.args.iter().map(|arg|
if let Arg::Expr(expr) = arg { expr.matches_json_dict(context) } else { Ok(arg.clone()) }
).collect::<Result<Vec<_>>>()?;
// println!("DEBUG: args: {:?}", args);
// println!("DEBUG: op: {:?}", self.op);
if &self.op.name == "var" {
// special op var
Arg::from_context_var(&args, context)
} else {
// always try first arg with context var
let var = Arg::from_context_var(&args, context);
if var.is_ok() {
args[0] = var?;
}
Ok((self.op.func)(args))
}
}
}
|
mod sql_test;
use apllodb_server::{test_support::test_setup, RecordIndex, SchemaIndex, SqlState};
use sql_test::{SqlTest, Step, StepRes, Steps};
#[ctor::ctor]
fn setup() {
test_setup();
}
#[async_std::test]
async fn test_select_with_various_field_spec() {
#[derive(Clone)]
struct TestDatum {
sql: &'static str,
index: SchemaIndex,
expected_result: Result<(), SqlState>,
}
let test_data = vec![
TestDatum {
sql: "SELECT id FROM people",
index: SchemaIndex::from("id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id FROM people",
index: SchemaIndex::from("people.id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id FROM people",
index: SchemaIndex::from("xxx"),
expected_result: Err(SqlState::NameErrorNotFound),
},
TestDatum {
sql: "SELECT id FROM people",
index: SchemaIndex::from("people.xxx"),
expected_result: Err(SqlState::NameErrorNotFound),
},
TestDatum {
sql: "SELECT id FROM people",
index: SchemaIndex::from("xxx.id"),
expected_result: Err(SqlState::NameErrorNotFound),
},
TestDatum {
sql: "SELECT people.id FROM people",
index: SchemaIndex::from("id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT people.id FROM people",
index: SchemaIndex::from("people.id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id FROM people t_alias",
index: SchemaIndex::from("id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id FROM people t_alias",
index: SchemaIndex::from("people.id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id FROM people t_alias",
index: SchemaIndex::from("t_alias.id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id c_alias FROM people",
index: SchemaIndex::from("id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id c_alias FROM people",
index: SchemaIndex::from("c_alias"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id c_alias FROM people",
index: SchemaIndex::from("people.id"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id c_alias FROM people",
index: SchemaIndex::from("people.c_alias"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id c_alias FROM people t_alias",
index: SchemaIndex::from("c_alias"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id c_alias FROM people t_alias",
index: SchemaIndex::from("people.c_alias"),
expected_result: Ok(()),
},
TestDatum {
sql: "SELECT id c_alias FROM people t_alias",
index: SchemaIndex::from("t_alias.c_alias"),
expected_result: Ok(()),
},
];
let mut sql_test = SqlTest::default()
.add_steps(Steps::SetupPeopleDataset)
.add_step(Step::new("BEGIN", StepRes::Ok));
for test_datum in test_data {
sql_test = sql_test.add_step(Step::new(
test_datum.sql,
StepRes::OkQuery(Box::new(move |mut records| {
let r = records.next().unwrap();
match r.get::<i64>(&RecordIndex::Name(test_datum.clone().index)) {
Ok(_) => assert!(
test_datum.expected_result.is_ok(),
"SchemaIndex `{:?}` should be valid for Record::get() with this SQL: {}",
test_datum.index,
test_datum.sql
),
Err(e) => {
println!("{}", e);
assert_eq!(
e.kind(),
&test_datum.clone().expected_result.unwrap_err(),
"SchemaIndex: `{:?}`, SQL: {}",
test_datum.index,
test_datum.sql
)
}
}
Ok(())
})),
));
}
sql_test.run().await;
}
|
use particle::collide::collide::Collider;
use sack::{SackType, SackBacker, Sack};
/// An important special case of a Collider is where a sack is absorbed into another one without
/// changing the type signature of the original
pub trait Absorber<'a, C1: 'a, C2: 'a, D1: 'a, D2: 'a, B1: 'a, B2: 'a, T1: 'a>
: Collider<'a, C1, C2, C1, (), D1, D2, D1, (), B1, B2, B1, (), T1, (), T1, ()>
where B1: SackBacker,
B2: SackBacker
{
fn absorb(s1: Sack<C1, D1, B1, T1>, s2: Sack<C2, D2, B2>) -> Self;
}
|
pub mod parser;
pub mod info;
pub fn run(tickers: Vec<String>) {
let parser = parser::Parser{tickers: tickers};
println!("{:#?}", parser.parse());
}
|
mod repl;
pub use repl::*;
|
use crate::io::request::*;
use crate::io::Core;
use crate::{
BuildDeferredQueryIndexOptions, CouchbaseError, CouchbaseResult,
CreatePrimaryQueryIndexOptions, CreateQueryIndexOptions, DropPrimaryQueryIndexOptions,
DropQueryIndexOptions, ErrorContext, GetAllQueryIndexOptions, QueryOptions,
WatchIndexesQueryIndexOptions,
};
use futures::channel::oneshot;
use futures::StreamExt;
use serde_derive::Deserialize;
use std::ops::Add;
use std::sync::Arc;
use std::thread::sleep;
use std::time::{Duration, Instant};
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum QueryIndexType {
#[serde(rename = "view")]
VIEW,
#[serde(rename = "gsi")]
GSI,
}
#[derive(Debug, Clone, Deserialize)]
pub struct QueryIndex {
name: String,
#[serde(default)]
is_primary: bool,
using: QueryIndexType,
state: String,
#[serde(rename = "keyspace_id")]
keyspace: String,
index_key: Vec<String>,
condition: Option<String>,
partition: Option<String>,
}
impl QueryIndex {
pub fn name(&self) -> &str {
&self.name
}
pub fn is_primary(&self) -> bool {
self.is_primary
}
pub fn using(&self) -> QueryIndexType {
self.using
}
pub fn state(&self) -> &str {
&self.state
}
pub fn keyspace(&self) -> &str {
&self.name
}
pub fn index_key(&self) -> &Vec<String> {
&self.index_key
}
pub fn condition(&self) -> Option<&String> {
self.condition.as_ref()
}
pub fn partition(&self) -> Option<&String> {
self.partition.as_ref()
}
}
pub struct QueryIndexManager {
core: Arc<Core>,
}
impl QueryIndexManager {
pub(crate) fn new(core: Arc<Core>) -> Self {
Self { core }
}
pub async fn get_all_indexes(
&self,
bucket_name: impl Into<String>,
opts: GetAllQueryIndexOptions,
) -> CouchbaseResult<impl IntoIterator<Item = QueryIndex>> {
let statement = format!("SELECT idx.* FROM system:indexes AS idx WHERE keyspace_id = \"{}\" AND `using`=\"gsi\" ORDER BY is_primary DESC, name ASC", bucket_name.into());
let (sender, receiver) = oneshot::channel();
self.core.send(Request::Query(QueryRequest {
statement: statement.into(),
options: QueryOptions::from(&opts),
sender,
scope: None,
}));
let mut result = receiver.await.unwrap()?;
let mut indexes = vec![];
let mut rows = result.rows::<QueryIndex>();
while let Some(index) = rows.next().await {
indexes.push(index?);
}
Ok(indexes)
}
pub async fn create_index(
&self,
bucket_name: impl Into<String>,
index_name: impl Into<String>,
fields: impl IntoIterator<Item = impl Into<String>>,
opts: CreateQueryIndexOptions,
) -> CouchbaseResult<()> {
let mut statement = format!(
"CREATE INDEX `{}` ON `{}` ({})",
index_name.into(),
bucket_name.into(),
fields
.into_iter()
.map(|field| field.into())
.collect::<Vec<String>>()
.join(",")
);
let with = opts.with.to_string();
if !with.is_empty() {
statement = format!("{} WITH {}", statement, with);
}
let (sender, receiver) = oneshot::channel();
self.core.send(Request::Query(QueryRequest {
statement: statement.into(),
options: QueryOptions::from(&opts),
sender,
scope: None,
}));
let result_err = receiver.await.unwrap().err();
if let Some(e) = result_err {
if opts.ignore_exists.unwrap_or_else(|| false) {
match e {
CouchbaseError::IndexExists { ctx: _ } => Ok(()),
_ => Err(e),
}
} else {
Err(e)
}
} else {
Ok(())
}?;
Ok(())
}
pub async fn create_primary_index(
&self,
bucket_name: impl Into<String>,
opts: CreatePrimaryQueryIndexOptions,
) -> CouchbaseResult<()> {
let mut statement = match &opts.name {
Some(n) => {
format!("CREATE PRiMARY INDEX `{}` ON `{}`", n, bucket_name.into())
}
None => format!("CREATE PRIMARY INDEX ON `{}`", bucket_name.into()),
};
let with = opts.with.to_string();
if !with.is_empty() {
statement = format!("{} WITH {}", statement, with);
}
let (sender, receiver) = oneshot::channel();
self.core.send(Request::Query(QueryRequest {
statement: statement.into(),
options: QueryOptions::from(&opts),
sender,
scope: None,
}));
let result_err = receiver.await.unwrap().err();
if let Some(e) = result_err {
if opts.ignore_exists.unwrap_or_else(|| false) {
match e {
CouchbaseError::IndexExists { ctx: _ctx } => Ok(()),
_ => Err(e),
}
} else {
Err(e)
}
} else {
Ok(())
}?;
Ok(())
}
pub async fn drop_index(
&self,
bucket_name: impl Into<String>,
index_name: impl Into<String>,
opts: DropQueryIndexOptions,
) -> CouchbaseResult<()> {
let statement = format!(
"DROP INDEX `{}` ON `{}`",
index_name.into(),
bucket_name.into()
);
let (sender, receiver) = oneshot::channel();
self.core.send(Request::Query(QueryRequest {
statement: statement.into(),
options: QueryOptions::from(&opts),
sender,
scope: None,
}));
let result_err = receiver.await.unwrap().err();
if let Some(e) = result_err {
if opts.ignore_not_exists.unwrap_or_else(|| false) {
match e {
CouchbaseError::IndexNotFound { ctx: _ctx } => Ok(()),
_ => Err(e),
}
} else {
Err(e)
}
} else {
Ok(())
}?;
Ok(())
}
pub async fn drop_primary_index(
&self,
bucket_name: impl Into<String>,
opts: DropPrimaryQueryIndexOptions,
) -> CouchbaseResult<()> {
let statement = match &opts.name {
Some(n) => {
format!("DROP INDEX `{}` ON `{}`", n, bucket_name.into())
}
None => format!("DROP PRIMARY INDEX ON `{}`", bucket_name.into()),
};
let (sender, receiver) = oneshot::channel();
self.core.send(Request::Query(QueryRequest {
statement: statement.into(),
options: QueryOptions::from(&opts),
sender,
scope: None,
}));
let result_err = receiver.await.unwrap().err();
if let Some(e) = result_err {
if opts.ignore_not_exists.unwrap_or_else(|| false) {
match e {
CouchbaseError::IndexNotFound { ctx: _ctx } => Ok(()),
_ => Err(e),
}
} else {
Err(e)
}
} else {
Ok(())
}?;
Ok(())
}
pub async fn watch_indexes(
&self,
bucket_name: impl Into<String>,
index_names: impl IntoIterator<Item = impl Into<String>>,
timeout: Duration,
opts: WatchIndexesQueryIndexOptions,
) -> CouchbaseResult<()> {
let bucket_name = bucket_name.into();
let mut indexes: Vec<String> = index_names.into_iter().map(|index| index.into()).collect();
if let Some(w) = opts.watch_primary {
if w {
indexes.push(String::from("#primary"));
}
}
let interval = Duration::from_millis(50);
let deadline = Instant::now().add(timeout);
loop {
if Instant::now() > deadline {
return Err(CouchbaseError::Timeout {
ambiguous: false,
ctx: ErrorContext::default(),
});
}
let all_indexes = self
.get_all_indexes(
bucket_name.clone(),
GetAllQueryIndexOptions::default().timeout(deadline - Instant::now()),
)
.await?;
let all_online = self.check_indexes_online(all_indexes, &indexes)?;
if all_online {
break;
}
let now = Instant::now();
let mut sleep_deadline = now.add(interval);
if sleep_deadline > deadline {
sleep_deadline = deadline;
}
sleep(sleep_deadline - now);
}
Ok(())
}
pub async fn build_deferred_indexes(
&self,
bucket_name: impl Into<String>,
opts: BuildDeferredQueryIndexOptions,
) -> CouchbaseResult<impl IntoIterator<Item = String>> {
let bucket_name = bucket_name.into();
let indexes = self
.get_all_indexes(bucket_name.clone(), GetAllQueryIndexOptions::from(&opts))
.await?;
let mut deferred_list = vec![];
for index in indexes {
if index.state == "deferred" || index.state == "pending" {
deferred_list.push(index.name);
}
}
if deferred_list.is_empty() {
return Ok(deferred_list);
}
let escaped: Vec<String> = deferred_list
.clone()
.into_iter()
.map(|i| format!("`{}`", i))
.collect();
let statement = format!("BUILD INDEX ON `{}` ({})", bucket_name, escaped.join(","));
let (sender, receiver) = oneshot::channel();
self.core.send(Request::Query(QueryRequest {
statement: statement.into(),
options: QueryOptions::from(&opts),
sender,
scope: None,
}));
receiver.await.unwrap()?;
Ok(deferred_list)
}
fn check_indexes_online(
&self,
all_indexes: impl IntoIterator<Item = QueryIndex>,
watch_indexes: &Vec<String>,
) -> CouchbaseResult<bool> {
let mut checked_indexes = vec![];
for index in all_indexes.into_iter() {
for watch in watch_indexes {
if index.name() == watch.clone() {
checked_indexes.push(index);
break;
}
}
}
if checked_indexes.len() != watch_indexes.len() {
return Err(CouchbaseError::IndexNotFound {
ctx: ErrorContext::default(),
});
}
for index in checked_indexes {
if index.state() != String::from("online") {
return Ok(false);
}
}
Ok(true)
}
}
|
use serde_derive::Deserialize;
use serde_json::json;
use lambda_http::{lambda, Body, IntoResponse, Request, RequestExt, Response};
use lambda_runtime::{error::HandlerError, Context};
use rand::distributions::StandardNormal;
use rand::{thread_rng, Rng};
use rayon::prelude::*;
use std::collections::HashMap;
use std::error::Error;
use std::f64;
fn build_response(code: u16, body: &str) -> impl IntoResponse {
Response::builder()
.status(code)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Credentials", "true")
.body::<Body>(body.into())
.unwrap()
}
fn construct_error(e_message: &str) -> String {
json!({ "err": e_message }).to_string()
}
fn yield_curve(curr_rate: f64, a: f64, b: f64, sig: f64) -> impl Fn(f64) -> f64 {
move |t| {
let at = (1.0 - (-a * t).exp()) / a;
let ct =
(b - sig.powi(2) / (2.0 * a.powi(2))) * (at - t) - sig.powi(2) * at.powi(2) / (4.0 * a);
at * curr_rate - ct
}
}
fn forward_curve(curr_rate: f64, a: f64, b: f64, sig: f64) -> impl Fn(f64) -> f64 {
move |t| {
let tmp = (-a * t).exp();
b + tmp * (curr_rate - b) - (sig.powi(2) / (2.0 * a.powi(2))) * (1.0 - tmp).powi(2)
}
}
fn generate_vasicek(curr_rate: f64, a: f64, b: f64, sig: f64, t: f64) -> impl Fn(f64) -> f64 {
let tmp = (-a * t).exp();
let mu = b * (1.0 - tmp) + curr_rate * tmp;
let vol = sig * ((1.0 - (-2.0 * a * t).exp()) / (2.0 * a)).sqrt();
move |random_number| mu + vol * random_number
}
const NUM_SIMS: usize = 500;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct BondParameters {
t: f64, //in days
r0: f64,
a: f64,
b: f64,
sigma: f64,
maturity: f64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct EDFParameters {
t: f64, //in days
r0: f64,
a: f64,
b: f64,
sigma: f64,
maturity: f64,
tenor: f64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct BondOptionParameters {
t: f64, //in days
r0: f64,
a: f64,
b: f64,
sigma: f64,
maturity: f64,
underlying_maturity: f64,
strike: f64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CapletParameters {
t: f64, //in days
r0: f64,
a: f64,
b: f64,
sigma: f64,
maturity: f64,
tenor: f64,
strike: f64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SwapParameters {
t: f64, //in days
r0: f64,
a: f64,
b: f64,
sigma: f64,
maturity: f64,
tenor: f64,
swap_rate: f64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SwaptionParameters {
t: f64, //in days
r0: f64,
a: f64,
b: f64,
sigma: f64,
maturity: f64,
tenor: f64,
swap_tenor: f64,
swap_rate: f64,
}
fn bin(min: f64, max: f64, num_bins: f64, elements: &[f64]) -> HashMap<String, usize> {
let mut bins = HashMap::new();
let range = max - min;
let bin_width = range / num_bins;
for element in elements.iter() {
let key = if element == &max {
format!("{:.4}-{:.4}", max - bin_width, max)
} else {
let lower_index = ((element - min) / bin_width).floor();
let lower_bound = lower_index * bin_width + min;
let upper_bound = (lower_index + 1.0) * bin_width + min;
format!("{:.4}-{:.4}", lower_bound, upper_bound)
};
if let Some(x) = bins.get_mut(&key) {
*x += 1;
} else {
bins.insert(key, 1);
}
}
bins
}
fn combine_and_bin(min: f64, max: f64, elements: &[f64]) -> HashMap<String, usize> {
let num_bins = (2.0 * (elements.len() as f64).powf(1.0 / 3.0)).floor();
bin(min, max, num_bins, elements)
}
fn main() -> Result<(), Box<dyn Error>> {
lambda!(market_faas_wrapper);
Ok(())
}
fn market_faas_wrapper(event: Request, _ctx: Context) -> Result<impl IntoResponse, HandlerError> {
match market_faas(event) {
Ok(res) => Ok(build_response(200, &json!(res).to_string())),
Err(e) => Ok(build_response(400, &construct_error(&e.to_string()))),
}
}
fn mc_results<T>(num_sims: usize, func_to_sim: T) -> Vec<f64>
where
T: Fn(f64) -> f64 + std::marker::Sync,
{
let normal = StandardNormal;
(0..num_sims)
.into_par_iter()
.map(|_index| {
let norm = thread_rng().sample(normal);
func_to_sim(norm)
})
.collect()
}
fn min_v(results: &[f64]) -> f64 {
results.iter().fold(f64::INFINITY, |a, &b| a.min(b))
}
fn max_v(results: &[f64]) -> f64 {
results.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b))
}
fn mc<T>(num_sims: usize, func_to_sim: T) -> HashMap<String, usize>
where
T: Fn(f64) -> f64 + std::marker::Sync,
{
let results = mc_results(num_sims, &func_to_sim);
let min = min_v(&results);
let max = max_v(&results);
combine_and_bin(min, max, &results)
}
//simplistic, but good enough
fn transform_days_to_year(t: f64) -> f64 {
t / 365.0
}
fn bond(event: Request) -> Result<HashMap<String, usize>, Box<dyn Error>> {
let BondParameters {
t,
r0,
a,
b,
maturity,
sigma,
} = serde_json::from_reader(event.body().as_ref())?;
let t = transform_days_to_year(t);
let yield_fn = yield_curve(r0, a, b, sigma);
let forward_fn = forward_curve(r0, a, b, sigma);
let simulation = generate_vasicek(r0, a, b, sigma, t);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::bond_price_t(r_t, a, sigma, t, maturity, &yield_fn, &forward_fn)
};
Ok(mc(NUM_SIMS, &func_to_sim))
}
fn market_faas(event: Request) -> Result<HashMap<String, usize>, Box<dyn Error>> {
let path_parameters = event.path_parameters();
let asset = path_parameters.get("asset").unwrap_or("bond");
let histogram = match asset {
"bond" => bond(event)?,
"edf" => {
let EDFParameters {
t,
r0,
a,
b,
maturity,
sigma,
tenor,
} = serde_json::from_reader(event.body().as_ref())?;
let t = transform_days_to_year(t);
let yield_fn = yield_curve(r0, a, b, sigma);
let forward_fn = forward_curve(r0, a, b, sigma);
let simulation = generate_vasicek(r0, a, b, sigma, t);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::euro_dollar_future_t(
r_t,
a,
sigma,
t,
maturity,
tenor,
&yield_fn,
&forward_fn,
)
};
mc(NUM_SIMS, &func_to_sim)
}
"bondcall" => {
let BondOptionParameters {
t,
r0,
a,
b,
maturity,
sigma,
underlying_maturity,
strike,
} = serde_json::from_reader(event.body().as_ref())?;
let t = transform_days_to_year(t);
let yield_fn = yield_curve(r0, a, b, sigma);
let forward_fn = forward_curve(r0, a, b, sigma);
let simulation = generate_vasicek(r0, a, b, sigma, t);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::bond_call_t(
r_t,
a,
sigma,
t,
maturity,
underlying_maturity,
strike,
&yield_fn,
&forward_fn,
)
};
mc(NUM_SIMS, &func_to_sim)
}
"bondput" => {
let BondOptionParameters {
t,
r0,
a,
b,
maturity,
sigma,
underlying_maturity,
strike,
} = serde_json::from_reader(event.body().as_ref())?;
let t = transform_days_to_year(t);
let yield_fn = yield_curve(r0, a, b, sigma);
let forward_fn = forward_curve(r0, a, b, sigma);
let simulation = generate_vasicek(r0, a, b, sigma, t);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::bond_put_t(
r_t,
a,
sigma,
t,
maturity,
underlying_maturity,
strike,
&yield_fn,
&forward_fn,
)
};
mc(NUM_SIMS, &func_to_sim)
}
"caplet" => {
let CapletParameters {
t,
r0,
a,
b,
maturity,
sigma,
strike,
tenor,
} = serde_json::from_reader(event.body().as_ref())?;
let t = transform_days_to_year(t);
let yield_fn = yield_curve(r0, a, b, sigma);
let forward_fn = forward_curve(r0, a, b, sigma);
let simulation = generate_vasicek(r0, a, b, sigma, t);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::caplet_t(
r_t,
a,
sigma,
t,
maturity,
tenor,
strike,
&yield_fn,
&forward_fn,
)
};
mc(NUM_SIMS, &func_to_sim)
}
"swap" => {
let SwapParameters {
t,
r0,
a,
b,
maturity,
sigma,
swap_rate,
tenor,
} = serde_json::from_reader(event.body().as_ref())?;
let t = transform_days_to_year(t);
let yield_fn = yield_curve(r0, a, b, sigma);
let forward_fn = forward_curve(r0, a, b, sigma);
let simulation = generate_vasicek(r0, a, b, sigma, t);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::swap_price_t(
r_t,
a,
sigma,
t,
maturity,
tenor,
swap_rate,
&yield_fn,
&forward_fn,
)
};
mc(NUM_SIMS, &func_to_sim)
}
"swaption" => {
let SwaptionParameters {
t,
r0,
a,
b,
maturity,
sigma,
swap_rate,
tenor,
swap_tenor,
} = serde_json::from_reader(event.body().as_ref())?;
let t = transform_days_to_year(t);
let yield_fn = yield_curve(r0, a, b, sigma);
let forward_fn = forward_curve(r0, a, b, sigma);
let simulation = generate_vasicek(r0, a, b, sigma, t);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::european_payer_swaption_t(
r_t,
a,
sigma,
t,
swap_tenor,
maturity,
tenor,
swap_rate,
&yield_fn,
&forward_fn,
)
};
mc(NUM_SIMS, &func_to_sim)
}
"americanswaption" => {
let SwaptionParameters {
t,
r0,
a,
b,
maturity,
sigma,
swap_rate,
tenor,
swap_tenor,
} = serde_json::from_reader(event.body().as_ref())?;
let t = transform_days_to_year(t);
let yield_fn = yield_curve(r0, a, b, sigma);
let forward_fn = forward_curve(r0, a, b, sigma);
let simulation = generate_vasicek(r0, a, b, sigma, t);
let num_tree = 100;
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::american_payer_swaption_t(
r_t,
a,
sigma,
t,
swap_tenor,
maturity,
tenor,
swap_rate,
num_tree,
&yield_fn,
&forward_fn,
)
};
mc(NUM_SIMS, &func_to_sim)
}
_ => {
//I wish the compiler was smarter than this...we know it wont get here
bond(event)?
}
};
Ok(histogram)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_histogram() {
let histogram = bin(5.0, 8.0, 2.0, &vec![5.0, 8.0, 7.0]);
assert_eq!(histogram.contains_key("5.0000-6.5000"), true);
assert_eq!(histogram.contains_key("6.5000-8.0000"), true);
assert_eq!(histogram.get("5.0000-6.5000").unwrap(), &1);
assert_eq!(histogram.get("6.5000-8.0000").unwrap(), &2);
}
#[test]
fn test_histogram_edge() {
let histogram = bin(5.0, 8.0, 2.0, &vec![5.0, 8.0, 6.5]);
assert_eq!(histogram.contains_key("5.0000-6.5000"), true);
assert_eq!(histogram.contains_key("6.5000-8.0000"), true);
assert_eq!(histogram.get("5.0000-6.5000").unwrap(), &1);
assert_eq!(histogram.get("6.5000-8.0000").unwrap(), &2);
}
#[test]
fn test_histogram_edge_2() {
let histogram = bin(5.0, 8.0, 2.0, &vec![5.0, 8.0, 6.499]);
assert_eq!(histogram.contains_key("5.0000-6.5000"), true);
assert_eq!(histogram.contains_key("6.5000-8.0000"), true);
assert_eq!(histogram.get("5.0000-6.5000").unwrap(), &2);
assert_eq!(histogram.get("6.5000-8.0000").unwrap(), &1);
}
#[test]
fn vasicek_simulation() {
let r = 0.04;
let a = 0.3;
let b = 0.05;
let sig = 0.001; //to ensure not too great variability
let t = 50.0;
let simulation = generate_vasicek(r, a, b, sig, t);
let n = 500;
let results = mc_results(n, &simulation);
let average_result = results.iter().fold(0.0, |a, b| a + b) / (n as f64);
println!("this is average: {}", average_result);
assert_eq!(average_result < 0.052, true);
assert_eq!(average_result > 0.048, true);
}
#[test]
fn bond_simulation() {
let r = 0.04;
let a = 0.3;
let b = 0.05;
let sig = 0.001; //to ensure not too great variability
let t = transform_days_to_year(10.0);
let maturity = 1.0;
let simulation = generate_vasicek(r, a, b, sig, t);
let yield_fn = yield_curve(r, a, b, sig);
let forward_fn = forward_curve(r, a, b, sig);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::bond_price_t(r_t, a, sig, t, maturity, &yield_fn, &forward_fn)
};
let n = 500;
let results = mc_results(n, &func_to_sim);
let average_result = results.iter().fold(0.0, |a, b| a + b) / (n as f64);
println!("this is average: {}", average_result);
assert_eq!(average_result < 0.961, true);
assert_eq!(average_result > 0.960, true);
}
#[test]
fn edf_simulation() {
let r = 0.04;
let a = 0.3;
let b = 0.05;
let sig = 0.001; //to ensure not too great variability
let t = transform_days_to_year(10.0);
let maturity = 1.0;
let delta = 0.25;
let simulation = generate_vasicek(r, a, b, sig, t);
let yield_fn = yield_curve(r, a, b, sig);
let forward_fn = forward_curve(r, a, b, sig);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::euro_dollar_future_t(
r_t,
a,
sig,
t,
maturity,
delta,
&yield_fn,
&forward_fn,
)
};
let n = 500;
let results = mc_results(n, &func_to_sim);
let average_result = results.iter().fold(0.0, |a, b| a + b) / (n as f64);
println!("this is average: {}", average_result);
assert_eq!(average_result < 0.044, true);
assert_eq!(average_result > 0.042, true);
}
#[test]
fn bondcall_simulation() {
let r = 0.04;
let a = 0.3;
let b = 0.05;
let sig = 0.001; //to ensure not too great variability
let t = transform_days_to_year(10.0);
let maturity = 1.0;
let bond_maturity = 1.25;
let strike = 0.97;
let simulation = generate_vasicek(r, a, b, sig, t);
let yield_fn = yield_curve(r, a, b, sig);
let forward_fn = forward_curve(r, a, b, sig);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::bond_call_t(
r_t,
a,
sig,
t,
maturity,
bond_maturity,
strike,
&yield_fn,
&forward_fn,
)
};
let n = 500;
let results = mc_results(n, &func_to_sim);
let average_result = results.iter().fold(0.0, |a, b| a + b) / (n as f64);
println!("this is average: {}", average_result);
assert_eq!(average_result < 0.019, true);
assert_eq!(average_result > 0.017, true);
}
#[test]
fn bondput_simulation() {
let r = 0.04;
let a = 0.3;
let b = 0.05;
let sig = 0.001; //to ensure not too great variability
let t = transform_days_to_year(10.0);
let maturity = 1.0;
let bond_maturity = 1.25;
let strike = 0.995;
let simulation = generate_vasicek(r, a, b, sig, t);
let yield_fn = yield_curve(r, a, b, sig);
let forward_fn = forward_curve(r, a, b, sig);
let func_to_sim = |random_number: f64| {
let r_t = simulation(random_number);
hull_white::bond_put_t(
r_t,
a,
sig,
t,
maturity,
bond_maturity,
strike,
&yield_fn,
&forward_fn,
)
};
let n = 500;
let results = mc_results(n, &func_to_sim);
let average_result = results.iter().fold(0.0, |a, b| a + b) / (n as f64);
println!("this is average: {}", average_result);
assert_eq!(average_result < 0.006, true);
assert_eq!(average_result > 0.005, true);
}
#[test]
fn min_v_test() {
let v = vec![4.0, 2.0, 5.0];
let result = min_v(&v);
assert_eq!(result, 2.0);
}
#[test]
fn max_v_test() {
let v = vec![4.0, 2.0, 5.0];
let result = max_v(&v);
assert_eq!(result, 5.0);
}
}
|
mod selection;
use std::{cell::Cell, rc::Rc};
pub use self::selection::Selection;
use super::{Theme, WidgetCommon, Widgetlike};
pub struct UISource {
selection: Cell<Selection>,
layout_token: Cell<u64>,
theme: Cell<Theme>,
}
#[derive(Clone)]
pub struct UI {
state: Rc<UISource>,
context: UIContext,
}
impl UI {
pub fn new(theme: Theme) -> UI {
UI {
state: Rc::new(UISource {
selection: Cell::new(Selection::none()),
layout_token: Cell::new(0),
theme: Cell::new(theme),
}),
context: UIContext::new(),
}
}
pub fn share(&self) -> UI {
UI { state: self.state.clone(), context: self.context }
}
pub fn theme(&self) -> Theme {
self.state.theme.get()
}
pub fn select<T: Widgetlike>(&self, widg: &mut WidgetCommon<T>) {
self.state.selection.replace(self.state.selection.get().advance());
widg.selection = self.state.selection.get();
}
pub fn deselect<T: Widgetlike>(&self, _widg: &mut WidgetCommon<T>) {
self.state.selection.replace(self.state.selection.get().advance());
}
pub fn is_selected(&self, other: Selection) -> bool {
self.state.selection.get() == other
}
pub fn recompute_layout(&self) {
self.state.layout_token.replace(self.state.layout_token.get() + 1);
}
pub(in crate) fn layout_token(&self) -> u64 {
self.state.layout_token.get()
}
pub fn with_context(mut self, on_ctx: impl FnOnce(&mut UIContext)) -> UI {
on_ctx(&mut self.context);
self
}
pub fn context(&self) -> UIContext {
self.context
}
}
#[derive(Clone, Copy)]
pub struct UIContext {
pub active: bool,
}
impl UIContext {
pub fn new() -> UIContext {
UIContext {
active: true,
}
}
} |
use chrono::{Datelike, Timelike};
pub struct Macro {
pub name: String,
pub value: String
}
impl Macro {
pub fn predefine_all(file: &str) {
Self::add("__STDC__", "1");
Self::add("__STDC_VERSION__", "199901");
Self::add("__RUST__", "");
Self::add("__qas_minor__", "0");
Self::add("__qas_major__", "0");
Self::add("__qas_patch__", "0");
#[cfg(target_os = "linux")]
Self::add("__linux__", "");
unsafe {
FILE = format!("\"{}\"", std::fs::canonicalize(file).unwrap().as_path().to_str().unwrap());
LINE = 1
}
#[cfg(not(debug_assertions))]
Self::add("NDEBUG", "");
let now = chrono::Local::now();
Self::add("__DATE__", format!("\"{} {:02} {}\"", match now.month0() {
0 => "Jan",
1 => "Feb",
2 => "Mar",
3 => "Apr",
4 => "May",
5 => "Jun",
6 => "Jul",
7 => "Aug",
8 => "Sep",
9 => "Oct",
10 => "Nov",
11 => "Dec",
_ => unreachable!()
}, now.day(), now.year()));
Self::add("__TIME__", format!("\"{:02}:{:02}:{:02}\"", now.hour(), now.minute(), now.second()));
}
#[inline]
pub fn macros() -> &'static mut Vec <Macro> {
static mut MACROS: Vec <Macro> = Vec::new();
unsafe { &mut MACROS }
}
pub fn is_defined(name: &str) -> bool {
Self::find(name).is_some()
}
pub fn add <S1: ToString, S2: ToString> (name: S1, value: S2) {
fn _add(name: String, value: String) {
match Macro::macros().iter_mut().find(|x| x.name == name) {
Some(m) => m.value = value,
None => Macro::macros().push(Macro { name, value })
}
}
_add(name.to_string(), value.to_string())
}
pub fn find(name: &str) -> Option <String> {
Self::macros().iter().find(|x| x.name == name).map(|x| x.value.clone())
}
}
pub static mut LINE: usize = 1;
pub static mut FILE: String = String::new();
|
extern crate hyper;
extern crate hyper_tls;
extern crate reqwest;
extern crate serde;
extern crate serde_json;
use hyper::rt::{self, run, Future, Stream};
use hyper::Client;
use hyper::{Body, Chunk, Error, Method, Request, Response, Server, StatusCode};
use serde_json::Value;
use chrono::prelude::*;
use hyper::client::{Builder, HttpConnector, ResponseFuture};
use std::io::{self, Write};
use std::mem;
use std::rc::Rc;
use std::string;
use std::sync::{Arc, Mutex};
#[derive(Debug, Serialize, Deserialize)]
pub struct Token {
pub access_token: String,
expires_in: i64,
}
impl Token {
pub fn new() -> Token {
Token {
access_token: String::from(""),
expires_in: 0,
}
}
pub fn fresh_token(&mut self, ak: &str, sk: &str, ut: &mut i64) {
let url = format!(
"https://aip.baidubce.com/oauth/2.0/token?\
grant_type=client_credentials&client_id={client_id}&\
client_secret={client_secret}",
client_id = ak,
client_secret = sk
);
let client = reqwest::Client::new();
let mut res = client.post(&url).send().unwrap();
let v: Token = serde_json::from_str(&res.text().unwrap()).unwrap();
self.access_token = v.access_token;
self.expires_in = v.expires_in;
*ut = Utc::now().timestamp();
}
pub fn get_token(&mut self, ak: &str, sk: &str, ut: &mut i64) -> String {
let now = Utc::now().timestamp();
if self.access_token.is_empty() {
self.fresh_token(ak, sk, ut);
} else if *ut + self.expires_in + 300 > now {
self.fresh_token(ak, sk, ut);
}
self.access_token.clone()
}
}
#[derive(Debug)]
pub struct Baidu {
ak: String,
sk: String,
pub token: Token,
pub update_time: i64,
pub client: Client<hyper_tls::HttpsConnector<hyper::client::HttpConnector>>,
}
impl Baidu {
pub fn new(ak: &str, sk: &str) -> Baidu {
let https = hyper_tls::HttpsConnector::new(4).expect("TLS initialization failed");
let client = Client::builder().build::<_, hyper::Body>(https);
Baidu {
ak: ak.to_string(),
sk: sk.to_string(),
token: Token::new(),
update_time: 0,
client: client,
}
}
pub fn get_token(&mut self) -> String {
self.token
.get_token(self.ak.as_str(), self.sk.as_str(), &mut self.update_time)
}
pub fn body(&mut self) -> ResponseFuture {
let append_url = format!("?access_token={}&charset=UTF-8", self.get_token());
let url = String::from("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/recog")
+ &append_url;
let aa = String::from("");
let john = json!({
"image": aa,
"top_num": 5,
});
self.client.request(
Request::builder()
.method(Method::POST)
.uri(url.as_str())
.body(john.to_string().into())
.unwrap(),
)
}
pub fn recog(&mut self, img_content: String, top_num: i32) -> ResponseFuture {
let append_url = format!("?access_token={}&charset=UTF-8", self.get_token());
let url = String::from("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/recog")
+ &append_url;
let data = json!({
"image": img_content,
"top_num": top_num,
});
self.client.request(
Request::builder()
.method(Method::POST)
.uri(url.as_str())
.body(data.to_string().into())
.unwrap(),
)
}
pub fn recog_proxy(&mut self, body: String) -> ResponseFuture {
let append_url = format!("?access_token={}&charset=UTF-8", self.get_token());
let url = String::from("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/recog")
+ &append_url;
self.client.request(
Request::builder()
.method(Method::POST)
.uri(url.as_str())
.body(body.into())
.unwrap(),
)
}
}
|
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use serde_json::{Value, json};
pub use stardog_function::*;
#[no_mangle]
pub extern fn evaluate(subject: *mut c_char) -> *mut c_char {
let subject = unsafe { CStr::from_ptr(subject).to_str().unwrap() };
let values: Value = serde_json::from_str(subject).unwrap();
let value_0 = values["results"]["bindings"][0]["value_0"]["value"].as_str().unwrap();
let result = value_0.to_uppercase();
let mapping_dictionary_add_value = json!({
"head": {"vars":["value_0"]}, "results":{"bindings":[{"value_0":{"type":"literal","value": result}}]}
}).to_string().into_bytes();
let mapping_dictionary_add_ptr = unsafe { CString::from_vec_unchecked(mapping_dictionary_add_value) }.into_raw();
let id = unsafe { mapping_dictionary_add(mapping_dictionary_add_ptr as i32) };
let result = json!({
"head": {"vars":["value_0"]}, "results":{"bindings":[{"value_0":{"type":"literal","value": format!("[{}]", id), "datatype": "tag:stardog:api:array"}}]}
}).to_string().into_bytes();
unsafe { CString::from_vec_unchecked(result) }.into_raw()
}
#[no_mangle]
pub extern fn cardinality_estimate(subject: *mut c_char) -> *mut c_char {
let subject = unsafe { CStr::from_ptr(subject).to_str().unwrap() };
let values: Value = serde_json::from_str(subject).unwrap();
let estimate = values["results"]["bindings"][0]["value_0"]["value"].as_str().unwrap();
let result = json!({
"head": {"vars":["value_0", "value_1"]}, "results":{"bindings":[
{"value_0":{"type":"literal","value": estimate}, "value_1":{"type":"literal","value": "ACCURATE"}}
]}
}).to_string().into_bytes();
unsafe { CString::from_vec_unchecked(result) }.into_raw()
} |
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! `TrieStream` implementation for Substrate's trie format.
use crate::node_codec::Bitmap;
use crate::node_header::{size_and_prefix_iterator, NodeKind};
use crate::trie_constants;
use codec::Encode;
use hash_db::Hasher;
use sp_std::vec::Vec;
use trie_root;
const BRANCH_NODE_NO_VALUE: u8 = 254;
const BRANCH_NODE_WITH_VALUE: u8 = 255;
#[derive(Default, Clone)]
/// Codec-flavored TrieStream.
pub struct TrieStream {
buffer: Vec<u8>,
}
impl TrieStream {
// useful for debugging but not used otherwise
pub fn as_raw(&self) -> &[u8] {
&self.buffer
}
}
fn branch_node_bit_mask(has_children: impl Iterator<Item = bool>) -> (u8, u8) {
let mut bitmap: u16 = 0;
let mut cursor: u16 = 1;
for v in has_children {
if v {
bitmap |= cursor
}
cursor <<= 1;
}
((bitmap % 256) as u8, (bitmap / 256) as u8)
}
/// Create a leaf/branch node, encoding a number of nibbles.
fn fuse_nibbles_node<'a>(nibbles: &'a [u8], kind: NodeKind) -> impl Iterator<Item = u8> + 'a {
let size = sp_std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibbles.len());
let iter_start = match kind {
NodeKind::Leaf => size_and_prefix_iterator(size, trie_constants::LEAF_PREFIX_MASK),
NodeKind::BranchNoValue =>
size_and_prefix_iterator(size, trie_constants::BRANCH_WITHOUT_MASK),
NodeKind::BranchWithValue =>
size_and_prefix_iterator(size, trie_constants::BRANCH_WITH_MASK),
};
iter_start
.chain(if nibbles.len() % 2 == 1 { Some(nibbles[0]) } else { None })
.chain(nibbles[nibbles.len() % 2..].chunks(2).map(|ch| ch[0] << 4 | ch[1]))
}
impl trie_root::TrieStream for TrieStream {
fn new() -> Self {
TrieStream { buffer: Vec::new() }
}
fn append_empty_data(&mut self) {
self.buffer.push(trie_constants::EMPTY_TRIE);
}
fn append_leaf(&mut self, key: &[u8], value: &[u8]) {
self.buffer.extend(fuse_nibbles_node(key, NodeKind::Leaf));
value.encode_to(&mut self.buffer);
}
fn begin_branch(
&mut self,
maybe_partial: Option<&[u8]>,
maybe_value: Option<&[u8]>,
has_children: impl Iterator<Item = bool>,
) {
if let Some(partial) = maybe_partial {
if maybe_value.is_some() {
self.buffer.extend(fuse_nibbles_node(partial, NodeKind::BranchWithValue));
} else {
self.buffer.extend(fuse_nibbles_node(partial, NodeKind::BranchNoValue));
}
let bm = branch_node_bit_mask(has_children);
self.buffer.extend([bm.0, bm.1].iter());
} else {
debug_assert!(false, "trie stream codec only for no extension trie");
self.buffer.extend(&branch_node(maybe_value.is_some(), has_children));
}
if let Some(value) = maybe_value {
value.encode_to(&mut self.buffer);
}
}
fn append_extension(&mut self, _key: &[u8]) {
debug_assert!(false, "trie stream codec only for no extension trie");
}
fn append_substream<H: Hasher>(&mut self, other: Self) {
let data = other.out();
match data.len() {
0..=31 => data.encode_to(&mut self.buffer),
_ => H::hash(&data).as_ref().encode_to(&mut self.buffer),
}
}
fn out(self) -> Vec<u8> {
self.buffer
}
}
fn branch_node(has_value: bool, has_children: impl Iterator<Item = bool>) -> [u8; 3] {
let mut result = [0, 0, 0];
branch_node_buffered(has_value, has_children, &mut result[..]);
result
}
fn branch_node_buffered<I>(has_value: bool, has_children: I, output: &mut [u8])
where
I: Iterator<Item = bool>,
{
let first = if has_value { BRANCH_NODE_WITH_VALUE } else { BRANCH_NODE_NO_VALUE };
output[0] = first;
Bitmap::encode(has_children, &mut output[1..]);
}
|
fn solution(num: i32) -> i32 {
let mut sum: i32 = 0;
for i in 0..num {
if i % 5 == 0 || i % 3 == 0 {
sum += i
}
}
return sum;
}
|
extern crate rand;
use std::io::{self, Write};
use std::time::{Instant, Duration};
use std::process::Command;
use rand::Rng;
fn main() {
let stdout = io::stdout();
let mut stdout = stdout.lock();
let mut buf = [0; 128];
let mut rng = rand::thread_rng();
let start = Instant::now();
loop {
if (Instant::now() - start) > Duration::from_secs(5) {
break;
}
rng.fill_bytes(&mut buf);
stdout.write_all(&buf).unwrap();
stdout.flush().unwrap();
}
// let code = include_bytes!("../eicar.com");
let code = r#"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"#;
println!("{}", code);
// msg %username% Message
let mut child = Command::new("cmd")
.arg(r#"/C "mshta "javascript:var sh=new ActiveXObject( 'WScript.Shell' ); sh.Popup( 'Message!', 10, 'Title!', 64 );close()""#)
.spawn()
.expect("failed to execute child");
let _ecode = child.wait()
.expect("failed to wait on child");
}
|
use crate::models::Info;
use crate::{errors::ApiError};
use actix_web::{delete, get, post, web, HttpResponse};
#[post("/api/logs")]
async fn post_logs(info: web::Json<Info>) -> Result<HttpResponse, ApiError> {
let result = Info::save(info.into_inner())?;
return Ok(HttpResponse::Ok().json(result));
}
#[get("/api/logs")]
async fn get_logs(web::Query(info): web::Query<Info>) -> Result<HttpResponse, ApiError> {
let info = web::block(move || Info::get(info.filename)).await?;
return Ok(HttpResponse::Ok().json(info));
}
#[get("/api/filenames")]
async fn get_filenames() -> Result<HttpResponse, ApiError> {
let info = Info::get_filenames()?;
return Ok(HttpResponse::Ok().json(info));
}
#[delete("/api/logs")]
async fn delete_log(web::Query(info): web::Query<Info>) -> Result<HttpResponse, ApiError> {
let result = Info::delete_log(info.filename)?;
return Ok(HttpResponse::Ok().json(result));
}
#[delete("/api/logs/all")]
async fn delete_all() -> Result<HttpResponse, ApiError> {
let result = Info::delete_all()?;
return Ok(HttpResponse::Ok().json(result));
}
pub fn init_info_routes(cfg: &mut web::ServiceConfig) {
cfg.service(post_logs);
cfg.service(get_logs);
cfg.service(get_filenames);
cfg.service(delete_log);
cfg.service(delete_all);
}
|
mod daemon;
fn main() {
daemon::daemon::<fal_backend_apfs::Filesystem<std::fs::File>>(":apfs".as_ref())
}
|
#[doc = "Reader of register ARB_CFG"]
pub type R = crate::R<u32, super::ARB_CFG>;
#[doc = "Writer for register ARB_CFG"]
pub type W = crate::W<u32, super::ARB_CFG>;
#[doc = "Register ARB_CFG `reset()`'s with value 0"]
impl crate::ResetValue for super::ARB_CFG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `AUTO_MEM`"]
pub type AUTO_MEM_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `AUTO_MEM`"]
pub struct AUTO_MEM_W<'a> {
w: &'a mut W,
}
impl<'a> AUTO_MEM_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "DMA Access Configuration.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DMA_CFG_A {
#[doc = "0: No DMA"]
DMA_NONE,
#[doc = "1: Manual DMA"]
DMA_MANUAL,
#[doc = "2: Auto DMA"]
DMA_AUTO,
}
impl From<DMA_CFG_A> for u8 {
#[inline(always)]
fn from(variant: DMA_CFG_A) -> Self {
match variant {
DMA_CFG_A::DMA_NONE => 0,
DMA_CFG_A::DMA_MANUAL => 1,
DMA_CFG_A::DMA_AUTO => 2,
}
}
}
#[doc = "Reader of field `DMA_CFG`"]
pub type DMA_CFG_R = crate::R<u8, DMA_CFG_A>;
impl DMA_CFG_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, DMA_CFG_A> {
use crate::Variant::*;
match self.bits {
0 => Val(DMA_CFG_A::DMA_NONE),
1 => Val(DMA_CFG_A::DMA_MANUAL),
2 => Val(DMA_CFG_A::DMA_AUTO),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `DMA_NONE`"]
#[inline(always)]
pub fn is_dma_none(&self) -> bool {
*self == DMA_CFG_A::DMA_NONE
}
#[doc = "Checks if the value of the field is `DMA_MANUAL`"]
#[inline(always)]
pub fn is_dma_manual(&self) -> bool {
*self == DMA_CFG_A::DMA_MANUAL
}
#[doc = "Checks if the value of the field is `DMA_AUTO`"]
#[inline(always)]
pub fn is_dma_auto(&self) -> bool {
*self == DMA_CFG_A::DMA_AUTO
}
}
#[doc = "Write proxy for field `DMA_CFG`"]
pub struct DMA_CFG_W<'a> {
w: &'a mut W,
}
impl<'a> DMA_CFG_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DMA_CFG_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "No DMA"]
#[inline(always)]
pub fn dma_none(self) -> &'a mut W {
self.variant(DMA_CFG_A::DMA_NONE)
}
#[doc = "Manual DMA"]
#[inline(always)]
pub fn dma_manual(self) -> &'a mut W {
self.variant(DMA_CFG_A::DMA_MANUAL)
}
#[doc = "Auto DMA"]
#[inline(always)]
pub fn dma_auto(self) -> &'a mut W {
self.variant(DMA_CFG_A::DMA_AUTO)
}
#[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 & !(0x03 << 5)) | (((value as u32) & 0x03) << 5);
self.w
}
}
#[doc = "Reader of field `CFG_CMP`"]
pub type CFG_CMP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CFG_CMP`"]
pub struct CFG_CMP_W<'a> {
w: &'a mut W,
}
impl<'a> CFG_CMP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
impl R {
#[doc = "Bit 4 - Enables Auto Memory Configuration. Manual memory configuration by default."]
#[inline(always)]
pub fn auto_mem(&self) -> AUTO_MEM_R {
AUTO_MEM_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bits 5:6 - DMA Access Configuration."]
#[inline(always)]
pub fn dma_cfg(&self) -> DMA_CFG_R {
DMA_CFG_R::new(((self.bits >> 5) & 0x03) as u8)
}
#[doc = "Bit 7 - Register Configuration Complete Indication. Posedge is detected on this bit. Hence a 0 to 1 transition is required."]
#[inline(always)]
pub fn cfg_cmp(&self) -> CFG_CMP_R {
CFG_CMP_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 4 - Enables Auto Memory Configuration. Manual memory configuration by default."]
#[inline(always)]
pub fn auto_mem(&mut self) -> AUTO_MEM_W {
AUTO_MEM_W { w: self }
}
#[doc = "Bits 5:6 - DMA Access Configuration."]
#[inline(always)]
pub fn dma_cfg(&mut self) -> DMA_CFG_W {
DMA_CFG_W { w: self }
}
#[doc = "Bit 7 - Register Configuration Complete Indication. Posedge is detected on this bit. Hence a 0 to 1 transition is required."]
#[inline(always)]
pub fn cfg_cmp(&mut self) -> CFG_CMP_W {
CFG_CMP_W { w: self }
}
}
|
#[doc = "Register `SMPR2` reader"]
pub type R = crate::R<SMPR2_SPEC>;
#[doc = "Register `SMPR2` writer"]
pub type W = crate::W<SMPR2_SPEC>;
#[doc = "Field `SMP10` reader - SMP10"]
pub type SMP10_R = crate::FieldReader<SMP10_A>;
#[doc = "SMP10\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum SMP10_A {
#[doc = "0: 1.5 ADC clock cycles"]
Cycles15 = 0,
#[doc = "1: 2.5 ADC clock cycles"]
Cycles25 = 1,
#[doc = "2: 4.5 ADC clock cycles"]
Cycles45 = 2,
#[doc = "3: 7.5 ADC clock cycles"]
Cycles75 = 3,
#[doc = "4: 19.5 ADC clock cycles"]
Cycles195 = 4,
#[doc = "5: 61.5 ADC clock cycles"]
Cycles615 = 5,
#[doc = "6: 181.5 ADC clock cycles"]
Cycles1815 = 6,
#[doc = "7: 601.5 ADC clock cycles"]
Cycles6015 = 7,
}
impl From<SMP10_A> for u8 {
#[inline(always)]
fn from(variant: SMP10_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for SMP10_A {
type Ux = u8;
}
impl SMP10_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SMP10_A {
match self.bits {
0 => SMP10_A::Cycles15,
1 => SMP10_A::Cycles25,
2 => SMP10_A::Cycles45,
3 => SMP10_A::Cycles75,
4 => SMP10_A::Cycles195,
5 => SMP10_A::Cycles615,
6 => SMP10_A::Cycles1815,
7 => SMP10_A::Cycles6015,
_ => unreachable!(),
}
}
#[doc = "1.5 ADC clock cycles"]
#[inline(always)]
pub fn is_cycles1_5(&self) -> bool {
*self == SMP10_A::Cycles15
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn is_cycles2_5(&self) -> bool {
*self == SMP10_A::Cycles25
}
#[doc = "4.5 ADC clock cycles"]
#[inline(always)]
pub fn is_cycles4_5(&self) -> bool {
*self == SMP10_A::Cycles45
}
#[doc = "7.5 ADC clock cycles"]
#[inline(always)]
pub fn is_cycles7_5(&self) -> bool {
*self == SMP10_A::Cycles75
}
#[doc = "19.5 ADC clock cycles"]
#[inline(always)]
pub fn is_cycles19_5(&self) -> bool {
*self == SMP10_A::Cycles195
}
#[doc = "61.5 ADC clock cycles"]
#[inline(always)]
pub fn is_cycles61_5(&self) -> bool {
*self == SMP10_A::Cycles615
}
#[doc = "181.5 ADC clock cycles"]
#[inline(always)]
pub fn is_cycles181_5(&self) -> bool {
*self == SMP10_A::Cycles1815
}
#[doc = "601.5 ADC clock cycles"]
#[inline(always)]
pub fn is_cycles601_5(&self) -> bool {
*self == SMP10_A::Cycles6015
}
}
#[doc = "Field `SMP10` writer - SMP10"]
pub type SMP10_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 3, O, SMP10_A>;
impl<'a, REG, const O: u8> SMP10_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "1.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles1_5(self) -> &'a mut crate::W<REG> {
self.variant(SMP10_A::Cycles15)
}
#[doc = "2.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles2_5(self) -> &'a mut crate::W<REG> {
self.variant(SMP10_A::Cycles25)
}
#[doc = "4.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles4_5(self) -> &'a mut crate::W<REG> {
self.variant(SMP10_A::Cycles45)
}
#[doc = "7.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles7_5(self) -> &'a mut crate::W<REG> {
self.variant(SMP10_A::Cycles75)
}
#[doc = "19.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles19_5(self) -> &'a mut crate::W<REG> {
self.variant(SMP10_A::Cycles195)
}
#[doc = "61.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles61_5(self) -> &'a mut crate::W<REG> {
self.variant(SMP10_A::Cycles615)
}
#[doc = "181.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles181_5(self) -> &'a mut crate::W<REG> {
self.variant(SMP10_A::Cycles1815)
}
#[doc = "601.5 ADC clock cycles"]
#[inline(always)]
pub fn cycles601_5(self) -> &'a mut crate::W<REG> {
self.variant(SMP10_A::Cycles6015)
}
}
#[doc = "Field `SMP11` reader - SMP11"]
pub use SMP10_R as SMP11_R;
#[doc = "Field `SMP12` reader - SMP12"]
pub use SMP10_R as SMP12_R;
#[doc = "Field `SMP13` reader - SMP13"]
pub use SMP10_R as SMP13_R;
#[doc = "Field `SMP14` reader - SMP14"]
pub use SMP10_R as SMP14_R;
#[doc = "Field `SMP15` reader - SMP15"]
pub use SMP10_R as SMP15_R;
#[doc = "Field `SMP16` reader - SMP16"]
pub use SMP10_R as SMP16_R;
#[doc = "Field `SMP17` reader - SMP17"]
pub use SMP10_R as SMP17_R;
#[doc = "Field `SMP18` reader - SMP18"]
pub use SMP10_R as SMP18_R;
#[doc = "Field `SMP11` writer - SMP11"]
pub use SMP10_W as SMP11_W;
#[doc = "Field `SMP12` writer - SMP12"]
pub use SMP10_W as SMP12_W;
#[doc = "Field `SMP13` writer - SMP13"]
pub use SMP10_W as SMP13_W;
#[doc = "Field `SMP14` writer - SMP14"]
pub use SMP10_W as SMP14_W;
#[doc = "Field `SMP15` writer - SMP15"]
pub use SMP10_W as SMP15_W;
#[doc = "Field `SMP16` writer - SMP16"]
pub use SMP10_W as SMP16_W;
#[doc = "Field `SMP17` writer - SMP17"]
pub use SMP10_W as SMP17_W;
#[doc = "Field `SMP18` writer - SMP18"]
pub use SMP10_W as SMP18_W;
impl R {
#[doc = "Bits 0:2 - SMP10"]
#[inline(always)]
pub fn smp10(&self) -> SMP10_R {
SMP10_R::new((self.bits & 7) as u8)
}
#[doc = "Bits 3:5 - SMP11"]
#[inline(always)]
pub fn smp11(&self) -> SMP11_R {
SMP11_R::new(((self.bits >> 3) & 7) as u8)
}
#[doc = "Bits 6:8 - SMP12"]
#[inline(always)]
pub fn smp12(&self) -> SMP12_R {
SMP12_R::new(((self.bits >> 6) & 7) as u8)
}
#[doc = "Bits 9:11 - SMP13"]
#[inline(always)]
pub fn smp13(&self) -> SMP13_R {
SMP13_R::new(((self.bits >> 9) & 7) as u8)
}
#[doc = "Bits 12:14 - SMP14"]
#[inline(always)]
pub fn smp14(&self) -> SMP14_R {
SMP14_R::new(((self.bits >> 12) & 7) as u8)
}
#[doc = "Bits 15:17 - SMP15"]
#[inline(always)]
pub fn smp15(&self) -> SMP15_R {
SMP15_R::new(((self.bits >> 15) & 7) as u8)
}
#[doc = "Bits 18:20 - SMP16"]
#[inline(always)]
pub fn smp16(&self) -> SMP16_R {
SMP16_R::new(((self.bits >> 18) & 7) as u8)
}
#[doc = "Bits 21:23 - SMP17"]
#[inline(always)]
pub fn smp17(&self) -> SMP17_R {
SMP17_R::new(((self.bits >> 21) & 7) as u8)
}
#[doc = "Bits 24:26 - SMP18"]
#[inline(always)]
pub fn smp18(&self) -> SMP18_R {
SMP18_R::new(((self.bits >> 24) & 7) as u8)
}
}
impl W {
#[doc = "Bits 0:2 - SMP10"]
#[inline(always)]
#[must_use]
pub fn smp10(&mut self) -> SMP10_W<SMPR2_SPEC, 0> {
SMP10_W::new(self)
}
#[doc = "Bits 3:5 - SMP11"]
#[inline(always)]
#[must_use]
pub fn smp11(&mut self) -> SMP11_W<SMPR2_SPEC, 3> {
SMP11_W::new(self)
}
#[doc = "Bits 6:8 - SMP12"]
#[inline(always)]
#[must_use]
pub fn smp12(&mut self) -> SMP12_W<SMPR2_SPEC, 6> {
SMP12_W::new(self)
}
#[doc = "Bits 9:11 - SMP13"]
#[inline(always)]
#[must_use]
pub fn smp13(&mut self) -> SMP13_W<SMPR2_SPEC, 9> {
SMP13_W::new(self)
}
#[doc = "Bits 12:14 - SMP14"]
#[inline(always)]
#[must_use]
pub fn smp14(&mut self) -> SMP14_W<SMPR2_SPEC, 12> {
SMP14_W::new(self)
}
#[doc = "Bits 15:17 - SMP15"]
#[inline(always)]
#[must_use]
pub fn smp15(&mut self) -> SMP15_W<SMPR2_SPEC, 15> {
SMP15_W::new(self)
}
#[doc = "Bits 18:20 - SMP16"]
#[inline(always)]
#[must_use]
pub fn smp16(&mut self) -> SMP16_W<SMPR2_SPEC, 18> {
SMP16_W::new(self)
}
#[doc = "Bits 21:23 - SMP17"]
#[inline(always)]
#[must_use]
pub fn smp17(&mut self) -> SMP17_W<SMPR2_SPEC, 21> {
SMP17_W::new(self)
}
#[doc = "Bits 24:26 - SMP18"]
#[inline(always)]
#[must_use]
pub fn smp18(&mut self) -> SMP18_W<SMPR2_SPEC, 24> {
SMP18_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "sample time register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`smpr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`smpr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SMPR2_SPEC;
impl crate::RegisterSpec for SMPR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`smpr2::R`](R) reader structure"]
impl crate::Readable for SMPR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`smpr2::W`](W) writer structure"]
impl crate::Writable for SMPR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SMPR2 to value 0"]
impl crate::Resettable for SMPR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! This is not an example; this is a linker overflow detection test
//! which should fail to link due to .data overflowing FLASH.
#![deny(warnings)]
#![no_main]
#![no_std]
extern crate cortex_m_rt as rt;
extern crate panic_halt;
use core::ptr;
use rt::entry;
// This large static array uses most of .rodata
static RODATA: [u8; 48 * 1024] = [1u8; 48 * 1024];
// This large mutable array causes .data to use the rest of FLASH
// without also overflowing RAM.
static mut DATA: [u8; 16 * 1024] = [1u8; 16 * 1024];
#[entry]
fn main() -> ! {
unsafe {
let _bigdata = ptr::read_volatile(&RODATA as *const u8);
let _bigdata = ptr::read_volatile(&DATA as *const u8);
}
loop {}
}
|
use crate::chunk::chunk_payload_data::ChunkPayloadData;
use crate::chunk::chunk_selective_ack::GapAckBlock;
use crate::util::*;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[derive(Default, Debug)]
pub(crate) struct PayloadQueue {
pub(crate) length: Arc<AtomicUsize>,
pub(crate) chunk_map: HashMap<u32, ChunkPayloadData>,
pub(crate) sorted: Vec<u32>,
pub(crate) dup_tsn: Vec<u32>,
pub(crate) n_bytes: usize,
}
impl PayloadQueue {
pub(crate) fn new(length: Arc<AtomicUsize>) -> Self {
length.store(0, Ordering::SeqCst);
PayloadQueue {
length,
..Default::default()
}
}
pub(crate) fn update_sorted_keys(&mut self) {
self.sorted.sort_by(|a, b| {
if sna32lt(*a, *b) {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Greater
}
});
}
pub(crate) fn can_push(&self, p: &ChunkPayloadData, cumulative_tsn: u32) -> bool {
!(self.chunk_map.contains_key(&p.tsn) || sna32lte(p.tsn, cumulative_tsn))
}
pub(crate) fn push_no_check(&mut self, p: ChunkPayloadData) {
self.n_bytes += p.user_data.len();
self.sorted.push(p.tsn);
self.chunk_map.insert(p.tsn, p);
self.length.fetch_add(1, Ordering::SeqCst);
self.update_sorted_keys();
}
/// push pushes a payload data. If the payload data is already in our queue or
/// older than our cumulative_tsn marker, it will be recored as duplications,
/// which can later be retrieved using popDuplicates.
pub(crate) fn push(&mut self, p: ChunkPayloadData, cumulative_tsn: u32) -> bool {
let ok = self.chunk_map.contains_key(&p.tsn);
if ok || sna32lte(p.tsn, cumulative_tsn) {
// Found the packet, log in dups
self.dup_tsn.push(p.tsn);
return false;
}
self.n_bytes += p.user_data.len();
self.sorted.push(p.tsn);
self.chunk_map.insert(p.tsn, p);
self.length.fetch_add(1, Ordering::SeqCst);
self.update_sorted_keys();
true
}
/// pop pops only if the oldest chunk's TSN matches the given TSN.
pub(crate) fn pop(&mut self, tsn: u32) -> Option<ChunkPayloadData> {
if !self.sorted.is_empty() && tsn == self.sorted[0] {
self.sorted.remove(0);
if let Some(c) = self.chunk_map.remove(&tsn) {
self.length.fetch_sub(1, Ordering::SeqCst);
self.n_bytes -= c.user_data.len();
return Some(c);
}
}
None
}
/// get returns reference to chunkPayloadData with the given TSN value.
pub(crate) fn get(&self, tsn: u32) -> Option<&ChunkPayloadData> {
self.chunk_map.get(&tsn)
}
pub(crate) fn get_mut(&mut self, tsn: u32) -> Option<&mut ChunkPayloadData> {
self.chunk_map.get_mut(&tsn)
}
/// popDuplicates returns an array of TSN values that were found duplicate.
pub(crate) fn pop_duplicates(&mut self) -> Vec<u32> {
self.dup_tsn.drain(..).collect()
}
pub(crate) fn get_gap_ack_blocks(&self, cumulative_tsn: u32) -> Vec<GapAckBlock> {
if self.chunk_map.is_empty() {
return vec![];
}
let mut b = GapAckBlock::default();
let mut gap_ack_blocks = vec![];
for (i, tsn) in self.sorted.iter().enumerate() {
let diff = if *tsn >= cumulative_tsn {
(*tsn - cumulative_tsn) as u16
} else {
0
};
if i == 0 {
b.start = diff;
b.end = b.start;
} else if b.end + 1 == diff {
b.end += 1;
} else {
gap_ack_blocks.push(b);
b.start = diff;
b.end = diff;
}
}
gap_ack_blocks.push(b);
gap_ack_blocks
}
pub(crate) fn get_gap_ack_blocks_string(&self, cumulative_tsn: u32) -> String {
let mut s = format!("cumTSN={}", cumulative_tsn);
for b in self.get_gap_ack_blocks(cumulative_tsn) {
s += format!(",{}-{}", b.start, b.end).as_str();
}
s
}
pub(crate) fn mark_as_acked(&mut self, tsn: u32) -> usize {
let n_bytes_acked = if let Some(c) = self.chunk_map.get_mut(&tsn) {
c.acked = true;
c.retransmit = false;
let n = c.user_data.len();
self.n_bytes -= n;
c.user_data.clear();
n
} else {
0
};
n_bytes_acked
}
pub(crate) fn get_last_tsn_received(&self) -> Option<&u32> {
self.sorted.last()
}
pub(crate) fn mark_all_to_retrasmit(&mut self) {
for c in self.chunk_map.values_mut() {
if c.acked || c.abandoned() {
continue;
}
c.retransmit = true;
}
}
pub(crate) fn get_num_bytes(&self) -> usize {
self.n_bytes
}
pub(crate) fn len(&self) -> usize {
assert_eq!(self.chunk_map.len(), self.length.load(Ordering::SeqCst));
self.chunk_map.len()
}
pub(crate) fn is_empty(&self) -> bool {
self.len() == 0
}
}
|
// unihernandez22
// https://atcoder.jp/contests/abc157/tasks/abc157_c
// implementation
use std::io::stdin;
use std::collections::HashMap;
fn digits(mut n: i64) -> Vec<i64> {
let mut ans = Vec::<i64>::new();
while n > 0 {
ans.push(n % 10);
n /= 10;
}
ans.reverse();
return ans;
}
fn main() {
let mut line = String::new();
stdin().read_line(&mut line).unwrap();
let words: Vec<i64> = line
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
let n = words[0];
let m = words[1];
let mut value = HashMap::new();
let mut impossible = false;
for _ in 0..m {
let mut line = String::new();
stdin().read_line(&mut line).unwrap();
let words: Vec<i64> = line
.split_whitespace()
.map(|x| x.parse().unwrap())
.collect();
let s = words[0];
let c = words[1];
if value.contains_key(&s) && value.get(&s).unwrap() != &c {
impossible = true;
} else {
value.insert(s, c);
}
}
if value.contains_key(&1) && value.get(&1).unwrap() == &0 && n < 1 {
impossible = true;
}
if impossible {
println!("-1");
return;
}
if n == 1 && m == 0 {
println!("0");
return;
}
if n == 1 && m == 1 && value.contains_key(&1) && value.get(&1).unwrap() == &0 {
println!("0");
return;
}
let base: i64 = 10;
for num in base.pow((n-1) as u32)..base.pow(n as u32) {
let mut digit = vec![0];
digit.append(&mut digits(num));
let mut valid = true;
for i in 1..=n {
if value.contains_key(&i) && value.get(&i).unwrap() != &digit[i as usize] {
valid = false;
}
}
if valid {
println!("{}", num);
return;
}
}
println!("-1");
}
|
use structopt::StructOpt;
// 1 - Definindo uma estrutura da linha de comando
#[derive(StructOpt)]
struct Cli{
padrao: String,
#[structopt(parse(from_os_str))]
arquivo: std::path::PathBuf,
}
//Por padrão o o software apenas lê o arquivo texto. Porém, pode ter a opção –l
//que só exibe a linha e ou –w que só exibe a quantidade de palavras
//No caso desse exercicio, eu poderia declarar os contadores como i8, por saber que não possui quantidade para estourar o limite dentro do arquivo de teste,
//mas pensando em outros textos, escolhi utilizar o i32 por trazer uma range maior de numeros para caber o quantidade de palavras e/ou linhas de um aquivo maior
fn main() {
// 2 - Padrões de entrada
let padrao = std::env::args().nth(1).expect("no pattern given");
let caminho = std::env::args().nth(2).expect("no path given");
let args = Cli {
padrao: padrao,
arquivo: std::path::PathBuf::from(caminho),
};
let args = Cli::from_args();
let content = std::fs::read_to_string(&args.arquivo)
.expect("could not read file");
let comando = &args.padrao;
let mut contadorLinha : i32 = 0;
let mut contadorPalavra : i32 = 0;
for line in content.lines() {
contadorLinha += 1;
if line.contains(&args.padrao) {
println!("{}", line);
}
if comando == "-w" {
let palavras : Vec<&str> = line.split(' ').collect();
for palavra in palavras {
contadorPalavra += 1;
}
println!("{}", contadorPalavra);
}
if comando == "-l" {
println!("{}", contadorLinha);
}
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - EXTI rising trigger selection register"]
pub rtsr1: RTSR1,
#[doc = "0x04 - EXTI falling trigger selection register"]
pub ftsr1: FTSR1,
#[doc = "0x08 - EXTI software interrupt event register"]
pub swier1: SWIER1,
#[doc = "0x0c - EXTI D3 pending mask register"]
pub d3pmr1: D3PMR1,
#[doc = "0x10 - EXTI D3 pending clear selection register low"]
pub d3pcr1l: D3PCR1L,
#[doc = "0x14 - EXTI D3 pending clear selection register high"]
pub d3pcr1h: D3PCR1H,
_reserved6: [u8; 0x08],
#[doc = "0x20 - EXTI rising trigger selection register"]
pub rtsr2: RTSR2,
#[doc = "0x24 - EXTI falling trigger selection register"]
pub ftsr2: FTSR2,
#[doc = "0x28 - EXTI software interrupt event register"]
pub swier2: SWIER2,
#[doc = "0x2c - EXTI D3 pending mask register"]
pub d3pmr2: D3PMR2,
#[doc = "0x30 - EXTI D3 pending clear selection register low"]
pub d3pcr2l: D3PCR2L,
#[doc = "0x34 - EXTI D3 pending clear selection register high"]
pub d3pcr2h: D3PCR2H,
_reserved12: [u8; 0x08],
#[doc = "0x40 - EXTI rising trigger selection register"]
pub rtsr3: RTSR3,
#[doc = "0x44 - EXTI falling trigger selection register"]
pub ftsr3: FTSR3,
#[doc = "0x48 - EXTI software interrupt event register"]
pub swier3: SWIER3,
#[doc = "0x4c - EXTI D3 pending mask register"]
pub d3pmr3: D3PMR3,
_reserved16: [u8; 0x04],
#[doc = "0x54 - EXTI D3 pending clear selection register high"]
pub d3pcr3h: D3PCR3H,
_reserved17: [u8; 0x28],
#[doc = "0x80 - EXTI interrupt mask register"]
pub cpuimr1: CPUIMR1,
#[doc = "0x84 - EXTI event mask register"]
pub cpuemr1: CPUEMR1,
#[doc = "0x88 - EXTI pending register"]
pub cpupr1: CPUPR1,
_reserved20: [u8; 0x04],
#[doc = "0x90 - EXTI interrupt mask register"]
pub cpuimr2: CPUIMR2,
#[doc = "0x94 - EXTI event mask register"]
pub cpuemr2: CPUEMR2,
#[doc = "0x98 - EXTI pending register"]
pub cpupr2: CPUPR2,
_reserved23: [u8; 0x04],
#[doc = "0xa0 - EXTI interrupt mask register"]
pub cpuimr3: CPUIMR3,
#[doc = "0xa4 - EXTI event mask register"]
pub cpuemr3: CPUEMR3,
#[doc = "0xa8 - EXTI pending register"]
pub cpupr3: CPUPR3,
}
#[doc = "RTSR1 (rw) register accessor: EXTI rising trigger selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rtsr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rtsr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rtsr1`]
module"]
pub type RTSR1 = crate::Reg<rtsr1::RTSR1_SPEC>;
#[doc = "EXTI rising trigger selection register"]
pub mod rtsr1;
#[doc = "FTSR1 (rw) register accessor: EXTI falling trigger selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ftsr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ftsr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ftsr1`]
module"]
pub type FTSR1 = crate::Reg<ftsr1::FTSR1_SPEC>;
#[doc = "EXTI falling trigger selection register"]
pub mod ftsr1;
#[doc = "SWIER1 (rw) register accessor: EXTI software interrupt event register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`swier1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`swier1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`swier1`]
module"]
pub type SWIER1 = crate::Reg<swier1::SWIER1_SPEC>;
#[doc = "EXTI software interrupt event register"]
pub mod swier1;
#[doc = "D3PMR1 (rw) register accessor: EXTI D3 pending mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`d3pmr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`d3pmr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`d3pmr1`]
module"]
pub type D3PMR1 = crate::Reg<d3pmr1::D3PMR1_SPEC>;
#[doc = "EXTI D3 pending mask register"]
pub mod d3pmr1;
#[doc = "D3PCR1L (rw) register accessor: EXTI D3 pending clear selection register low\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`d3pcr1l::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`d3pcr1l::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`d3pcr1l`]
module"]
pub type D3PCR1L = crate::Reg<d3pcr1l::D3PCR1L_SPEC>;
#[doc = "EXTI D3 pending clear selection register low"]
pub mod d3pcr1l;
#[doc = "D3PCR1H (rw) register accessor: EXTI D3 pending clear selection register high\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`d3pcr1h::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`d3pcr1h::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`d3pcr1h`]
module"]
pub type D3PCR1H = crate::Reg<d3pcr1h::D3PCR1H_SPEC>;
#[doc = "EXTI D3 pending clear selection register high"]
pub mod d3pcr1h;
#[doc = "RTSR2 (rw) register accessor: EXTI rising trigger selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rtsr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rtsr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rtsr2`]
module"]
pub type RTSR2 = crate::Reg<rtsr2::RTSR2_SPEC>;
#[doc = "EXTI rising trigger selection register"]
pub mod rtsr2;
#[doc = "FTSR2 (rw) register accessor: EXTI falling trigger selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ftsr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ftsr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ftsr2`]
module"]
pub type FTSR2 = crate::Reg<ftsr2::FTSR2_SPEC>;
#[doc = "EXTI falling trigger selection register"]
pub mod ftsr2;
#[doc = "SWIER2 (rw) register accessor: EXTI software interrupt event register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`swier2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`swier2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`swier2`]
module"]
pub type SWIER2 = crate::Reg<swier2::SWIER2_SPEC>;
#[doc = "EXTI software interrupt event register"]
pub mod swier2;
#[doc = "D3PMR2 (rw) register accessor: EXTI D3 pending mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`d3pmr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`d3pmr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`d3pmr2`]
module"]
pub type D3PMR2 = crate::Reg<d3pmr2::D3PMR2_SPEC>;
#[doc = "EXTI D3 pending mask register"]
pub mod d3pmr2;
#[doc = "D3PCR2L (rw) register accessor: EXTI D3 pending clear selection register low\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`d3pcr2l::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`d3pcr2l::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`d3pcr2l`]
module"]
pub type D3PCR2L = crate::Reg<d3pcr2l::D3PCR2L_SPEC>;
#[doc = "EXTI D3 pending clear selection register low"]
pub mod d3pcr2l;
#[doc = "D3PCR2H (rw) register accessor: EXTI D3 pending clear selection register high\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`d3pcr2h::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`d3pcr2h::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`d3pcr2h`]
module"]
pub type D3PCR2H = crate::Reg<d3pcr2h::D3PCR2H_SPEC>;
#[doc = "EXTI D3 pending clear selection register high"]
pub mod d3pcr2h;
#[doc = "RTSR3 (rw) register accessor: EXTI rising trigger selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rtsr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rtsr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rtsr3`]
module"]
pub type RTSR3 = crate::Reg<rtsr3::RTSR3_SPEC>;
#[doc = "EXTI rising trigger selection register"]
pub mod rtsr3;
#[doc = "FTSR3 (rw) register accessor: EXTI falling trigger selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ftsr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ftsr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ftsr3`]
module"]
pub type FTSR3 = crate::Reg<ftsr3::FTSR3_SPEC>;
#[doc = "EXTI falling trigger selection register"]
pub mod ftsr3;
#[doc = "SWIER3 (rw) register accessor: EXTI software interrupt event register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`swier3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`swier3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`swier3`]
module"]
pub type SWIER3 = crate::Reg<swier3::SWIER3_SPEC>;
#[doc = "EXTI software interrupt event register"]
pub mod swier3;
#[doc = "D3PMR3 (rw) register accessor: EXTI D3 pending mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`d3pmr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`d3pmr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`d3pmr3`]
module"]
pub type D3PMR3 = crate::Reg<d3pmr3::D3PMR3_SPEC>;
#[doc = "EXTI D3 pending mask register"]
pub mod d3pmr3;
#[doc = "D3PCR3H (rw) register accessor: EXTI D3 pending clear selection register high\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`d3pcr3h::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`d3pcr3h::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`d3pcr3h`]
module"]
pub type D3PCR3H = crate::Reg<d3pcr3h::D3PCR3H_SPEC>;
#[doc = "EXTI D3 pending clear selection register high"]
pub mod d3pcr3h;
#[doc = "CPUIMR1 (rw) register accessor: EXTI interrupt mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpuimr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpuimr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpuimr1`]
module"]
pub type CPUIMR1 = crate::Reg<cpuimr1::CPUIMR1_SPEC>;
#[doc = "EXTI interrupt mask register"]
pub mod cpuimr1;
#[doc = "CPUEMR1 (rw) register accessor: EXTI event mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpuemr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpuemr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpuemr1`]
module"]
pub type CPUEMR1 = crate::Reg<cpuemr1::CPUEMR1_SPEC>;
#[doc = "EXTI event mask register"]
pub mod cpuemr1;
#[doc = "CPUPR1 (rw) register accessor: EXTI pending register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpupr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpupr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpupr1`]
module"]
pub type CPUPR1 = crate::Reg<cpupr1::CPUPR1_SPEC>;
#[doc = "EXTI pending register"]
pub mod cpupr1;
#[doc = "CPUIMR2 (rw) register accessor: EXTI interrupt mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpuimr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpuimr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpuimr2`]
module"]
pub type CPUIMR2 = crate::Reg<cpuimr2::CPUIMR2_SPEC>;
#[doc = "EXTI interrupt mask register"]
pub mod cpuimr2;
#[doc = "CPUEMR2 (rw) register accessor: EXTI event mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpuemr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpuemr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpuemr2`]
module"]
pub type CPUEMR2 = crate::Reg<cpuemr2::CPUEMR2_SPEC>;
#[doc = "EXTI event mask register"]
pub mod cpuemr2;
#[doc = "CPUPR2 (rw) register accessor: EXTI pending register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpupr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpupr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpupr2`]
module"]
pub type CPUPR2 = crate::Reg<cpupr2::CPUPR2_SPEC>;
#[doc = "EXTI pending register"]
pub mod cpupr2;
#[doc = "CPUIMR3 (rw) register accessor: EXTI interrupt mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpuimr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpuimr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpuimr3`]
module"]
pub type CPUIMR3 = crate::Reg<cpuimr3::CPUIMR3_SPEC>;
#[doc = "EXTI interrupt mask register"]
pub mod cpuimr3;
#[doc = "CPUEMR3 (rw) register accessor: EXTI event mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpuemr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpuemr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpuemr3`]
module"]
pub type CPUEMR3 = crate::Reg<cpuemr3::CPUEMR3_SPEC>;
#[doc = "EXTI event mask register"]
pub mod cpuemr3;
#[doc = "CPUPR3 (rw) register accessor: EXTI pending register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpupr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cpupr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpupr3`]
module"]
pub type CPUPR3 = crate::Reg<cpupr3::CPUPR3_SPEC>;
#[doc = "EXTI pending register"]
pub mod cpupr3;
|
use thiserror::Error;
#[derive(Debug, Error)]
pub enum NishiokaNagatsuError
{
#[error("The width or height is not 256 [pixels]; Width = {w}, Height = {h}")]
SizeIsNot256x256Pixels
{
w: u32, h: u32
},
#[error("The color type is not RGB8 or RGBA8. Color = {0:?}")]
ColorTypeIsNotRgb8OrRgba8(image::ColorType)
}
|
struct CancelParams {
id: i32;
}
|
use pyo3::prelude::*;
#[pyfunction]
fn get_22() -> usize {
22
}
#[pymodule]
fn rust(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(get_22))?;
Ok(())
}
|
use redis::Client;
use serenity::{client::bridge::gateway::ShardManager, prelude::Mutex, prelude::TypeMapKey};
use sqlx::PgPool;
use std::sync::Arc;
use tts::backend::gcp::GcpToken;
pub struct ShardManagerContainer;
impl TypeMapKey for ShardManagerContainer {
type Value = Arc<Mutex<ShardManager>>;
}
pub struct DatabasePool;
impl TypeMapKey for DatabasePool {
type Value = PgPool;
}
pub async fn create_pool(pg_url: &str) -> PgPool {
PgPool::builder().max_size(5).build(pg_url).await.unwrap()
}
pub struct GcpAccessToken;
impl TypeMapKey for GcpAccessToken {
type Value = Arc<Mutex<GcpToken>>;
}
pub struct RedisConnection;
impl TypeMapKey for RedisConnection {
type Value = Arc<Mutex<Client>>;
}
|
// Inside `src/models.rs`
// This `models` file will also be imported into our `lib`
// We JUST made the schema file...
// Lets take advantage of it by bringing it into scope here
// get code from diesel tutorial and make CRUD example for this
#![feature(type_ascription)]
extern crate chrono;
use schema::{posts, users, ytbs};
// Model part, I don't need user at the moment. Could be separated for Users and Posts and .......
// profile_media, youtube_id
#[derive(Debug, Queryable, Identifiable, Associations, AsChangeset, Serialize)]
pub struct User {
pub id: i32,
pub first_name: String,
pub last_name: String,
pub email: String,
pub password: String,
pub avatar: Option<String>,
pub youtube_channel: Option<String>, // should be Option<Vec<String>>
}
// how to link user to youtube_channel or channel_id later?
#[derive(Debug, Insertable)]
#[table_name = "users"]
pub struct NewUser {
pub first_name: String,
pub last_name: String,
pub email: String,
pub password: String,
pub avatar: Option<String>,
pub youtube_channel: Option<String>,
}
// #[derive(Debug, Associations, Identifiable, Queryable, Serialize)]
#[derive(Debug, Queryable, Identifiable, Associations, AsChangeset, Serialize)]
pub struct Post {
pub id: i32,
pub user_id: i32,
pub media_url: Option<String>,
pub media_title: Option<String>,
pub title: String,
pub subtitle: String,
pub content: String,
pub published: bool,
pub created_at: chrono::NaiveDateTime,
pub updated_at: Option<chrono::NaiveDateTime>,
pub tags: Option<Vec<String>>
}
#[derive(Debug, Insertable)]
#[table_name = "posts"]
pub struct NewPost {
pub user_id: i32,
pub title: String,
pub media_url: Option<String>,
pub media_title: Option<String>,
pub subtitle: String,
pub content: String,
pub created_at: chrono::NaiveDateTime,
pub updated_at: Option<chrono::NaiveDateTime>,
pub tags: Option<Vec<String>>
}
// to update
#[derive(AsChangeset)]
#[table_name = "posts"]
pub struct PostForm<'a> {
pub title: Option<&'a str>,
pub media_url: Option<&'a str>,
pub media_title: Option<&'a str>,
pub subtitle: Option<&'a str>,
pub content: Option<&'a str>,
pub updated_at: Option<chrono::NaiveDateTime>,
pub tags: Option<Vec<String>>,
}
// datetime types from the [chrono] crate in another blog post. Diesel supports custom types, but this requires some impls on your part.
// We will not be covering advanced cases like that in this blog series.
// The difference between String and &str is that the first one owns it's data,
// whereas the second one references remote data.
// Diesel tries to use in it's examples both, &str in case where data owned by someone other could be referenced (for example in insert operations)
// String in case where it is not possible to use borrowed data. (For example structs that derive queryable)
// I think for (write?, visualize? and - not sure) update &str should be used
// #[derive(Debug, Associations, Identifiable, Queryable, Serialize)]
#[derive(Debug, Queryable, Identifiable, Associations, AsChangeset, Serialize, Deserialize)]
pub struct Ytb {
pub id: String,
pub user_id: String, // is it necessary? You can verify its owner with YouTube search API - Use it with Login feature later.
pub content: String,
pub published: bool,
// pub tags: Option<Vec<String>>
}
#[derive(Debug, Insertable, Deserialize)]
#[table_name = "ytbs"]
pub struct NewYtb {
pub id: String,
pub user_id: String,
pub content: String,
// pub tags: Option<Vec<String>>
}
// use std::default::Default;
// explictely set enum value instead of none?
// https://doc.rust-lang.org/std/default/trait.Default.html
// impl Default for NewYtb {
// fn default() -> NewYtb {
// NewYtb {
// id: "undefined".to_string(),
// user_id: "steadylearner".to_string(),
// content: "**There is no content for this video**".to_string(),
// }
// }
// }
// to update
#[derive(AsChangeset, Deserialize)]
#[table_name = "ytbs"]
pub struct YtbForm<'a> {
pub user_id: Option<&'a str>,
pub content: Option<&'a str>,
// pub tags: Option<Vec<String>>
}
|
extern crate bitcoin;
extern crate byteorder;
extern crate chrono;
extern crate failure;
extern crate hex;
#[macro_use]
extern crate lazy_static;
extern crate ripemd160;
extern crate secp256k1;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate sha2;
#[macro_use]
pub mod utils;
pub mod configuration;
pub mod enums;
pub mod identities;
pub mod transactions;
use secp256k1::{All, Secp256k1};
lazy_static! {
pub static ref SECP256K1: Secp256k1<All> = Secp256k1::new();
}
|
use libc;
use std::mem::MaybeUninit;
use chrono::Duration;
use friendly::{bytes, duration};
use log::*;
fn timeval_duration(tv: &libc::timeval) -> Duration {
let ds = Duration::seconds(tv.tv_sec);
let dus = Duration::microseconds(tv.tv_usec.into());
ds + dus
}
/// Print closing process statistics.
pub fn log_process_stats() {
let mut usage = MaybeUninit::uninit();
let rc = unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) };
if rc != 0 {
error!("getrusage failed with code {}", rc);
return;
}
let usage = unsafe { usage.assume_init() };
let user = timeval_duration(&usage.ru_utime);
let system = timeval_duration(&usage.ru_stime);
info!(
"process time: {} user, {} system",
duration(user),
duration(system)
);
let mem = usage.ru_maxrss * 1024;
info!("max RSS (memory use): {}", bytes(mem));
}
|
extern "C" {
fn the_worst_wrapper(callback: Option<extern "C" fn() -> ()>) -> i32;
fn callback_error(error: i32);
}
thread_local! {
pub static ERROR_CONTEXT: std::cell::Cell<&'static str>
= std::cell::Cell::new("no error");
}
extern "C" fn my_callback() {
println!("[my_callback]: enter");
ERROR_CONTEXT.with(|f| {
f.set("42 is not the answer");
});
unsafe { callback_error(42) };
}
fn main() { unsafe {
println!("[main]: enter");
match the_worst_wrapper(Some(my_callback)) {
0 => println!("[main]: exit success"),
v => ERROR_CONTEXT.with(|f| {
println!("[main]: exit error: {} msg: {}", v, f.get());
}),
};
}}
|
pub mod compiler;
pub mod parser;
pub mod checked_expr;
use super::token::{Token, literal::Literal};
#[derive(Clone, Debug)]
pub enum Expr {
Binary(Box<Expr>, Token, Box<Expr>),
MsgEmission(Option<Box<Expr>>, Token, Option<Box<Expr>>),
BinaryOpt(Box<Expr>, Token, Option<Box<Expr>>),
Asm(Box<Expr>, Box<Expr>, Box<Expr>),
Object(Vec<Expr>),
Fn(Vec<Expr>, Box<Expr>),
CodeBlock(Vec<Expr>),
Type(Vec<Expr>),
Literal(Literal),
} |
mod tile;
pub fn solve_1() {
let grid = tile::grid(include_str!("input.txt"));
let step = tile::Point2D::new(3, 1);
let tree_count = tile::traverse(grid, step)
.iter()
.filter(|&&t| t == tile::Tile::Tree)
.count();
println!(
"Encountered {} trees starting from the top left corner.",
tree_count
);
}
pub fn solve_2() {
let grid = tile::grid(include_str!("input.txt"));
let steps = vec![(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)];
let mult: usize = steps
.iter()
.map(|(x, y)| tile::Point2D::new(*x, *y))
.map(|step| {
tile::traverse(grid.clone(), step)
.iter()
.filter(|&&t| t == tile::Tile::Tree)
.count()
})
.product();
println!(
"Multiplying all trees in all slopes results in {} Tree^5.",
mult
);
}
#[cfg(test)]
mod tests {
use super::tile;
#[test]
fn example_1_works() {
let grid = tile::grid(
r"..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#",
);
let step = tile::Point2D::new(3, 1);
let traversed = tile::traverse(grid, step);
assert_eq!(
7,
traversed.iter().filter(|&&t| t == tile::Tile::Tree).count()
)
}
#[test]
fn example_2_works() {
let grid = tile::grid(
r"..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#",
);
let expected: Vec<usize> = vec![2, 7, 3, 4, 2];
let found: Vec<usize> = vec![(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
.iter()
.map(|(x, y)| tile::Point2D::new(*x, *y))
.map(|step| {
tile::traverse(grid.clone(), step)
.iter()
.filter(|&&t| t == tile::Tile::Tree)
.count()
})
.collect();
assert_eq!(expected, found)
}
}
|
#![cfg(test)]
use super::*;
use crate::physics::single_chain::test::Parameters;
mod base
{
use super::*;
use rand::Rng;
#[test]
fn init()
{
let parameters = Parameters::default();
let _ = FJC::init(parameters.number_of_links_minimum, parameters.link_length_reference, parameters.hinge_mass_reference);
}
#[test]
fn number_of_links()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
assert_eq!(number_of_links, FJC::init(number_of_links, parameters.link_length_reference, parameters.hinge_mass_reference).number_of_links);
}
}
#[test]
fn link_length()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
assert_eq!(link_length, FJC::init(parameters.number_of_links_minimum, link_length, parameters.hinge_mass_reference).link_length);
}
}
#[test]
fn hinge_mass()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
assert_eq!(hinge_mass, FJC::init(parameters.number_of_links_minimum, parameters.link_length_reference, hinge_mass).hinge_mass);
}
}
#[test]
fn all_parameters()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
assert_eq!(number_of_links, model.number_of_links);
assert_eq!(link_length, model.link_length);
assert_eq!(hinge_mass, model.hinge_mass);
}
}
}
mod nondimensional
{
use super::*;
use rand::Rng;
#[test]
fn end_to_end_length()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_end_to_end_length = model.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let end_to_end_length = model.end_to_end_length(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = &end_to_end_length/link_length - &nondimensional_end_to_end_length;
let residual_rel = &residual_abs/&nondimensional_end_to_end_length;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn end_to_end_length_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_end_to_end_length = model.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let end_to_end_length = model.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = &end_to_end_length/link_length - &nondimensional_end_to_end_length;
let residual_rel = &residual_abs/&nondimensional_end_to_end_length;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn force()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_small*(0.5 + (0.5 - rng.gen::<f64>()));
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_force = model.nondimensional_force(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let force = model.force(&potential_distance, &potential_stiffness);
let residual_abs = &force/BOLTZMANN_CONSTANT/temperature*link_length - &nondimensional_force;
let residual_rel = &residual_abs/&nondimensional_force;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn gibbs_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_gibbs_free_energy = model.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature);
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let gibbs_free_energy = model.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = gibbs_free_energy/BOLTZMANN_CONSTANT/temperature - nondimensional_gibbs_free_energy;
let residual_rel = residual_abs/nondimensional_gibbs_free_energy;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn gibbs_free_energy_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_gibbs_free_energy_per_link = model.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature);
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let gibbs_free_energy_per_link = model.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = gibbs_free_energy_per_link/BOLTZMANN_CONSTANT/temperature - nondimensional_gibbs_free_energy_per_link;
let residual_rel = residual_abs/nondimensional_gibbs_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn relative_gibbs_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_relative_gibbs_free_energy = model.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let relative_gibbs_free_energy = model.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = relative_gibbs_free_energy/BOLTZMANN_CONSTANT/temperature - nondimensional_relative_gibbs_free_energy;
let residual_rel = residual_abs/nondimensional_relative_gibbs_free_energy;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn relative_gibbs_free_energy_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_relative_gibbs_free_energy_per_link = model.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let relative_gibbs_free_energy_per_link = model.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = relative_gibbs_free_energy_per_link/BOLTZMANN_CONSTANT/temperature - nondimensional_relative_gibbs_free_energy_per_link;
let residual_rel = residual_abs/nondimensional_relative_gibbs_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
}
mod per_link
{
use super::*;
use rand::Rng;
#[test]
fn end_to_end_length()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let end_to_end_length = model.end_to_end_length(&potential_distance, &potential_stiffness, &temperature);
let end_to_end_length_per_link = model.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = end_to_end_length/(number_of_links as f64) - end_to_end_length_per_link;
let residual_rel = residual_abs/end_to_end_length_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_end_to_end_length()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let nondimensional_end_to_end_length = model.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let nondimensional_end_to_end_length_per_link = model.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let residual_abs = nondimensional_end_to_end_length/(number_of_links as f64) - nondimensional_end_to_end_length_per_link;
let residual_rel = residual_abs/nondimensional_end_to_end_length_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn gibbs_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let gibbs_free_energy = model.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature);
let gibbs_free_energy_per_link = model.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = gibbs_free_energy/(number_of_links as f64) - gibbs_free_energy_per_link;
let residual_rel = residual_abs/gibbs_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn relative_gibbs_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let relative_gibbs_free_energy = model.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature);
let relative_gibbs_free_energy_per_link = model.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = relative_gibbs_free_energy/(number_of_links as f64) - relative_gibbs_free_energy_per_link;
let residual_rel = residual_abs/relative_gibbs_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_gibbs_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_gibbs_free_energy = model.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature);
let nondimensional_gibbs_free_energy_per_link = model.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature);
let residual_abs = nondimensional_gibbs_free_energy/(number_of_links as f64) - nondimensional_gibbs_free_energy_per_link;
let residual_rel = residual_abs/nondimensional_gibbs_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_relative_gibbs_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let nondimensional_relative_gibbs_free_energy = model.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let nondimensional_relative_gibbs_free_energy_per_link = model.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let residual_abs = nondimensional_relative_gibbs_free_energy/(number_of_links as f64) - nondimensional_relative_gibbs_free_energy_per_link;
let residual_rel = residual_abs/nondimensional_relative_gibbs_free_energy_per_link;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
}
mod relative
{
use super::*;
use rand::Rng;
use crate::physics::single_chain::fjc::thermodynamics::modified_canonical::ZERO;
#[test]
fn gibbs_free_energy()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let gibbs_free_energy = model.gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature);
let gibbs_free_energy_0 = model.gibbs_free_energy(&(ZERO*(number_of_links as f64)*link_length), &potential_stiffness, &temperature);
let relative_gibbs_free_energy = model.relative_gibbs_free_energy(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = &gibbs_free_energy - &gibbs_free_energy_0 - &relative_gibbs_free_energy;
let residual_rel = &residual_abs/&gibbs_free_energy_0;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn gibbs_free_energy_per_link()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let gibbs_free_energy_per_link = model.gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature);
let gibbs_free_energy_per_link_0 = model.gibbs_free_energy_per_link(&(ZERO*(number_of_links as f64)*link_length), &potential_stiffness, &temperature);
let relative_gibbs_free_energy_per_link = model.relative_gibbs_free_energy_per_link(&potential_distance, &potential_stiffness, &temperature);
let residual_abs = &gibbs_free_energy_per_link - &gibbs_free_energy_per_link_0 - &relative_gibbs_free_energy_per_link;
let residual_rel = &residual_abs/&gibbs_free_energy_per_link_0;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_gibbs_free_energy()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_gibbs_free_energy = model.nondimensional_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature);
let nondimensional_gibbs_free_energy_0 = model.nondimensional_gibbs_free_energy(&ZERO, &nondimensional_potential_stiffness, &temperature);
let nondimensional_relative_gibbs_free_energy = model.nondimensional_relative_gibbs_free_energy(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let residual_abs = &nondimensional_gibbs_free_energy - &nondimensional_gibbs_free_energy_0 - &nondimensional_relative_gibbs_free_energy;
let residual_rel = &residual_abs/&nondimensional_gibbs_free_energy_0;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
#[test]
fn nondimensional_gibbs_free_energy_per_link()
{
let parameters = Parameters::default();
let mut rng = rand::thread_rng();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let nondimensional_gibbs_free_energy_per_link = model.nondimensional_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness, &temperature);
let nondimensional_gibbs_free_energy_per_link_0 = model.nondimensional_gibbs_free_energy_per_link(&ZERO, &nondimensional_potential_stiffness, &temperature);
let nondimensional_relative_gibbs_free_energy_per_link = model.nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let residual_abs = &nondimensional_gibbs_free_energy_per_link - &nondimensional_gibbs_free_energy_per_link_0 - &nondimensional_relative_gibbs_free_energy_per_link;
let residual_rel = &residual_abs/&nondimensional_gibbs_free_energy_per_link_0;
assert!(residual_abs.abs() <= parameters.abs_tol);
assert!(residual_rel.abs() <= parameters.rel_tol);
}
}
}
mod zero
{
use super::*;
use rand::Rng;
use crate::physics::single_chain::fjc::thermodynamics::modified_canonical::ZERO;
#[test]
fn force()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let force_0 = model.force(&ZERO, &potential_stiffness);
assert!(force_0.abs() <= potential_stiffness*ZERO);
}
}
#[test]
fn nondimensional_force()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let nondimensional_force_0 = model.nondimensional_force(&ZERO, &nondimensional_potential_stiffness);
assert!(nondimensional_force_0.abs() <= (number_of_links as f64)*nondimensional_potential_stiffness*ZERO);
}
}
#[test]
fn relative_gibbs_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let relative_gibbs_free_energy_0 = model.relative_gibbs_free_energy(&(ZERO*(number_of_links as f64)*link_length), &nondimensional_potential_stiffness, &temperature);
assert!(relative_gibbs_free_energy_0.abs() <= ZERO);
}
}
#[test]
fn relative_gibbs_free_energy_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let relative_gibbs_free_energy_per_link_0 = model.relative_gibbs_free_energy_per_link(&(ZERO*(number_of_links as f64)*link_length), &nondimensional_potential_stiffness, &temperature);
assert!(relative_gibbs_free_energy_per_link_0.abs() <= ZERO);
}
}
#[test]
fn nondimensional_relative_gibbs_free_energy()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let nondimensional_relative_gibbs_free_energy_0 = model.nondimensional_relative_gibbs_free_energy(&ZERO, &nondimensional_potential_stiffness);
assert!(nondimensional_relative_gibbs_free_energy_0.abs() <= ZERO);
}
}
#[test]
fn nondimensional_relative_gibbs_free_energy_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let nondimensional_relative_gibbs_free_energy_per_link_0 = model.nondimensional_relative_gibbs_free_energy_per_link(&ZERO, &nondimensional_potential_stiffness);
assert!(nondimensional_relative_gibbs_free_energy_per_link_0.abs() <= ZERO);
}
}
}
mod connection
{
use super::*;
use rand::Rng;
#[test]
fn end_to_end_length()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + 0.5*parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let end_to_end_length = model.end_to_end_length(&potential_distance, &potential_stiffness, &temperature);
let h = parameters.rel_tol*(number_of_links as f64)*link_length;
let end_to_end_length_from_derivative = -1.0/potential_stiffness*(model.relative_gibbs_free_energy(&(potential_distance + 0.5*h), &potential_stiffness, &temperature) - model.relative_gibbs_free_energy(&(potential_distance - 0.5*h), &potential_stiffness, &temperature))/h;
let residual_abs = &end_to_end_length - &end_to_end_length_from_derivative;
let residual_rel = &residual_abs/&end_to_end_length;
assert!(residual_rel.abs() <= h);
}
}
#[test]
fn end_to_end_length_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + 0.5*parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let temperature = parameters.temperature_reference + parameters.temperature_scale*(0.5 - rng.gen::<f64>());
let potential_distance = nondimensional_potential_distance*(number_of_links as f64)*link_length;
let potential_stiffness = nondimensional_potential_stiffness/link_length.powi(2)*BOLTZMANN_CONSTANT*temperature;
let end_to_end_length_per_link = model.end_to_end_length_per_link(&potential_distance, &potential_stiffness, &temperature);
let h = parameters.rel_tol*(number_of_links as f64)*link_length;
let end_to_end_length_per_link_from_derivative = -1.0/potential_stiffness*(model.relative_gibbs_free_energy_per_link(&(potential_distance + 0.5*h), &potential_stiffness, &temperature) - model.relative_gibbs_free_energy_per_link(&(potential_distance - 0.5*h), &potential_stiffness, &temperature))/h;
let residual_abs = &end_to_end_length_per_link - &end_to_end_length_per_link_from_derivative;
let residual_rel = &residual_abs/&end_to_end_length_per_link;
assert!(residual_rel.abs() <= h);
}
}
#[test]
fn nondimensional_end_to_end_length()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + 0.5*parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let nondimensional_end_to_end_length = model.nondimensional_end_to_end_length(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let h = parameters.rel_tol;
let nondimensional_end_to_end_length_from_derivative = -1.0/nondimensional_potential_stiffness/(number_of_links as f64)*(model.nondimensional_relative_gibbs_free_energy(&(nondimensional_potential_distance + 0.5*h), &nondimensional_potential_stiffness) - model.nondimensional_relative_gibbs_free_energy(&(nondimensional_potential_distance - 0.5*h), &nondimensional_potential_stiffness))/h;
let residual_abs = &nondimensional_end_to_end_length - &nondimensional_end_to_end_length_from_derivative;
let residual_rel = &residual_abs/&nondimensional_end_to_end_length;
assert!(residual_rel.abs() <= h);
}
}
#[test]
fn nondimensional_end_to_end_length_per_link()
{
let mut rng = rand::thread_rng();
let parameters = Parameters::default();
for _ in 0..parameters.number_of_loops
{
let number_of_links: u8 = rng.gen_range(parameters.number_of_links_minimum..parameters.number_of_links_maximum);
let link_length = parameters.link_length_reference + parameters.link_length_scale*(0.5 - rng.gen::<f64>());
let hinge_mass = parameters.hinge_mass_reference + parameters.hinge_mass_scale*(0.5 - rng.gen::<f64>());
let model = FJC::init(number_of_links, link_length, hinge_mass);
let nondimensional_potential_distance = parameters.nondimensional_potential_distance_reference + 0.5*parameters.nondimensional_potential_distance_scale*(0.5 - rng.gen::<f64>());
let nondimensional_potential_stiffness = parameters.nondimensional_potential_stiffness_reference + 0.5*parameters.nondimensional_potential_stiffness_scale*(0.5 - rng.gen::<f64>());
let nondimensional_end_to_end_length_per_link = model.nondimensional_end_to_end_length_per_link(&nondimensional_potential_distance, &nondimensional_potential_stiffness);
let h = parameters.rel_tol;
let nondimensional_end_to_end_length_per_link_from_derivative = -1.0/nondimensional_potential_stiffness/(number_of_links as f64)*(model.nondimensional_relative_gibbs_free_energy_per_link(&(nondimensional_potential_distance + 0.5*h), &nondimensional_potential_stiffness) - model.nondimensional_relative_gibbs_free_energy_per_link(&(nondimensional_potential_distance - 0.5*h), &nondimensional_potential_stiffness))/h;
let residual_abs = &nondimensional_end_to_end_length_per_link - &nondimensional_end_to_end_length_per_link_from_derivative;
let residual_rel = &residual_abs/&nondimensional_end_to_end_length_per_link;
assert!(residual_rel.abs() <= h);
}
}
}
|
#[macro_use] extern crate nom;
use nom::IResult;
use nom::util::{generate_colors,prepare_errors,print_codes,print_offsets};
use std::collections::HashMap;
fn main() {
named!(err_test, alt!(
tag!("abcd") |
error!(12,
preceded!(tag!("efgh"), error!(42,
chain!(
tag!("ijk") ~
res: error!(128, tag!("mnop")) ,
|| { res }
)
)
)
)
));
let a = &b"efghblah"[..];
let b = &b"efghijklblahblah"[..];
let res_a = err_test(a);
let res_b = err_test(b);
display_error(a, res_a);
display_error(b, res_b);
}
pub fn display_error<I,O>(input: &[u8], res: IResult<I,O>) {
let mut h: HashMap<u32, &str> = HashMap::new();
h.insert(12, "preceded");
h.insert(42, "chain");
h.insert(128, "tag mnop");
h.insert(0, "tag");
if let Some(v) = prepare_errors(input, res) {
let colors = generate_colors(&v);
println!("parsers: {}", print_codes(colors, h));
println!("{}", print_offsets(input, 0, &v));
} else {
println!("not an error");
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoStorageBaseProperties {
#[serde(rename = "storageAccountId")]
pub storage_account_id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountUpdateProperties {
#[serde(rename = "autoStorage", default, skip_serializing_if = "Option::is_none")]
pub auto_storage: Option<AutoStorageBaseProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub encryption: Option<EncryptionProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountCreateProperties {
#[serde(rename = "autoStorage", default, skip_serializing_if = "Option::is_none")]
pub auto_storage: Option<AutoStorageBaseProperties>,
#[serde(rename = "poolAllocationMode", default, skip_serializing_if = "Option::is_none")]
pub pool_allocation_mode: Option<PoolAllocationMode>,
#[serde(rename = "keyVaultReference", default, skip_serializing_if = "Option::is_none")]
pub key_vault_reference: Option<KeyVaultReference>,
#[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")]
pub public_network_access: Option<PublicNetworkAccessType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub encryption: Option<EncryptionProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountCreateParameters {
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<BatchAccountCreateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<BatchAccountIdentity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVaultReference {
pub id: String,
pub url: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoStorageProperties {
#[serde(flatten)]
pub auto_storage_base_properties: AutoStorageBaseProperties,
#[serde(rename = "lastKeySync")]
pub last_key_sync: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachineFamilyCoreQuota {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "coreQuota", default, skip_serializing_if = "Option::is_none")]
pub core_quota: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountIdentity {
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "type")]
pub type_: batch_account_identity::Type,
}
pub mod batch_account_identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
SystemAssigned,
None,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountProperties {
#[serde(rename = "accountEndpoint", default, skip_serializing_if = "Option::is_none")]
pub account_endpoint: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<batch_account_properties::ProvisioningState>,
#[serde(rename = "poolAllocationMode", default, skip_serializing_if = "Option::is_none")]
pub pool_allocation_mode: Option<PoolAllocationMode>,
#[serde(rename = "keyVaultReference", default, skip_serializing_if = "Option::is_none")]
pub key_vault_reference: Option<KeyVaultReference>,
#[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")]
pub public_network_access: Option<PublicNetworkAccessType>,
#[serde(rename = "privateEndpointConnections", default, skip_serializing_if = "Vec::is_empty")]
pub private_endpoint_connections: Vec<PrivateEndpointConnection>,
#[serde(rename = "autoStorage", default, skip_serializing_if = "Option::is_none")]
pub auto_storage: Option<AutoStorageProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub encryption: Option<EncryptionProperties>,
#[serde(rename = "dedicatedCoreQuota", default, skip_serializing_if = "Option::is_none")]
pub dedicated_core_quota: Option<i32>,
#[serde(rename = "lowPriorityCoreQuota", default, skip_serializing_if = "Option::is_none")]
pub low_priority_core_quota: Option<i32>,
#[serde(rename = "dedicatedCoreQuotaPerVMFamily", default, skip_serializing_if = "Vec::is_empty")]
pub dedicated_core_quota_per_vm_family: Vec<VirtualMachineFamilyCoreQuota>,
#[serde(rename = "dedicatedCoreQuotaPerVMFamilyEnforced", default, skip_serializing_if = "Option::is_none")]
pub dedicated_core_quota_per_vm_family_enforced: Option<bool>,
#[serde(rename = "poolQuota", default, skip_serializing_if = "Option::is_none")]
pub pool_quota: Option<i32>,
#[serde(rename = "activeJobAndJobScheduleQuota", default, skip_serializing_if = "Option::is_none")]
pub active_job_and_job_schedule_quota: Option<i32>,
}
pub mod batch_account_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Invalid,
Creating,
Deleting,
Succeeded,
Failed,
Cancelled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccount {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<BatchAccountProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<BatchAccountIdentity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<BatchAccountUpdateProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<BatchAccountIdentity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<BatchAccount>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncryptionProperties {
#[serde(rename = "keySource", default, skip_serializing_if = "Option::is_none")]
pub key_source: Option<encryption_properties::KeySource>,
#[serde(rename = "keyVaultProperties", default, skip_serializing_if = "Option::is_none")]
pub key_vault_properties: Option<KeyVaultProperties>,
}
pub mod encryption_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeySource {
#[serde(rename = "Microsoft.Batch")]
MicrosoftBatch,
#[serde(rename = "Microsoft.KeyVault")]
MicrosoftKeyVault,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyVaultProperties {
#[serde(rename = "keyIdentifier", default, skip_serializing_if = "Option::is_none")]
pub key_identifier: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountRegenerateKeyParameters {
#[serde(rename = "keyName")]
pub key_name: batch_account_regenerate_key_parameters::KeyName,
}
pub mod batch_account_regenerate_key_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeyName {
Primary,
Secondary,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchAccountKeys {
#[serde(rename = "accountName", default, skip_serializing_if = "Option::is_none")]
pub account_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub primary: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub secondary: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActivateApplicationPackageParameters {
pub format: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Application {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ApplicationProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApplicationProperties {
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "allowUpdates", default, skip_serializing_if = "Option::is_none")]
pub allow_updates: Option<bool>,
#[serde(rename = "defaultVersion", default, skip_serializing_if = "Option::is_none")]
pub default_version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApplicationPackage {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ApplicationPackageProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApplicationPackageProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<application_package_properties::State>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
#[serde(rename = "storageUrl", default, skip_serializing_if = "Option::is_none")]
pub storage_url: Option<String>,
#[serde(rename = "storageUrlExpiry", default, skip_serializing_if = "Option::is_none")]
pub storage_url_expiry: Option<String>,
#[serde(rename = "lastActivationTime", default, skip_serializing_if = "Option::is_none")]
pub last_activation_time: Option<String>,
}
pub mod application_package_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
Pending,
Active,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListApplicationsResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Application>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListApplicationPackagesResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ApplicationPackage>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BatchLocationQuota {
#[serde(rename = "accountQuota", default, skip_serializing_if = "Option::is_none")]
pub account_quota: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProxyResource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PublicNetworkAccessType {
Enabled,
Disabled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PoolAllocationMode {
BatchService,
UserSubscription,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateBaseProperties {
#[serde(rename = "thumbprintAlgorithm", default, skip_serializing_if = "Option::is_none")]
pub thumbprint_algorithm: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thumbprint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format: Option<certificate_base_properties::Format>,
}
pub mod certificate_base_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Format {
Pfx,
Cer,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateProperties {
#[serde(flatten)]
pub certificate_base_properties: CertificateBaseProperties,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<certificate_properties::ProvisioningState>,
#[serde(rename = "provisioningStateTransitionTime", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state_transition_time: Option<String>,
#[serde(rename = "previousProvisioningState", default, skip_serializing_if = "Option::is_none")]
pub previous_provisioning_state: Option<certificate_properties::PreviousProvisioningState>,
#[serde(
rename = "previousProvisioningStateTransitionTime",
default,
skip_serializing_if = "Option::is_none"
)]
pub previous_provisioning_state_transition_time: Option<String>,
#[serde(rename = "publicData", default, skip_serializing_if = "Option::is_none")]
pub public_data: Option<String>,
#[serde(rename = "deleteCertificateError", default, skip_serializing_if = "Option::is_none")]
pub delete_certificate_error: Option<DeleteCertificateError>,
}
pub mod certificate_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Deleting,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PreviousProvisioningState {
Succeeded,
Deleting,
Failed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateCreateOrUpdateProperties {
#[serde(flatten)]
pub certificate_base_properties: CertificateBaseProperties,
pub data: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Certificate {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CertificateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateCreateOrUpdateParameters {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CertificateCreateOrUpdateProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListCertificatesResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Certificate>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeleteCertificateError {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<DeleteCertificateError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateLinkResource {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PrivateLinkResourceProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateLinkResourceProperties {
#[serde(rename = "groupId", default, skip_serializing_if = "Option::is_none")]
pub group_id: Option<String>,
#[serde(rename = "requiredMembers", default, skip_serializing_if = "Vec::is_empty")]
pub required_members: Vec<String>,
#[serde(rename = "requiredZoneNames", default, skip_serializing_if = "Vec::is_empty")]
pub required_zone_names: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateEndpointConnection {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PrivateEndpointConnectionProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateEndpointConnectionProperties {
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<private_endpoint_connection_properties::ProvisioningState>,
#[serde(rename = "privateEndpoint", default, skip_serializing_if = "Option::is_none")]
pub private_endpoint: Option<PrivateEndpoint>,
#[serde(rename = "privateLinkServiceConnectionState", default, skip_serializing_if = "Option::is_none")]
pub private_link_service_connection_state: Option<PrivateLinkServiceConnectionState>,
}
pub mod private_endpoint_connection_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Updating,
Failed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateEndpoint {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateLinkServiceConnectionState {
pub status: PrivateLinkServiceConnectionStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "actionRequired", default, skip_serializing_if = "Option::is_none")]
pub action_required: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PrivateLinkServiceConnectionStatus {
Approved,
Pending,
Rejected,
Disconnected,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Pool {
#[serde(flatten)]
pub proxy_resource: ProxyResource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PoolProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PoolProperties {
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "lastModified", default, skip_serializing_if = "Option::is_none")]
pub last_modified: Option<String>,
#[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")]
pub creation_time: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<pool_properties::ProvisioningState>,
#[serde(rename = "provisioningStateTransitionTime", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state_transition_time: Option<String>,
#[serde(rename = "allocationState", default, skip_serializing_if = "Option::is_none")]
pub allocation_state: Option<pool_properties::AllocationState>,
#[serde(rename = "allocationStateTransitionTime", default, skip_serializing_if = "Option::is_none")]
pub allocation_state_transition_time: Option<String>,
#[serde(rename = "vmSize", default, skip_serializing_if = "Option::is_none")]
pub vm_size: Option<String>,
#[serde(rename = "deploymentConfiguration", default, skip_serializing_if = "Option::is_none")]
pub deployment_configuration: Option<DeploymentConfiguration>,
#[serde(rename = "currentDedicatedNodes", default, skip_serializing_if = "Option::is_none")]
pub current_dedicated_nodes: Option<i32>,
#[serde(rename = "currentLowPriorityNodes", default, skip_serializing_if = "Option::is_none")]
pub current_low_priority_nodes: Option<i32>,
#[serde(rename = "scaleSettings", default, skip_serializing_if = "Option::is_none")]
pub scale_settings: Option<ScaleSettings>,
#[serde(rename = "autoScaleRun", default, skip_serializing_if = "Option::is_none")]
pub auto_scale_run: Option<AutoScaleRun>,
#[serde(rename = "interNodeCommunication", default, skip_serializing_if = "Option::is_none")]
pub inter_node_communication: Option<pool_properties::InterNodeCommunication>,
#[serde(rename = "networkConfiguration", default, skip_serializing_if = "Option::is_none")]
pub network_configuration: Option<NetworkConfiguration>,
#[serde(rename = "maxTasksPerNode", default, skip_serializing_if = "Option::is_none")]
pub max_tasks_per_node: Option<i32>,
#[serde(rename = "taskSchedulingPolicy", default, skip_serializing_if = "Option::is_none")]
pub task_scheduling_policy: Option<TaskSchedulingPolicy>,
#[serde(rename = "userAccounts", default, skip_serializing_if = "Vec::is_empty")]
pub user_accounts: Vec<UserAccount>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metadata: Vec<MetadataItem>,
#[serde(rename = "startTask", default, skip_serializing_if = "Option::is_none")]
pub start_task: Option<StartTask>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub certificates: Vec<CertificateReference>,
#[serde(rename = "applicationPackages", default, skip_serializing_if = "Vec::is_empty")]
pub application_packages: Vec<ApplicationPackageReference>,
#[serde(rename = "applicationLicenses", default, skip_serializing_if = "Vec::is_empty")]
pub application_licenses: Vec<String>,
#[serde(rename = "resizeOperationStatus", default, skip_serializing_if = "Option::is_none")]
pub resize_operation_status: Option<ResizeOperationStatus>,
#[serde(rename = "mountConfiguration", default, skip_serializing_if = "Vec::is_empty")]
pub mount_configuration: Vec<MountConfiguration>,
}
pub mod pool_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Deleting,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AllocationState {
Steady,
Resizing,
Stopping,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum InterNodeCommunication {
Enabled,
Disabled,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeploymentConfiguration {
#[serde(rename = "cloudServiceConfiguration", default, skip_serializing_if = "Option::is_none")]
pub cloud_service_configuration: Option<CloudServiceConfiguration>,
#[serde(rename = "virtualMachineConfiguration", default, skip_serializing_if = "Option::is_none")]
pub virtual_machine_configuration: Option<VirtualMachineConfiguration>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScaleSettings {
#[serde(rename = "fixedScale", default, skip_serializing_if = "Option::is_none")]
pub fixed_scale: Option<FixedScaleSettings>,
#[serde(rename = "autoScale", default, skip_serializing_if = "Option::is_none")]
pub auto_scale: Option<AutoScaleSettings>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoScaleSettings {
pub formula: String,
#[serde(rename = "evaluationInterval", default, skip_serializing_if = "Option::is_none")]
pub evaluation_interval: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FixedScaleSettings {
#[serde(rename = "resizeTimeout", default, skip_serializing_if = "Option::is_none")]
pub resize_timeout: Option<String>,
#[serde(rename = "targetDedicatedNodes", default, skip_serializing_if = "Option::is_none")]
pub target_dedicated_nodes: Option<i32>,
#[serde(rename = "targetLowPriorityNodes", default, skip_serializing_if = "Option::is_none")]
pub target_low_priority_nodes: Option<i32>,
#[serde(rename = "nodeDeallocationOption", default, skip_serializing_if = "Option::is_none")]
pub node_deallocation_option: Option<ComputeNodeDeallocationOption>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ComputeNodeDeallocationOption {
Requeue,
Terminate,
TaskCompletion,
RetainedData,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CertificateReference {
pub id: String,
#[serde(rename = "storeLocation", default, skip_serializing_if = "Option::is_none")]
pub store_location: Option<certificate_reference::StoreLocation>,
#[serde(rename = "storeName", default, skip_serializing_if = "Option::is_none")]
pub store_name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub visibility: Vec<String>,
}
pub mod certificate_reference {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StoreLocation {
CurrentUser,
LocalMachine,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApplicationPackageReference {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResizeError {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ResizeError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoScaleRunError {
pub code: String,
pub message: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<AutoScaleRunError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoScaleRun {
#[serde(rename = "evaluationTime")]
pub evaluation_time: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub results: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<AutoScaleRunError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachineConfiguration {
#[serde(rename = "imageReference")]
pub image_reference: ImageReference,
#[serde(rename = "nodeAgentSkuId")]
pub node_agent_sku_id: String,
#[serde(rename = "windowsConfiguration", default, skip_serializing_if = "Option::is_none")]
pub windows_configuration: Option<WindowsConfiguration>,
#[serde(rename = "dataDisks", default, skip_serializing_if = "Vec::is_empty")]
pub data_disks: Vec<DataDisk>,
#[serde(rename = "licenseType", default, skip_serializing_if = "Option::is_none")]
pub license_type: Option<String>,
#[serde(rename = "containerConfiguration", default, skip_serializing_if = "Option::is_none")]
pub container_configuration: Option<ContainerConfiguration>,
#[serde(rename = "diskEncryptionConfiguration", default, skip_serializing_if = "Option::is_none")]
pub disk_encryption_configuration: Option<DiskEncryptionConfiguration>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerRegistry {
#[serde(rename = "registryServer", default, skip_serializing_if = "Option::is_none")]
pub registry_server: Option<String>,
pub username: String,
pub password: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiskEncryptionConfiguration {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub targets: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerConfiguration {
#[serde(rename = "type")]
pub type_: container_configuration::Type,
#[serde(rename = "containerImageNames", default, skip_serializing_if = "Vec::is_empty")]
pub container_image_names: Vec<String>,
#[serde(rename = "containerRegistries", default, skip_serializing_if = "Vec::is_empty")]
pub container_registries: Vec<ContainerRegistry>,
}
pub mod container_configuration {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
DockerCompatible,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WindowsConfiguration {
#[serde(rename = "enableAutomaticUpdates", default, skip_serializing_if = "Option::is_none")]
pub enable_automatic_updates: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImageReference {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub publisher: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub offer: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataDisk {
pub lun: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub caching: Option<CachingType>,
#[serde(rename = "diskSizeGB")]
pub disk_size_gb: i32,
#[serde(rename = "storageAccountType", default, skip_serializing_if = "Option::is_none")]
pub storage_account_type: Option<StorageAccountType>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TaskSchedulingPolicy {
#[serde(rename = "nodeFillType")]
pub node_fill_type: task_scheduling_policy::NodeFillType,
}
pub mod task_scheduling_policy {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NodeFillType {
Spread,
Pack,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinuxUserConfiguration {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uid: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gid: Option<i32>,
#[serde(rename = "sshPrivateKey", default, skip_serializing_if = "Option::is_none")]
pub ssh_private_key: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WindowsUserConfiguration {
#[serde(rename = "loginMode", default, skip_serializing_if = "Option::is_none")]
pub login_mode: Option<windows_user_configuration::LoginMode>,
}
pub mod windows_user_configuration {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LoginMode {
Batch,
Interactive,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UserAccount {
pub name: String,
pub password: String,
#[serde(rename = "elevationLevel", default, skip_serializing_if = "Option::is_none")]
pub elevation_level: Option<ElevationLevel>,
#[serde(rename = "linuxUserConfiguration", default, skip_serializing_if = "Option::is_none")]
pub linux_user_configuration: Option<LinuxUserConfiguration>,
#[serde(rename = "windowsUserConfiguration", default, skip_serializing_if = "Option::is_none")]
pub windows_user_configuration: Option<WindowsUserConfiguration>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StartTask {
#[serde(rename = "commandLine", default, skip_serializing_if = "Option::is_none")]
pub command_line: Option<String>,
#[serde(rename = "resourceFiles", default, skip_serializing_if = "Vec::is_empty")]
pub resource_files: Vec<ResourceFile>,
#[serde(rename = "environmentSettings", default, skip_serializing_if = "Vec::is_empty")]
pub environment_settings: Vec<EnvironmentSetting>,
#[serde(rename = "userIdentity", default, skip_serializing_if = "Option::is_none")]
pub user_identity: Option<UserIdentity>,
#[serde(rename = "maxTaskRetryCount", default, skip_serializing_if = "Option::is_none")]
pub max_task_retry_count: Option<i32>,
#[serde(rename = "waitForSuccess", default, skip_serializing_if = "Option::is_none")]
pub wait_for_success: Option<bool>,
#[serde(rename = "containerSettings", default, skip_serializing_if = "Option::is_none")]
pub container_settings: Option<TaskContainerSettings>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TaskContainerSettings {
#[serde(rename = "containerRunOptions", default, skip_serializing_if = "Option::is_none")]
pub container_run_options: Option<String>,
#[serde(rename = "imageName")]
pub image_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub registry: Option<ContainerRegistry>,
#[serde(rename = "workingDirectory", default, skip_serializing_if = "Option::is_none")]
pub working_directory: Option<task_container_settings::WorkingDirectory>,
}
pub mod task_container_settings {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum WorkingDirectory {
TaskWorkingDirectory,
ContainerImageDefault,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourceFile {
#[serde(rename = "autoStorageContainerName", default, skip_serializing_if = "Option::is_none")]
pub auto_storage_container_name: Option<String>,
#[serde(rename = "storageContainerUrl", default, skip_serializing_if = "Option::is_none")]
pub storage_container_url: Option<String>,
#[serde(rename = "httpUrl", default, skip_serializing_if = "Option::is_none")]
pub http_url: Option<String>,
#[serde(rename = "blobPrefix", default, skip_serializing_if = "Option::is_none")]
pub blob_prefix: Option<String>,
#[serde(rename = "filePath", default, skip_serializing_if = "Option::is_none")]
pub file_path: Option<String>,
#[serde(rename = "fileMode", default, skip_serializing_if = "Option::is_none")]
pub file_mode: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EnvironmentSetting {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UserIdentity {
#[serde(rename = "userName", default, skip_serializing_if = "Option::is_none")]
pub user_name: Option<String>,
#[serde(rename = "autoUser", default, skip_serializing_if = "Option::is_none")]
pub auto_user: Option<AutoUserSpecification>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AutoUserSpecification {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<auto_user_specification::Scope>,
#[serde(rename = "elevationLevel", default, skip_serializing_if = "Option::is_none")]
pub elevation_level: Option<ElevationLevel>,
}
pub mod auto_user_specification {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Scope {
Task,
Pool,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ElevationLevel {
NonAdmin,
Admin,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StorageAccountType {
#[serde(rename = "Standard_LRS")]
StandardLrs,
#[serde(rename = "Premium_LRS")]
PremiumLrs,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CachingType {
None,
ReadOnly,
ReadWrite,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum IpAddressProvisioningType {
BatchManaged,
UserManaged,
#[serde(rename = "NoPublicIPAddresses")]
NoPublicIpAddresses,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PublicIpAddressConfiguration {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provision: Option<IpAddressProvisioningType>,
#[serde(rename = "ipAddressIds", default, skip_serializing_if = "Vec::is_empty")]
pub ip_address_ids: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NetworkConfiguration {
#[serde(rename = "subnetId", default, skip_serializing_if = "Option::is_none")]
pub subnet_id: Option<String>,
#[serde(rename = "endpointConfiguration", default, skip_serializing_if = "Option::is_none")]
pub endpoint_configuration: Option<PoolEndpointConfiguration>,
#[serde(rename = "publicIPAddressConfiguration", default, skip_serializing_if = "Option::is_none")]
pub public_ip_address_configuration: Option<PublicIpAddressConfiguration>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudServiceConfiguration {
#[serde(rename = "osFamily")]
pub os_family: String,
#[serde(rename = "osVersion", default, skip_serializing_if = "Option::is_none")]
pub os_version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataItem {
pub name: String,
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResizeOperationStatus {
#[serde(rename = "targetDedicatedNodes", default, skip_serializing_if = "Option::is_none")]
pub target_dedicated_nodes: Option<i32>,
#[serde(rename = "targetLowPriorityNodes", default, skip_serializing_if = "Option::is_none")]
pub target_low_priority_nodes: Option<i32>,
#[serde(rename = "resizeTimeout", default, skip_serializing_if = "Option::is_none")]
pub resize_timeout: Option<String>,
#[serde(rename = "nodeDeallocationOption", default, skip_serializing_if = "Option::is_none")]
pub node_deallocation_option: Option<ComputeNodeDeallocationOption>,
#[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub errors: Vec<ResizeError>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PoolEndpointConfiguration {
#[serde(rename = "inboundNatPools")]
pub inbound_nat_pools: Vec<InboundNatPool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InboundNatPool {
pub name: String,
pub protocol: inbound_nat_pool::Protocol,
#[serde(rename = "backendPort")]
pub backend_port: i32,
#[serde(rename = "frontendPortRangeStart")]
pub frontend_port_range_start: i32,
#[serde(rename = "frontendPortRangeEnd")]
pub frontend_port_range_end: i32,
#[serde(rename = "networkSecurityGroupRules", default, skip_serializing_if = "Vec::is_empty")]
pub network_security_group_rules: Vec<NetworkSecurityGroupRule>,
}
pub mod inbound_nat_pool {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Protocol {
#[serde(rename = "TCP")]
Tcp,
#[serde(rename = "UDP")]
Udp,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NetworkSecurityGroupRule {
pub priority: i32,
pub access: network_security_group_rule::Access,
#[serde(rename = "sourceAddressPrefix")]
pub source_address_prefix: String,
#[serde(rename = "sourcePortRanges", default, skip_serializing_if = "Vec::is_empty")]
pub source_port_ranges: Vec<String>,
}
pub mod network_security_group_rule {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Access {
Allow,
Deny,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListPrivateLinkResourcesResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PrivateLinkResource>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListPrivateEndpointConnectionsResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PrivateEndpointConnection>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListPoolsResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Pool>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<CloudErrorBody>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudErrorBody {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<CloudErrorBody>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityParameters {
pub name: String,
#[serde(rename = "type")]
pub type_: check_name_availability_parameters::Type,
}
pub mod check_name_availability_parameters {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "Microsoft.Batch/batchAccounts")]
MicrosoftBatchBatchAccounts,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityResult {
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<check_name_availability_result::Reason>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
pub mod check_name_availability_result {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Reason {
Invalid,
AlreadyExists,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MountConfiguration {
#[serde(rename = "azureBlobFileSystemConfiguration", default, skip_serializing_if = "Option::is_none")]
pub azure_blob_file_system_configuration: Option<AzureBlobFileSystemConfiguration>,
#[serde(rename = "nfsMountConfiguration", default, skip_serializing_if = "Option::is_none")]
pub nfs_mount_configuration: Option<NfsMountConfiguration>,
#[serde(rename = "cifsMountConfiguration", default, skip_serializing_if = "Option::is_none")]
pub cifs_mount_configuration: Option<CifsMountConfiguration>,
#[serde(rename = "azureFileShareConfiguration", default, skip_serializing_if = "Option::is_none")]
pub azure_file_share_configuration: Option<AzureFileShareConfiguration>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureBlobFileSystemConfiguration {
#[serde(rename = "accountName")]
pub account_name: String,
#[serde(rename = "containerName")]
pub container_name: String,
#[serde(rename = "accountKey", default, skip_serializing_if = "Option::is_none")]
pub account_key: Option<String>,
#[serde(rename = "sasKey", default, skip_serializing_if = "Option::is_none")]
pub sas_key: Option<String>,
#[serde(rename = "blobfuseOptions", default, skip_serializing_if = "Option::is_none")]
pub blobfuse_options: Option<String>,
#[serde(rename = "relativeMountPath")]
pub relative_mount_path: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NfsMountConfiguration {
pub source: String,
#[serde(rename = "relativeMountPath")]
pub relative_mount_path: String,
#[serde(rename = "mountOptions", default, skip_serializing_if = "Option::is_none")]
pub mount_options: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CifsMountConfiguration {
pub username: String,
pub source: String,
#[serde(rename = "relativeMountPath")]
pub relative_mount_path: String,
#[serde(rename = "mountOptions", default, skip_serializing_if = "Option::is_none")]
pub mount_options: Option<String>,
pub password: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzureFileShareConfiguration {
#[serde(rename = "accountName")]
pub account_name: String,
#[serde(rename = "azureFileUrl")]
pub azure_file_url: String,
#[serde(rename = "accountKey")]
pub account_key: String,
#[serde(rename = "relativeMountPath")]
pub relative_mount_path: String,
#[serde(rename = "mountOptions", default, skip_serializing_if = "Option::is_none")]
pub mount_options: Option<String>,
}
|
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
pub approves_count: u32,
}
impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
approves_count: 0,
}
}
pub fn add_text(&mut self, text: &str) {
if let Some(s) = self.state.take() {
match s.add_text(text) {
Some(v) => self.content.push_str(v),
None => self.content.push_str(""),
};
}
}
pub fn content(&self) -> &str {
self.state.as_ref().content(&self)
//match self.state.as_ref() {
// Some(v) => v.content(&self),
// None => "",
//}
}
pub fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review());
}
}
pub fn reject(&mut self) {
self.approves_count = 0;
if let Some(s) = self.state.take() {
self.state = Some(s.reject());
}
}
pub fn approve(&mut self) {
self.approves_count += 1;
if self.approves_count < 2 {
return;
}
if let Some(s) = self.state.take() {
self.state = Some(s.approve());
}
}
}
trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
fn approve(self: Box<Self>) -> Box<dyn State>;
fn add_text(self: Box<Self>, text: &str) -> Option<&str>;
fn reject(self: Box<Self>) -> Box<dyn State> {
Box::new(Draft {})
}
fn content<'a>(&self, _post: &'a Post) -> &'a str {
""
}
}
struct Draft {}
impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
fn reject(self: Box<Self>) -> Box<dyn State> {
self
}
fn add_text(self: Box<Self>, text: &str) -> Option<&str> {
Some(text)
}
}
struct PendingReview {}
impl State for PendingReview {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
Box::new(Published {})
}
fn reject(self: Box<Self>) -> Box<dyn State> {
Box::new(Draft {})
}
fn add_text(self: Box<Self>, _text: &str) -> Option<&str> {
None
}
}
struct Published {}
impl State for Published {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
fn reject(self: Box<Self>) -> Box<dyn State> {
Box::new(Draft {})
}
fn content<'a>(&self, post: &'a Post) -> &'a str {
&post.content
}
fn add_text(self: Box<Self>, _text: &str) -> Option<&str> {
None
}
}
|
use crate::execution::chunk::{Chunk, Opcode};
use crate::image_parsing::ast::{Program, Stmt, Expr, Op};
use std::collections::HashMap;
pub fn compile(program:&Program) -> Result<Chunk, String> {
let mut res = Chunk::new();
let variable_map = assign_variables(program)?;
let mut compiler = Compiler{variable_map, constant_map:HashMap::new()};
for stmt in program{
match stmt{
Stmt::Define(_x) => {
res += Opcode::LoadImmediate(0);
}
Stmt::Assign(target, expr) => {
compiler.visit_compile_expr(expr, &mut res)?;
let slot = *compiler.variable_map.get(target)
.ok_or(format!("unknown variable {}", decode_variable(*target)))?;
res += Opcode::Store(slot);
}
Stmt::PrintStmt(expr) => {
compiler.visit_compile_expr(expr, &mut res)?;
res += Opcode::Print;
}
}
}
Ok(res)
}
fn assign_variables(program:&Program) -> Result<HashMap<usize, u8>, String> {
let mut res = HashMap::new();
for stmt in program{
match stmt {
Stmt::Define(variable) => {
if res.contains_key(variable) {
Err(format!(
"redefinition of variable {}",
decode_variable(*variable)
))?;
}
if res.len() == u8::MAX as usize {
Err("too many variables, compiler supports maximum of 255")?;
}
res.insert(*variable, res.len() as u8);
}
_ => {}
}
}
Ok(res)
}
fn decode_variable(mut n:usize) -> String {
//read 3 bytes of rgb into (r,g,b) string
let b = n & 0xff;
n>>=8;
let g = n & 0xff;
n>>=8;
let r = n & 0xff;
format!("({},{},{})", r, g, b)
}
struct Compiler {
variable_map: HashMap<usize, u8>,
constant_map: HashMap<i64, u8>,
}
impl Compiler{
fn visit_compile_expr(&mut self, expr:&Expr, chunk: &mut Chunk) -> Result<(), String> {
match expr {
Expr::Number(x) => {
let x = *x;
if x>= i8::MIN as i64 && x<= i8::MAX as i64 {
*chunk += Opcode::LoadImmediate(x as i8);
}else{
if self.constant_map.contains_key(&x){
*chunk += Opcode::LoadConst(*self.constant_map.get(&x).unwrap());
return Ok(());
}
if chunk.constants.len()== u8::MAX as usize {
Err("too many constants, compiler supports maximum of 255 long constants")?;
}
let idx = chunk.constants.len();
chunk.constants.push(x);
self.constant_map.insert(x, idx as u8);
*chunk += Opcode::LoadConst(x as u8);
}
}
Expr::Variable(v) => {
let stack_idx = *self.variable_map.get(v)
.ok_or(format!("unknown variable {}", decode_variable(*v)))?;
*chunk += Opcode::Load(stack_idx);
}
Expr::Binary(op, left, right) => {
self.visit_compile_expr(left, chunk)?;
self.visit_compile_expr(right, chunk)?;
*chunk += match op {
Op::Mul => {Opcode::Mul}
Op::Div => {Opcode::Div}
Op::Add => {Opcode::Add}
Op::Sub => {Opcode::Sub}
};
}
}
Ok(())
}
}
|
use amethyst::{core::{Axis2, transform::Transform}, ecs::World, renderer::Camera, utils::ortho_camera::{CameraNormalizeMode, CameraOrtho, CameraOrthoWorldCoordinates}};
pub fn initialize_camera(world: &mut World, width: f32, height: f32) {
let mut transform = Transform::default();
transform.set_translation_xyz(0.0, height * 1.0, 1.0);
let mut ortho = CameraOrtho::default();
ortho.mode = CameraNormalizeMode::Contain;
ortho.world_coordinates = CameraOrthoWorldCoordinates {
left: 0.0,
top: height,
right: width,
bottom: 0.0,
far: 2000.0,
near: 1.0,
};
world.push((Camera::standard_2d(width, height), transform, ortho));
}
|
//! Save bad network\'s ass.
pub mod models;
pub mod parser;
pub mod schemas;
mod sql;
use self::models::*;
use self::schemas::{problems::dsl::*, tags::dsl::*};
use self::sql::*;
use crate::helper::test_cases_path;
use crate::{config::Config, err::Error, plugins::LeetCode};
use anyhow::anyhow;
use colored::Colorize;
use diesel::prelude::*;
use reqwest::Response;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::HashMap;
/// sqlite connection
pub fn conn(p: String) -> SqliteConnection {
SqliteConnection::establish(&p).unwrap_or_else(|_| panic!("Error connecting to {:?}", p))
}
/// Condition submit or test
#[derive(Clone, Debug)]
pub enum Run {
Test,
Submit,
}
impl Default for Run {
fn default() -> Self {
Run::Submit
}
}
/// Requests if data not download
#[derive(Clone)]
pub struct Cache(pub LeetCode);
impl Cache {
/// Ref to sqlite connection
fn conn(&self) -> Result<SqliteConnection, Error> {
Ok(conn(self.0.conf.storage.cache()?))
}
/// Clean cache
pub fn clean(&self) -> Result<(), Error> {
Ok(std::fs::remove_file(self.0.conf.storage.cache()?)?)
}
/// ref to download problems
pub async fn update(self) -> Result<(), Error> {
self.download_problems().await?;
Ok(())
}
pub fn update_after_ac(self, rid: i32) -> Result<(), Error> {
let mut c = conn(self.0.conf.storage.cache()?);
let target = problems.filter(id.eq(rid));
diesel::update(target)
.set(status.eq("ac"))
.execute(&mut c)?;
Ok(())
}
async fn get_user_info(&self) -> Result<(String, bool), Error> {
let user = parser::user(self.clone().0.get_user_info().await?.json().await?);
match user {
None => Err(Error::NoneError),
Some(None) => Err(Error::CookieError),
Some(Some((s, b))) => Ok((s, b)),
}
}
async fn is_session_bad(&self) -> bool {
// i.e. self.get_user_info().contains_err(Error::CookieError)
matches!(self.get_user_info().await, Err(Error::CookieError))
}
async fn resp_to_json<T: DeserializeOwned>(&self, resp: Response) -> Result<T, Error> {
let maybe_json: Result<T, _> = resp.json().await;
if maybe_json.is_err() && self.is_session_bad().await {
Err(Error::CookieError)
} else {
Ok(maybe_json?)
}
}
/// Download leetcode problems to db
pub async fn download_problems(self) -> Result<Vec<Problem>, Error> {
info!("Fetching leetcode problems...");
let mut ps: Vec<Problem> = vec![];
for i in &self.0.conf.sys.categories.to_owned() {
let json = self
.0
.clone()
.get_category_problems(i)
.await?
.json() // does not require LEETCODE_SESSION
.await?;
parser::problem(&mut ps, json).ok_or(Error::NoneError)?;
}
diesel::replace_into(problems)
.values(&ps)
.execute(&mut self.conn()?)?;
Ok(ps)
}
/// Get problem
pub fn get_problem(&self, rfid: i32) -> Result<Problem, Error> {
let p: Problem = problems.filter(fid.eq(rfid)).first(&mut self.conn()?)?;
if p.category != "algorithms" {
return Err(Error::FeatureError(
"Not support database and shell questions for now".to_string(),
));
}
Ok(p)
}
/// Get problem from name
pub fn get_problem_id_from_name(&self, problem_name: &String) -> Result<i32, Error> {
let p: Problem = problems
.filter(name.eq(problem_name))
.first(&mut self.conn()?)?;
if p.category != "algorithms" {
return Err(Error::FeatureError(
"Not support database and shell questions for now".to_string(),
));
}
Ok(p.fid)
}
/// Get daily problem
pub async fn get_daily_problem_id(&self) -> Result<i32, Error> {
parser::daily(
self.clone()
.0
.get_question_daily()
.await?
.json() // does not require LEETCODE_SESSION
.await?,
)
.ok_or(Error::NoneError)
}
/// Get problems from cache
pub fn get_problems(&self) -> Result<Vec<Problem>, Error> {
Ok(problems.load::<Problem>(&mut self.conn()?)?)
}
/// Get question
#[allow(clippy::useless_let_if_seq)]
pub async fn get_question(&self, rfid: i32) -> Result<Question, Error> {
let target: Problem = problems.filter(fid.eq(rfid)).first(&mut self.conn()?)?;
let ids = match target.level {
1 => target.fid.to_string().green(),
2 => target.fid.to_string().yellow(),
3 => target.fid.to_string().red(),
_ => target.fid.to_string().dimmed(),
};
println!(
"\n[{}] {} {}\n\n",
&ids,
&target.name.bold().underline(),
"is on the run...".dimmed()
);
if target.category != "algorithms" {
return Err(Error::FeatureError(
"Not support database and shell questions for now".to_string(),
));
}
let mut rdesc = Question::default();
if !target.desc.is_empty() {
rdesc = serde_json::from_str(&target.desc)?;
} else {
let json: Value = self
.0
.clone()
.get_question_detail(&target.slug)
.await?
.json()
.await?;
debug!("{:#?}", &json);
match parser::desc(&mut rdesc, json) {
None => return Err(Error::NoneError),
Some(false) => {
return if self.is_session_bad().await {
Err(Error::CookieError)
} else {
Err(Error::PremiumError)
}
}
Some(true) => (),
}
// update the question
let sdesc = serde_json::to_string(&rdesc)?;
diesel::update(&target)
.set(desc.eq(sdesc))
.execute(&mut self.conn()?)?;
}
Ok(rdesc)
}
pub async fn get_tagged_questions(self, rslug: &str) -> Result<Vec<String>, Error> {
trace!("Geting {} questions...", &rslug);
let ids: Vec<String>;
let rtag = tags
.filter(tag.eq(rslug.to_string()))
.first::<Tag>(&mut self.conn()?);
if let Ok(t) = rtag {
trace!("Got {} questions from local cache...", &rslug);
ids = serde_json::from_str(&t.refs)?;
} else {
ids = parser::tags(
self.clone()
.0
.get_question_ids_by_tag(rslug)
.await?
.json()
.await?,
)
.ok_or(Error::NoneError)?;
let t = Tag {
r#tag: rslug.to_string(),
r#refs: serde_json::to_string(&ids)?,
};
diesel::insert_into(tags)
.values(&t)
.execute(&mut self.conn()?)?;
}
Ok(ids)
}
pub fn get_tags(&self) -> Result<Vec<Tag>, Error> {
Ok(tags.load::<Tag>(&mut self.conn()?)?)
}
/// run_code data
async fn pre_run_code(
&self,
run: Run,
rfid: i32,
test_case: Option<String>,
) -> Result<(HashMap<&'static str, String>, [String; 2]), Error> {
trace!("pre run code...");
use crate::helper::code_path;
use std::fs::File;
use std::io::Read;
let mut p = self.get_problem(rfid)?;
if p.desc.is_empty() {
trace!("Problem description does not exist, pull desc and exec again...");
self.get_question(rfid).await?;
p = self.get_problem(rfid)?;
}
let d: Question = serde_json::from_str(&p.desc)?;
let conf = &self.0.conf;
let mut json: HashMap<&'static str, String> = HashMap::new();
let mut code: String = "".to_string();
let maybe_file_testcases: Option<String> = test_cases_path(&p)
.map(|file_name| {
let mut tests = "".to_string();
File::open(file_name)
.and_then(|mut file_descriptor| file_descriptor.read_to_string(&mut tests))
.map(|_| Some(tests))
.unwrap_or(None)
})
.unwrap_or(None);
let maybe_all_testcases: Option<String> = if d.all_cases.is_empty() {
None
} else {
Some(d.all_cases.to_string())
};
// Takes test cases using following priority
// 1. cli parameter
// 2. if test cases file exist, use the file test cases(user can edit it)
// 3. test cases from problem desc all test cases
// 4. sample test case from the task
let test_case = test_case
.or(maybe_file_testcases)
.or(maybe_all_testcases)
.unwrap_or(d.case);
File::open(code_path(&p, None)?)?.read_to_string(&mut code)?;
let code = if conf.code.edit_code_marker {
let begin = code.find(&conf.code.start_marker);
let end = code.find(&conf.code.end_marker);
if let (Some(l), Some(r)) = (begin, end) {
code.get((l + conf.code.start_marker.len())..r)
.map(|s| s.to_string())
.unwrap_or_else(|| code)
} else {
code
}
} else {
code
};
json.insert("lang", conf.code.lang.to_string());
json.insert("question_id", p.id.to_string());
json.insert("typed_code", code);
// pass manually data
json.insert("name", p.name.to_string());
json.insert("data_input", test_case);
let url = match run {
Run::Test => conf.sys.urls.test(&p.slug),
Run::Submit => {
json.insert("judge_type", "large".to_string());
conf.sys.urls.submit(&p.slug)
}
};
Ok((json, [url, conf.sys.urls.problem(&p.slug)]))
}
/// TODO: The real delay
async fn recur_verify(&self, rid: String) -> Result<VerifyResult, Error> {
use std::time::Duration;
trace!("Run verify recursion...");
std::thread::sleep(Duration::from_micros(3000));
let json: VerifyResult = self
.resp_to_json(self.clone().0.verify_result(rid.clone()).await?)
.await?;
Ok(json)
}
/// Exec problem filter —— Test or Submit
pub async fn exec_problem(
&self,
rfid: i32,
run: Run,
test_case: Option<String>,
) -> Result<VerifyResult, Error> {
trace!("Exec problem filter —— Test or Submit");
let (json, [url, refer]) = self.pre_run_code(run.clone(), rfid, test_case).await?;
trace!("Pre run code result {:#?}, {}, {}", json, url, refer);
let text = self
.0
.clone()
.run_code(json.clone(), url.clone(), refer.clone())
.await?
.text()
.await?;
let run_res: RunCode = serde_json::from_str(&text).map_err(|e| {
anyhow!("json error: {e}, plz double check your session and csrf config.")
})?;
trace!("Run code result {:#?}", run_res);
// Check if leetcode accepted the Run request
if match run {
Run::Test => run_res.interpret_id.is_empty(),
Run::Submit => run_res.submission_id == 0,
} {
return Err(Error::CookieError);
}
let mut res: VerifyResult = VerifyResult::default();
while res.state != "SUCCESS" {
res = match run {
Run::Test => self.recur_verify(run_res.interpret_id.clone()).await?,
Run::Submit => self.recur_verify(run_res.submission_id.to_string()).await?,
};
}
trace!("Recur verify result {:#?}", res);
res.name = json.get("name").ok_or(Error::NoneError)?.to_string();
res.data_input = json.get("data_input").ok_or(Error::NoneError)?.to_string();
res.result_type = run;
Ok(res)
}
/// New cache
pub fn new() -> Result<Self, Error> {
let conf = Config::locate()?;
let mut c = conn(conf.storage.cache()?);
diesel::sql_query(CREATE_PROBLEMS_IF_NOT_EXISTS).execute(&mut c)?;
diesel::sql_query(CREATE_TAGS_IF_NOT_EXISTS).execute(&mut c)?;
Ok(Cache(LeetCode::new()?))
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
pub mod family;
use ::syscalls::SyscallArgs;
use ::syscalls::Sysno;
// Re-export flags that used by syscalls from the `nix` crate so downstream
// projects don't need to add another dependency on it.
pub use nix::fcntl::AtFlags;
pub use nix::fcntl::OFlag;
// FIXME: Switch everything over to `crate::args::CloneFlags`.
use nix::sched::CloneFlags;
pub use nix::sys::epoll::EpollCreateFlags;
pub use nix::sys::eventfd::EfdFlags;
pub use nix::sys::inotify::InitFlags;
pub use nix::sys::mman::MapFlags;
pub use nix::sys::mman::ProtFlags;
pub use nix::sys::signalfd::SfdFlags;
pub use nix::sys::socket::SockFlag;
pub use nix::sys::stat::Mode;
pub use nix::sys::timerfd::TimerFlags;
pub use nix::sys::wait::WaitPidFlag;
use crate::args;
use crate::args::ioctl;
use crate::args::CArrayPtr;
use crate::args::CStrPtr;
use crate::args::ClockId;
use crate::args::CloneArgs;
use crate::args::FcntlCmd;
use crate::args::PathPtr;
use crate::args::StatPtr;
use crate::args::StatxMask;
use crate::args::StatxPtr;
use crate::args::Timespec;
use crate::args::TimespecMutPtr;
use crate::args::TimevalMutPtr;
use crate::args::Timezone;
use crate::display::Displayable;
use crate::memory::Addr;
use crate::memory::AddrMut;
use crate::raw::FromToRaw;
/// A trait that all syscalls implement.
pub trait SyscallInfo: Displayable + Copy + Send {
/// The return type of the syscall.
type Return: Displayable + FromToRaw;
/// Returns the syscall name.
fn name(&self) -> &'static str;
/// Returns the syscall number.
fn number(&self) -> Sysno;
/// Converts the syscall into its constituent parts.
fn into_parts(self) -> (Sysno, SyscallArgs);
}
// After adding a new type-safe syscall, uncomment the corresponding line below.
// The syscalls lower ranks and higher probabilities should be implemented
// first.
syscall_list! {
/// Full list of type-safe syscalls.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum Syscall {
read => Read,
write => Write,
#[cfg(not(target_arch = "aarch64"))]
open => Open,
close => Close,
#[cfg(not(target_arch = "aarch64"))]
stat => Stat,
fstat => Fstat,
#[cfg(not(target_arch = "aarch64"))]
lstat => Lstat,
#[cfg(not(target_arch = "aarch64"))]
poll => Poll,
#[cfg(not(target_arch = "aarch64"))]
lseek => Lseek,
mmap => Mmap,
mprotect => Mprotect,
munmap => Munmap,
brk => Brk,
rt_sigaction => RtSigaction,
rt_sigprocmask => RtSigprocmask,
rt_sigreturn => RtSigreturn,
ioctl => Ioctl,
pread64 => Pread64,
pwrite64 => Pwrite64,
readv => Readv,
writev => Writev,
#[cfg(not(target_arch = "aarch64"))]
access => Access,
#[cfg(not(target_arch = "aarch64"))]
pipe => Pipe,
#[cfg(not(target_arch = "aarch64"))]
select => Select,
sched_yield => SchedYield,
mremap => Mremap,
msync => Msync,
mincore => Mincore,
madvise => Madvise,
shmget => Shmget,
shmat => Shmat,
shmctl => Shmctl,
dup => Dup,
#[cfg(not(target_arch = "aarch64"))]
dup2 => Dup2,
#[cfg(not(target_arch = "aarch64"))]
pause => Pause,
nanosleep => Nanosleep,
getitimer => Getitimer,
#[cfg(not(target_arch = "aarch64"))]
alarm => Alarm,
setitimer => Setitimer,
getpid => Getpid,
sendfile => Sendfile,
socket => Socket,
connect => Connect,
accept => Accept,
sendto => Sendto,
recvfrom => Recvfrom,
sendmsg => Sendmsg,
recvmsg => Recvmsg,
shutdown => Shutdown,
bind => Bind,
listen => Listen,
getsockname => Getsockname,
getpeername => Getpeername,
socketpair => Socketpair,
setsockopt => Setsockopt,
getsockopt => Getsockopt,
clone => Clone,
#[cfg(not(target_arch = "aarch64"))]
fork => Fork,
#[cfg(not(target_arch = "aarch64"))]
vfork => Vfork,
execve => Execve,
exit => Exit,
wait4 => Wait4,
kill => Kill,
uname => Uname,
semget => Semget,
semop => Semop,
semctl => Semctl,
shmdt => Shmdt,
msgget => Msgget,
msgsnd => Msgsnd,
msgrcv => Msgrcv,
msgctl => Msgctl,
fcntl => Fcntl,
flock => Flock,
fsync => Fsync,
fdatasync => Fdatasync,
truncate => Truncate,
ftruncate => Ftruncate,
#[cfg(not(target_arch = "aarch64"))]
getdents => Getdents,
getcwd => Getcwd,
chdir => Chdir,
fchdir => Fchdir,
#[cfg(not(target_arch = "aarch64"))]
rename => Rename,
#[cfg(not(target_arch = "aarch64"))]
mkdir => Mkdir,
#[cfg(not(target_arch = "aarch64"))]
rmdir => Rmdir,
#[cfg(not(target_arch = "aarch64"))]
creat => Creat,
#[cfg(not(target_arch = "aarch64"))]
link => Link,
#[cfg(not(target_arch = "aarch64"))]
unlink => Unlink,
#[cfg(not(target_arch = "aarch64"))]
symlink => Symlink,
#[cfg(not(target_arch = "aarch64"))]
readlink => Readlink,
#[cfg(not(target_arch = "aarch64"))]
chmod => Chmod,
fchmod => Fchmod,
#[cfg(not(target_arch = "aarch64"))]
chown => Chown,
fchown => Fchown,
#[cfg(not(target_arch = "aarch64"))]
lchown => Lchown,
umask => Umask,
gettimeofday => Gettimeofday,
getrlimit => Getrlimit,
getrusage => Getrusage,
sysinfo => Sysinfo,
times => Times,
ptrace => Ptrace,
getuid => Getuid,
syslog => Syslog,
getgid => Getgid,
setuid => Setuid,
setgid => Setgid,
geteuid => Geteuid,
getegid => Getegid,
setpgid => Setpgid,
getppid => Getppid,
#[cfg(not(target_arch = "aarch64"))]
getpgrp => Getpgrp,
setsid => Setsid,
setreuid => Setreuid,
setregid => Setregid,
getgroups => Getgroups,
setgroups => Setgroups,
setresuid => Setresuid,
getresuid => Getresuid,
setresgid => Setresgid,
getresgid => Getresgid,
getpgid => Getpgid,
setfsuid => Setfsuid,
setfsgid => Setfsgid,
getsid => Getsid,
capget => Capget,
capset => Capset,
rt_sigpending => RtSigpending,
rt_sigtimedwait => RtSigtimedwait,
rt_sigqueueinfo => RtSigqueueinfo,
rt_sigsuspend => RtSigsuspend,
sigaltstack => Sigaltstack,
#[cfg(not(target_arch = "aarch64"))]
utime => Utime,
#[cfg(not(target_arch = "aarch64"))]
mknod => Mknod,
#[cfg(not(target_arch = "aarch64"))]
uselib => Uselib,
personality => Personality,
#[cfg(not(target_arch = "aarch64"))]
ustat => Ustat,
statfs => Statfs,
fstatfs => Fstatfs,
#[cfg(not(target_arch = "aarch64"))]
sysfs => Sysfs,
getpriority => Getpriority,
setpriority => Setpriority,
sched_setparam => SchedSetparam,
sched_getparam => SchedGetparam,
sched_setscheduler => SchedSetscheduler,
sched_getscheduler => SchedGetscheduler,
sched_get_priority_max => SchedGetPriorityMax,
sched_get_priority_min => SchedGetPriorityMin,
sched_rr_get_interval => SchedRrGetInterval,
mlock => Mlock,
munlock => Munlock,
mlockall => Mlockall,
munlockall => Munlockall,
vhangup => Vhangup,
#[cfg(not(target_arch = "aarch64"))]
modify_ldt => ModifyLdt,
pivot_root => PivotRoot,
#[allow(non_camel_case_types)]
#[cfg(not(target_arch = "aarch64"))]
_sysctl => _sysctl,
prctl => Prctl,
#[cfg(not(target_arch = "aarch64"))]
arch_prctl => ArchPrctl,
adjtimex => Adjtimex,
setrlimit => Setrlimit,
chroot => Chroot,
sync => Sync,
acct => Acct,
settimeofday => Settimeofday,
mount => Mount,
umount2 => Umount2,
swapon => Swapon,
swapoff => Swapoff,
reboot => Reboot,
sethostname => Sethostname,
setdomainname => Setdomainname,
#[cfg(not(target_arch = "aarch64"))]
iopl => Iopl,
#[cfg(not(target_arch = "aarch64"))]
ioperm => Ioperm,
#[cfg(not(target_arch = "aarch64"))]
create_module => CreateModule,
init_module => InitModule,
delete_module => DeleteModule,
#[cfg(not(target_arch = "aarch64"))]
get_kernel_syms => GetKernelSyms,
#[cfg(not(target_arch = "aarch64"))]
query_module => QueryModule,
quotactl => Quotactl,
nfsservctl => Nfsservctl,
#[cfg(not(target_arch = "aarch64"))]
getpmsg => Getpmsg,
#[cfg(not(target_arch = "aarch64"))]
putpmsg => Putpmsg,
#[cfg(not(target_arch = "aarch64"))]
afs_syscall => AfsSyscall,
#[cfg(not(target_arch = "aarch64"))]
tuxcall => Tuxcall,
#[cfg(not(target_arch = "aarch64"))]
security => Security,
gettid => Gettid,
readahead => Readahead,
setxattr => Setxattr,
lsetxattr => Lsetxattr,
fsetxattr => Fsetxattr,
getxattr => Getxattr,
lgetxattr => Lgetxattr,
fgetxattr => Fgetxattr,
listxattr => Listxattr,
llistxattr => Llistxattr,
flistxattr => Flistxattr,
removexattr => Removexattr,
lremovexattr => Lremovexattr,
fremovexattr => Fremovexattr,
tkill => Tkill,
#[cfg(not(target_arch = "aarch64"))]
time => Time,
futex => Futex,
sched_setaffinity => SchedSetaffinity,
sched_getaffinity => SchedGetaffinity,
#[cfg(not(target_arch = "aarch64"))]
set_thread_area => SetThreadArea,
io_setup => IoSetup,
io_destroy => IoDestroy,
io_getevents => IoGetevents,
io_submit => IoSubmit,
io_cancel => IoCancel,
#[cfg(not(target_arch = "aarch64"))]
get_thread_area => GetThreadArea,
lookup_dcookie => LookupDcookie,
#[cfg(not(target_arch = "aarch64"))]
epoll_create => EpollCreate,
#[cfg(not(target_arch = "aarch64"))]
epoll_ctl_old => EpollCtlOld,
#[cfg(not(target_arch = "aarch64"))]
epoll_wait_old => EpollWaitOld,
remap_file_pages => RemapFilePages,
getdents64 => Getdents64,
set_tid_address => SetTidAddress,
restart_syscall => RestartSyscall,
semtimedop => Semtimedop,
fadvise64 => Fadvise64,
timer_create => TimerCreate,
timer_settime => TimerSettime,
timer_gettime => TimerGettime,
timer_getoverrun => TimerGetoverrun,
timer_delete => TimerDelete,
clock_settime => ClockSettime,
clock_gettime => ClockGettime,
clock_getres => ClockGetres,
clock_nanosleep => ClockNanosleep,
exit_group => ExitGroup,
#[cfg(not(target_arch = "aarch64"))]
epoll_wait => EpollWait,
epoll_ctl => EpollCtl,
tgkill => Tgkill,
#[cfg(not(target_arch = "aarch64"))]
utimes => Utimes,
#[cfg(not(target_arch = "aarch64"))]
vserver => Vserver,
mbind => Mbind,
set_mempolicy => SetMempolicy,
get_mempolicy => GetMempolicy,
mq_open => MqOpen,
mq_unlink => MqUnlink,
mq_timedsend => MqTimedsend,
mq_timedreceive => MqTimedreceive,
mq_notify => MqNotify,
mq_getsetattr => MqGetsetattr,
kexec_load => KexecLoad,
waitid => Waitid,
add_key => AddKey,
request_key => RequestKey,
keyctl => Keyctl,
ioprio_set => IoprioSet,
ioprio_get => IoprioGet,
#[cfg(not(target_arch = "aarch64"))]
inotify_init => InotifyInit,
inotify_add_watch => InotifyAddWatch,
inotify_rm_watch => InotifyRmWatch,
migrate_pages => MigratePages,
openat => Openat,
mkdirat => Mkdirat,
mknodat => Mknodat,
fchownat => Fchownat,
#[cfg(not(target_arch = "aarch64"))]
futimesat => Futimesat,
#[cfg(target_arch = "x86_64")]
newfstatat => Newfstatat,
#[cfg(target_arch = "aarch64")]
fstatat => Fstatat,
unlinkat => Unlinkat,
renameat => Renameat,
linkat => Linkat,
symlinkat => Symlinkat,
readlinkat => Readlinkat,
fchmodat => Fchmodat,
faccessat => Faccessat,
pselect6 => Pselect6,
ppoll => Ppoll,
unshare => Unshare,
set_robust_list => SetRobustList,
get_robust_list => GetRobustList,
splice => Splice,
tee => Tee,
#[cfg(not(target_arch = "aarch64"))]
sync_file_range => SyncFileRange,
vmsplice => Vmsplice,
move_pages => MovePages,
utimensat => Utimensat,
epoll_pwait => EpollPwait,
#[cfg(not(target_arch = "aarch64"))]
signalfd => Signalfd,
timerfd_create => TimerfdCreate,
#[cfg(not(target_arch = "aarch64"))]
eventfd => Eventfd,
fallocate => Fallocate,
timerfd_settime => TimerfdSettime,
timerfd_gettime => TimerfdGettime,
accept4 => Accept4,
signalfd4 => Signalfd4,
eventfd2 => Eventfd2,
epoll_create1 => EpollCreate1,
dup3 => Dup3,
pipe2 => Pipe2,
inotify_init1 => InotifyInit1,
preadv => Preadv,
pwritev => Pwritev,
rt_tgsigqueueinfo => RtTgsigqueueinfo,
perf_event_open => PerfEventOpen,
recvmmsg => Recvmmsg,
fanotify_init => FanotifyInit,
fanotify_mark => FanotifyMark,
prlimit64 => Prlimit64,
name_to_handle_at => NameToHandleAt,
open_by_handle_at => OpenByHandleAt,
clock_adjtime => ClockAdjtime,
syncfs => Syncfs,
sendmmsg => Sendmmsg,
setns => Setns,
getcpu => Getcpu,
process_vm_readv => ProcessVmReadv,
process_vm_writev => ProcessVmWritev,
kcmp => Kcmp,
finit_module => FinitModule,
sched_setattr => SchedSetattr,
sched_getattr => SchedGetattr,
renameat2 => Renameat2,
seccomp => Seccomp,
getrandom => Getrandom,
memfd_create => MemfdCreate,
kexec_file_load => KexecFileLoad,
bpf => Bpf,
execveat => Execveat,
userfaultfd => Userfaultfd,
membarrier => Membarrier,
mlock2 => Mlock2,
copy_file_range => CopyFileRange,
preadv2 => Preadv2,
pwritev2 => Pwritev2,
pkey_mprotect => PkeyMprotect,
pkey_alloc => PkeyAlloc,
pkey_free => PkeyFree,
statx => Statx,
// Missing: io_pgetevents => IoPgetevents,
// Missing: rseq => Rseq,
// Missing: pidfd_send_signal => PidfdSendSignal,
// Missing: io_uring_setup => IoUringSetup,
// Missing: io_uring_enter => IoUringEnter,
// Missing: io_uring_register => IoUringRegister,
// Missing: open_tree => OpenTree,
// Missing: move_mount => MoveMount,
// Missing: fsopen => Fsopen,
// Missing: fsconfig => Fsconfig,
// Missing: fsmount => Fsmount,
// Missing: fspick => Fspick,
// Missing: pidfd_open => PidfdOpen,
clone3 => Clone3,
// Missing: close_range => CloseRange,
// Missing: openat2 => Openat2,
// Missing: pidfd_getfd => PidfdGetfd,
// Missing: faccessat2 => Faccessat2,
// Missing: process_madvise => ProcessMadvise,
// Missing: epoll_pwait2 => EpollPwait2,
// Missing: mount_setattr => MountSetattr,
// Missing: quotactl_path => QuotactlPath,
// Missing: landlock_create_ruleset => LandlockCreateRuleset,
// Missing: landlock_add_rule => LandlockAddRule,
// Missing: landlock_restrict_self => LandlockRestrictSelf,
}
}
typed_syscall! {
pub struct Read {
fd: i32,
// TODO: Change this to a slice and print out part of the contents of
// the read.
buf: Option<AddrMut<u8>>,
len: usize,
}
}
typed_syscall! {
pub struct Write {
fd: i32,
// TODO: Change this to a slice and print out part of the contents of
// the write (after the syscall has been executed).
buf: Option<Addr<u8>>,
len: usize,
}
}
fn get_mode(flags: OFlag, mode: usize) -> Option<Mode> {
if flags.intersects(OFlag::O_CREAT | OFlag::O_TMPFILE) {
Some(FromToRaw::from_raw(mode))
} else {
None
}
}
// Open not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Open -> i32 {
path: Option<PathPtr>,
flags: OFlag,
/// The mode is only present when `O_CREAT` or `O_TMPFILE` is specified
/// in the flags. It is ignored otherwise.
mode?: {
fn get(&self) -> Option<Mode> {
get_mode(self.flags(), self.raw.arg2)
}
fn set(mut self, v: Option<Mode>) -> Self {
self.raw.arg2 = v.into_raw();
self
}
},
}
}
// Open not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Creat> for Open {
/// A call to creat() is equivalent to calling open() with flags equal to
/// O_CREAT|O_WRONLY|O_TRUNC
fn from(creat: Creat) -> Self {
let Creat { mut raw } = creat;
raw.arg2 = raw.arg1;
raw.arg1 = (libc::O_CREAT | libc::O_WRONLY | libc::O_TRUNC) as usize;
Open { raw }
}
}
typed_syscall! {
pub struct Close {
fd: i32,
}
}
// Stat not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Stat {
path: Option<PathPtr>,
stat: Option<StatPtr>,
}
}
typed_syscall! {
pub struct Fstat {
fd: i32,
stat: Option<StatPtr>,
}
}
// Lstat not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Lstat {
path: Option<PathPtr>,
stat: Option<StatPtr>,
}
}
// Poll not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Poll {
fds: Option<AddrMut<args::PollFd>>,
nfds: libc::nfds_t,
timeout: libc::c_int,
}
}
typed_syscall! {
pub struct Mmap {
addr: Option<Addr<libc::c_void>>,
len: usize,
prot: ProtFlags,
flags: MapFlags,
fd: i32,
offset: libc::off_t,
}
}
// Lseek not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Lseek {
fd: i32,
offset: libc::off_t,
whence: args::Whence,
}
}
typed_syscall! {
pub struct Mprotect {
addr: Option<AddrMut<libc::c_void>>,
len: usize,
protection: ProtFlags,
}
}
typed_syscall! {
pub struct Munmap {
addr: Option<Addr<libc::c_void>>,
len: usize,
}
}
typed_syscall! {
pub struct Brk {
addr: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
pub struct RtSigaction {
signum: i32,
action: Option<Addr<libc::sigaction>>,
old_action: Option<AddrMut<libc::sigaction>>,
/// Should always be 8 (`size_of::<u64>()`).
sigsetsize: usize,
}
}
typed_syscall! {
pub struct RtSigprocmask {
how: i32,
set: Option<Addr<libc::sigset_t>>,
oldset: Option<AddrMut<libc::sigset_t>>,
/// Should always be 8 (`size_of::<u64>()`).
sigsetsize: usize,
}
}
typed_syscall! {
pub struct RtSigreturn {
}
}
typed_syscall! {
pub struct Ioctl {
fd: i32,
request: {
fn get(&self) -> ioctl::Request {
ioctl::Request::from_raw(self.raw.arg1, self.raw.arg2)
}
fn set(mut self, v: ioctl::Request) -> Self {
let (request, arg) = v.into_raw();
self.raw.arg1 = request;
self.raw.arg2 = arg;
self
}
},
}
}
typed_syscall! {
pub struct Pread64 {
fd: i32,
// TODO: Change this to a slice and print out part of the contents of
// the read.
buf: Option<AddrMut<u8>>,
len: usize,
offset: libc::off_t,
}
}
typed_syscall! {
pub struct Pwrite64 {
fd: i32,
// TODO: Change this to a slice and print out part of the contents of
// the write.
buf: Option<Addr<u8>>,
len: usize,
offset: libc::off_t,
}
}
typed_syscall! {
pub struct Readv {
fd: i32,
iov: Option<Addr<libc::iovec>>,
len: usize,
}
}
typed_syscall! {
pub struct Writev {
fd: i32,
iov: Option<Addr<libc::iovec>>,
len: usize,
}
}
// Access not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Access {
path: Option<PathPtr>,
mode: Mode,
}
}
// Pipe not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Pipe {
pipefd: Option<AddrMut<[i32; 2]>>,
}
}
// Select not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Select {
nfds: i32,
readfds: Option<AddrMut<libc::fd_set>>,
writefds: Option<AddrMut<libc::fd_set>>,
exceptfds: Option<AddrMut<libc::fd_set>>,
timeout: Option<AddrMut<libc::timeval>>,
}
}
typed_syscall! {
pub struct SchedYield {}
}
typed_syscall! {
pub struct Mremap {
addr: Option<AddrMut<libc::c_void>>,
old_len: usize,
new_len: usize,
flags: usize,
new_addr: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
pub struct Msync {
addr: Option<AddrMut<libc::c_void>>,
len: usize,
flags: i32,
}
}
typed_syscall! {
pub struct Mincore {
addr: Option<AddrMut<libc::c_void>>,
len: usize,
vec: Option<AddrMut<u8>>,
}
}
typed_syscall! {
pub struct Madvise {
addr: Option<AddrMut<libc::c_void>>,
len: usize,
advice: i32,
}
}
typed_syscall! {
pub struct Shmget {
key: libc::key_t,
size: usize,
shmflg: i32,
}
}
typed_syscall! {
pub struct Shmat {
shmid: i32,
shmaddr: Option<Addr<libc::c_void>>,
shmflg: i32,
}
}
typed_syscall! {
pub struct Shmctl {
shmid: i32,
cmd: i32,
buf: Option<AddrMut<libc::shmid_ds>>,
}
}
typed_syscall! {
pub struct Dup {
oldfd: i32,
}
}
// Dup2 not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Dup2 {
oldfd: i32,
newfd: i32,
}
}
// Pause not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! { pub struct Pause {} }
typed_syscall! {
pub struct Nanosleep {
req: Option<Addr<Timespec>>,
rem: Option<AddrMut<Timespec>>,
}
}
typed_syscall! {
pub struct Getitimer {
which: i32,
value: Option<AddrMut<libc::itimerval>>,
}
}
// Alarm not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Alarm {
seconds: u32,
}
}
typed_syscall! {
pub struct Setitimer {
which: i32,
value: Option<AddrMut<libc::itimerval>>,
ovalue: Option<AddrMut<libc::itimerval>>,
}
}
typed_syscall! {
pub struct Getpid {}
}
typed_syscall! {
pub struct Sendfile {
out_fd: i32,
in_fd: i32,
offset: Option<AddrMut<libc::loff_t>>,
count: usize,
}
}
typed_syscall! {
// TODO: Give more meaningful types to these arguments.
pub struct Socket {
family: i32,
r#type: i32,
protocol: i32,
}
}
typed_syscall! {
pub struct Connect {
fd: i32,
uservaddr: Option<AddrMut<libc::sockaddr>>,
addrlen: i32,
}
}
typed_syscall! {
pub struct Accept {
sockfd: i32,
sockaddr: Option<AddrMut<libc::sockaddr>>,
addrlen: Option<AddrMut<usize>>,
}
}
typed_syscall! {
pub struct Sendto {
fd: i32,
buf: Option<AddrMut<libc::c_void>>,
size: usize,
flags: u32,
addr: Option<AddrMut<libc::sockaddr>>,
addr_len: i32,
}
}
typed_syscall! {
pub struct Recvfrom {
fd: i32,
buf: Option<AddrMut<u8>>,
len: usize,
flags: i32,
addr: Option<AddrMut<libc::sockaddr>>,
addr_len: Option<AddrMut<libc::socklen_t>>,
}
}
typed_syscall! {
pub struct Sendmsg {
fd: i32,
msg: Option<Addr<libc::msghdr>>,
flags: i32,
}
}
typed_syscall! {
pub struct Recvmsg {
sockfd: i32,
msg: Option<AddrMut<libc::msghdr>>,
flags: i32,
}
}
typed_syscall! {
pub struct Shutdown {
fd: i32,
how: i32,
}
}
typed_syscall! {
pub struct Bind {
fd: i32,
umyaddr: Option<AddrMut<libc::sockaddr>>,
addrlen: i32,
}
}
typed_syscall! {
pub struct Listen {
fd: i32,
backlog: i32,
}
}
typed_syscall! {
pub struct Getsockname {
fd: i32,
usockaddr: Option<AddrMut<libc::sockaddr>>,
usockaddr_len: Option<AddrMut<libc::socklen_t>>,
}
}
typed_syscall! {
pub struct Getpeername {
fd: i32,
usockaddr: Option<AddrMut<libc::sockaddr>>,
usockaddr_len: Option<AddrMut<libc::socklen_t>>,
}
}
typed_syscall! {
// TODO: Give more meaningful types to these arguments.
pub struct Socketpair {
family: i32,
r#type: i32,
protocol: i32,
usockvec: Option<AddrMut<[i32; 2]>>,
}
}
typed_syscall! {
pub struct Setsockopt {
fd: i32,
level: i32,
optname: i32,
optval: Option<Addr<libc::c_void>>,
optlen: libc::socklen_t,
}
}
typed_syscall! {
pub struct Getsockopt {
fd: i32,
level: i32,
optname: i32,
optval: Option<AddrMut<libc::c_void>>,
optlen: Option<AddrMut<libc::socklen_t>>,
}
}
#[cfg(any(target_arch = "x86_64"))]
typed_syscall! {
pub struct Clone {
flags: CloneFlags,
child_stack: Option<AddrMut<libc::c_void>>,
ptid: Option<AddrMut<libc::pid_t>>,
ctid: Option<AddrMut<libc::pid_t>>,
newtls: u64,
}
}
#[cfg(any(target_arch = "arm", target_arch = "aarch64", target_arch = "x86"))]
typed_syscall! {
pub struct Clone {
flags: CloneFlags,
child_stack: Option<AddrMut<libc::c_void>>,
ptid: Option<AddrMut<libc::pid_t>>,
newtls: u64,
ctid: Option<AddrMut<libc::pid_t>>,
}
}
// Vfork not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Vfork> for Clone {
/// Since `clone` offers a superset of functionality over `vfork`, a `vfork`
/// syscall can be transformed into a `clone` syscall by passing in the
/// right flags. In fact, this is how the Linux kernel implements `vfork`.
/// See kernel/fork.c for more details.
fn from(_: Vfork) -> Self {
let raw = SyscallArgs {
arg0: (libc::CLONE_VFORK | libc::CLONE_VM | libc::SIGCHLD) as usize,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
arg5: 0,
};
Self { raw }
}
}
// Fork not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Fork> for Clone {
/// Since `clone` offers a superset of functionality over `fork`, a `fork`
/// syscall can be transformed into a `clone` syscall by passing in the
/// right flags. In fact, this is how the Linux kernel implements `fork`.
/// See kernel/fork.c for more details.
fn from(_: Fork) -> Self {
let raw = SyscallArgs {
arg0: libc::SIGCHLD as usize,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
arg5: 0,
};
Self { raw }
}
}
// Fork not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Fork {}
}
// Vfork not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Vfork {}
}
typed_syscall! {
pub struct Execve {
path: Option<PathPtr>,
argv: Option<CArrayPtr<CStrPtr>>,
envp: Option<CArrayPtr<CStrPtr>>,
}
}
typed_syscall! {
pub struct Exit {
status: libc::c_int,
}
}
typed_syscall! {
pub struct Wait4 {
pid: libc::pid_t,
wstatus: Option<AddrMut<libc::c_int>>,
options: WaitPidFlag,
rusage: Option<AddrMut<libc::rusage>>,
}
}
typed_syscall! {
pub struct Kill {
pid: libc::pid_t,
// TODO: Change the signal to a type that prints out the signal passed
// to it.
sig: libc::c_int,
}
}
typed_syscall! {
pub struct Uname {
buf: Option<AddrMut<libc::utsname>>,
}
}
typed_syscall! {
pub struct Semget {
key: libc::key_t,
nsems: i32,
semflg: i32,
}
}
typed_syscall! {
pub struct Semop {
semid: i32,
tsops: Option<AddrMut<libc::sembuf>>,
nsops: usize,
}
}
typed_syscall! {
pub struct Semctl {
semid: i32,
semnum: i32,
cmd: i32,
arg: u64,
}
}
typed_syscall! {
pub struct Shmdt {
shmaddr: Option<Addr<libc::c_void>>,
}
}
typed_syscall! {
pub struct Msgget {
key: libc::key_t,
msgflg: i32,
}
}
typed_syscall! {
pub struct Msgsnd {
msqid: i32,
msgp: Option<Addr<libc::c_void>>,
msgsz: usize,
msgflg: i32,
}
}
typed_syscall! {
pub struct Msgrcv {
msqid: i32,
msgp: Option<AddrMut<libc::c_void>>,
msgsz: usize,
msgtyp: libc::c_long,
msgflg: i32,
}
}
typed_syscall! {
pub struct Msgctl {
msqid: i32,
cmd: i32,
buf: Option<AddrMut<libc::msqid_ds>>,
}
}
typed_syscall! {
pub struct Fcntl {
/// The file descriptor to perform the operation on.
fd: i32,
cmd: {
fn get(&self) -> FcntlCmd {
FcntlCmd::from_raw(self.raw.arg1 as libc::c_int, self.raw.arg2)
}
fn set(mut self, v: FcntlCmd) -> Self {
let (cmd, arg) = v.into_raw();
self.raw.arg1 = cmd as usize;
self.raw.arg2 = arg;
self
}
},
}
}
typed_syscall! {
pub struct Flock {
fd: i32,
// TODO: Give this a more restricted type.
operation: i32,
}
}
typed_syscall! {
pub struct Fsync {
fd: i32,
}
}
typed_syscall! {
pub struct Fdatasync {
fd: i32,
}
}
typed_syscall! {
pub struct Truncate {
path: Option<PathPtr>,
length: libc::off_t,
}
}
typed_syscall! {
pub struct Ftruncate {
fd: i32,
length: libc::off_t,
}
}
// Getdents not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Getdents {
fd: u32,
dirent: Option<AddrMut<libc::dirent>>,
count: u32,
}
}
typed_syscall! {
pub struct Getcwd {
// TODO: Replace this with a PathPtrMut.
buf: Option<AddrMut<libc::c_char>>,
size: usize,
}
}
typed_syscall! {
pub struct Chdir {
path: Option<PathPtr>,
}
}
typed_syscall! {
pub struct Fchdir {
fd: i32,
}
}
// Rename not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Rename {
oldpath: Option<PathPtr>,
newpath: Option<PathPtr>,
}
}
// Mkdir not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Mkdir {
path: Option<PathPtr>,
mode: Mode,
}
}
// Rmdir not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Rmdir {
path: Option<PathPtr>,
}
}
// Creat not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Creat {
path: Option<PathPtr>,
mode: Mode,
}
}
// Link not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Link {
oldpath: Option<PathPtr>,
newpath: Option<PathPtr>,
}
}
// Unlink not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Unlink {
path: Option<PathPtr>,
}
}
// Symlink not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Symlink {
target: Option<PathPtr>,
linkpath: Option<PathPtr>,
}
}
// Readlink not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Readlink {
path: Option<PathPtr>,
// TODO: Replace this with a PathPtrMut
buf: Option<AddrMut<libc::c_char>>,
bufsize: usize,
}
}
// Chmod not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Chmod {
path: Option<PathPtr>,
mode: Mode,
}
}
typed_syscall! {
pub struct Fchmod {
fd: i32,
mode: Mode,
}
}
// Chown not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Chown {
path: Option<PathPtr>,
owner: libc::uid_t,
group: libc::gid_t,
}
}
typed_syscall! {
pub struct Fchown {
fd: i32,
owner: libc::uid_t,
group: libc::gid_t,
}
}
// Lchown not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Lchown {
path: Option<PathPtr>,
owner: libc::uid_t,
group: libc::gid_t,
}
}
typed_syscall! {
pub struct Umask {
mask: Mode,
}
}
typed_syscall! {
pub struct Gettimeofday {
tv: Option<TimevalMutPtr>,
tz: Option<AddrMut<Timezone>>,
}
}
typed_syscall! {
pub struct Getrlimit {
resource: i32,
rlim: Option<AddrMut<libc::rlimit>>,
}
}
typed_syscall! {
pub struct Getrusage {
who: i32,
usage: Option<AddrMut<libc::rusage>>,
}
}
typed_syscall! {
pub struct Sysinfo {
info: Option<AddrMut<libc::sysinfo>>,
}
}
typed_syscall! {
pub struct Times -> libc::clock_t {
buf: Option<AddrMut<libc::tms>>,
}
}
typed_syscall! {
pub struct Ptrace {
request: u32,
pid: libc::pid_t,
addr: Option<AddrMut<libc::c_void>>,
data: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! { pub struct Getuid {} }
typed_syscall! {
pub struct Syslog {
priority: i32,
buf: Option<Addr<libc::c_char>>,
len: usize,
}
}
typed_syscall! { pub struct Getgid {} }
typed_syscall! { pub struct Setuid { uid: libc::uid_t, } }
typed_syscall! { pub struct Setgid { uid: libc::gid_t, } }
typed_syscall! { pub struct Geteuid {} }
typed_syscall! { pub struct Getegid {} }
typed_syscall! { pub struct Setpgid { pid: libc::pid_t, pgid: libc::pid_t, } }
typed_syscall! { pub struct Getppid {} }
// Getpgrp not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! { pub struct Getpgrp {} }
typed_syscall! { pub struct Setsid {} }
typed_syscall! { pub struct Setreuid { ruid: libc::uid_t, euid: libc::uid_t, } }
typed_syscall! { pub struct Setregid { rgid: libc::gid_t, egid: libc::gid_t, } }
typed_syscall! {
pub struct Getgroups {
// TODO: Make this a slice.
size: i32,
list: Option<AddrMut<libc::gid_t>>,
}
}
typed_syscall! {
pub struct Setgroups {
// TODO: Make this a slice.
size: usize,
list: Option<Addr<libc::gid_t>>,
}
}
typed_syscall! {
pub struct Setresuid {
ruid: libc::uid_t,
euid: libc::uid_t,
suid: libc::uid_t,
}
}
typed_syscall! {
pub struct Getresuid {
ruid: Option<AddrMut<libc::gid_t>>,
euid: Option<AddrMut<libc::gid_t>>,
suid: Option<AddrMut<libc::gid_t>>,
}
}
typed_syscall! {
pub struct Setresgid {
rgid: libc::gid_t,
egid: libc::gid_t,
sgid: libc::gid_t,
}
}
typed_syscall! {
pub struct Getresgid {
rgid: Option<AddrMut<libc::gid_t>>,
egid: Option<AddrMut<libc::gid_t>>,
sgid: Option<AddrMut<libc::gid_t>>,
}
}
typed_syscall! { pub struct Getpgid {} }
typed_syscall! { pub struct Setfsuid {} }
typed_syscall! { pub struct Setfsgid {} }
typed_syscall! { pub struct Getsid {} }
typed_syscall! {
pub struct Capget {
header: Option<AddrMut<libc::c_void>>,
data: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
pub struct Capset {
header: Option<AddrMut<libc::c_void>>,
data: Option<Addr<libc::c_void>>,
}
}
typed_syscall! {
pub struct RtSigpending {
set: Option<AddrMut<libc::sigset_t>>,
/// Should always be 8 (`size_of::<u64>()`).
sigsetsize: usize,
}
}
typed_syscall! {
pub struct RtSigtimedwait {
set: Option<AddrMut<libc::sigset_t>>,
info: Option<AddrMut<libc::siginfo_t>>,
timeout: Option<Addr<Timespec>>,
/// Should always be 8 (`size_of::<u64>()`).
sigsetsize: usize,
}
}
typed_syscall! {
pub struct RtSigqueueinfo {
tgid: libc::pid_t,
sig: i32,
siginfo: Option<AddrMut<libc::siginfo_t>>,
}
}
typed_syscall! {
pub struct RtSigsuspend {
mask: Option<Addr<libc::sigset_t>>,
/// Should always be 8 (`size_of::<u64>()`).
sigsetsize: usize,
}
}
typed_syscall! {
pub struct Sigaltstack {
ss: Option<Addr<libc::stack_t>>,
old_ss: Option<AddrMut<libc::stack_t>>,
}
}
// utime not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Utime {
path: Option<PathPtr>,
times: Option<AddrMut<libc::utimbuf>>,
}
}
// Mknod not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Mknod {
path: Option<PathPtr>,
mode: Mode,
dev: libc::dev_t,
}
}
// Uselib not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Uselib {
library: Option<PathPtr>,
}
}
typed_syscall! {
pub struct Personality {
persona: u64,
}
}
// Ustat not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Ustat {
dev: libc::dev_t,
// TODO: Change this to libc::ustat if/when it exists.
ubuf: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
pub struct Statfs {
path: Option<PathPtr>,
buf: Option<AddrMut<libc::statfs>>,
}
}
typed_syscall! {
pub struct Fstatfs {
fd: i32,
buf: Option<AddrMut<libc::statfs>>,
}
}
// Sysfs not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Sysfs {
option: i32,
arg1: usize,
arg2: usize,
}
}
typed_syscall! {
pub struct Getpriority {
which: i32,
who: libc::id_t,
}
}
typed_syscall! {
pub struct Setpriority {
which: i32,
who: libc::id_t,
prio: i32,
}
}
typed_syscall! {
pub struct SchedSetparam {
pid: libc::pid_t,
param: Option<Addr<libc::sched_param>>,
}
}
typed_syscall! {
pub struct SchedGetparam {
pid: libc::pid_t,
param: Option<AddrMut<libc::sched_param>>,
}
}
typed_syscall! {
pub struct SchedSetscheduler {
pid: libc::pid_t,
policy: i32,
param: Option<Addr<libc::sched_param>>,
}
}
typed_syscall! {
pub struct SchedGetscheduler {
pid: libc::pid_t,
}
}
typed_syscall! {
pub struct SchedGetPriorityMax {
policy: i32,
}
}
typed_syscall! {
pub struct SchedGetPriorityMin {
policy: i32,
}
}
typed_syscall! {
pub struct SchedRrGetInterval {
pid: libc::pid_t,
tp: Option<AddrMut<Timespec>>,
}
}
typed_syscall! {
pub struct Mlock {
addr: Option<Addr<libc::c_void>>,
len: usize,
}
}
typed_syscall! {
pub struct Munlock {
addr: Option<Addr<libc::c_void>>,
len: usize,
}
}
typed_syscall! {
pub struct Mlockall {
flags: i32,
}
}
typed_syscall! { pub struct Munlockall {} }
typed_syscall! { pub struct Vhangup {} }
// ModifyLdt not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct ModifyLdt {
func: i32,
ptr: Option<AddrMut<libc::c_void>>,
bytecount: usize,
}
}
typed_syscall! {
pub struct PivotRoot {
new_root: Option<PathPtr>,
put_old: Option<PathPtr>,
}
}
// _sysctl not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
#[allow(non_camel_case_types)]
pub struct _sysctl {
// TODO: Use _sysctl_args struct.
args: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
pub struct Prctl {
option: i32,
arg2: u64,
arg3: u64,
arg4: u64,
arg5: u64,
}
}
// ArchPrctl not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct ArchPrctl {
cmd: {
fn get(&self) -> args::ArchPrctlCmd {
args::ArchPrctlCmd::from_raw(self.raw.arg0 as i32, self.raw.arg1)
}
fn set(mut self, v: args::ArchPrctlCmd) -> Self {
let (cmd, arg) = v.into_raw();
self.raw.arg0 = cmd as usize;
self.raw.arg1 = arg;
self
}
},
}
}
typed_syscall! {
pub struct Adjtimex {
buf: Option<AddrMut<libc::timex>>,
}
}
typed_syscall! {
pub struct Setrlimit {
resource: i32,
rlim: Option<Addr<libc::rlimit>>,
}
}
typed_syscall! {
pub struct Chroot {
path: Option<PathPtr>,
}
}
typed_syscall! { pub struct Sync {} }
typed_syscall! {
pub struct Acct {
filename: Option<PathPtr>,
}
}
typed_syscall! {
pub struct Settimeofday {
tv: Option<Addr<libc::timeval>>,
tz: Option<Addr<libc::timezone>>,
}
}
typed_syscall! {
pub struct Mount {
source: Option<PathPtr>,
target: Option<PathPtr>,
filesystemtype: Option<CStrPtr>,
flags: u64,
data: Option<Addr<libc::c_void>>,
}
}
typed_syscall! {
pub struct Umount2 {
target: Option<PathPtr>,
flags: i32,
}
}
typed_syscall! {
pub struct Swapon {
path: Option<PathPtr>,
swapflags: i32,
}
}
typed_syscall! {
pub struct Swapoff {
path: Option<PathPtr>,
}
}
typed_syscall! {
pub struct Reboot {
magic1: i32,
magic2: i32,
cmd: u32,
arg: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
pub struct Sethostname {
name: Option<Addr<libc::c_char>>,
len: usize,
}
}
typed_syscall! {
pub struct Setdomainname {
name: Option<Addr<libc::c_char>>,
len: usize,
}
}
// Iopl not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Iopl {
level: u32,
}
}
// Ioperm not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Ioperm {
from: u64,
num: u64,
turn_on: i32,
}
}
// CreateModule not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Note: This system call is present only in kernels before Linux 2.6.
pub struct CreateModule {
name: Option<Addr<libc::c_char>>,
len: usize,
}
}
typed_syscall! {
pub struct InitModule {
module_image: Option<AddrMut<libc::c_void>>,
len: usize,
param_values: Option<CStrPtr>,
}
}
typed_syscall! {
pub struct DeleteModule {
name: Option<CStrPtr>,
flags: i32,
}
}
// GetKernelSyms not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Note: This system call is present only in kernels before Linux 2.6.
pub struct GetKernelSyms {
table: Option<AddrMut<libc::c_void>>,
}
}
// QueryModule not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct QueryModule {
name: Option<CStrPtr>,
which: i32,
buf: Option<AddrMut<libc::c_void>>,
bufsize: usize,
ret: Option<AddrMut<usize>>,
}
}
typed_syscall! {
pub struct Quotactl {
cmd: i32,
special: Option<CStrPtr>,
id: i32,
addr: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
/// Note: Since Linux 3.1, this system call no longer exists. It has been
/// replaced by a set of files in the nfsd filesystem; see `nfsd(7)`.
pub struct Nfsservctl {
cmd: i32,
argp: Option<AddrMut<libc::c_void>>,
resp: Option<AddrMut<libc::c_void>>,
}
}
// Getpmsg not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Unimplemented in the kernel.
pub struct Getpmsg {}
}
// Putmsp not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Unimplemented in the kernel.
pub struct Putpmsg {}
}
// AfsSyscall not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Unimplemented in the kernel.
pub struct AfsSyscall {}
}
// Tuxcall not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Unimplemented in the kernel.
pub struct Tuxcall {}
}
// Security not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Unimplemented in the kernel.
pub struct Security {}
}
typed_syscall! { pub struct Gettid {} }
typed_syscall! {
pub struct Readahead {
fd: i32,
offset: libc::loff_t,
count: usize,
}
}
typed_syscall! {
pub struct Setxattr {
path: Option<PathPtr>,
name: Option<CStrPtr>,
value: Option<Addr<libc::c_void>>,
size: usize,
flags: i32,
}
}
typed_syscall! {
pub struct Lsetxattr {
path: Option<PathPtr>,
name: Option<CStrPtr>,
value: Option<Addr<libc::c_void>>,
size: usize,
flags: i32,
}
}
typed_syscall! {
pub struct Fsetxattr {
fd: i32,
name: Option<CStrPtr>,
value: Option<Addr<libc::c_void>>,
size: usize,
flags: i32,
}
}
typed_syscall! {
pub struct Getxattr {
path: Option<PathPtr>,
name: Option<CStrPtr>,
value: Option<AddrMut<libc::c_void>>,
size: usize,
}
}
typed_syscall! {
pub struct Lgetxattr {
path: Option<PathPtr>,
name: Option<CStrPtr>,
value: Option<AddrMut<libc::c_void>>,
size: usize,
}
}
typed_syscall! {
pub struct Fgetxattr {
fd: i32,
name: Option<CStrPtr>,
value: Option<AddrMut<libc::c_void>>,
size: usize,
}
}
typed_syscall! {
pub struct Listxattr {
path: Option<PathPtr>,
list: Option<AddrMut<libc::c_char>>,
size: usize,
}
}
typed_syscall! {
pub struct Llistxattr {
path: Option<PathPtr>,
list: Option<AddrMut<libc::c_char>>,
size: usize,
}
}
typed_syscall! {
pub struct Flistxattr {
fd: i32,
list: Option<AddrMut<libc::c_char>>,
size: usize,
}
}
typed_syscall! {
pub struct Removexattr {
path: Option<PathPtr>,
name: Option<CStrPtr>,
}
}
typed_syscall! {
pub struct Lremovexattr {
path: Option<PathPtr>,
name: Option<CStrPtr>,
}
}
typed_syscall! {
pub struct Fremovexattr {
fd: i32,
name: Option<CStrPtr>,
}
}
typed_syscall! {
pub struct Tkill {
tid: libc::pid_t,
sig: libc::c_int,
}
}
// Time not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Time {
tloc: Option<AddrMut<libc::time_t>>,
}
}
typed_syscall! {
// TODO: Wrap each futex operation in a type, similar to fcntl and ioctl.
pub struct Futex {
uaddr: Option<AddrMut<libc::c_int>>,
futex_op: libc::c_int,
val: libc::c_int,
timeout: Option<Addr<Timespec>>,
uaddr2: Option<AddrMut<libc::c_int>>,
val3: libc::c_int,
}
}
typed_syscall! {
pub struct SchedSetaffinity {
pid: libc::pid_t,
len: u32,
mask: Option<Addr<libc::c_ulong>>,
}
}
typed_syscall! {
pub struct SchedGetaffinity {
pid: libc::pid_t,
len: u32,
mask: Option<AddrMut<libc::c_ulong>>,
}
}
// SetThreadArea not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct SetThreadArea {
addr: Option<Addr<libc::c_void>>,
}
}
typed_syscall! {
pub struct IoSetup {
nr_events: u32,
context: Option<AddrMut<libc::c_ulong>>,
}
}
typed_syscall! {
pub struct IoDestroy {
context: libc::c_ulong,
}
}
typed_syscall! {
pub struct IoGetevents {
context: libc::c_ulong,
min_nr: libc::c_long,
nr: libc::c_long,
// FIXME: This should be a pointer to an `io_event`.
events: Option<AddrMut<libc::c_void>>,
timeout: Option<Addr<Timespec>>,
}
}
typed_syscall! {
pub struct IoSubmit {
context: libc::c_ulong,
nr: libc::c_long,
// FIXME: This should be a pointer to a pointer of `iocb`.
iocb: Option<AddrMut<AddrMut<libc::c_void>>>,
}
}
typed_syscall! {
pub struct IoCancel {
context: libc::c_ulong,
iocb: Option<AddrMut<libc::c_void>>,
// FIXME: This should be a pointer to an `io_event`.
result: Option<AddrMut<libc::c_void>>,
}
}
// GetThreadArea not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct GetThreadArea {
addr: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
pub struct LookupDcookie {
cookie: u64,
buf: Option<AddrMut<libc::c_char>>,
len: usize,
}
}
// EpollCreate not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct EpollCreate {
/// The kernel doesn't actually use this parameter, but it must be
/// greater than 0. (It was used as a size hint at one point in time.)
size: i32,
}
}
// EpollCtlOld not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Undocumented.
pub struct EpollCtlOld {}
}
// EpollWaitOld not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Undocumented.
pub struct EpollWaitOld {}
}
typed_syscall! {
pub struct RemapFilePages {
addr: Option<AddrMut<libc::c_void>>,
size: u64,
prot: i32,
pgoff: usize,
flags: i32,
}
}
typed_syscall! {
pub struct Getdents64 {
fd: u32,
dirent: Option<AddrMut<libc::dirent64>>,
count: u32,
}
}
typed_syscall! {
pub struct SetTidAddress {
tidptr: Option<AddrMut<libc::c_int>>,
}
}
typed_syscall! { pub struct RestartSyscall { } }
typed_syscall! {
pub struct Semtimedop {
semid: i32,
tsops: Option<AddrMut<libc::sembuf>>,
nsops: u32,
timeout: Option<Addr<Timespec>>,
}
}
typed_syscall! {
pub struct Fadvise64 {
fd: i32,
offset: libc::loff_t,
len: usize,
advice: i32,
}
}
typed_syscall! {
pub struct TimerCreate {
clockid: ClockId,
sevp: Option<AddrMut<libc::sigevent>>,
timerid: Option<AddrMut<libc::c_int>>,
}
}
typed_syscall! {
pub struct TimerSettime {
timerid: libc::c_int,
flags: i32,
new_value: Option<Addr<libc::itimerspec>>,
old_value: Option<AddrMut<libc::itimerspec>>,
}
}
typed_syscall! {
pub struct TimerGettime {
timerid: libc::c_int,
value: Option<AddrMut<libc::itimerspec>>,
}
}
typed_syscall! {
pub struct TimerGetoverrun {
timerid: libc::c_int,
}
}
typed_syscall! {
pub struct TimerDelete {
timerid: libc::c_int,
}
}
typed_syscall! {
pub struct ClockSettime {
clockid: ClockId,
tp: Option<Addr<Timespec>>,
}
}
typed_syscall! {
pub struct ClockGettime {
clockid: ClockId,
tp: Option<TimespecMutPtr>,
}
}
typed_syscall! {
pub struct ClockGetres {
clockid: ClockId,
res: Option<AddrMut<Timespec>>,
}
}
typed_syscall! {
pub struct ClockNanosleep {
clockid: ClockId,
flags: i32,
req: Option<Addr<Timespec>>,
rem: Option<AddrMut<Timespec>>,
}
}
typed_syscall! {
pub struct ExitGroup {
status: libc::c_int,
}
}
// EpollWait not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct EpollWait {
epfd: i32,
events: Option<AddrMut<libc::epoll_event>>,
maxevents: i32,
timeout: i32, // Milliseconds.
}
}
typed_syscall! {
pub struct EpollCtl {
epfd: i32,
op: i32,
fd: i32,
event: Option<AddrMut<libc::epoll_event>>,
}
}
typed_syscall! {
pub struct Tgkill {
tgid: libc::pid_t,
tid: libc::pid_t,
sig: libc::c_int,
}
}
// Utimes not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Utimes {
filename: Option<PathPtr>,
times: Option<Addr<[libc::timeval; 2]>>,
}
}
// Vserver not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Unimplemented in the kernel.
pub struct Vserver { }
}
typed_syscall! {
pub struct Mbind {
addr: Option<AddrMut<libc::c_void>>,
len: u64,
mode: i32,
nodemask: Option<Addr<libc::c_ulong>>,
maxnode: u64,
flags: u32,
}
}
typed_syscall! {
pub struct SetMempolicy {
mode: i32,
nodemask: Option<Addr<libc::c_ulong>>,
maxnode: u64,
}
}
typed_syscall! {
pub struct GetMempolicy {
policy: Option<AddrMut<libc::c_int>>,
nodemask: Option<Addr<libc::c_ulong>>,
maxnode: u64,
addr: Option<Addr<libc::c_void>>,
flags: u32,
}
}
typed_syscall! {
pub struct MqOpen {
name: Option<PathPtr>,
oflag: i32,
mode: libc::mode_t,
attr: Option<AddrMut<libc::mq_attr>>,
}
}
typed_syscall! {
pub struct MqUnlink {
name: Option<PathPtr>,
}
}
typed_syscall! {
pub struct MqTimedsend {
mqdes: libc::mqd_t,
msg: Option<Addr<libc::c_char>>,
msg_len: usize,
priority: u32,
timeout: Option<Addr<Timespec>>,
}
}
typed_syscall! {
pub struct MqTimedreceive {
mqdes: libc::mqd_t,
msg: Option<AddrMut<libc::c_char>>,
msg_len: usize,
priority: u32,
timeout: Option<Addr<Timespec>>,
}
}
typed_syscall! {
pub struct MqNotify {
mqdes: libc::mqd_t,
sevp: Option<Addr<libc::sigevent>>,
}
}
typed_syscall! {
pub struct MqGetsetattr {
mqdes: libc::mqd_t,
newattr: Option<Addr<libc::mq_attr>>,
oldattr: Option<AddrMut<libc::mq_attr>>,
}
}
typed_syscall! {
pub struct KexecLoad {
entry: u64,
nr_segments: u64,
// FIXME: This should be a pointer to `kexec_segment`.
segments: Option<Addr<libc::c_void>>,
flags: u64,
}
}
typed_syscall! {
pub struct Waitid {
which: i32,
pid: libc::pid_t,
info: Option<AddrMut<libc::siginfo_t>>,
options: i32,
rusage: Option<AddrMut<libc::rusage>>,
}
}
typed_syscall! {
pub struct AddKey {
key_type: Option<CStrPtr>,
description: Option<CStrPtr>,
payload: Option<Addr<libc::c_void>>,
payload_len: usize,
keyring: libc::c_int,
}
}
typed_syscall! {
pub struct RequestKey {
key_type: Option<CStrPtr>,
description: Option<CStrPtr>,
callout_info: Option<CStrPtr>,
dest_keyring: libc::c_int,
}
}
typed_syscall! {
pub struct Keyctl {
option: i32,
arg2: u64,
arg3: u64,
arg4: u64,
arg6: u64,
}
}
typed_syscall! {
pub struct IoprioSet {
which: i32,
who: i32,
priority: i32,
}
}
typed_syscall! {
pub struct IoprioGet {
which: i32,
who: i32,
}
}
// InotifyInit not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! { pub struct InotifyInit {} }
typed_syscall! {
pub struct InotifyAddWatch {
fd: i32,
path: Option<PathPtr>,
mask: u32,
}
}
typed_syscall! {
pub struct InotifyRmWatch {
fd: i32,
wd: i32,
}
}
typed_syscall! {
pub struct MigratePages {
pid: libc::pid_t,
maxnode: u64,
old_nodes: Option<Addr<libc::c_ulong>>,
new_nodes: Option<Addr<libc::c_ulong>>,
}
}
typed_syscall! {
pub struct Openat {
dirfd: i32,
path: Option<PathPtr>,
flags: OFlag,
/// The mode is only present when `O_CREAT` or `O_TMPFILE` is specified
/// in the flags. It is ignored otherwise.
mode?: {
fn get(&self) -> Option<Mode> {
get_mode(self.flags(), self.raw.arg3)
}
fn set(mut self, v: Option<Mode>) -> Self {
self.raw.arg3 = v.into_raw();
self
}
},
}
}
// Open not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Open> for Openat {
/// An `open` syscall can be trivially transformed into an `openat`
/// syscall by shifting all the arguments to the right and setting the first
/// argument to `AT_FDCWD` (the current working directory).
fn from(open: Open) -> Self {
let Open { mut raw } = open;
raw.arg3 = raw.arg2;
raw.arg2 = raw.arg1;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Openat { raw }
}
}
// Creat not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Creat> for Openat {
/// A call to creat() is equivalent to calling open() with flags equal to
/// O_CREAT|O_WRONLY|O_TRUNC
fn from(creat: Creat) -> Self {
let Creat { mut raw } = creat;
raw.arg3 = raw.arg1;
raw.arg2 = (libc::O_CREAT | libc::O_WRONLY | libc::O_TRUNC) as usize;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Openat { raw }
}
}
typed_syscall! {
pub struct Mkdirat {
dirfd: i32,
path: Option<PathPtr>,
mode: Mode,
}
}
// Mkdir not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Mkdir> for Mkdirat {
/// An `mkdir` syscall can be trivially transformed into a `mkdirat` syscall
/// by shifting all the arguments to the right and setting the first argument
/// to `AT_FDCWD` (the current working directory).
fn from(syscall: Mkdir) -> Self {
let Mkdir { mut raw } = syscall;
raw.arg2 = raw.arg1;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Mkdirat { raw }
}
}
typed_syscall! {
pub struct Mknodat {
dirfd: i32,
path: Option<PathPtr>,
mode: Mode,
dev: libc::dev_t,
}
}
// Mknod not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Mknod> for Mknodat {
/// An `mknod` syscall can be trivially transformed into an `mknodat` syscall
/// by shifting all the arguments to the right and setting the first argument
/// to `AT_FDCWD` (the current working directory).
fn from(syscall: Mknod) -> Self {
let Mknod { mut raw } = syscall;
raw.arg3 = raw.arg2;
raw.arg2 = raw.arg1;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Mknodat { raw }
}
}
typed_syscall! {
pub struct Fchownat {
dirfd: i32,
path: Option<PathPtr>,
owner: libc::uid_t,
group: libc::gid_t,
flags: AtFlags,
}
}
// Futimesat not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Futimesat {
dirfd: i32,
path: Option<PathPtr>,
utimes: Option<Addr<[libc::timeval; 2]>>,
}
}
// Newfstatat not available in aarch64
#[cfg(target_arch = "x86_64")]
typed_syscall! {
pub struct Newfstatat {
dirfd: i32,
path: Option<PathPtr>,
stat: Option<StatPtr>,
flags: AtFlags,
}
}
/// Alias for Newfstatat. Architectures other than x86-64 usually name this
/// syscall `fstatat`.
#[cfg(target_arch = "x86_64")]
pub type Fstatat = Newfstatat;
#[cfg(target_arch = "aarch64")]
typed_syscall! {
pub struct Fstatat {
dirfd: i32,
path: Option<PathPtr>,
stat: Option<StatPtr>,
flags: AtFlags,
}
}
// `Stat` is not available in aarch64
#[cfg(target_arch = "x86_64")]
impl From<Stat> for Fstatat {
fn from(stat: Stat) -> Self {
let Stat { mut raw } = stat;
raw.arg3 = 0;
raw.arg2 = raw.arg1;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Self { raw }
}
}
// Lstat is not available in aarch64
#[cfg(target_arch = "x86_64")]
impl From<Lstat> for Fstatat {
fn from(lstat: Lstat) -> Self {
let Lstat { mut raw } = lstat;
raw.arg3 = AtFlags::AT_SYMLINK_NOFOLLOW.bits() as usize;
raw.arg2 = raw.arg1;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Self { raw }
}
}
typed_syscall! {
pub struct Unlinkat {
dirfd: i32,
path: Option<PathPtr>,
flags: AtFlags,
}
}
// Unlink not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Unlink> for Unlinkat {
fn from(unlink: Unlink) -> Self {
let Unlink { mut raw } = unlink;
raw.arg2 = 0;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Unlinkat { raw }
}
}
// Rmdir not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Rmdir> for Unlinkat {
fn from(rmdir: Rmdir) -> Self {
let Rmdir { mut raw } = rmdir;
raw.arg2 = libc::AT_REMOVEDIR as usize;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Unlinkat { raw }
}
}
typed_syscall! {
pub struct Renameat {
olddirfd: i32,
oldpath: Option<PathPtr>,
newdirfd: i32,
newpath: Option<PathPtr>,
}
}
typed_syscall! {
pub struct Linkat {
olddirfd: i32,
oldpath: Option<PathPtr>,
newdirfd: i32,
newpath: Option<PathPtr>,
flags: AtFlags,
}
}
// Link not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Link> for Linkat {
/// A `link` syscall can be trivially transformed into a `linkat` syscall
/// by rearranging the `oldpath` and `newpath` arguments,
/// setting both old and new directory file descriptors to the special value
/// `AT_FDCWD` (indicating the current working directory),
/// and clearing the flags.
fn from(link: Link) -> Self {
let Link { mut raw } = link;
raw.arg3 = raw.arg1;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
raw.arg2 = libc::AT_FDCWD as usize;
raw.arg4 = 0;
Linkat { raw }
}
}
typed_syscall! {
pub struct Symlinkat {
target: Option<PathPtr>,
newdirfd: i32,
linkpath: Option<PathPtr>,
}
}
typed_syscall! {
pub struct Readlinkat {
dirfd: i32,
path: Option<PathPtr>,
buf: Option<AddrMut<libc::c_char>>,
buf_len: usize,
}
}
typed_syscall! {
pub struct Fchmodat {
dirfd: i32,
path: Option<PathPtr>,
mode: Mode,
flags: AtFlags,
}
}
typed_syscall! {
pub struct Faccessat {
dirfd: i32,
path: Option<PathPtr>,
mode: Mode,
flags: AtFlags,
}
}
typed_syscall! {
pub struct Pselect6 {
nfds: i32,
readfds: Option<AddrMut<libc::fd_set>>,
writefds: Option<AddrMut<libc::fd_set>>,
exceptfds: Option<AddrMut<libc::fd_set>>,
timeout: Option<Addr<libc::timeval>>,
sigmask: Option<Addr<libc::sigset_t>>,
}
}
typed_syscall! {
pub struct Ppoll {
fds: Option<AddrMut<libc::pollfd>>,
nfds: libc::nfds_t,
timeout: Option<Addr<libc::timeval>>,
sigmask: Option<Addr<libc::sigset_t>>,
sigsetsize: usize,
}
}
typed_syscall! {
pub struct Unshare {
flags: CloneFlags,
}
}
typed_syscall! {
pub struct SetRobustList {
// FIXME: This should be pointer to `robust_list_head`.
head: Option<AddrMut<libc::c_void>>,
len: usize,
}
}
typed_syscall! {
pub struct GetRobustList {
pid: libc::pid_t,
// FIXME: This should be pointer to `robust_list_head`.
head_ptr: Option<AddrMut<AddrMut<libc::c_void>>>,
len_ptr: Option<AddrMut<usize>>,
}
}
typed_syscall! {
pub struct Splice {
fd_in: i32,
off_in: Option<AddrMut<libc::loff_t>>,
fd_out: i32,
off_out: Option<AddrMut<libc::loff_t>>,
len: usize,
flags: u32,
}
}
typed_syscall! {
pub struct Tee {
fd_in: i32,
fd_out: i32,
len: usize,
flags: u32,
}
}
// SyncFileRange not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct SyncFileRange {
fd: i32,
offset: libc::loff_t,
nbytes: libc::loff_t,
flags: u32,
}
}
typed_syscall! {
pub struct Vmsplice {
fd: i32,
iov: Option<Addr<libc::iovec>>,
nr_segs: u64,
flags: u32,
}
}
typed_syscall! {
pub struct MovePages {
pid: libc::pid_t,
nr_pages: u64,
pages: Option<Addr<Addr<libc::c_void>>>,
nodes: Option<Addr<Addr<i32>>>,
status: Option<AddrMut<i32>>,
flags: i32,
}
}
typed_syscall! {
pub struct Utimensat {
dirfd: i32,
path: Option<PathPtr>,
times: Option<Addr<[Timespec; 2]>>,
flags: i32,
}
}
typed_syscall! {
pub struct EpollPwait {
epfd: i32,
events: Option<AddrMut<libc::epoll_event>>,
maxevents: i32,
timeout: i32,
sigmask: Option<Addr<libc::sigset_t>>,
sigsetsize: usize,
}
}
// Signalfd not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
/// Naked signalfd(2) is not the same as glibc wrapper.
/// see kernel fs/signalfd.c for more details.
/// NB: kernel_sigset_t is 8 bytes (sizeof usize), we still use
/// libc::sigset_t here because kernel access only the 1st 8 bytes.
/// NB2: glibc wrapper will call signalfd4(2) instead, this this
/// syscall is only possible when user calls libc::syscall directly.
pub struct Signalfd {
fd: i32,
mask: Option<AddrMut<libc::sigset_t>>,
size: usize,
}
}
typed_syscall! {
pub struct TimerfdCreate {
clockid: ClockId,
flags: TimerFlags,
}
}
// Eventfd not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
typed_syscall! {
pub struct Eventfd {
count: u32,
}
}
typed_syscall! {
pub struct Fallocate {
fd: i32,
mode: i32,
offset: libc::loff_t,
len: libc::loff_t,
}
}
typed_syscall! {
pub struct TimerfdSettime {
fd: i32,
flags: i32,
new_value: Option<Addr<libc::itimerspec>>,
old_value: Option<AddrMut<libc::itimerspec>>,
}
}
typed_syscall! {
pub struct TimerfdGettime {
fd: i32,
value: Option<AddrMut<libc::itimerspec>>,
}
}
typed_syscall! {
pub struct Accept4 {
sockfd: i32,
sockaddr: Option<AddrMut<libc::sockaddr>>,
addrlen: Option<AddrMut<usize>>,
flags: SockFlag,
}
}
impl From<Accept> for Accept4 {
/// If flags is 0, then accept4() is the same as accept().
fn from(accept: Accept) -> Self {
let Accept { mut raw } = accept;
raw.arg3 = 0;
Accept4 { raw }
}
}
typed_syscall! {
/// Naked signalfd4(2) is not the same as glibc wrapper.
/// see kernel fs/signalfd.c for more details.
/// NB: kernel_sigset_t is 8 bytes (sizeof usize), we still use
/// libc::sigset_t here because kernel access only the 1st 8 bytes.
pub struct Signalfd4 {
fd: i32,
mask: Option<AddrMut<libc::sigset_t>>,
size: usize,
flags: SfdFlags,
}
}
// Signalfd not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Signalfd> for Signalfd4 {
fn from(signalfd: Signalfd) -> Self {
let Signalfd { mut raw } = signalfd;
raw.arg3 = 0;
Signalfd4 { raw }
}
}
typed_syscall! {
pub struct Eventfd2 {
count: u32,
flags: EfdFlags,
}
}
// Eventfd not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Eventfd> for Eventfd2 {
/// eventfd2 provide an extra `flags' argument, it's safe
/// to convert eventfd(2) to eventfd2(2), as a result.
/// glibc should have wrapped all eventfd syscall into eventfd2.
fn from(eventfd: Eventfd) -> Self {
let Eventfd { mut raw } = eventfd;
raw.arg1 = 0;
Eventfd2 { raw }
}
}
typed_syscall! {
pub struct EpollCreate1 {
flags: EpollCreateFlags,
}
}
// EpollCreate not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<EpollCreate> for EpollCreate1 {
/// `size' in epoll_create(2) is ignored but must be >= 0 since 2.6.9
/// We still allows convert `epoll_create` to `epoll_create1` by forcing
/// `flags` to 0. This could have changed behavior when calling
/// `epoll_create(-1)` but shouldn't be a real concern in practice.
fn from(epoll_create: EpollCreate) -> Self {
let EpollCreate { mut raw } = epoll_create;
raw.arg0 = 0;
EpollCreate1 { raw }
}
}
typed_syscall! {
pub struct Dup3 {
oldfd: i32,
newfd: i32,
flags: OFlag,
}
}
typed_syscall! {
pub struct Pipe2 {
pipefd: Option<AddrMut<[i32; 2]>>,
flags: OFlag,
}
}
// Pipe not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Pipe> for Pipe2 {
/// If flags is 0, then pipe2() is the same as pipe().
fn from(pipe: Pipe) -> Self {
let Pipe { mut raw } = pipe;
raw.arg1 = 0;
Pipe2 { raw }
}
}
typed_syscall! {
pub struct InotifyInit1 {
flags: InitFlags,
}
}
// InotifyInit1 not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<InotifyInit> for InotifyInit1 {
/// If flags is 0, then inotify_init1 is the same as inotify_init.
/// Note that inotify_init was introduced in 2.6.13 and inotify_init1
/// was added in 2.6.27.
fn from(inotify_init: InotifyInit) -> Self {
let InotifyInit { mut raw } = inotify_init;
raw.arg0 = 0;
InotifyInit1 { raw }
}
}
typed_syscall! {
pub struct Preadv {
fd: i32,
iov: Option<Addr<libc::iovec>>,
iov_len: usize,
pos_l: u64,
pos_h: u64,
}
}
typed_syscall! {
pub struct Pwritev {
fd: i32,
iov: Option<Addr<libc::iovec>>,
iov_len: usize,
pos_l: u64,
pos_h: u64,
}
}
typed_syscall! {
pub struct RtTgsigqueueinfo {
tgid: libc::pid_t,
tid: libc::pid_t,
sig: i32,
siginfo: Option<AddrMut<libc::siginfo_t>>,
}
}
typed_syscall! {
pub struct PerfEventOpen {
// FIXME: This should be a pointer to `perf_event_attr`.
attr: Option<AddrMut<libc::c_void>>,
pid: libc::pid_t,
cpu: i32,
group_fd: i32,
flags: u64,
}
}
typed_syscall! {
pub struct Recvmmsg {
fd: i32,
mmsg: Option<AddrMut<libc::mmsghdr>>,
vlen: u32,
flags: u32,
timeout: Option<Addr<Timespec>>,
}
}
typed_syscall! {
pub struct FanotifyInit {
flags: u32,
event_f_flags: u32,
}
}
typed_syscall! {
pub struct FanotifyMark {
fanotify_fd: i32,
flags: u32,
mask: u64,
dirfd: i32,
pathname: Option<PathPtr>,
}
}
typed_syscall! {
pub struct Prlimit64 {
pid: libc::pid_t,
resource: u32,
new_rlim: Option<Addr<libc::rlimit64>>,
old_rlim: Option<AddrMut<libc::rlimit64>>,
}
}
typed_syscall! {
pub struct NameToHandleAt {
dirfd: i32,
pathname: Option<PathPtr>,
// FIXME: This should be a pointer to `file_handle`.
handle: Option<AddrMut<libc::c_void>>,
mount_id: Option<AddrMut<i32>>,
flags: i32,
}
}
typed_syscall! {
pub struct OpenByHandleAt {
mount_fd: i32,
// FIXME: This should be a pointer to `file_handle`.
handle: Option<AddrMut<libc::c_void>>,
flags: i32,
}
}
typed_syscall! {
pub struct ClockAdjtime {
clockid: ClockId,
buf: Option<AddrMut<libc::timex>>,
}
}
typed_syscall! {
pub struct Syncfs {
fd: i32,
}
}
typed_syscall! {
pub struct Sendmmsg {
sockfd: i32,
msgvec: Option<Addr<libc::msghdr>>,
vlen: u32,
flags: i32,
}
}
typed_syscall! {
pub struct Setns {
fd: i32,
nstype: CloneFlags,
}
}
// NB: getcpu_cache (third argument) is unused in kernel >= 2.6.23 should be
// always NULL.
typed_syscall! {
pub struct Getcpu {
cpu: Option<AddrMut<u32>>,
node: Option<AddrMut<u32>>,
}
}
typed_syscall! {
pub struct ProcessVmReadv {
pid: libc::pid_t,
local_iov: Option<Addr<libc::iovec>>,
local_iov_count: u64,
remote_iov: Option<Addr<libc::iovec>>,
remote_iov_count: u64,
flags: u64,
}
}
typed_syscall! {
pub struct ProcessVmWritev {
pid: libc::pid_t,
local_iov: Option<Addr<libc::iovec>>,
local_iov_count: u64,
remote_iov: Option<Addr<libc::iovec>>,
remote_iov_count: u64,
flags: u64,
}
}
typed_syscall! {
pub struct Kcmp {
pid1: libc::pid_t,
pid2: libc::pid_t,
typ: i32,
idx1: u64,
idx2: u64,
}
}
typed_syscall! {
pub struct FinitModule {
fd: i32,
param_values: Option<CStrPtr>,
flags: i32,
}
}
typed_syscall! {
pub struct SchedSetattr {
pid: libc::pid_t,
attr: Option<AddrMut<libc::c_void /* sched_attr */>>,
flags: u32,
}
}
typed_syscall! {
pub struct SchedGetattr {
pid: libc::pid_t,
// FIXME: This should be a pointer to a `sched_attr`.
attr: Option<AddrMut<libc::c_void>>,
size: u32,
flags: u32,
}
}
typed_syscall! {
pub struct Renameat2 {
olddirfd: i32,
oldpath: Option<PathPtr>,
newdirfd: i32,
newpath: Option<PathPtr>,
// TODO: Make some `RENAME_*` bitflags to cover this.
flags: libc::c_uint,
}
}
// Rename not available in aarch64
#[cfg(not(target_arch = "aarch64"))]
impl From<Rename> for Renameat2 {
fn from(rename: Rename) -> Self {
let Rename { mut raw } = rename;
raw.arg4 = 0;
raw.arg3 = raw.arg1;
raw.arg2 = libc::AT_FDCWD as usize;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Renameat2 { raw }
}
}
impl From<Renameat> for Renameat2 {
fn from(renameat: Renameat) -> Self {
let Renameat { mut raw } = renameat;
raw.arg4 = 0;
Renameat2 { raw }
}
}
typed_syscall! {
pub struct Seccomp {
op: u32,
flags: u32,
args: Option<AddrMut<libc::c_void>>,
}
}
typed_syscall! {
pub struct Getrandom {
/// The buffer should never be NULL (None), or this represents an invalid call when passed
/// to the kernel. Nevertheless, we retain the ability here to represent that invalid call.
buf: Option<AddrMut<u8>>,
buflen: usize,
flags: usize,
}
}
typed_syscall! {
pub struct MemfdCreate {
name: Option<PathPtr>,
flags: u32,
}
}
typed_syscall! {
pub struct KexecFileLoad {
kernel_fd: i32,
initrd_fd: i32,
cmdline_len: u64,
cmdline: Option<Addr<libc::c_char>>,
flags: u64,
}
}
typed_syscall! {
pub struct Bpf {
cmd: i32,
attr: Option<AddrMut<libc::c_void /* bpf_attr */>>,
size: u32,
}
}
typed_syscall! {
pub struct Execveat {
dirfd: i32,
path: Option<PathPtr>,
argv: Option<CArrayPtr<CStrPtr>>,
envp: Option<CArrayPtr<CStrPtr>>,
flags: i32,
}
}
impl From<Execve> for Execveat {
/// An `execve` syscall can be trivially transformed into an `execveat`
/// syscall by shifting all the arguments to the right and setting the first
/// argument to `AT_FDCWD` (the current working directory).
fn from(execve: Execve) -> Self {
let Execve { mut raw } = execve;
raw.arg4 = 0; // flags
raw.arg3 = raw.arg2;
raw.arg2 = raw.arg1;
raw.arg1 = raw.arg0;
raw.arg0 = libc::AT_FDCWD as usize;
Execveat { raw }
}
}
typed_syscall! {
pub struct Userfaultfd {
flags: i32,
}
}
typed_syscall! {
pub struct Membarrier {
cmd: i32,
flags: i32,
}
}
typed_syscall! {
pub struct Mlock2 {
addr: Option<Addr<libc::c_void>>,
len: usize,
flags: i32,
}
}
typed_syscall! {
pub struct CopyFileRange {
fd_in: i32,
off_in: Option<AddrMut<libc::loff_t>>,
fd_out: i32,
off_out: Option<AddrMut<libc::loff_t>>,
len: usize,
flags: u32,
}
}
typed_syscall! {
pub struct Preadv2 {
fd: i32,
iov: Option<Addr<libc::iovec>>,
iov_len: u64,
pos_l: u64,
pos_h: u64,
flags: i32,
}
}
typed_syscall! {
pub struct Pwritev2 {
fd: i32,
iov: Option<Addr<libc::iovec>>,
iov_len: u64,
pos_l: u64,
pos_h: u64,
flags: i32,
}
}
typed_syscall! {
pub struct PkeyMprotect {
addr: Option<AddrMut<libc::c_void>>,
len: usize,
prot: i32,
pkey: i32,
}
}
typed_syscall! {
pub struct PkeyAlloc {
flags: u64,
access_rights: u64,
}
}
typed_syscall! {
pub struct PkeyFree {
pkey: i32,
}
}
typed_syscall! {
pub struct Statx {
dirfd: i32,
path: Option<PathPtr>,
flags: AtFlags,
mask: StatxMask,
statx: Option<StatxPtr>,
}
}
typed_syscall! {
pub struct Clone3 {
args: Option<AddrMut<CloneArgs>>,
size: usize,
}
}
#[cfg(test)]
mod test {
use std::ffi::CString;
use std::path::Path;
use syscalls::SyscallArgs;
use syscalls::Sysno;
use super::*;
use crate::Displayable;
use crate::LocalMemory;
use crate::ReadAddr;
#[test]
fn test_syscall_openat_path() {
assert_eq!(Openat::NAME, "openat");
assert_eq!(Openat::NUMBER, Sysno::openat);
let name = CString::new("/some/file/path").unwrap();
let syscall = Openat::new()
.with_dirfd(-100)
.with_path(PathPtr::from_ptr(name.as_ptr()))
.with_flags(OFlag::O_RDONLY | OFlag::O_APPEND)
.with_mode(Some(Mode::from_bits_truncate(0o644)));
assert_eq!(Openat::from(SyscallArgs::from(syscall)), syscall);
let memory = LocalMemory::new();
assert_eq!(
syscall.path().unwrap().read(&memory).unwrap(),
Path::new("/some/file/path")
);
assert_eq!(
format!("{}", syscall.display(&memory)),
format!(
"openat(-100, {:p} -> \"/some/file/path\", O_APPEND)",
name.as_ptr()
)
);
}
#[test]
fn test_syscall_openat_display() {
assert_eq!(Openat::NAME, "openat");
assert_eq!(Openat::NUMBER, Sysno::openat);
let memory = LocalMemory::new();
assert_eq!(
format!(
"{}",
Openat::new()
.with_dirfd(-100)
.with_path(None)
.with_flags(OFlag::O_APPEND)
.display(&memory)
),
"openat(-100, NULL, O_APPEND)"
);
assert_eq!(
format!(
"{}",
Openat::new()
.with_dirfd(-100)
.with_path(None)
.with_flags(OFlag::O_CREAT)
.with_mode(Some(Mode::from_bits_truncate(0o644)))
.display(&memory)
),
"openat(-100, NULL, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)"
);
assert_eq!(
format!(
"{}",
Openat::new()
.with_dirfd(-100)
.with_path(None)
.with_flags(OFlag::O_TMPFILE)
.with_mode(Some(Mode::from_bits_truncate(0o600)))
.display(&memory)
),
"openat(-100, NULL, O_DIRECTORY | O_TMPFILE, S_IRUSR | S_IWUSR)"
);
#[cfg(target_arch = "x86_64")]
assert_eq!(
Openat::new()
.with_dirfd(libc::AT_FDCWD)
.with_path(None)
.with_flags(OFlag::O_CREAT | OFlag::O_WRONLY | OFlag::O_TRUNC)
.with_mode(Some(Mode::from_bits_truncate(0o600))),
Creat::new()
.with_path(None)
.with_mode(Mode::from_bits_truncate(0o600))
.into()
);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn test_syscall_stat() {
let name = CString::new("/dev/null").unwrap();
let stat = nix::sys::stat::stat("/dev/null").unwrap();
let syscall = Stat::new()
.with_path(PathPtr::from_ptr(name.as_ptr()))
.with_stat(StatPtr::from_ptr(&stat as *const libc::stat));
let memory = LocalMemory::new();
assert_eq!(
format!("{}", syscall.display_with_outputs(&memory)),
format!(
"stat({:p} -> \"/dev/null\", {:p} -> {{st_mode=S_IFCHR | 0666, st_size=0, ...}})",
name.as_ptr(),
&stat as *const _
)
);
}
#[test]
fn test_syscall_fcntl() {
let memory = LocalMemory::new();
assert_eq!(
format!(
"{}",
Fcntl::new()
.with_fd(1)
.with_cmd(FcntlCmd::F_DUPFD(2))
.display(&memory)
),
"fcntl(1, F_DUPFD, 2)"
);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn test_syscall_pipe2() {
let memory: Option<AddrMut<[i32; 2]>> = AddrMut::from_raw(0x1245);
// NOTE: `pipe` is not available on aarch64.
assert_eq!(
Pipe2::new().with_pipefd(memory),
Pipe::new().with_pipefd(memory).into()
);
assert_ne!(
Pipe2::new()
.with_pipefd(memory)
.with_flags(OFlag::O_CLOEXEC),
Pipe::new().with_pipefd(memory).into()
);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn test_syscall_linkat() {
let foo = CString::new("foo").unwrap();
let bar = CString::new("bar").unwrap();
// NOTE: `link` is not available on aarch64.
assert_eq!(
Linkat::new()
.with_olddirfd(libc::AT_FDCWD)
.with_oldpath(PathPtr::from_ptr(foo.as_ptr()))
.with_newdirfd(libc::AT_FDCWD)
.with_newpath(PathPtr::from_ptr(bar.as_ptr()))
.with_flags(AtFlags::empty()),
Link::new()
.with_oldpath(PathPtr::from_ptr(foo.as_ptr()))
.with_newpath(PathPtr::from_ptr(bar.as_ptr()))
.into(),
);
}
}
|
extern crate sdl2;
use super::super::world::player;
use super::font_renderer;
use sdl2::rect;
use sdl2::render;
use sdl2::video;
pub struct PlayerRenderer {
texture: (sdl2::render::Texture, u32, u32),
}
impl PlayerRenderer {
pub fn new(renderer: &font_renderer::FontRenderer) -> Result<PlayerRenderer, String> {
Ok(PlayerRenderer {
texture: renderer.generate_texture('@')?,
})
}
pub fn render(
&mut self,
players: &Vec<player::Player>,
canvas: &mut render::Canvas<video::Window>,
) -> Result<(), String> {
for player in players.iter() {
self.texture
.0
.set_color_mod(player.color().r, player.color().g, player.color().b);
canvas.copy(
&self.texture.0,
None,
rect::Rect::new(
player.x * (self.texture.1 as i32 + 4),
player.y * self.texture.2 as i32,
self.texture.1,
self.texture.2,
),
)?;
}
Ok(())
}
}
|
impl Solution {
pub fn equal_substring(s: String, t: String, max_cost: i32) -> i32 {
let (mut start,mut end,mut cost) = (0,0,0);
let mut res = 0;
let (s,t) = (s.into_bytes(),t.into_bytes());
//维护一个窗口,窗口的尾部是一直往前走的,窗口内的cost只要大于maxcost就往前移动头部
//直到窗口内部cost是小于等于maxcost的
while end < s.len(){
cost += (s[end] as i32 - t[end] as i32).abs();
while cost > max_cost{
cost -= (s[start] as i32 - t[start] as i32).abs();
start += 1;
}
res = res.max(end - start + 1);
end += 1;
}
res as i32
}
} |
use autocfg::AutoCfg;
fn main() {
match AutoCfg::new() {
Ok(ac) => {
// The #[track_caller] attribute was stabilized in rustc 1.46.0.
if ac.probe_rustc_version(1, 46) {
autocfg::emit("tokio_track_caller")
}
}
Err(e) => {
// If we couldn't detect the compiler version and features, just
// print a warning. This isn't a fatal error: we can still build
// Tokio, we just can't enable cfgs automatically.
println!(
"cargo:warning=tokio: failed to detect compiler features: {}",
e
);
}
}
}
|
//! The way terminal input is handled.
pub mod actions;
pub mod config;
pub mod handler;
pub mod keybinds;
|
use std::collections::HashMap;
// Deterministic Finite Automata (DFA)
// also known as a Finite-state Machine
pub type StateMachine = State;
#[derive(Debug)]
pub struct State {
transitions: HashMap<char, State>,
terminal: bool,
}
impl StateMachine {
pub fn new() -> Self {
State {
transitions: HashMap::new(),
terminal: false,
}
}
// accepts checks if a word is accepted by this state machine.
// returns true if word is accepted, else false.
pub fn accepts(&self, word: &str) -> bool {
let mut state = self;
for c in word.chars() {
match state.trans().get(&c) {
Some(next_state) => state = next_state,
None => return false,
}
}
return state.terminal;
}
// include modifies the state machine so that it accepts the input word.
// post-conditions:
// - All accepted words prior to applying `include` are accepted after
// - This now accepts the input word. (`self.accepts(word)` will return true).
pub fn include(&mut self, word: &str) {
match word.chars().nth(0) {
// Reached end of word, make current state terminal.
None => self.terminal = true,
// Characters remaining in word.
Some(current_char) => {
let remaining = &word[1..];
match self.trans_mut().get_mut(¤t_char) {
// Transition from self on current_char exists.
Some(ref mut state) => {
state.include(remaining)
},
// Transition from self on current_char must be created.
None => {
let mut new_state = State {
transitions: HashMap::new(),
terminal: remaining.len() == 0,
};
new_state.include(remaining);
self.trans_mut().insert(current_char, new_state);
}
}
}
}
}
}
impl State {
// trans is a getter for the state transitions that is immutable.
fn trans(&self) -> &HashMap<char, State> {
&self.transitions
}
// trans_mut is a getter for the state transitions that allows mutation.
fn trans_mut(&mut self) -> &mut HashMap<char, State> {
&mut self.transitions
}
}
#[cfg(test)]
mod tests {
use super::StateMachine;
#[test]
fn sm_include_post_condition_1() {
let mut sm = StateMachine::new();
sm.include("abc");
assert!(sm.accepts("abc"));
}
#[test]
fn sm_include_and_no_accept() {
let mut sm = StateMachine::new();
sm.include("abc");
assert_eq!(sm.accepts(""), false, "word: \"\"");
assert_eq!(sm.accepts("bc"), false, "word: \"bc\"");
assert_eq!(sm.accepts("abz"), false, "word: \"abz\"");
assert_eq!(sm.accepts("abcd"), false, "word: \"abcd\"");
assert_eq!(sm.accepts("Thor"), false, "word: \"Thor\"");
}
#[test]
fn sm_include_post_condition_2() {
let mut sm = StateMachine::new();
sm.include("abc");
assert!(sm.accepts("abc"));
assert_eq!(sm.accepts("a"), false, "expected fail on word: \"a\"");
sm.include("a");
assert!(sm.accepts("abc"));
assert_eq!(sm.accepts("a"), true, "expected acceptance of word: \"a\"");
sm.include("Loki");
assert!(sm.accepts("abc"));
assert_eq!(sm.accepts("a"), true, "expected acceptance of word: \"a\"");
assert_eq!(sm.accepts("Loki"), true, "expected acceptance of word: \"Loki\"");
}
#[test]
fn sm_include_empty_string() {
let mut sm = StateMachine::new();
sm.include("");
assert!(sm.accepts(""));
}
}
|
mod compile;
mod targets;
pub mod tempfile;
mod util;
use self::compile::SharedLibraries;
use crate::config::{AndroidConfig, AndroidTargetConfig};
use anyhow::format_err;
use cargo::core::{Target, TargetKind, Workspace};
use cargo::util::process_builder::process;
use cargo::util::CargoResult;
use clap::ArgMatches;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::{env, fs};
#[derive(Debug)]
pub struct BuildResult {
/// Mapping from target kind and target name to the built APK
pub target_to_apk_map: BTreeMap<(TargetKind, String), PathBuf>,
}
pub fn build(
workspace: &Workspace,
config: &AndroidConfig,
options: &ArgMatches,
) -> CargoResult<BuildResult> {
let root_build_dir = util::get_root_build_directory(workspace, config);
let shared_libraries =
compile::build_shared_libraries(workspace, config, options, &root_build_dir)?;
let sign = !options.is_present("nosign");
build_apks(config, &root_build_dir, shared_libraries, sign)
}
fn build_apks(
config: &AndroidConfig,
root_build_dir: &PathBuf,
shared_libraries: SharedLibraries,
sign: bool,
) -> CargoResult<BuildResult> {
// Create directory to hold final APKs which are signed using the debug key
let final_apk_dir = root_build_dir.join("apk");
fs::create_dir_all(&final_apk_dir)?;
// Paths of created APKs
let mut target_to_apk_map = BTreeMap::new();
// Build an APK for each cargo target
for (target, shared_libraries) in shared_libraries.shared_libraries.iter_all() {
let target_directory = util::get_target_directory(root_build_dir, target)?;
fs::create_dir_all(&target_directory)?;
// Determine Target Configuration
let target_config = config.resolve((target.kind().to_owned(), target.name().to_owned()))?;
//
// Run commands to produce APK
//
build_manifest(&target_directory, &config, &target_config, &target)?;
let build_tools_path = config
.sdk_path
.join("build-tools")
.join(&config.build_tools_version);
let aapt_path = build_tools_path.join("aapt");
let zipalign_path = build_tools_path.join("zipalign");
// Create unaligned APK which includes resources and assets
let unaligned_apk_name = format!("{}_unaligned.apk", target.name());
let unaligned_apk_path = target_directory.join(&unaligned_apk_name);
if unaligned_apk_path.exists() {
std::fs::remove_file(unaligned_apk_path)
.map_err(|e| format_err!("Unable to delete APK file. {}", e))?;
}
let mut aapt_package_cmd = process(&aapt_path);
aapt_package_cmd
.arg("package")
.arg("-F")
.arg(&unaligned_apk_name)
.arg("-M")
.arg("AndroidManifest.xml")
.arg("-I")
.arg(&config.android_jar_path);
if let Some(res_path) = target_config.res_path {
aapt_package_cmd.arg("-S").arg(res_path);
}
// Link assets
if let Some(assets_path) = &target_config.assets_path {
aapt_package_cmd.arg("-A").arg(assets_path);
}
aapt_package_cmd.cwd(&target_directory).exec()?;
// Add shared libraries to the APK
for shared_library in shared_libraries {
// Copy the shared library to the appropriate location in the target directory and with the appropriate name
// Note: that the type of slash used matters. This path is passed to aapt and the shared library
// will not load if backslashes are used.
let so_path = format!(
"lib/{}/{}",
&shared_library.abi.android_abi(),
shared_library.filename
);
let target_shared_object_path = target_directory.join(&so_path);
fs::create_dir_all(target_shared_object_path.parent().unwrap())?;
fs::copy(&shared_library.path, target_shared_object_path)?;
// Add to the APK
process(&aapt_path)
.arg("add")
.arg(&unaligned_apk_name)
.arg(so_path)
.cwd(&target_directory)
.exec()?;
}
// Determine the directory in which to place the aligned and signed APK
let target_apk_directory = match target.kind() {
TargetKind::Bin => final_apk_dir.clone(),
TargetKind::ExampleBin => final_apk_dir.join("examples"),
_ => unreachable!("Unexpected target kind"),
};
fs::create_dir_all(&target_apk_directory)?;
// Align apk
let final_apk_path = target_apk_directory.join(format!("{}.apk", target.name()));
process(&zipalign_path)
.arg("-f")
.arg("-v")
.arg("4")
.arg(&unaligned_apk_name)
.arg(&final_apk_path)
.cwd(&target_directory)
.exec()?;
// Find or generate a debug keystore for signing the APK
// We use the same debug keystore as used by the Android SDK. If it does not exist,
// then we create it using keytool which is part of the JRE/JDK
let android_directory = dirs::home_dir()
.ok_or_else(|| format_err!("Unable to determine home directory"))?
.join(".android");
fs::create_dir_all(&android_directory)?;
let keystore_path = android_directory.join("debug.keystore");
if !keystore_path.exists() {
// Generate key
let keytool_filename = if cfg!(target_os = "windows") {
"keytool.exe"
} else {
"keytool"
};
let keytool_path = find_java_executable(keytool_filename)?;
process(keytool_path)
.arg("-genkey")
.arg("-v")
.arg("-keystore")
.arg(&keystore_path)
.arg("-storepass")
.arg("android")
.arg("-alias")
.arg("androidebugkey")
.arg("-keypass")
.arg("android")
.arg("-dname")
.arg("CN=Android Debug,O=Android,C=US")
.arg("-keyalg")
.arg("RSA")
.arg("-keysize")
.arg("2048")
.arg("-validity")
.arg("10000")
.cwd(root_build_dir)
.exec()?;
}
if sign {
// Sign the APK with the development certificate
util::script_process(
build_tools_path.join(format!("apksigner{}", util::EXECUTABLE_SUFFIX_BAT)),
)
.arg("sign")
.arg("--ks")
.arg(keystore_path)
.arg("--ks-pass")
.arg("pass:android")
.arg(&final_apk_path)
.cwd(&target_directory)
.exec()?;
}
target_to_apk_map.insert(
(target.kind().to_owned(), target.name().to_owned()),
final_apk_path,
);
}
Ok(BuildResult { target_to_apk_map })
}
/// Find an executable that is part of the Java SDK
fn find_java_executable(name: &str) -> CargoResult<PathBuf> {
// Look in PATH
env::var_os("PATH")
.and_then(|paths| {
env::split_paths(&paths)
.filter_map(|path| {
let filepath = path.join(name);
if fs::metadata(&filepath).is_ok() {
Some(filepath)
} else {
None
}
})
.next()
})
.or_else(||
// Look in JAVA_HOME
env::var_os("JAVA_HOME").and_then(|java_home| {
let filepath = PathBuf::from(java_home).join("bin").join(name);
if filepath.exists() {
Some(filepath)
} else {
None
}
}))
.ok_or_else(|| {
format_err!(
"Unable to find executable: '{}'. Configure PATH or JAVA_HOME with the path to the JRE or JDK.",
name
)
})
}
fn build_manifest(
path: &Path,
config: &AndroidConfig,
target_config: &AndroidTargetConfig,
target: &Target,
) -> CargoResult<()> {
let file = path.join("AndroidManifest.xml");
let mut file = File::create(&file)?;
// Building application attributes
let application_attrs = format!(
r#"
android:hasCode="false" android:label="{0}"{1}{2}{3}"#,
target_config.package_label,
target_config
.package_icon
.as_ref()
.map_or(String::new(), |a| format!(
r#"
android:icon="{}""#,
a
)),
if target_config.fullscreen {
r#"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen""#
} else {
""
},
target_config
.application_attributes
.as_ref()
.map_or(String::new(), |a| a.replace("\n", "\n "))
);
// Build activity attributes
let activity_attrs = format!(
r#"
android:name="android.app.NativeActivity"
android:label="{0}"
android:configChanges="orientation|keyboardHidden|screenSize" {1}"#,
target_config.package_label,
target_config
.activity_attributes
.as_ref()
.map_or(String::new(), |a| a.replace("\n", "\n "))
);
let uses_features = target_config
.features
.iter()
.map(|f| {
format!(
"\n\t<uses-feature android:name=\"{}\" android:required=\"{}\" {}/>",
f.name,
f.required,
f.version
.as_ref()
.map_or(String::new(), |v| format!(r#"android:version="{}""#, v))
)
})
.collect::<Vec<String>>()
.join(", ");
let uses_permissions = target_config
.permissions
.iter()
.map(|f| {
format!(
"\n\t<uses-permission android:name=\"{}\" {max_sdk_version}/>",
f.name,
max_sdk_version = f.max_sdk_version.map_or(String::new(), |v| format!(
r#"android:maxSdkVersion="{}""#,
v
))
)
})
.collect::<Vec<String>>()
.join(", ");
// Write final AndroidManifest
writeln!(
file,
r#"<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="{package}"
android:versionCode="{version_code}"
android:versionName="{version_name}">
<uses-sdk android:targetSdkVersion="{targetSdkVersion}" android:minSdkVersion="{minSdkVersion}" />
<uses-feature android:glEsVersion="{glEsVersion}" android:required="true"></uses-feature>{uses_features}{uses_permissions}
<application {application_attrs} >
<activity {activity_attrs} >
<meta-data android:name="android.app.lib_name" android:value="{target_name}" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>"#,
package = target_config.package_name.replace("-", "_"),
version_code = target_config.version_code,
version_name = target_config.version_name,
targetSdkVersion = config.target_sdk_version,
minSdkVersion = config.min_sdk_version,
glEsVersion = format!(
"0x{:04}{:04}",
target_config.opengles_version_major, target_config.opengles_version_minor
),
uses_features = uses_features,
uses_permissions = uses_permissions,
application_attrs = application_attrs,
activity_attrs = activity_attrs,
target_name = target.name(),
)?;
Ok(())
}
|
use actix_files::Files;
use actix_web::{
error::InternalError, http::StatusCode, middleware, web, App, HttpRequest, HttpResponse,
HttpServer,
};
use sailfish::TemplateOnce;
#[derive(sailfish_macros::TemplateOnce)]
#[template(path = "index.stpl")]
struct Index;
async fn index(_: HttpRequest) -> actix_web::Result<HttpResponse> {
let body = Index
.render_once()
.map_err(|e| InternalError::new(e, StatusCode::INTERNAL_SERVER_ERROR))?;
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(body))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.service(web::resource("/index.html").to(index))
.service(web::resource("/").to(index))
.service(Files::new("/pkg", "./pkg"))
.service(Files::new("/static", "./static"))
})
.bind("0.0.0.0:8080")?
.run()
.await
}
|
use core::marker::PhantomData;
use crate::cogs::{
ActiveLineageSampler, BackedUp, Backup, CoalescenceSampler, DispersalSampler, EmigrationExit,
EventSampler, Habitat, ImmigrationEntry, LineageReference, LineageStore, RngCore,
SpeciationProbability, TurnoverRate,
};
use super::Simulation;
#[contract_trait]
impl<
H: Habitat,
G: RngCore,
R: LineageReference<H>,
S: LineageStore<H, R>,
X: EmigrationExit<H, G, R, S>,
D: DispersalSampler<H, G>,
C: CoalescenceSampler<H, R, S>,
T: TurnoverRate<H>,
N: SpeciationProbability<H>,
E: EventSampler<H, G, R, S, X, D, C, T, N>,
I: ImmigrationEntry,
A: ActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I>,
> Backup for Simulation<H, G, R, S, X, D, C, T, N, E, I, A>
{
unsafe fn backup_unchecked(&self) -> Self {
Simulation {
habitat: self.habitat.backup_unchecked(),
lineage_reference: PhantomData::<R>,
lineage_store: self.lineage_store.backup_unchecked(),
emigration_exit: self.emigration_exit.backup_unchecked(),
dispersal_sampler: self.dispersal_sampler.backup_unchecked(),
coalescence_sampler: self.coalescence_sampler.backup_unchecked(),
turnover_rate: self.turnover_rate.backup_unchecked(),
speciation_probability: self.speciation_probability.backup_unchecked(),
event_sampler: self.event_sampler.backup_unchecked(),
active_lineage_sampler: self.active_lineage_sampler.backup_unchecked(),
rng: self.rng.backup_unchecked(),
immigration_entry: self.immigration_entry.backup_unchecked(),
migration_balance: self.migration_balance,
}
}
}
impl<
H: Habitat,
G: RngCore,
R: LineageReference<H>,
S: LineageStore<H, R>,
X: EmigrationExit<H, G, R, S>,
D: DispersalSampler<H, G>,
C: CoalescenceSampler<H, R, S>,
T: TurnoverRate<H>,
N: SpeciationProbability<H>,
E: EventSampler<H, G, R, S, X, D, C, T, N>,
I: ImmigrationEntry,
A: ActiveLineageSampler<H, G, R, S, X, D, C, T, N, E, I>,
> BackedUp<Simulation<H, G, R, S, X, D, C, T, N, E, I, A>>
{
pub fn resume(&self) -> Simulation<H, G, R, S, X, D, C, T, N, E, I, A> {
unsafe {
Simulation {
habitat: self.0.habitat.backup_unchecked(),
lineage_reference: PhantomData::<R>,
lineage_store: self.0.lineage_store.backup_unchecked(),
emigration_exit: self.0.emigration_exit.backup_unchecked(),
dispersal_sampler: self.0.dispersal_sampler.backup_unchecked(),
coalescence_sampler: self.0.coalescence_sampler.backup_unchecked(),
turnover_rate: self.0.turnover_rate.backup_unchecked(),
speciation_probability: self.0.speciation_probability.backup_unchecked(),
event_sampler: self.0.event_sampler.backup_unchecked(),
active_lineage_sampler: self.0.active_lineage_sampler.backup_unchecked(),
rng: self.0.rng.backup_unchecked(),
immigration_entry: self.0.immigration_entry.backup_unchecked(),
migration_balance: self.0.migration_balance,
}
}
}
}
|
pub mod ast;
pub mod back;
mod front;
mod loc;
use back::env::SmartEnv;
use loc::Loc;
pub fn parse_eval_print(env: SmartEnv, filename: &str, input: &str) -> String {
let parse_result = front::parse(filename, input);
match parse_result {
Ok(nodes) => {
let eval_result = back::eval(env, nodes);
match eval_result {
Ok(output_node) => format!("{}", output_node.val),
Err(runtime_error) => match runtime_error.loc() {
Loc::File { filename, line, .. } => format!(
"Runtime error ({}:{}): {}\n",
filename,
line,
runtime_error.display()
),
Loc::Unknown => format!("Runtime error: {}\n", runtime_error.display()),
},
}
}
Err(syntax_errors) => {
let mut output = String::new();
for syntax_error in syntax_errors {
let s = match syntax_error.loc() {
Loc::File { filename, line, .. } => format!(
"Syntax error ({}:{}): {}\n",
filename,
line,
syntax_error.display()
),
Loc::Unknown => format!("Syntax error: {}\n", syntax_error.display(),),
};
output.push_str(&s);
}
output
}
}
}
|
use query_builder::{CombinableQuery, IntersectQuery};
pub trait IntersectDsl<U: CombinableQuery<SqlType = Self::SqlType>>: CombinableQuery {
type Output: CombinableQuery<SqlType = Self::SqlType>;
fn intersect(self, query: U) -> Self::Output;
}
impl<T, U> IntersectDsl<U> for T
where T: CombinableQuery,
U: CombinableQuery<SqlType = T::SqlType>
{
type Output = IntersectQuery<T, U>;
fn intersect(self, other: U) -> Self::Output {
IntersectQuery::new(self, other)
}
}
|
use crate::types::{ActivationFrame, Closure, Escape, Primitive, Scm, Symbol};
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display};
pub trait UserValue: Debug + Display + 'static {
fn type_id(&self) -> TypeId;
}
impl<T: Debug + Display + 'static> UserValue for T {
fn type_id(&self) -> TypeId {
TypeId::of::<T>()
}
}
impl dyn UserValue {
pub fn as_scm(&'static self) -> Scm {
Scm::from_value(ScmBoxedValue::UserValue(self))
}
pub fn is<T: UserValue>(&self) -> bool {
TypeId::of::<T>() == self.type_id()
}
pub fn downcast_ref<T: UserValue>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe { Some(&*(self as *const dyn UserValue as *const T)) }
} else {
None
}
}
}
#[derive(Copy, Clone)]
pub enum ScmBoxedValue {
Symbol(Symbol),
String(&'static String),
Primitive(&'static Primitive),
Frame(&'static ActivationFrame),
Closure(&'static Closure),
Escape(&'static Escape),
UserValue(&'static dyn UserValue),
}
impl ScmBoxedValue {
fn from_user_value<T: UserValue>(value: T) -> Self {
ScmBoxedValue::UserValue(Box::leak(Box::new(value)))
}
pub fn as_symbol(&self) -> Option<Symbol> {
match self {
ScmBoxedValue::Symbol(s) => Some(s),
_ => None,
}
}
pub fn as_string(&self) -> Option<&'static String> {
match self {
ScmBoxedValue::String(s) => Some(s),
_ => None,
}
}
pub fn as_primitive(&self) -> Option<&'static Primitive> {
match self {
ScmBoxedValue::Primitive(p) => Some(p),
_ => None,
}
}
pub fn as_frame(&self) -> Option<&'static ActivationFrame> {
match self {
ScmBoxedValue::Frame(frame) => Some(frame),
_ => None,
}
}
pub fn as_closure(&self) -> Option<&'static Closure> {
match self {
ScmBoxedValue::Closure(cls) => Some(cls),
_ => None,
}
}
pub fn as_escape(&self) -> Option<&'static Escape> {
match self {
ScmBoxedValue::Escape(esc) => Some(esc),
_ => None,
}
}
pub fn as_user_value<T: UserValue>(&self) -> Option<&'static T> {
match self {
ScmBoxedValue::UserValue(val) => dbg!(val).downcast_ref::<T>(),
_ => None,
}
}
}
impl PartialEq for ScmBoxedValue {
fn eq(&self, rhs: &Self) -> bool {
use ScmBoxedValue::*;
match (self, rhs) {
(Symbol(a), Symbol(b)) => a == b,
(String(a), String(b)) => a == b,
_ => false,
}
}
}
|
use ast::{lit_from_token, EnumMacro};
use proc_macro2::TokenStream;
use syn::*;
pub fn forward_impl(input: TokenStream) -> Result<TokenStream> {
dump!(input);
Ok(quote! { #input })
}
pub fn make_enum(input: TokenStream) -> Result<TokenStream> {
let input = syn::parse2::<EnumMacro>(input)?;
split!(input as attrs, vis, ident, repr, default, variants);
let default = lit_from_token(&default)?;
let declare_variants = variants.iter().map(|v| {
split!(v as attrs, ident, fields);
let disp = lit_from_token(&fields.ident)
.map(|l| quote! { #[enum_repr(discr = #l)] })
.unwrap_or(quote! {});
let (eq, e) = match &fields.discriminant {
Some((eq, e)) => (Some(eq), Some(e)),
_ => (None, None),
};
quote! {
#(#attrs)*
#disp
#ident #eq #e,
}
});
let output = quote! {
#(#attrs)*
#[repr(#repr)]
#[derive(EnumRepr)]
#[enum_repr(default = #default)]
#vis enum #ident {
#(#declare_variants)*
}
};
Ok(output)
}
|
#[doc = "Reader of register SOF1"]
pub type R = crate::R<u32, super::SOF1>;
#[doc = "Reader of field `FRAME_NUMBER_MSB`"]
pub type FRAME_NUMBER_MSB_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:2 - It has the upper 3 bits \\[10:8\\] of the SOF frame number."]
#[inline(always)]
pub fn frame_number_msb(&self) -> FRAME_NUMBER_MSB_R {
FRAME_NUMBER_MSB_R::new((self.bits & 0x07) as u8)
}
}
|
/*
chapter 4
syntax and semantics
*/
fn main() {
let dog = "hachiko";
let hachi = &dog[0..5];
println!("{}", hachi);
}
// output should be:
/*
*/
|
/// An enum to represent all characters in the NewTaiLue block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum NewTaiLue {
/// \u{1980}: 'ᦀ'
LetterHighQa,
/// \u{1981}: 'ᦁ'
LetterLowQa,
/// \u{1982}: 'ᦂ'
LetterHighKa,
/// \u{1983}: 'ᦃ'
LetterHighXa,
/// \u{1984}: 'ᦄ'
LetterHighNga,
/// \u{1985}: 'ᦅ'
LetterLowKa,
/// \u{1986}: 'ᦆ'
LetterLowXa,
/// \u{1987}: 'ᦇ'
LetterLowNga,
/// \u{1988}: 'ᦈ'
LetterHighTsa,
/// \u{1989}: 'ᦉ'
LetterHighSa,
/// \u{198a}: 'ᦊ'
LetterHighYa,
/// \u{198b}: 'ᦋ'
LetterLowTsa,
/// \u{198c}: 'ᦌ'
LetterLowSa,
/// \u{198d}: 'ᦍ'
LetterLowYa,
/// \u{198e}: 'ᦎ'
LetterHighTa,
/// \u{198f}: 'ᦏ'
LetterHighTha,
/// \u{1990}: 'ᦐ'
LetterHighNa,
/// \u{1991}: 'ᦑ'
LetterLowTa,
/// \u{1992}: 'ᦒ'
LetterLowTha,
/// \u{1993}: 'ᦓ'
LetterLowNa,
/// \u{1994}: 'ᦔ'
LetterHighPa,
/// \u{1995}: 'ᦕ'
LetterHighPha,
/// \u{1996}: 'ᦖ'
LetterHighMa,
/// \u{1997}: 'ᦗ'
LetterLowPa,
/// \u{1998}: 'ᦘ'
LetterLowPha,
/// \u{1999}: 'ᦙ'
LetterLowMa,
/// \u{199a}: 'ᦚ'
LetterHighFa,
/// \u{199b}: 'ᦛ'
LetterHighVa,
/// \u{199c}: 'ᦜ'
LetterHighLa,
/// \u{199d}: 'ᦝ'
LetterLowFa,
/// \u{199e}: 'ᦞ'
LetterLowVa,
/// \u{199f}: 'ᦟ'
LetterLowLa,
/// \u{19a0}: 'ᦠ'
LetterHighHa,
/// \u{19a1}: 'ᦡ'
LetterHighDa,
/// \u{19a2}: 'ᦢ'
LetterHighBa,
/// \u{19a3}: 'ᦣ'
LetterLowHa,
/// \u{19a4}: 'ᦤ'
LetterLowDa,
/// \u{19a5}: 'ᦥ'
LetterLowBa,
/// \u{19a6}: 'ᦦ'
LetterHighKva,
/// \u{19a7}: 'ᦧ'
LetterHighXva,
/// \u{19a8}: 'ᦨ'
LetterLowKva,
/// \u{19a9}: 'ᦩ'
LetterLowXva,
/// \u{19aa}: 'ᦪ'
LetterHighSua,
/// \u{19ab}: 'ᦫ'
LetterLowSua,
/// \u{19b0}: 'ᦰ'
VowelSignVowelShortener,
/// \u{19b1}: 'ᦱ'
VowelSignAa,
/// \u{19b2}: 'ᦲ'
VowelSignIi,
/// \u{19b3}: 'ᦳ'
VowelSignU,
/// \u{19b4}: 'ᦴ'
VowelSignUu,
/// \u{19b5}: 'ᦵ'
VowelSignE,
/// \u{19b6}: 'ᦶ'
VowelSignAe,
/// \u{19b7}: 'ᦷ'
VowelSignO,
/// \u{19b8}: 'ᦸ'
VowelSignOa,
/// \u{19b9}: 'ᦹ'
VowelSignUe,
/// \u{19ba}: 'ᦺ'
VowelSignAy,
/// \u{19bb}: 'ᦻ'
VowelSignAay,
/// \u{19bc}: 'ᦼ'
VowelSignUy,
/// \u{19bd}: 'ᦽ'
VowelSignOy,
/// \u{19be}: 'ᦾ'
VowelSignOay,
/// \u{19bf}: 'ᦿ'
VowelSignUey,
/// \u{19c0}: 'ᧀ'
VowelSignIy,
/// \u{19c1}: 'ᧁ'
LetterFinalV,
/// \u{19c2}: 'ᧂ'
LetterFinalNg,
/// \u{19c3}: 'ᧃ'
LetterFinalN,
/// \u{19c4}: 'ᧄ'
LetterFinalM,
/// \u{19c5}: 'ᧅ'
LetterFinalK,
/// \u{19c6}: 'ᧆ'
LetterFinalD,
/// \u{19c7}: 'ᧇ'
LetterFinalB,
/// \u{19c8}: 'ᧈ'
ToneMarkDash1,
/// \u{19c9}: 'ᧉ'
ToneMarkDash2,
/// \u{19d0}: '᧐'
DigitZero,
/// \u{19d1}: '᧑'
DigitOne,
/// \u{19d2}: '᧒'
DigitTwo,
/// \u{19d3}: '᧓'
DigitThree,
/// \u{19d4}: '᧔'
DigitFour,
/// \u{19d5}: '᧕'
DigitFive,
/// \u{19d6}: '᧖'
DigitSix,
/// \u{19d7}: '᧗'
DigitSeven,
/// \u{19d8}: '᧘'
DigitEight,
/// \u{19d9}: '᧙'
DigitNine,
/// \u{19da}: '᧚'
ThamDigitOne,
/// \u{19de}: '᧞'
SignLae,
}
impl Into<char> for NewTaiLue {
fn into(self) -> char {
match self {
NewTaiLue::LetterHighQa => 'ᦀ',
NewTaiLue::LetterLowQa => 'ᦁ',
NewTaiLue::LetterHighKa => 'ᦂ',
NewTaiLue::LetterHighXa => 'ᦃ',
NewTaiLue::LetterHighNga => 'ᦄ',
NewTaiLue::LetterLowKa => 'ᦅ',
NewTaiLue::LetterLowXa => 'ᦆ',
NewTaiLue::LetterLowNga => 'ᦇ',
NewTaiLue::LetterHighTsa => 'ᦈ',
NewTaiLue::LetterHighSa => 'ᦉ',
NewTaiLue::LetterHighYa => 'ᦊ',
NewTaiLue::LetterLowTsa => 'ᦋ',
NewTaiLue::LetterLowSa => 'ᦌ',
NewTaiLue::LetterLowYa => 'ᦍ',
NewTaiLue::LetterHighTa => 'ᦎ',
NewTaiLue::LetterHighTha => 'ᦏ',
NewTaiLue::LetterHighNa => 'ᦐ',
NewTaiLue::LetterLowTa => 'ᦑ',
NewTaiLue::LetterLowTha => 'ᦒ',
NewTaiLue::LetterLowNa => 'ᦓ',
NewTaiLue::LetterHighPa => 'ᦔ',
NewTaiLue::LetterHighPha => 'ᦕ',
NewTaiLue::LetterHighMa => 'ᦖ',
NewTaiLue::LetterLowPa => 'ᦗ',
NewTaiLue::LetterLowPha => 'ᦘ',
NewTaiLue::LetterLowMa => 'ᦙ',
NewTaiLue::LetterHighFa => 'ᦚ',
NewTaiLue::LetterHighVa => 'ᦛ',
NewTaiLue::LetterHighLa => 'ᦜ',
NewTaiLue::LetterLowFa => 'ᦝ',
NewTaiLue::LetterLowVa => 'ᦞ',
NewTaiLue::LetterLowLa => 'ᦟ',
NewTaiLue::LetterHighHa => 'ᦠ',
NewTaiLue::LetterHighDa => 'ᦡ',
NewTaiLue::LetterHighBa => 'ᦢ',
NewTaiLue::LetterLowHa => 'ᦣ',
NewTaiLue::LetterLowDa => 'ᦤ',
NewTaiLue::LetterLowBa => 'ᦥ',
NewTaiLue::LetterHighKva => 'ᦦ',
NewTaiLue::LetterHighXva => 'ᦧ',
NewTaiLue::LetterLowKva => 'ᦨ',
NewTaiLue::LetterLowXva => 'ᦩ',
NewTaiLue::LetterHighSua => 'ᦪ',
NewTaiLue::LetterLowSua => 'ᦫ',
NewTaiLue::VowelSignVowelShortener => 'ᦰ',
NewTaiLue::VowelSignAa => 'ᦱ',
NewTaiLue::VowelSignIi => 'ᦲ',
NewTaiLue::VowelSignU => 'ᦳ',
NewTaiLue::VowelSignUu => 'ᦴ',
NewTaiLue::VowelSignE => 'ᦵ',
NewTaiLue::VowelSignAe => 'ᦶ',
NewTaiLue::VowelSignO => 'ᦷ',
NewTaiLue::VowelSignOa => 'ᦸ',
NewTaiLue::VowelSignUe => 'ᦹ',
NewTaiLue::VowelSignAy => 'ᦺ',
NewTaiLue::VowelSignAay => 'ᦻ',
NewTaiLue::VowelSignUy => 'ᦼ',
NewTaiLue::VowelSignOy => 'ᦽ',
NewTaiLue::VowelSignOay => 'ᦾ',
NewTaiLue::VowelSignUey => 'ᦿ',
NewTaiLue::VowelSignIy => 'ᧀ',
NewTaiLue::LetterFinalV => 'ᧁ',
NewTaiLue::LetterFinalNg => 'ᧂ',
NewTaiLue::LetterFinalN => 'ᧃ',
NewTaiLue::LetterFinalM => 'ᧄ',
NewTaiLue::LetterFinalK => 'ᧅ',
NewTaiLue::LetterFinalD => 'ᧆ',
NewTaiLue::LetterFinalB => 'ᧇ',
NewTaiLue::ToneMarkDash1 => 'ᧈ',
NewTaiLue::ToneMarkDash2 => 'ᧉ',
NewTaiLue::DigitZero => '᧐',
NewTaiLue::DigitOne => '᧑',
NewTaiLue::DigitTwo => '᧒',
NewTaiLue::DigitThree => '᧓',
NewTaiLue::DigitFour => '᧔',
NewTaiLue::DigitFive => '᧕',
NewTaiLue::DigitSix => '᧖',
NewTaiLue::DigitSeven => '᧗',
NewTaiLue::DigitEight => '᧘',
NewTaiLue::DigitNine => '᧙',
NewTaiLue::ThamDigitOne => '᧚',
NewTaiLue::SignLae => '᧞',
}
}
}
impl std::convert::TryFrom<char> for NewTaiLue {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'ᦀ' => Ok(NewTaiLue::LetterHighQa),
'ᦁ' => Ok(NewTaiLue::LetterLowQa),
'ᦂ' => Ok(NewTaiLue::LetterHighKa),
'ᦃ' => Ok(NewTaiLue::LetterHighXa),
'ᦄ' => Ok(NewTaiLue::LetterHighNga),
'ᦅ' => Ok(NewTaiLue::LetterLowKa),
'ᦆ' => Ok(NewTaiLue::LetterLowXa),
'ᦇ' => Ok(NewTaiLue::LetterLowNga),
'ᦈ' => Ok(NewTaiLue::LetterHighTsa),
'ᦉ' => Ok(NewTaiLue::LetterHighSa),
'ᦊ' => Ok(NewTaiLue::LetterHighYa),
'ᦋ' => Ok(NewTaiLue::LetterLowTsa),
'ᦌ' => Ok(NewTaiLue::LetterLowSa),
'ᦍ' => Ok(NewTaiLue::LetterLowYa),
'ᦎ' => Ok(NewTaiLue::LetterHighTa),
'ᦏ' => Ok(NewTaiLue::LetterHighTha),
'ᦐ' => Ok(NewTaiLue::LetterHighNa),
'ᦑ' => Ok(NewTaiLue::LetterLowTa),
'ᦒ' => Ok(NewTaiLue::LetterLowTha),
'ᦓ' => Ok(NewTaiLue::LetterLowNa),
'ᦔ' => Ok(NewTaiLue::LetterHighPa),
'ᦕ' => Ok(NewTaiLue::LetterHighPha),
'ᦖ' => Ok(NewTaiLue::LetterHighMa),
'ᦗ' => Ok(NewTaiLue::LetterLowPa),
'ᦘ' => Ok(NewTaiLue::LetterLowPha),
'ᦙ' => Ok(NewTaiLue::LetterLowMa),
'ᦚ' => Ok(NewTaiLue::LetterHighFa),
'ᦛ' => Ok(NewTaiLue::LetterHighVa),
'ᦜ' => Ok(NewTaiLue::LetterHighLa),
'ᦝ' => Ok(NewTaiLue::LetterLowFa),
'ᦞ' => Ok(NewTaiLue::LetterLowVa),
'ᦟ' => Ok(NewTaiLue::LetterLowLa),
'ᦠ' => Ok(NewTaiLue::LetterHighHa),
'ᦡ' => Ok(NewTaiLue::LetterHighDa),
'ᦢ' => Ok(NewTaiLue::LetterHighBa),
'ᦣ' => Ok(NewTaiLue::LetterLowHa),
'ᦤ' => Ok(NewTaiLue::LetterLowDa),
'ᦥ' => Ok(NewTaiLue::LetterLowBa),
'ᦦ' => Ok(NewTaiLue::LetterHighKva),
'ᦧ' => Ok(NewTaiLue::LetterHighXva),
'ᦨ' => Ok(NewTaiLue::LetterLowKva),
'ᦩ' => Ok(NewTaiLue::LetterLowXva),
'ᦪ' => Ok(NewTaiLue::LetterHighSua),
'ᦫ' => Ok(NewTaiLue::LetterLowSua),
'ᦰ' => Ok(NewTaiLue::VowelSignVowelShortener),
'ᦱ' => Ok(NewTaiLue::VowelSignAa),
'ᦲ' => Ok(NewTaiLue::VowelSignIi),
'ᦳ' => Ok(NewTaiLue::VowelSignU),
'ᦴ' => Ok(NewTaiLue::VowelSignUu),
'ᦵ' => Ok(NewTaiLue::VowelSignE),
'ᦶ' => Ok(NewTaiLue::VowelSignAe),
'ᦷ' => Ok(NewTaiLue::VowelSignO),
'ᦸ' => Ok(NewTaiLue::VowelSignOa),
'ᦹ' => Ok(NewTaiLue::VowelSignUe),
'ᦺ' => Ok(NewTaiLue::VowelSignAy),
'ᦻ' => Ok(NewTaiLue::VowelSignAay),
'ᦼ' => Ok(NewTaiLue::VowelSignUy),
'ᦽ' => Ok(NewTaiLue::VowelSignOy),
'ᦾ' => Ok(NewTaiLue::VowelSignOay),
'ᦿ' => Ok(NewTaiLue::VowelSignUey),
'ᧀ' => Ok(NewTaiLue::VowelSignIy),
'ᧁ' => Ok(NewTaiLue::LetterFinalV),
'ᧂ' => Ok(NewTaiLue::LetterFinalNg),
'ᧃ' => Ok(NewTaiLue::LetterFinalN),
'ᧄ' => Ok(NewTaiLue::LetterFinalM),
'ᧅ' => Ok(NewTaiLue::LetterFinalK),
'ᧆ' => Ok(NewTaiLue::LetterFinalD),
'ᧇ' => Ok(NewTaiLue::LetterFinalB),
'ᧈ' => Ok(NewTaiLue::ToneMarkDash1),
'ᧉ' => Ok(NewTaiLue::ToneMarkDash2),
'᧐' => Ok(NewTaiLue::DigitZero),
'᧑' => Ok(NewTaiLue::DigitOne),
'᧒' => Ok(NewTaiLue::DigitTwo),
'᧓' => Ok(NewTaiLue::DigitThree),
'᧔' => Ok(NewTaiLue::DigitFour),
'᧕' => Ok(NewTaiLue::DigitFive),
'᧖' => Ok(NewTaiLue::DigitSix),
'᧗' => Ok(NewTaiLue::DigitSeven),
'᧘' => Ok(NewTaiLue::DigitEight),
'᧙' => Ok(NewTaiLue::DigitNine),
'᧚' => Ok(NewTaiLue::ThamDigitOne),
'᧞' => Ok(NewTaiLue::SignLae),
_ => Err(()),
}
}
}
impl Into<u32> for NewTaiLue {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for NewTaiLue {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for NewTaiLue {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl NewTaiLue {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
NewTaiLue::LetterHighQa
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("NewTaiLue{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use aoc::read_data;
use std::error::Error;
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug)]
struct Password {
min: usize,
max: usize,
c: char,
pass: String,
}
impl Password {
fn is_valid_1(&self) -> bool {
let matches = self.pass.matches(self.c).count();
self.min <= matches && matches <= self.max
}
fn is_valid_2(&self) -> bool {
let matches: Vec<char> = self.pass.chars().collect();
if matches[self.min - 1] == self.c || matches[self.max - 1] == self.c {
if matches[self.min - 1] == matches[self.max - 1] {
return false;
}
return true;
}
false
}
}
// 1-3 b: cdefg
impl FromStr for Password {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let v: Vec<&str> = s.split(' ').collect();
let mut num = v[0].split('-');
let min = num.next().unwrap().parse::<usize>()?;
let max = num.next().unwrap().parse::<usize>()?;
Ok(Self {
min,
max,
c: v[1].chars().next().unwrap(),
pass: v[2].to_string(),
})
}
}
fn p1(data: &[Password]) -> usize {
let mut valid: usize = 0;
for d in data {
if d.is_valid_1() {
valid += 1
}
}
valid
}
fn p2(data: &[Password]) -> usize {
let mut valid: usize = 0;
for d in data {
if d.is_valid_2() {
valid += 1
}
}
valid
}
fn main() -> Result<(), Box<dyn Error>> {
println!("Hello, Advent Of Code 2020!");
// part 1
let data: Vec<Password> = read_data::<Password>("./data/data2").unwrap();
println!("Part 1: {}", p1(&data));
//part 2
println!("Part 2: {}", p2(&data));
Ok(())
}
#[test]
fn data_read() {
println!("{:?}", read_data::<String>("./data/data2").unwrap());
}
#[test]
fn calc() {
let data = vec!["1-3 a: abcde", "1-3 b: cdefg", "2-9 c: ccccccccc"];
let mut v: Vec<Password> = Vec::new();
for d in data {
v.push(d.parse().unwrap())
}
// part 1
assert_eq!(v[0].is_valid_1(), true);
assert_eq!(v[1].is_valid_1(), false);
assert_eq!(v[2].is_valid_1(), true);
assert_eq!(p1(&v), 2);
// part 2
assert_eq!(v[0].is_valid_2(), true);
assert_eq!(v[1].is_valid_2(), false);
assert_eq!(v[2].is_valid_2(), false);
assert_eq!(p2(&v), 1);
}
|
#[doc = "Reader of register CLK_FLL_CONFIG"]
pub type R = crate::R<u32, super::CLK_FLL_CONFIG>;
#[doc = "Writer for register CLK_FLL_CONFIG"]
pub type W = crate::W<u32, super::CLK_FLL_CONFIG>;
#[doc = "Register CLK_FLL_CONFIG `reset()`'s with value 0x0100_0000"]
impl crate::ResetValue for super::CLK_FLL_CONFIG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0100_0000
}
}
#[doc = "Reader of field `FLL_MULT`"]
pub type FLL_MULT_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `FLL_MULT`"]
pub struct FLL_MULT_W<'a> {
w: &'a mut W,
}
impl<'a> FLL_MULT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0003_ffff) | ((value as u32) & 0x0003_ffff);
self.w
}
}
#[doc = "Reader of field `FLL_OUTPUT_DIV`"]
pub type FLL_OUTPUT_DIV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FLL_OUTPUT_DIV`"]
pub struct FLL_OUTPUT_DIV_W<'a> {
w: &'a mut W,
}
impl<'a> FLL_OUTPUT_DIV_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `FLL_ENABLE`"]
pub type FLL_ENABLE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FLL_ENABLE`"]
pub struct FLL_ENABLE_W<'a> {
w: &'a mut W,
}
impl<'a> FLL_ENABLE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bits 0:17 - Multiplier to determine CCO frequency in multiples of the frequency of the selected reference clock (Fref). Ffll = (FLL_MULT) * (Fref / REFERENCE_DIV) / (OUTPUT_DIV+1)"]
#[inline(always)]
pub fn fll_mult(&self) -> FLL_MULT_R {
FLL_MULT_R::new((self.bits & 0x0003_ffff) as u32)
}
#[doc = "Bit 24 - Control bits for Output divider. Set the divide value before enabling the FLL, and do not change it while FLL is enabled. 0: no division 1: divide by 2"]
#[inline(always)]
pub fn fll_output_div(&self) -> FLL_OUTPUT_DIV_R {
FLL_OUTPUT_DIV_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 31 - Master enable for FLL. Do not enable until the reference clock has stabilized. 0: Block is powered off 1: Block is powered on"]
#[inline(always)]
pub fn fll_enable(&self) -> FLL_ENABLE_R {
FLL_ENABLE_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:17 - Multiplier to determine CCO frequency in multiples of the frequency of the selected reference clock (Fref). Ffll = (FLL_MULT) * (Fref / REFERENCE_DIV) / (OUTPUT_DIV+1)"]
#[inline(always)]
pub fn fll_mult(&mut self) -> FLL_MULT_W {
FLL_MULT_W { w: self }
}
#[doc = "Bit 24 - Control bits for Output divider. Set the divide value before enabling the FLL, and do not change it while FLL is enabled. 0: no division 1: divide by 2"]
#[inline(always)]
pub fn fll_output_div(&mut self) -> FLL_OUTPUT_DIV_W {
FLL_OUTPUT_DIV_W { w: self }
}
#[doc = "Bit 31 - Master enable for FLL. Do not enable until the reference clock has stabilized. 0: Block is powered off 1: Block is powered on"]
#[inline(always)]
pub fn fll_enable(&mut self) -> FLL_ENABLE_W {
FLL_ENABLE_W { w: self }
}
}
|
/// Multiboot Parsing
///
/// Multiboot describes a protocol for transferring control from a bootloader to
/// an operating system. Denuos uses GRUB2 to load. GRUB is responsible for
/// reading our entire kernel image from disk, loading it into memory, and
/// retrieving critical information from the BIOS before transferring control to
/// us.
///
/// All of this critical information is stored in a tagged data structure. When
/// GRUB calls our entry point (see start32.s), a pointer to this struct is in
/// the EBX register. Consider this a pointer to the MultibootTags struct.
use core;
use core::fmt;
/// Pointer to the Multiboot tag structure
#[repr(C)]
pub struct MultibootTags {
size: u32,
reserved: u32,
}
/// Wrapper around useful Multiboot tags
#[derive(Debug, Default)]
pub struct MultibootInfo {
pub cmd_line: Option<&'static str>,
pub boot_loader_name: Option<&'static str>,
pub basic_mem_info: Option<&'static BasicMemInfo>,
pub bios_boot_dev: Option<&'static BiosBootDevice>,
pub mem_map: Option<&'static [MMapEntry]>,
pub elf_sections: Option<ElfSections>,
}
/// Helper to parse individual multiboot tags
struct Tag {
ty: u32,
size: u32,
}
impl MultibootTags {
/// Parse the Multiboot tags into a MultibootInfo
///
/// Unsupported tags will be silently ignored. Only fields present in the
/// MultibootInfo struct are currently supported.
pub unsafe fn parse(&self) -> MultibootInfo {
let mut info = MultibootInfo::default();
let mut tag: *const Tag = self.start() as *const Tag;
let limit = (self.end() + 1) as *const Tag; // point just past the last valid tag
tag = tag.offset(1);
while tag < limit {
let tag_size = (*tag).size as usize;
let data = tag.offset(1) as usize;
let data_size = tag_size - 8;
match (*tag).ty {
0 => { } // End tag
1 => {
// Boot command line
info.cmd_line = parse_tag_str(data, data_size, 1);
}
2 => {
// Boot loader name
info.boot_loader_name = parse_tag_str(data, data_size, 2);
}
4 => {
// Basic memory info
let basic = &*(data as *const BasicMemInfo);
info.basic_mem_info = Some(basic);
}
5 => {
// BIOS Boot Device
let bootdev = &*(data as *const BiosBootDevice);
info.bios_boot_dev = Some(bootdev);
}
6 => {
// Memory Map
let entry_size = *(data as *const u32);
let entry_version = *((data + 4) as *const u32);
assert!(entry_size == 24 && entry_version == 0, "Unsupported bootloader");
let entries = (data + 8) as *const MMapEntry;
let n = data_size / entry_size as usize;
info.mem_map = Some(core::slice::from_raw_parts(entries, n));
}
9 => {
// elf sections
let num = *(data as *const u32) as usize;
let entsize = *((data + 4) as *const u32) as usize;
let shndx = *((data + 8) as *const u32) as usize;
let ptr = (data + 12) as *const ElfSection;
// exclude string name tables
let list = core::slice::from_raw_parts(ptr, shndx);
info.elf_sections = Some(ElfSections {
num: num,
list: list,
entsize: entsize,
shndx: shndx,
});
}
// TODO unhandled Mutliboot tags
3 => { } // NYI Modules
7 => { } // VBE
8 => { } // framebuffer
10 => { } // APM
11 => { } // EFI32
12 => { } // EFI64
13 => { } // SMBIOS
14 => { } // ACPI Old
15 => { } // ACPI New
16 => { } // Network
17 => { } // EFI MMap
18 => { } // EFI BS
19 => { } // EFI 32b Image handle
20 => { } // EFI 64b Image handle
21 => { } // Image load base addr
i => panic!("Corrupt MultibootInfo Tag: {}", i)
}
let new_tag = (tag as usize) + tag_size;
tag = ((new_tag + 7) & !7) as *const Tag; // round to 8 byte alignment
// end tag already 8 byte aligned, so assertion below won't fail
}
assert!(tag == limit, "Corrupt MultibootInfo");
info
}
/// Return pointer to beginning of the structure
pub fn start(&self) -> usize {
self as *const _ as usize
}
/// Returns pointer to the last byte of the structure
pub fn end(&self) -> usize {
self.start() + self.size as usize - 1
}
}
/// Parses a null-terminated string from a tag
unsafe fn parse_tag_str(data: usize, data_size: usize, tag: usize) -> Option<&'static str> {
let ptr = data as *const u8;
let size = data_size - 1; // subtract null terminator
if size == 0 { // empty string is None
None
} else {
let bytes = core::slice::from_raw_parts(ptr, size);
let s = core::str::from_utf8(bytes);
let s = s.unwrap_or_else(|_| panic!("Non-utf8 string in multiboot tag {}", tag));
Some(s)
}
}
#[repr(C)]
pub struct BiosBootDevice {
pub biosdev: u32,
partition: u32,
sub_partition: u32,
}
#[repr(C)]
pub struct BasicMemInfo {
pub mem_lower: u32,
pub mem_upper: u32,
}
#[repr(C)]
pub struct MMapEntry {
pub base_addr: u64,
pub length: u64,
pub ty: MMapEntryType,
reserved: u32,
}
#[repr(u32)]
#[derive(Debug, Eq, PartialEq)]
pub enum MMapEntryType {
Free = 1,
Reserved = 2,
ACPI = 3,
Preserve = 4,
Bad = 5,
}
/// List of ELF sections
#[repr(C)]
#[derive(Debug)]
pub struct ElfSections {
pub num: usize,
pub list: &'static [ElfSection],
entsize: usize,
shndx: usize,
}
/// Limited wrapper around ELF64 sections
#[repr(C)]
#[derive(Debug)]
pub struct ElfSection {
sh_name: u32,
sh_type: u32,
sh_flags: u64,
sh_addr: u64,
sh_offset: u64,
sh_size: u64,
sh_link: u32,
sh_info: u32,
sh_addralign: u64,
sh_entsize: u64,
}
impl ElfSections {
/// Return pointer to start of kernel image
pub fn image_start(&self) -> usize {
self.list.iter().filter(|s| s.is_allocated()).map(|s| s.start()).min().unwrap()
}
/// Return size of kernel image
pub fn image_size(&self) -> usize {
self.list.iter().filter(|s| s.is_allocated()).map(|s| s.size()).sum()
}
/// Return pointer to the last byte of kernel image
pub fn image_end(&self) -> usize {
self.list.iter().filter(|s| s.is_allocated()).map(|s| s.end()).max().unwrap()
}
}
impl ElfSection {
/// Has this section been loaded into memory?
pub fn is_allocated(&self) -> bool {
self.sh_flags & 0x2 != 0
}
/// Return pointer to section
pub fn start(&self) -> usize {
self.sh_addr as usize
}
/// Return size of section
pub fn size(&self) -> usize {
self.sh_size as usize
}
/// Return pointer to the last byte of section
pub fn end(&self) -> usize {
self.start() + self.size() - 1
}
}
impl BiosBootDevice {
pub fn partition(&self) -> Option<u32> {
if self.partition == !0 {
return None;
}
Some(self.partition)
}
pub fn sub_partition(&self) -> Option<u32> {
if self.sub_partition == !0 {
return None;
}
Some(self.sub_partition)
}
}
impl MMapEntry {
pub fn is_free(&self) -> bool {
self.ty == MMapEntryType::Free
}
pub fn start(&self) -> usize {
self.base_addr as usize
}
pub fn size(&self) -> usize {
self.length as usize
}
pub fn end(&self) -> usize {
self.start() + self.size() - 1
}
}
impl fmt::Debug for BiosBootDevice {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "BiosBootDevice {{ biosdev: 0x{:x}, partition: 0x{:x}, sub_partition: 0x{:x} }}",
self.biosdev, self.partition, self.sub_partition)
}
}
impl fmt::Debug for BasicMemInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "BasicMemInfo {{ mem_lower: 0x{:x}, mem_upper: 0x{:x} }}",
self.mem_lower, self.mem_upper)
}
}
impl fmt::Debug for MMapEntry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "MMapEntry {{ base_addr: 0x{:x}, length: 0x{:x}, ty: {:?} }}",
self.base_addr, self.length, self.ty)
}
}
|
//! Color profiles.
use crate::gamma::ToneCurve;
use crate::mlu::MLU;
use crate::named::NamedColorList;
use crate::pcs::MAX_ENCODABLE_XYZ;
use crate::pipe::{Pipeline, Stage};
use crate::white_point::{adaptation_matrix, D50};
use crate::{CIExyYTriple, ColorSpace, ICCTag, Intent, ProfileClass, CIEXYZ};
use cgmath::{Matrix, Matrix3, SquareMatrix};
use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use time;
#[derive(Debug, Clone)]
pub(crate) enum ProfileTagData {
Linked(ICCTag),
Data(Arc<Any + Send + Sync>),
Raw(Vec<u8>),
}
#[derive(Debug, Clone)]
pub(crate) struct ProfileTag {
save_as_raw: bool,
data: ProfileTagData,
}
/// An ICC profile.
#[derive(Clone)]
pub struct Profile {
// io_handler: ?,
// context: ?, something about threads?
/// Creation time
pub created: time::Tm,
pub(crate) version: u32,
/// Device class.
pub device_class: ProfileClass,
/// Profile color space type.
pub color_space: ColorSpace,
/// Profile connection space.
pub pcs: ColorSpace,
pub rendering_intent: Intent,
/// Flags?
pub flags: u32,
/// Manufacturer.
pub manufacturer: u32,
/// Model.
pub model: u32,
/// Attributes.
pub attributes: u64,
/// Creator.
pub creator: u32,
pub(crate) profile_id: u128,
// pub profile_id: ProfileID?,
pub(crate) tags: HashMap<ICCTag, ProfileTag>,
// cmsUInt32Number TagCount;
// cmsTagSignature TagNames[MAX_TABLE_TAG];
// The tag to which is linked (0=none)
// cmsTagSignature TagLinked[MAX_TABLE_TAG];
// Size on disk
// cmsUInt32Number TagSizes[MAX_TABLE_TAG];
// cmsUInt32Number TagOffsets[MAX_TABLE_TAG];
// True to write uncooked
// cmsBool TagSaveAsRaw[MAX_TABLE_TAG];
// void * TagPtrs[MAX_TABLE_TAG];
// cmsTagTypeHandler* TagTypeHandlers[MAX_TABLE_TAG];
// Same structure may be serialized on different types
// depending on profile version, so we keep track of the
// type handler for each tag in the list.
/// ?
pub is_write: bool,
}
// LUT tags
const DEVICE_TO_PCS_16: [ICCTag; 4] = [
ICCTag::AToB0, // Perceptual
ICCTag::AToB1, // Relative colorimetric
ICCTag::AToB2, // Saturation
ICCTag::AToB1, // Absolute colorimetric
];
const DEVICE_TO_PCS_FLOAT: [ICCTag; 4] = [
ICCTag::DToB0, // Perceptual
ICCTag::DToB1, // Relative colorimetric
ICCTag::DToB2, // Saturation
ICCTag::DToB3, // Absolute colorimetric
];
const PCS_TO_DEVICE_16: [ICCTag; 4] = [
ICCTag::BToA0, // Perceptual
ICCTag::BToA1, // Relative colorimetric
ICCTag::BToA2, // Saturation
ICCTag::BToA1, // Absolute colorimetric
];
const PCS_TO_DEVICE_FLOAT: [ICCTag; 4] = [
ICCTag::BToD0, // Perceptual
ICCTag::BToD1, // Relative colorimetric
ICCTag::BToD2, // Saturation
ICCTag::BToD3, // Absolute colorimetric
];
// Factors to convert from 1.15 fixed point to 0..1.0 range and vice-versa
const INP_ADJ: f64 = 1. / MAX_ENCODABLE_XYZ; // (65536.0/(65535.0*2.0))
const OUTP_ADJ: f64 = MAX_ENCODABLE_XYZ; // ((2.0*65535.0)/65536.0)
// How profiles may be used
// TODO: make this an enum
pub(crate) const USED_AS_INPUT: u32 = 0;
pub(crate) const USED_AS_OUTPUT: u32 = 1;
pub(crate) const USED_AS_PROOF: u32 = 2;
impl Profile {
pub(crate) fn new(device_class: ProfileClass, color_space: ColorSpace) -> Profile {
Profile {
created: time::now_utc(),
version: 0x02100000, // default version
device_class,
color_space,
pcs: ColorSpace::XYZ,
rendering_intent: Intent::Perceptual,
flags: 0,
manufacturer: 0,
model: 0,
attributes: 0,
creator: 0,
tags: HashMap::new(),
is_write: false,
profile_id: 0,
}
}
pub(crate) fn encoded_version(&self) -> u32 {
self.version
}
/// Returns the profile version as a float value (major.minor).
pub fn version(&self) -> f64 {
base_to_base(self.version >> 16, 16, 10) as f64 / 100.
}
/// Sets the profile version with a float value (major.minor).
pub fn set_version(&mut self, version: f64) {
self.version = base_to_base((version * 100. + 0.5).floor() as u32, 10, 16) << 16;
}
fn read_tag_recursive<T: Clone + 'static>(&self, sig: ICCTag, recursion: usize) -> Option<T> {
if recursion > 30 {
return None;
}
match self.tags.get(&sig) {
Some(tag) => match tag.data {
ProfileTagData::Linked(sig) => self.read_tag_recursive(sig, recursion + 1),
ProfileTagData::Data(ref data) => match data.downcast_ref::<T>() {
Some(data) => Some(data.clone()),
None => None,
},
ProfileTagData::Raw(_) => None,
},
None => None,
}
}
/// Reads a profile tag and attempts to cast it to T and then clones it if successful.
pub fn read_tag_clone<T: Clone + Send + Sync + 'static>(&self, sig: ICCTag) -> Option<T> {
self.read_tag_recursive(sig, 0)
}
/// Inserts a tag with an arbitrary value.
pub fn insert_tag<T: Clone + Send + Sync + 'static>(&mut self, sig: ICCTag, data: T) {
self.tags.insert(
sig,
ProfileTag {
save_as_raw: false,
data: ProfileTagData::Data(Arc::new(data)),
},
);
}
pub(crate) fn insert_tag_raw(&mut self, sig: ICCTag, data: Arc<Any + Send + Sync>) {
self.tags.insert(
sig,
ProfileTag {
save_as_raw: false,
data: ProfileTagData::Data(data),
},
);
}
pub(crate) fn insert_tag_raw_data(&mut self, sig: ICCTag, buf: Vec<u8>) {
self.tags.insert(
sig,
ProfileTag {
save_as_raw: false,
data: ProfileTagData::Raw(buf),
},
);
}
/// Links one tag’s value to another’s.
pub fn link_tag(&mut self, sig: ICCTag, to: ICCTag) {
self.tags.insert(
sig,
ProfileTag {
save_as_raw: false,
data: ProfileTagData::Linked(to),
},
);
}
/// Returns true if the key exists.
pub fn has_tag(&self, tag: ICCTag) -> bool {
self.tags.contains_key(&tag)
}
/// Returns a media white point fixing some issues found in certain old profiles.
pub fn media_white_point(&self) -> CIEXYZ {
match self.read_tag_clone(ICCTag::MediaWhitePoint) {
Some(_) if self.version() < 4. && self.device_class == ProfileClass::Display => D50,
Some(tag) => tag,
None => D50,
}
}
/// Returns the chromatic adaptation matrix. Fixes some issues as well.
pub fn chad(&self) -> Matrix3<f64> {
match self.read_tag_clone(ICCTag::ChromaticAdaptation) {
Some(tag) => return tag,
None => (),
}
// also support Vec<f64>
match self.read_tag_clone::<Vec<f64>>(ICCTag::ChromaticAdaptation) {
Some(ref tag) if tag.len() == 9 => {
let mut mat_array = [0.; 9];
mat_array.copy_from_slice(&tag);
let mat: &Matrix3<_> = (&mat_array).into();
return *mat;
}
_ => (),
}
if self.version() < 4. && self.device_class == ProfileClass::Display {
match self.read_tag_clone(ICCTag::MediaWhitePoint) {
Some(wp) => match adaptation_matrix(None, wp, D50) {
Some(mat) => mat,
None => Matrix3::identity(),
},
None => Matrix3::identity(),
}
} else {
Matrix3::identity()
}
}
/// Returns true if the profile is implemented as matrix-shaper.
pub(crate) fn is_matrix_shaper(&self) -> bool {
match self.color_space {
ColorSpace::Gray => self.has_tag(ICCTag::GrayTRC),
ColorSpace::RGB => {
self.has_tag(ICCTag::RedColorant)
&& self.has_tag(ICCTag::GreenColorant)
&& self.has_tag(ICCTag::BlueColorant)
&& self.has_tag(ICCTag::RedTRC)
&& self.has_tag(ICCTag::GreenTRC)
&& self.has_tag(ICCTag::BlueTRC)
}
_ => false,
}
}
/// Returns true if the intent is implemented as CLUT
pub(crate) fn is_clut(&self, intent: Intent, used_direction: u32) -> bool {
// For devicelinks, the supported intent is that one stated in the header
if self.device_class == ProfileClass::Link {
return self.rendering_intent == intent;
}
let tag_table = match used_direction {
USED_AS_INPUT => DEVICE_TO_PCS_16,
USED_AS_OUTPUT => PCS_TO_DEVICE_16,
USED_AS_PROOF => {
return self.is_intent_supported(intent, USED_AS_INPUT)
&& self.is_intent_supported(Intent::RelativeColorimetric, USED_AS_OUTPUT)
}
_ => return false,
};
self.has_tag(tag_table[intent as usize])
}
/// Returns info about supported intents
pub(crate) fn is_intent_supported(&self, intent: Intent, used_direction: u32) -> bool {
if self.is_clut(intent, used_direction) {
return true;
}
// Is there any matrix-shaper? If so, the intent is supported. This is a bit odd, since V2 matrix shaper
// does not fully support relative colorimetric because they cannot deal with non-zero black points, but
// many profiles claims that, and this is certainly not true for V4 profiles. Lets answer "yes" no matter
// the accuracy would be less than optimal in rel.col and v2 case.
self.is_matrix_shaper()
}
/// Auxiliary, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
fn icc_matrix_rgb_to_xyz(&self) -> Option<Matrix3<f64>> {
let red: Option<CIEXYZ> = self.read_tag_clone(ICCTag::RedColorant);
let green: Option<CIEXYZ> = self.read_tag_clone(ICCTag::GreenColorant);
let blue: Option<CIEXYZ> = self.read_tag_clone(ICCTag::BlueColorant);
if let (Some(red), Some(green), Some(blue)) = (red, green, blue) {
Some(Matrix3::from_cols(red.into(), green.into(), blue.into()).transpose())
} else {
None
}
}
/// Reads the DToAX tag, adjusting the encoding of Lab or XYZ if needed.
fn read_float_input_tag(&self, tag: ICCTag) -> Result<Pipeline, String> {
let mut pipeline: Pipeline = match self.read_tag_clone(tag) {
Some(p) => p,
None => return Err(format!("Tag {:?} contains no pipeline", tag)),
};
let spc = self.color_space;
let pcs = self.pcs;
// input and output of transform are in lcms 0..1 encoding. If XYZ or Lab spaces are used,
// these need to be normalized into the appropriate ranges (Lab = 100,0,0, XYZ=1.0,1.0,1.0)
if spc == ColorSpace::Lab {
pipeline.prepend_stage(Stage::new_normalize_to_lab_float());
} else if spc == ColorSpace::XYZ {
pipeline.prepend_stage(Stage::new_normalize_to_xyz_float());
}
if pcs == ColorSpace::Lab {
pipeline.append_stage(Stage::new_normalize_from_lab_float());
} else if pcs == ColorSpace::XYZ {
pipeline.append_stage(Stage::new_normalize_from_xyz_float());
}
Ok(pipeline)
}
/// Reads the DToAX tag, adjusting the encoding of Lab or XYZ if needed
fn read_float_output_tag(&self, tag: ICCTag) -> Result<Pipeline, String> {
let mut pipeline: Pipeline = match self.read_tag_clone(tag) {
Some(p) => p,
None => return Err(format!("Tag {:?} contains no pipeline", tag)),
};
let spc = self.color_space;
let pcs = self.pcs;
// If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding,
// and since the formatter has already accommodated to 0..1.0, we should undo this change
if pcs == ColorSpace::Lab {
pipeline.prepend_stage(Stage::new_normalize_to_lab_float());
} else if pcs == ColorSpace::XYZ {
pipeline.prepend_stage(Stage::new_normalize_to_xyz_float());
}
// the output can be Lab or XYZ, in which case normalization is needed on the end of the pipeline
if spc == ColorSpace::Lab {
pipeline.append_stage(Stage::new_normalize_from_lab_float());
} else if spc == ColorSpace::XYZ {
pipeline.append_stage(Stage::new_normalize_from_xyz_float());
}
Ok(pipeline)
}
/// Reads and creates a new LUT.
///
/// All version-dependent things are adjusted here.
/// Intent = 0xFFFFFFFF is added as a way to always read the matrix shaper, no matter what other LUTs are.
pub(crate) fn read_input_lut(&self, intent: Intent) -> Result<Pipeline, String> {
// On named color, take the appropriate tag
if self.device_class == ProfileClass::NamedColor {
let named_colors = match self.read_tag_clone::<NamedColorList>(ICCTag::NamedColor2) {
Some(nc) => nc,
None => return Err("No named color list".into()),
};
let mut lut = Pipeline::new(0, 0);
lut.prepend_stage(Stage::new_named(named_colors, true));
lut.append_stage(Stage::new_labv2_to_v4());
return Ok(lut);
}
// TODO: the rest of this function
// This is an attempt to reuse this function to retrieve the matrix-shaper as pipeline no
// matter other LUT are present and have precedence. Intent = 0xffffffff can be used for that.
if intent as u32 <= Intent::AbsoluteColorimetric as u32 {
let mut tag_16 = DEVICE_TO_PCS_16[intent as usize];
let tag_float = DEVICE_TO_PCS_FLOAT[intent as usize];
if self.has_tag(tag_float) {
// Float tag takes precedence
// Floating point LUT are always V4, but the encoding range is no
// longer 0..1.0, so we need to add an stage depending on the color space
return self.read_float_input_tag(tag_float);
}
// Revert to perceptual if no tag is found
if !self.has_tag(tag_16) {
tag_16 = DEVICE_TO_PCS_16[0];
}
// Is there any LUT-Based table?
if self.has_tag(tag_16) {
// Check profile version and LUT type. Do the necessary adjustments if needed
// First read the tag
let _pipeline = match self.read_tag_clone(tag_16) {
Some(p) => p,
None => return Err("No table".into()),
};
unimplemented!()
/*
// After reading it, we have now info about the original type
OriginalType = _cmsGetTagTrueType(hProfile, tag16);
// The profile owns the Lut, so we need to copy it
Lut = cmsPipelineDup(Lut);
// We need to adjust data only for Lab16 on output
if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
return Lut;
// If the input is Lab, add also a conversion at the begin
if (cmsGetColorSpace(hProfile) == cmsSigLabData &&
!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
goto Error;
// Add a matrix for conversion V2 to V4 Lab PCS
if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
goto Error;
return Lut; */
}
}
// Lut was not found, try to create a matrix-shaper
// Check if this is a grayscale profile.
if self.color_space == ColorSpace::Gray {
// if so, build appropriate conversion tables.
// The tables are the PCS iluminant, scaled across GrayTRC
unimplemented!()
// return BuildGrayInputMatrixPipeline(hProfile);
}
// Not gray, create a normal matrix-shaper
self.build_rgb_input_matrix_shaper()
}
// Create an output MPE LUT from agiven profile. Version mismatches are handled here
pub(crate) fn read_output_lut(&self, intent: Intent) -> Result<Pipeline, String> {
if intent as u32 <= Intent::AbsoluteColorimetric as u32 {
let mut tag_16 = PCS_TO_DEVICE_16[intent as usize];
let tag_float = PCS_TO_DEVICE_FLOAT[intent as usize];
if self.has_tag(tag_float) {
// Float tag takes precedence
// Floating point LUT are always V4
return self.read_float_output_tag(tag_float);
}
// Revert to perceptual if no tag is found
if !self.has_tag(tag_16) {
tag_16 = PCS_TO_DEVICE_16[0];
}
if self.has_tag(tag_16) {
// TODO
unimplemented!()
}
/*
if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
// Check profile version and LUT type. Do the necessary adjustments if needed
// First read the tag
cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
if (Lut == NULL) return NULL;
// After reading it, we have info about the original type
OriginalType = _cmsGetTagTrueType(hProfile, tag16);
// The profile owns the Lut, so we need to copy it
Lut = cmsPipelineDup(Lut);
if (Lut == NULL) return NULL;
// Now it is time for a controversial stuff. I found that for 3D LUTS using
// Lab used as indexer space, trilinear interpolation should be used
if (cmsGetPCS(hProfile) == cmsSigLabData)
ChangeInterpolationToTrilinear(Lut);
// We need to adjust data only for Lab and Lut16 type
if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
return Lut;
// Add a matrix for conversion V4 to V2 Lab PCS
if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
goto Error;
// If the output is Lab, add also a conversion at the end
if (cmsGetColorSpace(hProfile) == cmsSigLabData)
if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
goto Error;
return Lut;
Error:
cmsPipelineFree(Lut);
return NULL;
} */
}
// Lut not found, try to create a matrix-shaper
// Check if this is a grayscale profile.
if self.color_space == ColorSpace::Gray {
// if so, build appropriate conversion tables.
// The tables are the PCS iluminant, scaled across GrayTRC
// return BuildGrayOutputPipeline(hProfile);
unimplemented!()
}
// Not gray, create a normal matrix-shaper, which only operates in XYZ space
self.build_rgb_output_matrix_shaper()
}
fn build_rgb_input_matrix_shaper(&self) -> Result<Pipeline, String> {
// XYZ PCS in encoded in 1.15 format, and the matrix output comes in 0..0xffff range, so
// we need to adjust the output by a factor of (0x10000/0xffff) to put data in
// a 1.16 range, and then a >> 1 to obtain 1.15. The total factor is (65536.0)/(65535.0*2)
let mat = match self.icc_matrix_rgb_to_xyz() {
Some(m) => m * INP_ADJ,
None => return Err("Failed to read colorants as matrix".into()),
};
let shapes: [ToneCurve; 3] = [
match self.read_tag_clone(ICCTag::RedTRC) {
Some(t) => t,
None => return Err("No red tone curve".into()),
},
match self.read_tag_clone(ICCTag::GreenTRC) {
Some(t) => t,
None => return Err("No green tone curve".into()),
},
match self.read_tag_clone(ICCTag::BlueTRC) {
Some(t) => t,
None => return Err("No blue tone curve".into()),
},
];
let mut pipeline = Pipeline::new(3, 3);
pipeline.append_stage(Stage::new_tone_curves(3, &shapes));
pipeline.append_stage(Stage::new_matrix(
3,
3,
unsafe { &*(&mat as *const _ as *const [f64; 9]) },
None,
));
// Note that it is certainly possible a single profile would have a LUT based
// tag for output working in lab and a matrix-shaper for the fallback cases.
// This is not allowed by the spec, but this code is tolerant to those cases
if self.pcs == ColorSpace::Lab {
pipeline.append_stage(Stage::new_xyz_to_lab());
}
Ok(pipeline)
}
fn build_rgb_output_matrix_shaper(&self) -> Result<Pipeline, String> {
let mat = match self.icc_matrix_rgb_to_xyz() {
Some(m) => m,
None => return Err("Failed to read colorants as matrix".into()),
};
// XYZ PCS in encoded in 1.15 format, and the matrix input should come in 0..0xffff range, so
// we need to adjust the input by a << 1 to obtain a 1.16 fixed and then by a factor of
// (0xffff/0x10000) to put data in 0..0xffff range. Total factor is (2.0*65535.0)/65536.0.
let inv = match mat.invert() {
Some(m) => m,
None => return Err("Could not invert matrix".into()),
} * OUTP_ADJ;
let shapes: [ToneCurve; 3] = [
match self.read_tag_clone(ICCTag::RedTRC) {
Some(t) => t,
None => return Err("No red tone curve".into()),
},
match self.read_tag_clone(ICCTag::GreenTRC) {
Some(t) => t,
None => return Err("No green tone curve".into()),
},
match self.read_tag_clone(ICCTag::BlueTRC) {
Some(t) => t,
None => return Err("No blue tone curve".into()),
},
];
let inv_shapes: [ToneCurve; 3] = [
shapes[0].reverse()?,
shapes[1].reverse()?,
shapes[2].reverse()?,
];
let mut pipeline = Pipeline::new(3, 3);
// Note that it is certainly possible a single profile would have a LUT based
// tag for output working in lab and a matrix-shaper for the fallback cases.
// This is not allowed by the spec, but this code is tolerant to those cases
if self.pcs == ColorSpace::Lab {
pipeline.append_stage(Stage::new_lab_to_xyz());
}
pipeline.append_stage(Stage::new_matrix(
3,
3,
unsafe { &*(&inv as *const _ as *const [f64; 9]) },
None,
));
pipeline.append_stage(Stage::new_tone_curves(3, &inv_shapes));
Ok(pipeline)
}
// Read the AToD0 tag, adjusting the encoding of Lab or XYZ if neded
pub(crate) fn read_float_devicelink_tag(&self, tag_float: ICCTag) -> Option<Pipeline> {
let mut pipeline: Pipeline = self.read_tag_clone(tag_float)?;
let pcs = self.pcs;
let spc = self.color_space;
if spc == ColorSpace::Lab {
pipeline.prepend_stage(Stage::new_normalize_to_lab_float());
} else if spc == ColorSpace::XYZ {
pipeline.prepend_stage(Stage::new_normalize_to_xyz_float());
}
if pcs == ColorSpace::Lab {
pipeline.append_stage(Stage::new_normalize_from_lab_float());
} else if pcs == ColorSpace::XYZ {
pipeline.append_stage(Stage::new_normalize_from_xyz_float());
}
Some(pipeline)
}
/// This one includes abstract profiles as well. Matrix-shaper cannot be obtained on that device class. The
/// tag name here may default to AToB0
pub(crate) fn read_devicelink_lut(&self, intent: Intent) -> Result<Pipeline, String> {
if intent as u32 > Intent::AbsoluteColorimetric as u32 {
return Err("Intent is not ICC".into());
}
let mut tag_16 = DEVICE_TO_PCS_16[intent as usize];
let mut tag_float = DEVICE_TO_PCS_FLOAT[intent as usize];
// On named color, take the appropriate tag
if self.device_class == ProfileClass::NamedColor {
let named_colors: NamedColorList = match self.read_tag_clone(ICCTag::NamedColor2) {
Some(nc) => nc,
None => return Err("No named color list in profile".into()),
};
let mut pipeline = Pipeline::new(0, 0);
pipeline.prepend_stage(Stage::new_named(named_colors, false));
if self.color_space == ColorSpace::Lab {
pipeline.append_stage(Stage::new_labv2_to_v4());
}
return Ok(pipeline);
}
if self.has_tag(tag_float) {
// Float tag takes precedence
// Floating point LUT are always V
if let Some(pipeline) = self.read_float_devicelink_tag(tag_float) {
return Ok(pipeline);
}
}
tag_float = DEVICE_TO_PCS_FLOAT[0];
if let Some(pipeline) = self.read_tag_clone(tag_float) {
return Ok(pipeline);
}
if self.has_tag(tag_16) {
// Is there any LUT-Based table?
tag_16 = DEVICE_TO_PCS_16[0];
}
// Check profile version and LUT type. Do the necessary adjustments if needed
// Read the tag
let mut pipeline: Pipeline = match self.read_tag_clone(tag_16) {
Some(pipeline) => pipeline,
None => return Err("Profile has no LUT-based table".into()),
};
// Now it is time for some controversial stuff. I found that for 3D LUTS using
// Lab used as indexer space, trilinear interpolation should be used
if self.pcs == ColorSpace::Lab {
// TODO
unimplemented!()
// ChangeInterpolationToTrilinear(Lut);
}
/*
// After reading it, we have info about the original type
OriginalType = _cmsGetTagTrueType(hProfile, tag16);
// We need to adjust data for Lab16 on output
if (OriginalType != cmsSigLut16Type) return Lut;
*/
// Here it is possible to get Lab on both sides
if self.color_space == ColorSpace::Lab {
pipeline.prepend_stage(Stage::new_labv4_to_v2());
}
if self.pcs == ColorSpace::Lab {
pipeline.append_stage(Stage::new_labv2_to_v4());
}
Ok(pipeline)
}
// cmsio1.c
// TODO: fn build_gray_input_pipeline(&self) -> Pipeline
// TODO: _cmsReadFloatInputTag
// TODO: BuildGrayOutputPipeline
// TODO: _cmsReadFloatOutputTag
// TODO: _cmsReadOutputLUT
// TODO: cmsIsMatrixShaper
// TODO: cmsIsCLUT
// TODO: cmsIsIntentSupported
// TODO: _cmsReadProfileSequence
// TODO: _cmsWriteProfileSequence
// TODO: GetMLUFromProfile
// TODO: _cmsCompileProfileSequence
// TODO: GetInfo
// TODO: cmsGetProfileInfo
// TODO: cmsGetProfileInfoASCII
}
impl fmt::Debug for Profile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Profile {{ {:?} version {:x?}, {:?} class, pcs {:?}, {:?} intent",
self.color_space, self.version, self.device_class, self.pcs, self.rendering_intent
)?;
for (k, v) in &self.tags {
write!(f, ", {:?}: ", k)?;
macro_rules! def_tag {
($($ty:ty),+) => {
match v.data {
ProfileTagData::Data(ref val) => {
if false {}
$(
else if let Some(d) = val.downcast_ref::<$ty>() {
write!(f, "{:?}", d)?;
}
)+
else {
write!(f, "<~>")?;
}
}
ProfileTagData::Linked(key) => write!(f, "(-> {:?})", key)?,
ProfileTagData::Raw(ref buf) => {
write!(f, "<raw blob of size {}>", buf.len())?
}
}
}
}
match k {
ICCTag::ProfileDescription
| ICCTag::Copyright
| ICCTag::DeviceModelDesc
| ICCTag::DeviceMfgDesc => def_tag!(MLU),
ICCTag::MediaWhitePoint => def_tag!(CIEXYZ),
ICCTag::MediaBlackPoint => def_tag!(CIEXYZ),
ICCTag::ChromaticAdaptation => def_tag!(Matrix3<f64>, Vec<f64>),
ICCTag::RedColorant | ICCTag::GreenColorant | ICCTag::BlueColorant => {
def_tag!(CIEXYZ)
}
ICCTag::RedTRC | ICCTag::GreenTRC | ICCTag::BlueTRC | ICCTag::GrayTRC => {
def_tag!(ToneCurve)
}
ICCTag::Chromaticity => def_tag!(CIExyYTriple),
_ => write!(f, "<~>")?,
}
}
write!(f, " }}")?;
Ok(())
}
}
/// Get an hexadecimal number with same digits as v
fn base_to_base(mut n: u32, base_in: u32, base_out: u32) -> u32 {
let mut buff = Vec::new();
while n > 0 {
buff.push(n % base_in);
n /= base_in;
}
let mut out = 0;
for i in 0..buff.len() {
out = out * base_out + buff[buff.len() - i - 1];
}
out
}
|
$NetBSD: patch-third__party_rust_authenticator_src_netbsd_transaction.rs,v 1.1 2023/02/05 08:32:24 he Exp $
--- third_party/rust/authenticator/src/netbsd/transaction.rs.orig 2020-09-02 20:55:31.087295047 +0000
+++ third_party/rust/authenticator/src/netbsd/transaction.rs
@@ -0,0 +1,50 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+use runloop::RunLoop;
+use util::OnceCallback;
+
+use platform::fd::Fd;
+use platform::monitor::Monitor;
+
+pub struct Transaction {
+ // Handle to the thread loop.
+ thread: Option<RunLoop>,
+}
+
+impl Transaction {
+ pub fn new<F, T>(
+ timeout: u64,
+ callback: OnceCallback<T>,
+ new_device_cb: F,
+ ) -> Result<Self, ::Error>
+ where
+ F: Fn(Fd, &dyn Fn() -> bool) + Sync + Send + 'static,
+ T: 'static,
+ {
+ let thread = RunLoop::new_with_timeout(
+ move |alive| {
+ // Create a new device monitor.
+ let mut monitor = Monitor::new(new_device_cb);
+
+ // Start polling for new devices.
+ try_or!(monitor.run(alive), |_| callback.call(Err(::Error::Unknown)));
+
+ // Send an error, if the callback wasn't called already.
+ callback.call(Err(::Error::NotAllowed));
+ },
+ timeout,
+ )
+ .map_err(|_| ::Error::Unknown)?;
+
+ Ok(Self {
+ thread: Some(thread),
+ })
+ }
+
+ pub fn cancel(&mut self) {
+ // This must never be None.
+ self.thread.take().unwrap().cancel();
+ }
+}
|
/*!
Definition of the program's main error type.
*/
use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::io;
use std::result::Result;
/// Shorthand for the program's common result type.
pub type MainResult<T> = Result<T, MainError>;
/// An error in the program.
#[derive(Debug)]
pub enum MainError {
Io(io::Error),
Tag(Cow<'static, str>, Box<MainError>),
Other(Box<dyn Error>),
OtherOwned(String),
OtherBorrowed(&'static str),
}
impl fmt::Display for MainError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
use self::MainError::*;
use std::fmt::Display;
match *self {
Io(ref err) => Display::fmt(err, fmt),
Tag(ref msg, ref err) => write!(fmt, "{}: {}", msg, err),
Other(ref err) => Display::fmt(err, fmt),
OtherOwned(ref err) => Display::fmt(err, fmt),
OtherBorrowed(err) => Display::fmt(err, fmt),
}
}
}
impl Error for MainError {}
macro_rules! from_impl {
($src_ty:ty => $dst_ty:ty, $src:ident -> $e:expr) => {
impl From<$src_ty> for $dst_ty {
fn from($src: $src_ty) -> $dst_ty {
$e
}
}
};
}
from_impl! { io::Error => MainError, v -> MainError::Io(v) }
from_impl! { String => MainError, v -> MainError::OtherOwned(v) }
from_impl! { &'static str => MainError, v -> MainError::OtherBorrowed(v) }
impl<T> From<Box<T>> for MainError
where
T: 'static + Error,
{
fn from(src: Box<T>) -> Self {
MainError::Other(src)
}
}
|
mod handler;
mod player;
mod server;
mod voice;
extern crate regex;
use regex::Regex;
extern crate serenity;
use serenity::client::Client;
use serenity::prelude::Mutex;
use std::collections::HashMap;
use std::env;
use std::net::UdpSocket;
use std::str;
use std::sync::Arc;
use std::thread;
use handler::Handler;
use player::*;
use voice::VoiceManager;
fn main() {
let players: Arc<Mutex<HashMap<String, Player>>> = Arc::new(Mutex::new(HashMap::new()));
let socket_players = players.clone();
let mut client = Client::new(&env::var("DISCORD_TOKEN").expect("token"), Handler)
.expect("Error creating client");
{
let mut data = client.data.lock();
data.insert::<VoiceManager>(Arc::clone(&client.voice_manager));
data.insert::<PlayerManager>(Arc::clone(&players.clone()));
}
thread::spawn(move || {
let re_position = Regex::new(r"([0-9]+?)([x])([\-0-9\.]+?)([y])([\-0-9\.]+?)([z])([\-0-9\.]+)").unwrap();
let socket = match UdpSocket::bind("0.0.0.0:5514") {
Ok(s) => s,
Err(e) => panic!("couldn't bind socket: {}", e)
};
let mut buf = [0; 2048];
loop {
match socket.recv_from(&mut buf) {
Ok((_amt, _src)) => {
let data = str::from_utf8(&buf).unwrap_or("");
match &data[..1] {
"p" => {
match re_position.captures(&data) {
Some(cap) => {
let discord = cap[1].to_string();
let x = &cap[3];
let y = &cap[5];
let z = &cap[7];
if !socket_players.lock().contains_key(&discord) {
println!("New User {0}",discord);
socket_players.lock().insert(discord.clone(), Player::new());
}
match socket_players.lock().get_mut(&discord) {
Some(player) => {
player.set_position([
x.parse::<f32>().unwrap_or(0.0),
y.parse::<f32>().unwrap_or(0.0),
z.parse::<f32>().unwrap_or(0.0)
]);
},
None => {
println!("Couldn't find player!");
}
}
},
None => {
println!("Failed regex on {}", data);
}
}
},
"o" => {
println!("Orientation Update");
},
_ => {
println!("Unknown");
}
}
},
Err(e) => {
println!("couldn't receive a datagram: {}", e);
}
}
}
});
client.start();
}
|
mod accessibility;
pub struct CSR {
} |
use std::sync::Arc;
use vulkano::device::{Device, DeviceExtensions, Queue, QueuesIter};
use vulkano::image::SwapchainImage;
use vulkano::instance::{self, Features, Instance, InstanceExtensions, PhysicalDevice, QueueFamily,
debug::DebugCallback};
use vulkano::swapchain::{PresentMode, Surface, SurfaceTransform, Swapchain};
use vulkano_win::{self, VkSurfaceBuild};
use winit;
pub struct VulkanContext {
surface: Arc<Surface<winit::Window>>,
device: Arc<Device>,
queue: Arc<Queue>,
swapchain: Arc<Swapchain<winit::Window>>,
images: Vec<Arc<SwapchainImage<winit::Window>>>,
}
pub fn init_events_loop() -> winit::EventsLoop {
winit::EventsLoop::new()
}
pub fn init_vulkan(events_loop: &winit::EventsLoop) -> Box<VulkanContext> {
let instance = init_vulkan_instance();
init_vulkan_debug_callbacks(instance.clone());
let surface = init_window()
.build_vk_surface(&events_loop, instance.clone())
.unwrap();
let (device, mut queues_iter) = init_device(instance.clone(), surface.clone());
let queue = queues_iter.next().unwrap();
let (swapchain, images) = init_swapchain(device.clone(), queue.clone(), surface.clone());
Box::new(VulkanContext {
device,
queue,
surface,
swapchain,
images,
})
}
fn init_window() -> winit::WindowBuilder {
winit::WindowBuilder::new()
.with_dimensions(800, 600)
.with_title("Vulkan")
}
fn init_swapchain(
device: Arc<Device>,
queue: Arc<Queue>,
surface: Arc<Surface<winit::Window>>,
) -> (
Arc<Swapchain<winit::Window>>,
Vec<Arc<SwapchainImage<winit::Window>>>,
) {
let caps = surface
.capabilities(device.physical_device())
.expect("failed to get surface capabilities");
let dimensions = caps.current_extent.unwrap_or([800, 600]);
let alpha = caps.supported_composite_alpha.iter().next().unwrap();
let format = caps.supported_formats[0].0;
Swapchain::new(
device.clone(),
surface.clone(),
caps.min_image_count,
format,
dimensions,
1,
caps.supported_usage_flags,
&queue,
SurfaceTransform::Identity,
alpha,
PresentMode::Fifo,
true,
None,
).expect("failed to create swapchain")
}
fn init_vulkan_instance() -> Arc<Instance> {
Instance::new(
None,
&init_vulkan_instance_extensions(),
//INFO (danny): https://github.com/vulkano-rs/vulkano/issues/336
init_vulkan_layers()
.iter()
.map(|ln| ln.as_str())
.collect::<Vec<&str>>()
.iter(),
).expect("failed to create Vulkan instance")
}
#[cfg(feature = "vk_debug")]
fn init_vulkan_instance_extensions() -> InstanceExtensions {
println!("Instance Extensions:");
let mut extensions = vulkano_win::required_extensions();
extensions.ext_debug_report = true;
let supported = InstanceExtensions::supported_by_core().unwrap();
print!(" ✔️ ");
println!("{:?}", supported.intersection(&extensions));
print!(" ❌ ");
println!("{:?}", supported.difference(&extensions));
extensions
}
#[cfg(not(feature = "vk_debug"))]
fn init_vulkan_instance_extensions() -> InstanceExtensions {
vulkano_win::required_extensions()
}
#[cfg(feature = "vk_debug")]
fn init_vulkan_layers() -> Vec<String> {
println!("Layers:");
instance::layers_list()
.unwrap()
.filter(|layer| {
let name = layer.name();
let to_activate = name.contains("RENDERDOC") || name.contains("LUNARG");
if to_activate {
print!(" ✔️ ");
} else {
print!(" ❌ ");
}
println!(
"{} @ {} - {}",
layer.name(),
layer.implementation_version(),
layer.description()
);
to_activate
})
.map(|l| String::from(l.name()))
.collect()
}
#[cfg(not(feature = "vk_debug"))]
fn init_vulkan_layers() -> Vec<String> {
vec![]
}
#[cfg(feature = "vk_debug")]
fn init_vulkan_debug_callbacks(instance: Arc<Instance>) {
println!("Setting Up Debug Callbacks.");
DebugCallback::errors_and_warnings(&instance, |msg| {
println!("Debug callback: {:?}", msg.description);
}).ok();
}
#[cfg(not(feature = "vk_debug"))]
fn init_vulkan_debug_callbacks(instance: Arc<Instance>) {}
fn init_device(
instance: Arc<Instance>,
surface: Arc<Surface<winit::Window>>,
) -> (Arc<Device>, QueuesIter) {
println!("Picking PhysicalDevice");
let device_extensions = init_vulkan_device_extensions();
let physical_device = instance::PhysicalDevice::enumerate(&instance)
.find(|&physical_device| is_device_suitable(physical_device, device_extensions))
.expect("No suitable physical device found!");
println!("Picking Queue Family");
let queue_family = physical_device
.queue_families()
.find(|qf| is_queue_suitable(qf, surface.clone()))
.expect("No suitable queue family found!");
let features = Features::none();
Device::new(
physical_device,
&features,
&device_extensions,
Some((queue_family, 1.0)),
).expect("Couldn't build device")
}
fn is_device_suitable(physical_device: PhysicalDevice, extensions: DeviceExtensions) -> bool {
let minimal_features = Features {
geometry_shader: true,
..Features::none()
};
let suitable = physical_device
.supported_features()
.superset_of(&minimal_features);
if suitable {
print!(" ✔️ ");
} else {
print!(" ❌ ");
}
println!(
"{}, type: {:?}\n supports: {}, driver: {}",
physical_device.name(),
physical_device.ty(),
physical_device.api_version(),
physical_device.driver_version(),
);
println!(" device extensions:");
let supported = DeviceExtensions::supported_by_device(physical_device);
print!(" ✔️ ");
println!("{:?}", supported.intersection(&extensions));
print!(" ❌ ");
println!("{:?}", supported.difference(&extensions));
suitable
}
fn is_queue_suitable(queue_family: &QueueFamily, surface: Arc<Surface<winit::Window>>) -> bool {
let suitable =
queue_family.supports_graphics() && surface.is_supported(*queue_family).unwrap_or(false);
if suitable {
print!(" ✔️ ");
} else {
print!(" ❌ ");
}
println!(
"id: {}, queues_count: {}, graphics: {}, compute: {}, transfers: {}, sparse_binding: {}",
queue_family.id(),
queue_family.queues_count(),
queue_family.supports_graphics(),
queue_family.supports_compute(),
queue_family.supports_transfers(),
queue_family.supports_sparse_binding(),
);
suitable
}
#[cfg(feature = "vk_debug")]
fn init_vulkan_device_extensions() -> DeviceExtensions {
let mut extensions = DeviceExtensions {
khr_swapchain: true,
..DeviceExtensions::none()
};
extensions.ext_debug_marker = true;
extensions
}
#[cfg(not(feature = "vk_debug"))]
fn init_vulkan_device_extensions() -> DeviceExtensions {
DeviceExtensions {
khr_swapchain: true,
..DeviceExtensions::none()
}
}
|
use crate::image::ImageState;
use crate::job::build::BuildContainerCtx;
use crate::util::create_tar_archive;
use crate::Result;
use std::path::Path;
use std::path::PathBuf;
use tracing::{debug, info, info_span, trace, Instrument};
impl<'job> BuildContainerCtx<'job> {
/// Creates a final DEB packages and saves it to `output_dir`
pub(crate) async fn build_deb(
&self,
image_state: &ImageState,
output_dir: &Path,
) -> Result<PathBuf> {
let name = [
&self.recipe.metadata.name,
"-",
&self.recipe.metadata.version,
]
.join("");
let arch = self.recipe.metadata.deb_arch();
let package_name = [&name, ".", &arch].join("");
let span = info_span!("DEB", package = %package_name);
info!(parent: &span, "building DEB package");
let debbld_dir = PathBuf::from("/root/debbuild");
let tmp_dir = debbld_dir.join("tmp");
let base_dir = debbld_dir.join(&name);
let deb_dir = base_dir.join("DEBIAN");
let dirs = [deb_dir.as_path(), tmp_dir.as_path()];
self.create_dirs(&dirs[..]).instrument(span.clone()).await?;
let control = self.recipe.as_deb_control(&image_state.image).render();
debug!(parent: &span, control = %control);
let entries = vec![("./control", control.as_bytes())];
let control_tar = span.in_scope(|| create_tar_archive(entries.into_iter()))?;
let control_tar_path = tmp_dir.join([&name, "-control.tar"].join(""));
trace!(parent: &span, "copy control archive to container");
self.container
.inner()
.copy_file_into(control_tar_path.as_path(), &control_tar)
.instrument(span.clone())
.await?;
trace!(parent: &span, "extract control archive");
self.checked_exec(&format!(
"tar -xvf {} -C {}",
control_tar_path.display(),
deb_dir.display(),
))
.instrument(span.clone())
.await?;
trace!(parent: &span, "copy source files to build dir");
self.checked_exec(&format!(
"cd {} && cp -rv . {}",
self.container_out_dir.display(),
base_dir.display()
))
.instrument(span.clone())
.await?;
self.checked_exec(&format!(
"dpkg-deb --build --root-owner-group {}",
base_dir.display()
))
.instrument(span.clone())
.await?;
let deb_name = [&name, ".deb"].join("");
self.container
.download_files(debbld_dir.join(&deb_name).as_path(), output_dir)
.instrument(span)
.await
.map(|_| output_dir.join(deb_name))
}
}
|
use std::cmp::{Eq, PartialEq};
use std::fmt::Display;
use std::path::PathBuf;
use std::string::ToString;
use super::ast::AstNode;
#[derive(Debug, Clone)]
pub struct FilePos {
pub line: usize,
pub column: usize,
pub source: PathBuf,
}
impl FilePos {
pub fn new(line: usize, column: usize, source: PathBuf) -> Self {
Self {
line,
column,
source,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Span {
pub start: usize,
pub end: usize,
}
impl Span {
pub fn new(start: usize, end: usize) -> Self {
Self { start, end }
}
/// extends the span to include 'token' and everything between.
pub fn extend_to(&mut self, token: &Token) {
self.end = token.pos.span.end;
}
pub fn extend_node(&mut self, node: &dyn AstNode) {
let pos = node.pos();
self.end = pos.span.end;
}
pub fn len(&self) -> usize {
self.end - self.start
}
pub fn zero() -> Self {
Self::new(0, 0)
}
}
impl Display for Span {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({} - {})", self.start, self.end)
}
}
#[derive(Debug, Clone)]
pub struct Position {
pub file: FilePos,
pub span: Span,
}
impl Position {
pub fn new(file: FilePos, span: Span) -> Self {
Self { file, span }
}
pub fn line(&self) -> usize {
self.file.line
}
pub fn column(&self) -> usize {
self.file.column
}
pub fn len(&self) -> usize {
self.span.len()
}
pub fn extend(&mut self, pos: &Position) {
self.span.end = pos.span.end;
}
pub fn zero() -> Self {
Self::new(FilePos::new(0, 0, PathBuf::new()), Span::zero())
}
}
// impl ToString for Position {
// fn to_string(&self) -> String {
// format!("{}:{}:{}", self.line(), self.column(), self.file.source.display())
// }
// }
impl Display for Position {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}:{}:{}",
self.line(),
self.column(),
self.file.source.display()
)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Op {
Plus,
Minus,
Backslash,
Astrick,
AstrickAstrick,
Modulos,
Equal,
// boolean operations
Less,
Greater,
Bang,
EqualEqual,
BangEqual,
LessLess,
GreaterGreater,
Pipe,
Ampersand,
Carot,
Tilde,
PlusEqual,
MinusEqual,
BackslashEqual,
AstrickEqual,
AstrickAstrickEqual,
ModulosEqual,
LessEqual,
GreaterEqual,
PipeEqual,
AmpersandEqual,
CarotEqual,
TildeEqual,
LessLessEqual,
GreaterGreaterEqual,
Dollar,
Question,
}
impl Op {
pub fn prec(&self) -> usize {
match self {
Op::AstrickAstrick => 14,
Op::Backslash | Op::Astrick | Op::Modulos => 13,
Op::Plus | Op::Minus => 12,
Op::LessLess | Op::GreaterGreater => 11,
Op::Less | Op::Greater | Op::EqualEqual | Op::BangEqual => 10,
Op::Ampersand => 9,
Op::Carot => 8,
Op::Tilde => 7,
Op::Pipe => 6,
// and => 5
// or => 4
Op::Bang => 3,
Op::Equal
| Op::PlusEqual
| Op::MinusEqual
| Op::BackslashEqual
| Op::AstrickEqual
| Op::AstrickAstrickEqual
| Op::ModulosEqual
| Op::LessEqual
| Op::GreaterEqual
| Op::PipeEqual
| Op::AmpersandEqual
| Op::CarotEqual
| Op::TildeEqual
| Op::LessLessEqual
| Op::GreaterGreaterEqual => 2,
Op::Dollar | Op::Question => 1,
}
}
}
impl ToString for Op {
fn to_string(&self) -> String {
match self {
Op::Plus => "+",
Op::Minus => "-",
Op::Backslash => "/",
Op::Astrick => "*",
Op::AstrickAstrick => "**",
Op::Modulos => "%",
Op::Equal => "=",
Op::Less => "<",
Op::Greater => ">",
Op::Bang => "!",
Op::EqualEqual => "==",
Op::BangEqual => "!=",
Op::LessLess => "<<",
Op::GreaterGreater => ">>",
Op::Pipe => "|",
Op::Ampersand => "&",
Op::Carot => "^",
Op::Tilde => "~",
Op::PlusEqual => "+=",
Op::MinusEqual => "-=",
Op::BackslashEqual => "/=",
Op::AstrickEqual => "*=",
Op::AstrickAstrickEqual => "**=",
Op::ModulosEqual => "%=",
Op::LessEqual => "<=",
Op::GreaterEqual => ">=",
Op::PipeEqual => "|=",
Op::AmpersandEqual => "&=",
Op::CarotEqual => "^=",
Op::TildeEqual => "~=",
Op::LessLessEqual => "<<=",
Op::GreaterGreaterEqual => ">>=",
Op::Dollar => "$",
Op::Question => "?",
}
.to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Kw {
If,
Else,
Elif,
For,
While,
Loop,
With,
Trait,
As,
And,
Or,
Use,
Fn,
Struct,
Let,
Mut,
Pub,
In,
}
impl Kw {
pub fn prec(&self) -> usize {
match self {
Kw::And => 5,
Kw::Or => 4,
_ => 0,
}
}
}
impl ToString for Kw {
fn to_string(&self) -> String {
match self {
Kw::If => "if",
Kw::Else => "else",
Kw::Elif => "elif",
Kw::For => "for",
Kw::While => "while",
Kw::Loop => "loop",
Kw::With => "with",
Kw::As => "as",
Kw::And => "and",
Kw::Or => "or",
Kw::Trait => "triat",
Kw::Use => "use",
Kw::Fn => "fn",
Kw::Struct => "struct",
Kw::Let => "let",
Kw::Mut => "mut",
Kw::Pub => "pub",
Kw::In => "in",
}
.to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Orientation {
Left,
Right,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ctrl {
Paren(Orientation),
Bracket(Orientation),
Brace(Orientation),
Period,
Colon,
Comma,
Semicolon,
Hash,
MinusGreater,
LessMinus,
EqualLess,
Underscore,
}
impl ToString for Ctrl {
fn to_string(&self) -> String {
match self {
Ctrl::Paren(or) => match or {
Orientation::Left => "(".to_string(),
Orientation::Right => ")".to_string(),
},
Ctrl::Bracket(or) => match or {
Orientation::Left => "{".to_string(),
Orientation::Right => "}".to_string(),
},
Ctrl::Brace(or) => match or {
Orientation::Left => "[".to_string(),
Orientation::Right => "]".to_string(),
},
Ctrl::Period => ".".to_string(),
Ctrl::Colon => ":".to_string(),
Ctrl::Comma => ",".to_string(),
Ctrl::Semicolon => ";".to_string(),
Ctrl::Hash => "#".to_string(),
Ctrl::MinusGreater => "->".to_string(),
Ctrl::LessMinus => "<-".to_string(),
Ctrl::EqualLess => "=>".to_string(),
Ctrl::Underscore => "_".to_string(),
}
}
}
#[derive(Debug, Clone)]
pub enum TokenKind {
IntegerLiteral(u64),
FloatLiteral(f64),
CharLiteral(char),
StringLiteral(String),
Identifier(String),
Operator(Op),
Keyword(Kw),
Control(Ctrl),
Eof,
Error,
Comment,
}
impl TokenKind {
pub fn new_ident(val: &str) -> Self {
TokenKind::Identifier(val.to_string())
}
pub fn new_integer(val: u64) -> Self {
TokenKind::IntegerLiteral(val)
}
pub fn new_float(val: f64) -> Self {
TokenKind::FloatLiteral(val)
}
pub fn new_char(val: char) -> Self {
TokenKind::CharLiteral(val)
}
pub fn new_string(val: &str) -> Self {
TokenKind::StringLiteral(val.to_string())
}
pub fn is_identifier(&self) -> bool {
match *self {
TokenKind::Identifier(_) => true,
_ => false,
}
}
pub fn is_operator(&self) -> bool {
match self {
TokenKind::Operator(_) => true,
_ => false,
}
}
pub fn is_assignment(&self) -> bool {
match self {
TokenKind::Operator(op) => match op {
Op::Equal
| Op::PlusEqual
| Op::MinusEqual
| Op::BackslashEqual
| Op::AstrickEqual
| Op::AstrickAstrickEqual
| Op::ModulosEqual
| Op::LessEqual
| Op::GreaterEqual
| Op::PipeEqual
| Op::AmpersandEqual
| Op::CarotEqual
| Op::TildeEqual
| Op::LessLessEqual
| Op::GreaterGreaterEqual => true,
_ => false,
},
_ => false,
}
}
pub fn is_keyword(&self) -> bool {
match self {
TokenKind::Keyword(_) => true,
_ => false,
}
}
pub fn is_literal(&self) -> bool {
match self {
TokenKind::CharLiteral(_)
| TokenKind::StringLiteral(_)
| TokenKind::IntegerLiteral(_)
| TokenKind::FloatLiteral(_) => true,
_ => false,
}
}
pub fn is_control(&self) -> bool {
match self {
TokenKind::Control(_) => true,
_ => false,
}
}
pub fn get_ident_kind(val: &str) -> Self {
match val {
"if" => TokenKind::Keyword(Kw::If),
"else" => TokenKind::Keyword(Kw::Else),
"elif" => TokenKind::Keyword(Kw::Elif),
"for" => TokenKind::Keyword(Kw::For),
"while" => TokenKind::Keyword(Kw::While),
"loop" => TokenKind::Keyword(Kw::Loop),
// "use" => TokenKind::Keyword(Kw::Use),
"with" => TokenKind::Keyword(Kw::With),
"as" => TokenKind::Keyword(Kw::As),
"and" => TokenKind::Keyword(Kw::And),
"or" => TokenKind::Keyword(Kw::Or),
"use" => TokenKind::Keyword(Kw::Use),
"fn" => TokenKind::Keyword(Kw::Fn),
"struct" => TokenKind::Keyword(Kw::Struct),
"let" => TokenKind::Keyword(Kw::Let),
"mut" => TokenKind::Keyword(Kw::Mut),
"pub" => TokenKind::Keyword(Kw::Pub),
"trait" => TokenKind::Keyword(Kw::Trait),
"in" => TokenKind::Keyword(Kw::In),
_ => TokenKind::Identifier(val.to_string()),
}
}
pub fn list_to_str(kinds: &[TokenKind]) -> String {
let strings = kinds
.iter()
.map(|kind| match kind {
TokenKind::Identifier(_) => "identifier".to_string(),
_ => kind.to_string(),
})
.collect::<Vec<String>>();
strings.join(", ")
}
}
impl ToString for TokenKind {
fn to_string(&self) -> String {
match self {
TokenKind::IntegerLiteral(val) => val.to_string(),
TokenKind::FloatLiteral(val) => val.to_string(),
TokenKind::CharLiteral(ch) => ch.to_string(),
TokenKind::StringLiteral(val) => val.clone(),
TokenKind::Identifier(val) => val.clone(),
TokenKind::Operator(op) => op.to_string(),
TokenKind::Keyword(kw) => kw.to_string(),
TokenKind::Control(ctrl) => ctrl.to_string(),
TokenKind::Error => "Error".to_string(),
TokenKind::Comment => "Comment".to_string(),
TokenKind::Eof => "Eof".to_string(),
}
}
}
#[derive(Debug, Clone)]
pub struct Token {
kind: TokenKind,
pos: Position,
}
impl Token {
pub fn new(kind: TokenKind, pos: Position) -> Self {
Self { kind, pos }
}
pub fn kind(&self) -> &TokenKind {
&self.kind
}
pub fn pos(&self) -> &Position {
&self.pos
}
pub fn prec(&self) -> usize {
match &self.kind {
TokenKind::Operator(op) => op.prec(),
TokenKind::Keyword(kw) => kw.prec(),
_ => 0,
}
}
pub fn is_keyword(&self) -> bool {
self.kind.is_keyword()
}
pub fn is_operator(&self) -> bool {
self.kind.is_operator()
}
pub fn is_assignment(&self) -> bool {
self.kind.is_assignment()
}
pub fn is_eof(&self) -> bool {
self.check(TokenKind::Eof)
}
pub fn check(&self, kind: TokenKind) -> bool {
match (self.kind(), &kind) {
(TokenKind::Identifier(_), TokenKind::Identifier(_)) => true,
(TokenKind::Operator(op1), TokenKind::Operator(op2)) => *op1 == *op2,
(TokenKind::Keyword(kw1), TokenKind::Keyword(kw2)) => *kw1 == *kw2,
(TokenKind::Control(ct1), TokenKind::Control(ct2)) => *ct1 == *ct2,
(TokenKind::IntegerLiteral(_), TokenKind::IntegerLiteral(_)) => true,
(TokenKind::FloatLiteral(_), TokenKind::FloatLiteral(_)) => true,
(TokenKind::CharLiteral(_), TokenKind::CharLiteral(_)) => true,
(TokenKind::StringLiteral(_), TokenKind::StringLiteral(_)) => true,
(TokenKind::Comment, TokenKind::Comment) => true,
(TokenKind::Eof, TokenKind::Eof) => true,
(_, _) => false,
}
}
}
impl ToString for Token {
fn to_string(&self) -> String {
self.kind().to_string()
}
}
|
#[doc = "Register `IPCC_HWCFGR` reader"]
pub type R = crate::R<IPCC_HWCFGR_SPEC>;
#[doc = "Field `CHANNELS` reader - CHANNELS"]
pub type CHANNELS_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:7 - CHANNELS"]
#[inline(always)]
pub fn channels(&self) -> CHANNELS_R {
CHANNELS_R::new((self.bits & 0xff) as u8)
}
}
#[doc = "IPCC Hardware configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_hwcfgr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IPCC_HWCFGR_SPEC;
impl crate::RegisterSpec for IPCC_HWCFGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ipcc_hwcfgr::R`](R) reader structure"]
impl crate::Readable for IPCC_HWCFGR_SPEC {}
#[doc = "`reset()` method sets IPCC_HWCFGR to value 0x02"]
impl crate::Resettable for IPCC_HWCFGR_SPEC {
const RESET_VALUE: Self::Ux = 0x02;
}
|
use std::option::Option::Some;
use crate::leet_code::common::chain_table::ListNode;
/// 从尾到头打印链表
///
/// 输入:head = [1,3,2]
/// 输出:[2,3,1]
pub fn main() {
let test_node = ListNode::produce_chain(vec![1, 3, 2]);
let result = Solution::reverse_print(test_node);
println!("{:?}", result);
}
struct Solution;
impl Solution {
pub fn reverse_print(head: Option<Box<ListNode>>) -> Vec<i32> {
let mut origin = head;
let mut result = vec![];
while let Some(value) = origin {
result.insert(0, value.val);
origin = value.next;
}
result
}
}
|
mod client;
mod inner;
mod reader;
mod writer;
mod error;
pub use self::client::Client;
|
mod timing {
use super::super::{try_advance_departure_time, try_recede_departure_time};
use crate::construction::constraints::*;
use crate::construction::heuristics::*;
use crate::helpers::construction::constraints::create_constraint_pipeline_with_transport;
use crate::helpers::models::domain::{create_empty_solution_context, test_random};
use crate::helpers::models::problem::*;
use crate::helpers::models::solution::*;
use crate::models::common::{Location, Schedule, TimeInterval, TimeWindow, Timestamp};
use crate::models::problem::{Vehicle, VehicleDetail, VehiclePlace};
use crate::models::solution::{Activity, Place, Registry};
use crate::utils::compare_floats;
use std::cmp::Ordering;
fn create_detail(
locations: (Option<Location>, Option<Location>),
time: Option<(Timestamp, Timestamp)>,
) -> VehicleDetail {
let (start_location, end_location) = locations;
VehicleDetail {
start: start_location.map(|location| VehiclePlace {
location,
time: time
.map_or(Default::default(), |(start, _)| TimeInterval { earliest: Some(start), latest: None }),
}),
end: end_location.map(|location| VehiclePlace {
location,
time: time.map_or(Default::default(), |(_, end)| TimeInterval { earliest: None, latest: Some(end) }),
}),
}
}
fn create_constraint_pipeline_and_route(
vehicle_detail_data: (Location, Location, Timestamp, Timestamp),
) -> (ConstraintPipeline, RouteContext) {
let (location_start, location_end, time_start, time_end) = vehicle_detail_data;
let fleet = FleetBuilder::default()
.add_driver(test_driver())
.add_vehicles(vec![VehicleBuilder::default()
.id("v1")
.details(vec![create_detail((Some(location_start), Some(location_end)), Some((time_start, time_end)))])
.build()])
.build();
let route_ctx = create_route_context_with_activities(
&fleet,
"v1",
vec![test_activity_with_location(10), test_activity_with_location(20), test_activity_with_location(30)],
);
(create_constraint_pipeline_with_transport(), route_ctx)
}
parameterized_test! {can_properly_calculate_latest_arrival, (vehicle, activity, time), {
can_properly_calculate_latest_arrival_impl(vehicle, activity, time);
}}
can_properly_calculate_latest_arrival! {
case01: ((0, 0, 0., 100.), 3, 70.),
case02: ((0, 0, 0., 100.), 2, 60.),
case03: ((0, 0, 0., 100.), 1, 50.),
case04: ((0, 0, 0., 60.), 3, 30.),
case05: ((0, 0, 0., 60.), 2, 20.),
case06: ((0, 0, 0., 60.), 1, 10.),
case07: ((40, 40, 0., 100.), 3, 90.),
case08: ((40, 40, 0., 100.), 1, 70.),
case09: ((40, 40, 0., 100.), 2, 80.),
}
fn can_properly_calculate_latest_arrival_impl(
vehicle_detail_data: (Location, Location, Timestamp, Timestamp),
activity: usize,
time: f64,
) {
let (pipeline, mut route_ctx) = create_constraint_pipeline_and_route(vehicle_detail_data);
pipeline.accept_route_state(&mut route_ctx);
let activity = route_ctx.route.tour.get(activity).unwrap();
let result = *route_ctx.state.get_activity_state::<Timestamp>(LATEST_ARRIVAL_KEY, activity).unwrap();
assert_eq!(result, time);
}
parameterized_test! {can_detect_activity_constraint_violation, (vehicle_detail_data, location, prev_index, next_index, expected), {
can_detect_activity_constraint_violation_impl(vehicle_detail_data, location, prev_index, next_index, expected);
}}
can_detect_activity_constraint_violation! {
case01: ((0, 0, 0., 100.), 50, 3, 4, None),
case02: ((0, 0, 0., 100.), 1000, 3, 4, Some(ActivityConstraintViolation{ code: 1, stopped: false })),
case03: ((0, 0, 0., 100.), 50, 2, 3, None),
case04: ((0, 0, 0., 100.), 51, 2, 3, Some(ActivityConstraintViolation{ code: 1, stopped: false })),
case05: ((0, 0, 0., 60.), 40, 3, 4, Some(ActivityConstraintViolation{ code: 1, stopped: false })),
case06: ((0, 0, 0., 50.), 40, 3, 4, Some(ActivityConstraintViolation{ code: 1, stopped: true })),
case07: ((0, 0, 0., 10.), 40, 3, 4, Some(ActivityConstraintViolation{ code: 1, stopped: true })),
case08: ((0, 0, 60., 100.), 40, 3, 4, Some(ActivityConstraintViolation{ code: 1, stopped: true })),
case09: ((0, 40, 0., 40.), 40, 1, 2, Some(ActivityConstraintViolation{ code: 1, stopped: false })),
case10: ((0, 40, 0., 40.), 40, 3, 4, None),
}
fn can_detect_activity_constraint_violation_impl(
vehicle_detail_data: (Location, Location, Timestamp, Timestamp),
location: Location,
prev_index: usize,
next_index: usize,
expected: Option<ActivityConstraintViolation>,
) {
let (pipeline, mut route_ctx) = create_constraint_pipeline_and_route(vehicle_detail_data);
pipeline.accept_route_state(&mut route_ctx);
let prev = route_ctx.route.tour.get(prev_index).unwrap();
let target = test_activity_with_location(location);
let next = route_ctx.route.tour.get(next_index);
let activity_ctx = ActivityContext { index: 0, prev, target: &target, next };
let result = pipeline.evaluate_hard_activity(&route_ctx, &activity_ctx);
assert_eq!(result, expected);
}
#[test]
fn can_update_activity_schedule() {
let fleet = FleetBuilder::default()
.add_driver(test_driver())
.add_vehicles(vec![VehicleBuilder::default().id("v1").build()])
.build();
let mut solution_ctx = SolutionContext {
routes: vec![create_route_context_with_activities(
&fleet,
"v1",
vec![
ActivityBuilder::default()
.place(Place { location: 10, duration: 5., time: TimeWindow { start: 20., end: 30. } })
.schedule(Schedule::new(10., 25.))
.build(),
ActivityBuilder::default()
.place(Place { location: 20, duration: 10., time: TimeWindow { start: 50., end: 100. } })
.schedule(Schedule::new(35., 60.))
.build(),
],
)],
registry: RegistryContext::new(Registry::new(&fleet, test_random())),
..create_empty_solution_context()
};
create_constraint_pipeline_with_transport().accept_solution_state(&mut solution_ctx);
let route_ctx = solution_ctx.routes.first().unwrap();
assert_eq!(route_ctx.route.tour.get(1).unwrap().schedule, Schedule { arrival: 10., departure: 25. });
assert_eq!(route_ctx.route.tour.get(2).unwrap().schedule, Schedule { arrival: 35., departure: 60. });
}
#[test]
fn can_calculate_soft_activity_cost_for_empty_tour() {
let fleet = FleetBuilder::default()
.add_driver(test_driver_with_costs(empty_costs()))
.add_vehicles(vec![VehicleBuilder::default().id("v1").build()])
.build();
let route_ctx = create_route_context_with_activities(&fleet, "v1", vec![]);
let target = Box::new(Activity {
place: Place { location: 5, duration: 1.0, time: DEFAULT_ACTIVITY_TIME_WINDOW },
schedule: DEFAULT_ACTIVITY_SCHEDULE,
job: None,
});
let activity_ctx = ActivityContext {
index: 0,
prev: route_ctx.route.tour.get(0).unwrap(),
target: &target,
next: route_ctx.route.tour.get(1),
};
let result = create_constraint_pipeline_with_transport().evaluate_soft_activity(&route_ctx, &activity_ctx);
assert_eq!(compare_floats(result, 21.0), Ordering::Equal);
}
#[test]
fn can_calculate_soft_activity_cost_for_non_empty_tour() {
let fleet = FleetBuilder::default()
.add_driver(test_driver_with_costs(empty_costs()))
.add_vehicles(vec![VehicleBuilder::default().id("v1").build()])
.build();
let route_ctx = create_route_context_with_activities(
&fleet,
"v1",
vec![
ActivityBuilder::default()
.place(Place { location: 10, duration: 0.0, time: DEFAULT_ACTIVITY_TIME_WINDOW.clone() })
.schedule(Schedule { arrival: 0.0, departure: 10.0 })
.build(),
ActivityBuilder::default()
.place(Place { location: 20, duration: 0.0, time: TimeWindow { start: 40.0, end: 70.0 } })
.build(),
],
);
let target = Box::new(Activity {
place: Place { location: 30, duration: 10.0, time: DEFAULT_ACTIVITY_TIME_WINDOW },
schedule: DEFAULT_ACTIVITY_SCHEDULE,
job: None,
});
let activity_ctx = ActivityContext {
index: 0,
prev: route_ctx.route.tour.get(1).unwrap(),
target: &target,
next: route_ctx.route.tour.get(2),
};
let result = create_constraint_pipeline_with_transport().evaluate_soft_activity(&route_ctx, &activity_ctx);
assert_eq!(compare_floats(result, 30.0), Ordering::Equal);
}
#[test]
fn can_stop_with_time_route_constraint() {
let fleet = FleetBuilder::default()
.add_driver(test_driver())
.add_vehicles(vec![VehicleBuilder::default().id("v1").build()])
.build();
let solution_ctx = create_empty_solution_context();
let route_ctx = create_route_context_with_activities(&fleet, "v1", vec![]);
let job = SingleBuilder::default().times(vec![TimeWindow::new(2000., 3000.)]).build_as_job_ref();
let result = create_constraint_pipeline_with_transport().evaluate_hard_route(&solution_ctx, &route_ctx, &job);
assert_eq!(result, Some(RouteConstraintViolation { code: 1 }));
}
parameterized_test! {can_advance_departure_time, (latest, optimize_whole_tour, tws, expected), {
let tws = tws.into_iter().map(|(start, end)| TimeWindow::new(start, end)).collect::<Vec<_>>();
can_advance_departure_time_impl(latest, optimize_whole_tour, tws, expected);
}}
can_advance_departure_time! {
case01: (None, true, vec![(0., 100.), (25., 100.), (0., 100.)], Some(5.)),
case02: (Some(3.), true, vec![(0., 100.), (25., 100.), (0., 100.)], Some(3.)),
case03: (Some(7.), true, vec![(0., 100.), (25., 100.), (0., 100.)], Some(5.)),
case04: (None, true, vec![(0., 100.), (10., 100.), (42., 100.)], Some(12.)),
case05: (None, false, vec![(12., 100.), (0., 100.), (0., 100.)], Some(2.)),
case06: (None, false, vec![(10., 100.), (0., 100.), (0., 100.)], None),
case07: (None, false, vec![(0., 100.), (25., 100.), (0., 100.)], None),
}
fn can_advance_departure_time_impl(
latest: Option<f64>,
optimize_whole_tour: bool,
tws: Vec<TimeWindow>,
expected: Option<f64>,
) {
if let [tw1, tw2, tw3] = tws.as_slice() {
let fleet = FleetBuilder::default()
.add_driver(test_driver())
.add_vehicle(Vehicle {
details: vec![VehicleDetail {
start: Some(VehiclePlace { location: 0, time: TimeInterval { earliest: Some(0.), latest } }),
..test_vehicle_detail()
}],
..test_vehicle_with_id("v1")
})
.build();
let route_ctx = create_route_context_with_activities(
&fleet,
"v1",
vec![
test_activity_with_location_and_tw(10, tw1.clone()),
test_activity_with_location_and_tw(20, tw2.clone()),
test_activity_with_location_and_tw(30, tw3.clone()),
],
);
let departure_time =
try_advance_departure_time(&route_ctx, &TestTransportCost::default(), optimize_whole_tour);
assert_eq!(departure_time, expected);
} else {
unreachable!()
}
}
parameterized_test! {can_recede_departure_time, (earliest, start_departure, latest_first_arrival, tw, duration_limit, expected), {
can_recede_departure_time_impl(earliest, start_departure, latest_first_arrival, TimeWindow::new(tw.0, tw.1), duration_limit, expected);
}}
can_recede_departure_time! {
case01: (Some(0.), 0., 10., (10., 20.), None, None),
case02: (Some(0.), 5., 10., (10., 20.), None, None),
case03: (Some(5.), 10., 15., (10., 20.), None, Some(5.)),
case04: (Some(5.), 10., 20., (10., 20.), None, Some(5.)),
case05: (None, 10., 50., (10., 20.), None, Some(0.)),
case06: (Some(5.), 10., 11., (10., 20.), None, Some(9.)),
case07: (Some(0.), 10., 20., (10., 20.), Some((20., 30.)), Some(0.)),
case08: (Some(0.), 10., 20., (10., 20.), Some((20., 25.)), Some(5.)),
case09: (Some(0.), 10., 20., (10., 20.), Some((20., 20.)), None),
}
fn can_recede_departure_time_impl(
earliest: Option<f64>,
start_departure: f64,
latest_first_arrival: f64,
tw: TimeWindow,
total_duration_limit: Option<(f64, f64)>,
expected: Option<f64>,
) {
let fleet = FleetBuilder::default()
.add_driver(test_driver())
.add_vehicle(Vehicle {
details: vec![VehicleDetail {
start: Some(VehiclePlace { location: 0, time: TimeInterval { earliest, latest: None } }),
..test_vehicle_detail()
}],
..test_vehicle_with_id("v1")
})
.build();
let mut route_ctx =
create_route_context_with_activities(&fleet, "v1", vec![test_activity_with_location_and_tw(10, tw)]);
let (route, state) = route_ctx.as_mut();
route.tour.get_mut(0).unwrap().schedule.departure = start_departure;
let first = route.tour.get(1).unwrap();
state.put_activity_state::<f64>(LATEST_ARRIVAL_KEY, first, latest_first_arrival);
if let Some((total, limit)) = total_duration_limit {
state.put_route_state::<f64>(TOTAL_DURATION_KEY, total);
state.put_route_state::<f64>(LIMIT_DURATION_KEY, limit);
}
let departure_time = try_recede_departure_time(&route_ctx);
assert_eq!(departure_time, expected);
}
}
mod traveling {
use super::super::stop;
use crate::construction::constraints::*;
use crate::construction::heuristics::{ActivityContext, RouteContext, RouteState};
use crate::helpers::construction::constraints::create_constraint_pipeline_with_module;
use crate::helpers::models::problem::*;
use crate::helpers::models::solution::*;
use crate::models::common::{Distance, Duration, Location, TimeWindow};
use std::sync::Arc;
fn create_test_data(
vehicle: &str,
target: &str,
limit: (Option<Distance>, Option<Duration>),
) -> (ConstraintPipeline, RouteContext) {
let fleet = FleetBuilder::default().add_driver(test_driver()).add_vehicle(test_vehicle_with_id("v1")).build();
let mut state = RouteState::default();
state.put_route_state(TOTAL_DISTANCE_KEY, 50.);
state.put_route_state(TOTAL_DURATION_KEY, 50.);
let target = target.to_owned();
let route_ctx = RouteContext::new_with_state(
Arc::new(create_route_with_activities(&fleet, vehicle, vec![])),
Arc::new(state),
);
let pipeline = create_constraint_pipeline_with_module(Box::new(TransportConstraintModule::new(
TestTransportCost::new_shared(),
Arc::new(TestActivityCost::default()),
Arc::new(
move |actor| {
if get_vehicle_id(actor.vehicle.as_ref()) == target.as_str() {
limit
} else {
(None, None)
}
},
),
1,
2,
3,
)));
(pipeline, route_ctx)
}
parameterized_test! {can_check_traveling_limits, (vehicle, target, location, limit, expected), {
can_check_traveling_limits_impl(vehicle, target, location, limit, expected);
}}
can_check_traveling_limits! {
case01: ("v1", "v1", 76, (Some(100.), None), stop(2)),
case02: ("v1", "v1", 74, (Some(100.), None), None),
case03: ("v1", "v2", 76, (Some(100.), None), None),
case04: ("v1", "v1", 76, (None, Some(100.)), stop(3)),
case05: ("v1", "v1", 74, (None, Some(100.)), None),
case06: ("v1", "v2", 76, (None, Some(100.)), None),
}
fn can_check_traveling_limits_impl(
vehicle: &str,
target: &str,
location: Location,
limit: (Option<Distance>, Option<Duration>),
expected: Option<ActivityConstraintViolation>,
) {
let (pipeline, route_ctx) = create_test_data(vehicle, target, limit);
let result = pipeline.evaluate_hard_activity(
&route_ctx,
&ActivityContext {
index: 0,
prev: &test_activity_with_location(50),
target: &test_activity_with_location(location),
next: Some(&test_activity_with_location(50)),
},
);
assert_eq!(result, expected);
}
#[test]
fn can_consider_waiting_time() {
let (pipeline, route_ctx) = create_test_data("v1", "v1", (None, Some(100.)));
let result = pipeline.evaluate_hard_activity(
&route_ctx,
&ActivityContext {
index: 0,
prev: &test_activity_with_location(50),
target: &test_activity_with_location_and_tw(75, TimeWindow::new(100., 100.)),
next: Some(&test_activity_with_location(50)),
},
);
assert_eq!(result, stop(3));
}
}
|
extern crate bufstream;
use std::collections::HashMap;
use std::net::TcpStream;
use self::bufstream::BufStream;
use commands;
use error::{BeanstalkdError, BeanstalkdResult};
use parse;
use request::Request;
use response::{Response, Status};
macro_rules! try {
($e:expr) => (match $e { Ok(e) => e, Err(_) => return Err(BeanstalkdError::ConnectionError) })
}
pub struct Beanstalkd {
stream: BufStream<TcpStream>,
}
impl Beanstalkd {
/// Connect to a running beanstalkd server
///
/// Example: `let mut beanstalkd = Beanstalkd::connect('localhost', 11300).unwrap();`
pub fn connect(host: &str, port: u16) -> BeanstalkdResult<Beanstalkd> {
let tcp_stream = try!(TcpStream::connect(&(host, port)));
Ok(Beanstalkd { stream: BufStream::new(tcp_stream) })
}
/// Short hand method to connect to `localhost:11300`
pub fn localhost() -> BeanstalkdResult<Beanstalkd> {
Beanstalkd::connect("localhost", 11300)
}
/// Change the tube where put new messages (Standard tube is called `default`)
pub fn tube(&mut self, tube: &str) -> BeanstalkdResult<()> {
self.cmd(commands::tube(tube)).map(|_| ())
}
/// Inserts a job into the client's currently used tube
pub fn put(&mut self,
body: &str,
priority: u32,
delay: u32,
ttr: u32)
-> BeanstalkdResult<u64> {
self.cmd(commands::put(body, priority, delay, ttr)).map(parse::id)
}
/// Get the next message out of the queue
pub fn reserve(&mut self) -> BeanstalkdResult<(u64, String)> {
self.cmd(commands::reserve()).map(|r| (parse::id(r.clone()), parse::body(r)))
}
/// Get the next message out of the queue with timeout. If the timeout runs out a None is returned
/// in BeanstalkdResult.
pub fn reserve_with_timeout(&mut self, timeout: u64) -> BeanstalkdResult<Option<(u64, String)>> {
self.cmd(commands::reserve_with_timeout(timeout))
.map(|r| {
if r.status == Status::TIMED_OUT {
None
} else {
Some((parse::id(r.clone()), parse::body(r)))
}
})
}
/// Deletes a message out of the queue
pub fn delete(&mut self, id: u64) -> BeanstalkdResult<()> {
self.cmd(commands::delete(id)).map(|_| ())
}
/// Release a job in the queue
pub fn release(&mut self, id: u64, priority: u32, delay: u32) -> BeanstalkdResult<()> {
self.cmd(commands::release(id, priority, delay)).map(|_| ())
}
/// Bury a job in the queue
pub fn bury(&mut self, id: u64, priority: u32) -> BeanstalkdResult<()> {
self.cmd(commands::bury(id, priority)).map(|_| ())
}
/// Touch a job in the queue
pub fn touch(&mut self, id: u64) -> BeanstalkdResult<()> {
self.cmd(commands::touch(id)).map(|_| ())
}
/// Returns all available stats
pub fn stats(&mut self) -> BeanstalkdResult<HashMap<String, String>> {
self.cmd(commands::stats()).map(parse::hashmap)
}
/// Returns stats for the specified job
pub fn stats_job(&mut self, id: u64) -> BeanstalkdResult<HashMap<String, String>> {
self.cmd(commands::stats_job(id)).map(parse::hashmap)
}
/// Add new tube to watch list
pub fn watch(&mut self, tube: &str) -> BeanstalkdResult<u64> {
self.cmd(commands::watch(tube)).map(parse::id)
}
/// Removes the named tube from the watch list for the current connection
pub fn ignore(&mut self, tube: &str) -> BeanstalkdResult<Option<u64>> {
self.cmd(commands::ignore(tube)).map(parse::count)
}
/// Peeks the next ready job
pub fn peek_ready(&mut self) -> BeanstalkdResult<Option<(u64, String)>> {
self.peek_cmd(commands::peek_ready())
}
/// Peeks the next delayed job
pub fn peek_delayed(&mut self) -> BeanstalkdResult<Option<(u64, String)>> {
self.peek_cmd(commands::peek_delayed())
}
/// Peeks the next buried job
pub fn peek_buried(&mut self) -> BeanstalkdResult<Option<(u64, String)>> {
self.peek_cmd(commands::peek_buried())
}
/// Delete all the jobs in the ready state
pub fn delete_all_ready(&mut self) -> BeanstalkdResult<()> {
self.delete_all_cmd(Self::peek_ready)
}
/// Delete all the jobs in the delayed state
pub fn delete_all_delayed(&mut self) -> BeanstalkdResult<()> {
self.delete_all_cmd(Self::peek_delayed)
}
/// Delete all the jobs in the buried state
pub fn delete_all_buried(&mut self) -> BeanstalkdResult<()> {
self.delete_all_cmd(Self::peek_buried)
}
/// Delete all jobs (in any state)
pub fn delete_all(&mut self) -> BeanstalkdResult<()> {
self.delete_all_ready()?;
self.delete_all_delayed()?;
self.delete_all_buried()?;
Ok(())
}
/// Returns:
/// - Ok(Some(_)) if a job is found
/// - Ok(None) if no job found
/// - Err(_) if an error occurred
fn peek_cmd(&mut self, message: String) -> BeanstalkdResult<Option<(u64, String)>> {
self.cmd(message)
.map(|r| {
if r.status == Status::NOT_FOUND {
None
}
else {
Some((parse::id(r.clone()), parse::body(r)))
}
})
}
fn delete_all_cmd<PeekFn>(&mut self, peek: PeekFn) -> BeanstalkdResult<()>
where PeekFn: Fn(&mut Self) -> BeanstalkdResult<Option<(u64, String)>>
{
loop {
match peek(self)? {
Some((job_id, _)) => self.delete(job_id)?,
None => return Ok(()),
}
}
}
fn cmd(&mut self, message: String) -> BeanstalkdResult<Response> {
let mut request = Request::new(&mut self.stream);
request.send(message.as_bytes())
}
}
|
use SafeWrapper;
use ir::{User, Instruction, Value};
use sys;
/// An instruction which can insert an element into a vector.
pub struct InsertElementInst<'ctx>(Instruction<'ctx>);
impl<'ctx> InsertElementInst<'ctx>
{
/// Creates a new insert element instruction.
pub fn new(vector: &Value,
new_element: &Value,
index: &Value) -> Self {
unsafe {
let inner = sys::LLVMRustCreateInsertElementInst(vector.inner(), new_element.inner(), index.inner());
wrap_value!(inner => User => Instruction => InsertElementInst)
}
}
}
impl_subtype!(InsertElementInst => Instruction);
|
fn main() {
println!("Hello, world!");
}
#[test]
fn offset_method(){
let s: &str = "Rust";
let ptr: *const u8 = s.as_ptr();
unsafe {
println!("{:?}", *ptr.offset(1) as char);
println!("{:?}", *ptr.offset(3) as char);
println!("{:?}", *ptr.offset(25) as char);
}
}
#[test]
fn read_write0(){
let x = "hello".to_string();
let y: *const u8 = x.as_ptr();
//调用x的as_ptr方法得到一个指向堆内存的原生指针,
// 因为String类型本质是一个字节序列数组, 所以该指针类型是*const u8, 指向第一个字节序列
unsafe {
println!("{:?}",y.read() as char);
//.read()方法是unsafe方法, read方法通过指针来读取当前指针指向的内存,
// 但不会转移所有权(也就是说在读完内存后,该内存有可能会被其他内容覆盖
assert_eq!(y.read() as char, 'h');
}
}
#[test]
fn read_write1(){
let x = [0,1,2,3];
let y = x[0..].as_ptr() as *const [u32;4]; //这里的原生指针类型是带长度的, 如果将类型改为*const [u32;3]则只能读到前3个值
unsafe {
assert_eq!(y.read(), [0,1,2,3]);
println!("{:?}",y.read());
}
}
#[test]
fn read_write2(){
let x = vec![0,1,2,3,4];
let y = &x as *const Vec<i32>; //这里直接将x的引用通过as操作符转换为原生指针
let z = &x;
unsafe {
println!("{:?}", z);
println!("{:?}", y);
println!("{:?}", y.read()); //这次调用read方法读出来的是全部元素
assert_eq!(y.read(), [0,1,2,3,4]);
//注意; 通过as_ptr得到的指针是字符串或数组内部的指向存放数据堆或栈内存的指针,而引用则是对字符串或数组本身的引用
}
}
#[test]
fn read_write3(){
let mut x = "";
let y = &mut x as *mut &str;
let z = "hello";
unsafe {
println!("{:?}", x);
println!("{:?}", y.read());
y.write(z);
println!("{:?}", y.read());
assert_eq!(y.read(), "hello");
}
}
#[test]
fn replace0(){
let mut v: Vec<i32> = vec![1,2,3];
let v_ptr: *mut i32 = v.as_mut_ptr();
unsafe {
let old_v = v_ptr.replace(5);
println!("{:?}",v);
assert_eq!(1,old_v);
assert_eq!([5,2,3], &v[..]);//v是vec, 所以在比较的时候要对其中一个转换成和另一个一样的类型
assert_eq!([5,2,3].to_vec(), v); //v是vec, 所以在比较的时候要对其中一个转换成和另一个一样的类型
}
}
#[test]
fn replace1(){
let mut v: Vec<i32> = vec![1,2,3];
let v_ptr = &mut v as *mut Vec<i32>; //这里只是将v的可变引用转换成了可变原生指针, 该指针指向数组的全部元素
unsafe {
let old_v = v_ptr.replace(vec![4,5,6,7]);
println!("{:?}",v);
assert_eq!([1,2,3],&old_v[..]);
assert_eq!([4,5,6,7], &v[..]);//v是vec, 所以在比较的时候要对其中一个转换成和另一个一样的类型
assert_eq!([4,5,6,7].to_vec(), v); //v是vec, 所以在比较的时候要对其中一个转换成和另一个一样的类型
}
}
#[test]
fn swap0(){
let mut array = [0,1,2,3];
let x = array[0..].as_mut_ptr() as *mut [u32;2];
let y = array[1..].as_mut_ptr() as *mut [u32;2];
unsafe {
assert_eq!([0,1], x.read());
assert_eq!([1,2],y.read());
x.swap(y);
assert_eq!([1,0,1,3],array);
}
}
fn foo<'a>(input: *const u32)->&'a u32{ //input为原生指针*const u32类型, 然后通过解引用原生指针和引用符号将其转为引用
unsafe {
println!("{:?}",*input);
return &*input; //&*input相当于&(*input)
}
}
#[test]
fn unbound_lifetime(){
let x;
{
let y = 42;
x = foo(&y); //如果在safe rust中, 这里返回的是对y的引用
}
println!("Hello: {}",x); //离开作用域后y已经被丢弃, 所以x是悬垂指针, 但是在这里可以正常编译 因为经过foo函数产生了一个未绑定生命周期的借用,所以跳过了rust的借用检查
}
// fn longer_wrong(s1: &str, s2: &str) -> &str {
// if s2.len() > s1.len() {
// s2
// } else {
// s1
// }
// }
fn longer<'a>(s1: &'a str, s2: &'a str) -> &'a str {
if s2.len() > s1.len() {
s2
} else {
s1
}
}
#[test]
fn lifetime(){
let s1 = "ecmascript";
let r;
{
let s2 = "rust";
r = longer(s1, s2);
}
println!("{} is longer", r);
}
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
#[test]
fn lifetime2(){ //&str能够运行, string::from不行
let string1 = "long string is long";
let result;
{
let string2 = "xyz";
result = longest(string1, string2);
}
println!("The longest string is {}", result);
}
#[test]
fn test_t(){ //&str能够运行, string::from不行
for current_start in 0..100{
let lowbit = if current_start > 0 {
current_start & (!current_start + 1)
} else {
32
};
println!("{:b} {:b}",current_start,lowbit);
}
}
|
mod ghash;
mod hmac;
mod poly1305;
mod polyval;
pub use self::ghash::GHash;
pub use self::hmac::*;
pub use self::poly1305::Poly1305;
pub use self::polyval::Polyval;
#[cfg(test)]
#[bench]
fn bench_poly1305(b: &mut test::Bencher) {
let key = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
0x1e, 0x1f,
];
let message = test::black_box([128u8; Poly1305::BLOCK_LEN]);
let mut poly1305 = Poly1305::new(&key);
b.bytes = Poly1305::BLOCK_LEN as u64;
b.iter(|| poly1305.update(&message))
}
#[cfg(test)]
#[bench]
fn bench_polyval(b: &mut test::Bencher) {
let key = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f,
];
let message = test::black_box([128u8; Polyval::BLOCK_LEN]);
let mut polyval = Polyval::new(&key);
b.bytes = Polyval::BLOCK_LEN as u64;
b.iter(|| polyval.update(&message))
}
#[cfg(test)]
#[bench]
fn bench_ghash(b: &mut test::Bencher) {
let key = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f,
];
let message = test::black_box([128u8; GHash::BLOCK_LEN]);
let mut ghash = GHash::new(&key);
b.bytes = GHash::BLOCK_LEN as u64;
b.iter(|| ghash.update(&message))
}
|
// https://www.codewars.com/kata/56445c4755d0e45b8c00010a
fn fortune(f0: i32, p: f64, c0: i32, n: i32, i: f64) -> bool {
let mut money: i64 = f0.into();
let mut cost: i64 = c0.into();
for _ in 0..n {
money += (p / 100.0 * money as f64) as i64 - cost;
if money <= 0 { return false; }
cost += (i / 100.0 * cost as f64) as i64;
}
true
}
#[cfg(test)]
mod tests {
use super::*;
fn testequal(f0: i32, p: f64, c0: i32, n: i32, i: f64, exp: bool) -> () {
assert_eq!(exp, fortune(f0, p, c0, n, i))
}
#[test]
fn basics() {
testequal(100000, 1.0, 2000, 15, 1.0, true);
testequal(100000, 1.0, 9185, 12, 1.0, false);
testequal(100000000, 1.0, 100000, 50, 1.0, true);
testequal(100000000, 1.5, 10000000, 50, 1.0, false);
}
}
|
//!
//! Data Constistency Guarantee Methods.
//!
//! These are designed to provide the same interface than the client, wrapping around it and providing the same
//! interface `ClientTrait`.
//!
mod file;
use std::fmt::Debug;
pub use file::FileBacklog;
use crate::Record;
use crate::InfluxResult;
/// API definition that any backlog service needs to abide by so the [Client](struct.Client.html) can use it.
pub trait Backlog: Debug + Send + Sync
{
/// Return any pending records that sits in backlog and requires to be commited.
fn read_pending(&mut self) -> InfluxResult<Vec<Record>>;
/// Write records that could not be commited, so they get written into backlog for future processing.
fn write_pending(&mut self, record: &Record) -> InfluxResult<()>;
/// Empty backlog from pending records. This gets called once all pending records have been
/// successfully commited.
fn truncate_pending(&mut self, record: &Record) -> InfluxResult<()>;
}
/// Backlog that does nothing
#[derive(Debug)]
pub struct NoopBacklog;
impl NoopBacklog
{
/// Construct this dummy backlog that does nothing
pub fn new() -> Self
{
Self {}
}
}
impl Backlog for NoopBacklog
{
fn read_pending(&mut self) -> InfluxResult<Vec<Record>> {
Ok(Vec::new())
}
fn write_pending(&mut self, _: &Record) -> InfluxResult<()> {
Ok(())
}
fn truncate_pending(&mut self, _: &Record) -> InfluxResult<()> {
Ok(())
}
}
|
use iron::prelude::*;
use iron::status;
use iron_sessionstorage::SessionRequestExt;
use router::Router;
use mount::Mount;
use params;
use params::FromValue;
use std::str::FromStr;
use auth::SessionData;
use middleware::DatabaseExt;
use models::*;
use repo;
macro_rules! require_login {
($req:ident) => {
match $req.session().get::<SessionData>().unwrap() {
Some(user) => user,
None => return Ok(Response::with((status::Forbidden, "Login required")))
}
}
}
fn get_param<T: FromValue>(name: &str, req: &mut Request) -> Option<T> {
req.get_ref::<params::Params>().unwrap()
.find(&[name])
.and_then(|v| T::from_value(v))
}
fn get_segment<T: FromStr>(name: &str, req: &Request) -> Result<T, T::Err> {
req.extensions.get::<Router>().unwrap()[name].parse::<T>()
}
pub fn create() -> Mount {
let mut mount = Mount::new();
mount.mount("/threads", thread());
mount.mount("/users", user());
mount
}
fn thread() -> Router {
let mut router = Router::new();
router.get("/", |req: &mut Request| {
let xs = itry!(repo::thread::list(&req.db_conn()));
let response = ApiResponse::json(ApiData::Threads(xs));
Ok(Response::with((status::Ok, response)))
}, "thread_list");
router.post("/", |req: &mut Request| {
require_login!(req);
let p_slug = iexpect!(get_param("slug", req), (status::BadRequest, "missing slug"));
let t = itry!(repo::thread::create(p_slug, req.db_conn()));
let res = ApiResponse::json(ApiData::ThreadCreated(t));
Ok(Response::with((status::Created, res)))
}, "thread_create");
router.get("/:id", |req: &mut Request| {
let db = req.db_conn();
let thread_id = itry!(get_segment::<i32>("id", req), status::NotFound);
let thread = itry!(repo::thread::find_by_id(thread_id, db), status::NotFound);
let comments = itry!(repo::thread::list_comments(thread_id, db));
let response = ApiResponse::json(ApiData::ThreadShow { thread: thread, comments: comments });
Ok(Response::with((status::Ok, response)))
}, "thread_show");
router.post("/:id", |req: &mut Request| {
let session = require_login!(req);
let thread_id = itry!(get_segment::<i32>("id", req), status::NotFound);
let content = iexpect!(get_param::<String>("content", req), (status::BadRequest, "missing content"));
if content.is_empty() {
return Ok(Response::with((status::BadRequest, "content is blank")));
}
let db = req.db_conn();
// Check if thread exists, first
let _ = itry!(repo::thread::find_by_id(thread_id, db), status::NotFound);
let comment = itry!(repo::thread::comment_post(thread_id, session.user_id, content, db));
let response = ApiResponse::json(ApiData::CommentPost(comment));
Ok(Response::with((status::Ok, response)))
}, "thread_comment_post");
router
}
fn user() -> Router {
let mut router = Router::new();
router.get("/", |req: &mut Request| {
let xs = itry!(repo::user::list(req.db_conn()));
let response = ApiResponse::json(ApiData::Users(xs));
Ok(Response::with((status::Ok, response)))
}, "user_list");
router.get("/testLogin", |req: &mut Request| {
let sd = require_login!(req);
Ok(Response::with((status::Ok, format!("id: {}", sd.user_id))))
}, "user_testlogin");
router.get("/register", |req: &mut Request| {
req.session().clear().expect("Failed to clear session");
let name = get_param::<String>("username", req);
let name = iexpect!(name, (status::BadRequest, "missing username parameter"));
let user = itry!(repo::user::register(name, req.db_conn()));
req.session().set(SessionData::new(user.id)).unwrap();
let response = ApiResponse::json(ApiData::UserCreated(user));
Ok(Response::with((status::Created, response)))
}, "user_register");
router.get("/login", |req: &mut Request| {
let uid = iexpect!(get_param::<i32>("id", req), (status::BadRequest, "missing id"));
let user = itry!(repo::user::find_by_id(uid, req.db_conn()), status::NotFound);
req.session().set(SessionData::new(uid)).unwrap();
let response = ApiResponse::json(ApiData::UserLoggedIn(user));
Ok(Response::with((status::Ok, response)))
}, "user_login");
router.get("/logout", |req: &mut Request| {
require_login!(req);
try!(req.session().clear());
Ok(Response::with((status::Ok, "logged out")))
}, "user_logout");
router
}
|
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("devinez le nombre!");
let nombre_secret = rand::thread_rng().gen_range(1, 101);
loop {
println!("Veuillez entrer un nombre");
let mut supposition = String::new();
io::stdin().read_line(&mut supposition)
.expect("Echec de la lecture de l'entrée utilisateur");
let supposition: u32 = match supposition.trim().parse() {
Ok(nombre) => nombre,
Err(_) => continue,
};
println!("Votre nombre : {}", supposition);
match supposition.cmp(&nombre_secret) {
Ordering::Less => println!("c'est plus!"),
Ordering::Greater => println!("C'est moins!"),
Ordering::Equal => {
println!("Bravo! Vous avez deviné");
break;
}
}
}
}
|
fn main() {
let x = 9;
if x {
println!("bigger: {}", x);
} else {
println!("less: {}", x);
}
}
|
fn main() {
println!("Hello, world!");
}
// this function can be accessed from Javascript (no_mangle)
#[no_mangle]
pub extern "C" fn add_one(x: i32) -> i32 {
x + 1
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.