text stringlengths 8 4.13M |
|---|
extern crate lazy_static;
pub mod log;
pub mod stream;
pub mod ui;
|
//
use std::fmt;
use vec3::*;
#[derive(Copy, Clone, Debug)]
pub struct Ray {
a: Vec3,
b: Vec3,
}
impl Ray {
pub fn new(ia: Vec3, ib: Vec3) -> Ray { Ray { a:ia, b:ib } }
pub fn origin(&self) -> Vec3 { self.a }
pub fn direction(&self) -> Vec3 { self.b }
pub fn point_at_parameter(&self, t: f32) -> Vec3 { self.a + t*self.b }
}
impl fmt::Display for Ray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Ray(origin={}, directon={})", self.a, self.b)
}
}
|
use crate::prelude::*;
use byteorder::{LittleEndian, ReadBytesExt};
pub struct X11 {
pub conn: xcb::Connection,
pub preferred_screen: i32,
}
impl X11 {
pub fn connect() -> Self {
let (conn, preferred_screen) = xcb::Connection::connect(None)
.expect("Could not connect to X server");
Self {
conn,
preferred_screen,
}
}
pub fn create_atom(&self, atom_name: &str) -> Option<xcb::Atom> {
let net_wm_name_atom_cookie =
xcb::intern_atom(&self.conn, false, atom_name);
net_wm_name_atom_cookie
.get_reply()
.ok()
.map(|rep| rep.atom())
}
pub fn get_root_win(&self) -> Option<xcb::Window> {
let setup: xcb::Setup = self.conn.get_setup();
let mut roots: xcb::ScreenIterator = setup.roots();
let preferred_screen_pos = usize::try_from(self.preferred_screen)
.expect("x11 preferred_screen is not positive");
roots.nth(preferred_screen_pos).map(|screen| screen.root())
}
pub fn get_win_prop(
&self,
win: xcb::Window,
atom: xcb::Atom,
) -> Option<xcb::Window> {
let reply = xcb::get_property(
&self.conn,
false,
win,
atom,
xcb::ATOM_WINDOW,
0,
1,
)
.get_reply()
.ok()?;
// No value available, or the value is more than 1 (which is unexpected).
if reply.value_len() != 1 {
return None;
}
let mut raw = reply.value();
// Window properties are expected to be 4 bytes.
if raw.len() != 4 {
return None;
}
let window = raw.read_u32::<LittleEndian>().unwrap() as xcb::Window;
if window == xcb::WINDOW_NONE {
None
} else {
Some(window)
}
}
}
|
#[cfg(test)]
mod tests {
use lib::get_missing_number;
#[test]
fn test_get_missing_number() {
let array: [u32; 4] = [4, 2, 1, 5];
assert_eq!(get_missing_number(&array), 3);
}
}
|
mod sequential_allocation;
use std::cmp::Ordering;
#[derive(Debug,PartialEq)]
pub enum LinearListError {
OutOfRange,
MemoryOverflow,
}
pub type LinearListResult<T> = Result<T, LinearListError>;
trait LinearList {
type Item;
fn length(&self) -> usize;
fn get(&self, pos: usize) -> Option<&Self::Item>;
fn get_mut(&mut self, pos: usize) -> Option<&mut Self::Item>;
fn insert_before(&mut self, pos: usize, item: Self::Item) -> LinearListResult<()>;
fn delete(&mut self, pos: usize) -> LinearListResult<Self::Item>;
fn insert_after(&mut self, pos: usize, item: Self::Item) -> LinearListResult<()> {
self.insert_before(pos + 1, item)
}
fn combine<T>(&mut self, mut other: T) where T: LinearList<Item=Self::Item> {
while let Ok(item) = other.delete(0) { // Take the first item in other
let len = self.length(); // And push it back in self
self.insert_before(len, item).unwrap();
}
}
fn combine_all<T>(&mut self, others: Vec<T>) where T: LinearList<Item=Self::Item>, T: Sized {
for list in others {
self.combine(list);
}
}
fn clone(&self) -> Self where Self::Item: Clone, Self: Default {
let mut new_list = Self::default();
for i in 0..self.length() {
new_list.insert_before(i, self.get(i).unwrap().clone()).unwrap();
}
new_list
}
fn clone_combine<T>(&mut self, other: &T) where T: LinearList<Item=Self::Item>, Self::Item: Clone {
for i in 0..other.length() {
let item = other.get(i).unwrap(); // Take the current item in other
let len = self.length(); // And push it back in self
self.insert_before(len, item.clone()).unwrap();
}
}
fn clone_combine_all<T>(&mut self, others: &[T]) where T: LinearList<Item=Self::Item>, T: Sized, Self::Item: Clone {
for list in others {
self.clone_combine(list);
}
}
fn sort(&mut self) where Self::Item: Ord {
let mut sorted = false;
while !sorted {
sorted = true;
let i_iter = 0..self.length();
let j_iter = i_iter.clone().skip(1);
for (i, j) in i_iter.zip(j_iter) {
let a : *mut _ = self.get_mut(i).unwrap();
let b : *mut _ = self.get_mut(j).unwrap();
if unsafe { *a > *b } {
sorted = false;
unsafe {
::std::ptr::swap(a, b);
}
}
}
}
}
fn sort_by<F>(&mut self, compare: F) where F: Fn(&Self::Item, &Self::Item) -> Ordering {
let mut sorted = false;
while !sorted {
sorted = true;
let i_iter = 0..self.length();
let j_iter = i_iter.clone().skip(1);
for (i, j) in i_iter.zip(j_iter) {
let a : *mut _ = self.get_mut(i).unwrap();
let b : *mut _ = self.get_mut(j).unwrap();
match compare(unsafe { &*a }, unsafe { &*b }) {
Ordering::Greater => {
sorted = false;
unsafe {
::std::ptr::swap(a, b);
}
},
_ => ()
}
}
}
}
fn search_by<P>(&self, predicate: P) -> Option<&Self::Item> where P: Fn(&Self::Item) -> bool {
for i in 0..self.length() {
let item = self.get(i).unwrap();
if predicate(item) {
return Some(item);
}
}
None
}
} |
//! Allocator logging.
//!
//! This allows for detailed logging for `ralloc`.
/// Log to the appropriate source.
///
/// The first argument defines the log level, the rest of the arguments are just `write!`-like
/// formatters.
#[macro_export]
macro_rules! log {
(INTERNAL, $( $x:tt )*) => {
log!(@["INTERNAL: ", 1], $( $x )*);
};
(DEBUG, $( $x:tt )*) => {
log!(@["DEBUG: ", 2], $( $x )*);
};
(CALL, $( $x:tt )*) => {
log!(@["CALL: ", 3], $( $x )*);
};
(NOTE, $( $x:tt )*) => {
log!(@["NOTE: ", 5], $( $x )*);
};
(WARNING, $( $x:tt )*) => {
log!(@["WARNING: ", 5], $( $x )*);
};
(ERROR, $( $x:tt )*) => {
log!(@["ERROR: ", 6], $( $x )*);
};
(@[$kind:expr, $lv:expr], $( $arg:expr ),*) => {
#[cfg(feature = "log")]
{
use core::fmt::Write;
use log::internal::{LogWriter, level};
// Set the level.
if level($lv) {
// Print the pool state.
let mut log = LogWriter::new();
// Print the log message.
let _ = write!(log, $kind);
let _ = write!(log, $( $arg ),*);
let _ = writeln!(log, " (at {}:{})", file!(), line!());
}
}
};
}
/// Log with bookkeeper data to the appropriate source.
///
/// The first argument this takes is of the form `pool;cursor`, which is used to print the
/// block pools state. `cursor` is what the operation "revolves around" to give a sense of
/// position.
///
/// If the `;cursor` part is left out, no cursor will be printed.
///
/// The rest of the arguments are just normal formatters.
///
/// This logs to level 2.
#[macro_export]
macro_rules! bk_log {
($pool:expr, $( $arg:expr ),*) => {
bk_log!($pool;(), $( $arg ),*);
};
($bk:expr;$cur:expr, $( $arg:expr ),*) => {
#[cfg(feature = "log")]
{
use log::internal::{IntoCursor, BlockLogger};
log!(INTERNAL, "({:2}) {:10?} : {}", $bk.id, BlockLogger {
cur: $cur.clone().into_cursor(),
blocks: &$bk.pool,
}, format_args!($( $arg ),*));
}
};
}
/// Make a runtime assertion.
///
/// The only way it differs from the one provided by `libcore` is the panicking strategy, which
/// allows for aborting, non-allocating panics when running the tests.
#[macro_export]
#[cfg(feature = "write")]
macro_rules! assert {
($e:expr) => {
assert!($e, "No description.");
};
($e:expr, $( $arg:expr ),*) => {{
use core::intrinsics;
if !$e {
log!(ERROR, $( $arg ),*);
#[allow(unused_unsafe)]
unsafe {
// LAST AUDIT: 2016-08-21 (Ticki).
// Right now there is no safe interface exposed for this, but it is safe no matter
// what.
intrinsics::abort();
}
}
}}
}
/// Make a runtime assertion in debug mode.
///
/// The only way it differs from the one provided by `libcore` is the panicking strategy, which
/// allows for aborting, non-allocating panics when running the tests.
#[cfg(feature = "write")]
#[macro_export]
macro_rules! debug_assert {
// We force the programmer to provide explanation of their assertion.
($first:expr, $( $arg:tt )*) => {{
if cfg!(debug_assertions) {
assert!($first, $( $arg )*);
}
}}
}
/// Make a runtime equality assertion in debug mode.
///
/// The only way it differs from the one provided by `libcore` is the panicking strategy, which
/// allows for aborting, non-allocating panics when running the tests.
#[cfg(feature = "write")]
#[macro_export]
macro_rules! assert_eq {
($left:expr, $right:expr) => ({
// We evaluate _once_.
let left = &$left;
let right = &$right;
assert!(left == right, "(left: '{:?}', right: '{:?}')", left, right)
})
}
/// Top-secret module.
#[cfg(feature = "log")]
pub mod internal {
use prelude::*;
use core::fmt;
use core::cell::Cell;
use core::ops::Range;
use shim::config;
use sync;
/// The log lock.
///
/// This lock is used to avoid bungling and intertwining the log.
#[cfg(not(feature = "no_log_lock"))]
pub static LOG_LOCK: Mutex<()> = Mutex::new(());
/// A log writer.
///
/// This writes to the shim logger.
pub struct LogWriter {
/// The inner lock.
#[cfg(not(feature = "no_log_lock"))]
_lock: sync::MutexGuard<'static, ()>,
}
impl LogWriter {
/// Standard error output.
pub fn new() -> LogWriter {
#[cfg(feature = "no_log_lock")]
{
LogWriter {}
}
#[cfg(not(feature = "no_log_lock"))]
LogWriter {
_lock: LOG_LOCK.lock(),
}
}
}
impl fmt::Write for LogWriter {
fn write_str(&mut self, s: &str) -> fmt::Result {
if config::log(s) == !0 { Err(fmt::Error) } else { Ok(()) }
}
}
/// A "cursor".
///
/// Cursors represents a block or an interval in the log output. This trait is implemented for
/// various types that can represent a cursor.
pub trait Cursor {
/// Iteration at n.
///
/// This is called in the logging loop. The cursor should then write, what it needs, to the
/// formatter if the underlying condition is true.
///
/// For example, a plain position cursor will write `"|"` when `n == self.pos`.
// TODO: Use an iterator instead.
fn at(&self, f: &mut fmt::Formatter, n: usize) -> fmt::Result;
/// The after hook.
///
/// This is runned when the loop is over. The aim is to e.g. catch up if the cursor wasn't
/// printed (i.e. is out of range).
fn after(&self, f: &mut fmt::Formatter) -> fmt::Result;
}
/// Types that can be converted into a cursor.
pub trait IntoCursor {
/// The end result.
type Cursor: Cursor;
/// Convert this value into its equivalent cursor.
fn into_cursor(self) -> Self::Cursor;
}
/// A single-point cursor.
pub struct UniCursor {
/// The position where this cursor will be placed.
pos: usize,
/// Is this cursor printed?
///
/// This is used for the after hook.
is_printed: Cell<bool>,
}
impl Cursor for UniCursor {
fn at(&self, f: &mut fmt::Formatter, n: usize) -> fmt::Result {
if self.pos == n {
self.is_printed.set(true);
write!(f, "|")?;
}
Ok(())
}
fn after(&self, f: &mut fmt::Formatter) -> fmt::Result {
if !self.is_printed.get() {
write!(f, "…|")?;
}
Ok(())
}
}
impl IntoCursor for usize {
type Cursor = UniCursor;
fn into_cursor(self) -> UniCursor {
UniCursor {
pos: self,
is_printed: Cell::new(false),
}
}
}
impl Cursor for () {
fn at(&self, _: &mut fmt::Formatter, _: usize) -> fmt::Result { Ok(()) }
fn after(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
}
impl IntoCursor for () {
type Cursor = ();
fn into_cursor(self) -> () {
()
}
}
/// A interval/range cursor.
///
/// The start of the range is marked by `[` and the end by `]`.
pub struct RangeCursor {
/// The range of this cursor.
range: Range<usize>,
}
impl Cursor for RangeCursor {
fn at(&self, f: &mut fmt::Formatter, n: usize) -> fmt::Result {
if self.range.start == n {
write!(f, "[")?;
} else if self.range.end == n {
write!(f, "]")?;
}
Ok(())
}
fn after(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
}
impl IntoCursor for Range<usize> {
type Cursor = RangeCursor;
fn into_cursor(self) -> RangeCursor {
RangeCursor {
range: self,
}
}
}
/// A "block logger".
///
/// This intend to show the structure of a block pool. The syntax used is like:
///
/// ```
/// xxx__|xx_
/// ```
///
/// where `x` denotes an non-empty block. `_` denotes an empty block, with `|` representing the
/// cursor.
pub struct BlockLogger<'a, T> {
/// The cursor.
///
/// This is where the `|` will be printed.
pub cur: T,
/// The blocks.
pub blocks: &'a [Block],
}
impl<'a, T: Cursor> fmt::Debug for BlockLogger<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO: Handle alignment etc.
for (n, i) in self.blocks.iter().enumerate() {
self.cur.at(f, n)?;
if i.is_empty() {
// Empty block.
write!(f, "_")?;
} else {
// Non-empty block.
write!(f, "x")?;
}
}
self.cur.after(f)?;
Ok(())
}
}
/// Check if this log level is enabled.
#[allow(absurd_extreme_comparisons)]
#[inline]
pub fn level(lv: u8) -> bool {
lv >= config::MIN_LOG_LEVEL
}
}
|
use wasm_bindgen::prelude::*;
#[wasm_bindgen(module = "/src/imports.js")]
extern {
#[wasm_bindgen]
pub fn log(s: &str);
#[wasm_bindgen]
pub fn now() -> f64;
}
#[wasm_bindgen]
pub fn demo_main(n: u64) -> u64 {
let start = now();
let mut gen = PrimeGenerator::new();
let res = gen.nearest_prime(n);
let end = now();
log(&format!("elapsed time: {} ms", end - start));
return res;
}
struct PrimeGenerator {
primes: Vec<u64>,
last: u64,
}
impl PrimeGenerator {
pub fn new() -> Self {
let primes = vec![2, 3];
Self {
primes,
last: 3,
}
}
pub fn nearest_prime(&mut self, n: u64) -> u64 {
while self.last < n {
self.next();
}
let idx = self.primes.binary_search(&n).unwrap_or_else(|i| i - 1);
self.primes[idx]
}
fn is_prime(&self, x: u64) -> bool {
for p in &self.primes {
if x % p == 0 { return false };
}
true
}
}
impl Iterator for PrimeGenerator {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
let mut x = self.last;
while !self.is_prime(x) {
x += 2;
}
self.last = x;
self.primes.push(x);
Some(x)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nearest_primes_is_correct() {
let mut gen = PrimeGenerator::new();
let p = gen.nearest_prime(100);
assert_eq!(p, 97);
}
#[test]
fn nearest_prime_can_return_n() {
let mut gen = PrimeGenerator::new();
let p = gen.nearest_prime(101);
assert_eq!(p, 101);
}
}
|
use lib::*;
/// Param type subset generatable by WASM contract
#[derive(Debug, Clone)]
pub enum ParamType {
// Unsigned integer (mapped from u32)
U32,
// Unsigned integer (mapped from u64)
U64,
// Signed integer (mapped from i32)
I32,
// Signed integer (mapped from i64)
I64,
// Address (mapped from H160/Address)
Address,
// 256-bit unsigned integer (mapped from U256)
U256,
// 256-bit hash (mapped from H256)
H256,
// Byte array (mapped from Vec<u8>)
Bytes,
// Variable-length array (mapped from Vec<T>)
Array(ArrayRef),
// Boolean (mapped from bool)
Bool,
// String (mapped from String/str)
String,
}
impl ParamType {
pub fn to_member(&self, s: &mut String) {
match *self {
ParamType::I32 => s.push_str("int32"),
ParamType::U32 => s.push_str("uint32"),
ParamType::I64 => s.push_str("int64"),
ParamType::U64 => s.push_str("uint64"),
ParamType::Address => s.push_str("address"),
ParamType::U256 => s.push_str("uint256"),
ParamType::H256 => s.push_str("uint256"),
ParamType::Bytes => s.push_str("bytes"),
ParamType::Bool => s.push_str("bool"),
ParamType::String => s.push_str("string"),
ParamType::Array(ref p_n) => { p_n.as_ref().to_member(s); s.push_str("[]"); },
}
}
}
#[derive(Debug, Clone)]
pub enum ArrayRef {
Owned(Box<ParamType>),
Static(&'static ParamType),
}
impl ArrayRef {
pub fn as_ref(&self) -> &ParamType {
match *self {
ArrayRef::Owned(ref p) => p.as_ref(),
ArrayRef::Static(p) => p,
}
}
}
impl From<ParamType> for ArrayRef {
fn from(p: ParamType) -> Self {
ArrayRef::Owned(Box::new(p))
}
} |
struct SomeStruct;
fn uses_it(arg: &SomeStruct) {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1() {
let val = SomeStruct;
uses_it(&val);
}
}
|
//! Traits for abstracting over different Ethereum 2.0 network protocols.
//!
//! Currently only [`BeaconBlock`]s and beacon [`Attestation`]s can be gossiped, because those are
//! the only types of objects supported by Hobbits. Methods for [other types of objects] will be
//! added later.
//!
//! [`Attestation`]: types::types::Attestation
//! [`BeaconBlock`]: types::types::BeaconBlock
//!
//! [other types of objects]: https://github.com/ethereum/eth2.0-specs/blob/1f3a5b156f7a0e7616f7c8bc31e27fa4da392139/specs/networking/p2p-interface.md#message
use anyhow::Result;
use types::{
config::Config,
primitives::{Epoch, Slot, Version, H256},
types::{Attestation, BeaconBlock},
};
#[derive(Clone, Copy, Debug)]
pub struct Status {
pub fork_version: Version,
pub finalized_root: H256,
pub finalized_epoch: Epoch,
pub head_root: H256,
pub head_slot: Slot,
}
pub trait Network<C: Config> {
fn publish_beacon_block(&self, beacon_block: BeaconBlock<C>) -> Result<()>;
fn publish_beacon_attestation(&self, attestation: Attestation<C>) -> Result<()>;
}
pub trait Networked<C: Config>: 'static {
fn accept_beacon_block(&mut self, beacon_block: BeaconBlock<C>) -> Result<()>;
fn accept_beacon_attestation(&mut self, attestation: Attestation<C>) -> Result<()>;
fn get_status(&self) -> Status;
fn get_beacon_block(&self, root: H256) -> Option<&BeaconBlock<C>>;
}
|
#[doc = "Register `ICR` writer"]
pub type W = crate::W<ICR_SPEC>;
#[doc = "Field `SEIF` writer - SEIF"]
pub type SEIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `XONEIF` writer - Execute-only execute-Never Error Interrupt Flag clear"]
pub type XONEIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `KEIF` writer - KEIF"]
pub type KEIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl W {
#[doc = "Bit 0 - SEIF"]
#[inline(always)]
#[must_use]
pub fn seif(&mut self) -> SEIF_W<ICR_SPEC, 0> {
SEIF_W::new(self)
}
#[doc = "Bit 1 - Execute-only execute-Never Error Interrupt Flag clear"]
#[inline(always)]
#[must_use]
pub fn xoneif(&mut self) -> XONEIF_W<ICR_SPEC, 1> {
XONEIF_W::new(self)
}
#[doc = "Bit 2 - KEIF"]
#[inline(always)]
#[must_use]
pub fn keif(&mut self) -> KEIF_W<ICR_SPEC, 2> {
KEIF_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 = "OTFDEC interrupt clear register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`icr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ICR_SPEC;
impl crate::RegisterSpec for ICR_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`icr::W`](W) writer structure"]
impl crate::Writable for ICR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets ICR to value 0"]
impl crate::Resettable for ICR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
pub mod cr {
pub mod en1 {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40007400u32 as *const u32) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFFFFFEu32;
reg |= val & 0x1;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod boff1 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 1) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFFFFFDu32;
reg |= (val & 0x1) << 1;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod ten1 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 2) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFFFFFBu32;
reg |= (val & 0x1) << 2;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod tsel1 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 3) & 0x7
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFFFFC7u32;
reg |= (val & 0x7) << 3;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod wave1 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 6) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFFFF3Fu32;
reg |= (val & 0x3) << 6;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod mamp1 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 8) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFFF0FFu32;
reg |= (val & 0xF) << 8;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod dmaen1 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 12) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFFEFFFu32;
reg |= (val & 0x1) << 12;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod en2 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 16) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFEFFFFu32;
reg |= (val & 0x1) << 16;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod boff2 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 17) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFDFFFFu32;
reg |= (val & 0x1) << 17;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod ten2 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 18) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFFBFFFFu32;
reg |= (val & 0x1) << 18;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod tsel2 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 19) & 0x7
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFFC7FFFFu32;
reg |= (val & 0x7) << 19;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod wave2 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 22) & 0x3
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xFF3FFFFFu32;
reg |= (val & 0x3) << 22;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod mamp2 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 24) & 0xF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xF0FFFFFFu32;
reg |= (val & 0xF) << 24;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
pub mod dmaen2 {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007400u32 as *const u32) >> 28) & 0x1
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007400u32 as *const u32);
reg &= 0xEFFFFFFFu32;
reg |= (val & 0x1) << 28;
core::ptr::write_volatile(0x40007400u32 as *mut u32, reg);
}
}
}
}
pub mod swtrigr {
pub mod swtrig1 {
pub fn set(val: u32) {
unsafe {
let reg = val & 0x1;
core::ptr::write_volatile(0x40007404u32 as *mut u32, reg);
}
}
}
pub mod swtrig2 {
pub fn set(val: u32) {
unsafe {
let reg = (val & 0x1) << 1;
core::ptr::write_volatile(0x40007404u32 as *mut u32, reg);
}
}
}
}
pub mod dhr12r1 {
pub mod dacc1dhr {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40007408u32 as *const u32) & 0xFFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007408u32 as *const u32);
reg &= 0xFFFFF000u32;
reg |= val & 0xFFF;
core::ptr::write_volatile(0x40007408u32 as *mut u32, reg);
}
}
}
}
pub mod dhr12l1 {
pub mod dacc1dhr {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x4000740Cu32 as *const u32) >> 4) & 0xFFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x4000740Cu32 as *const u32);
reg &= 0xFFFF000Fu32;
reg |= (val & 0xFFF) << 4;
core::ptr::write_volatile(0x4000740Cu32 as *mut u32, reg);
}
}
}
}
pub mod dhr8r1 {
pub mod dacc1dhr {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40007410u32 as *const u32) & 0xFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007410u32 as *const u32);
reg &= 0xFFFFFF00u32;
reg |= val & 0xFF;
core::ptr::write_volatile(0x40007410u32 as *mut u32, reg);
}
}
}
}
pub mod dhr12r2 {
pub mod dacc2dhr {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40007414u32 as *const u32) & 0xFFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007414u32 as *const u32);
reg &= 0xFFFFF000u32;
reg |= val & 0xFFF;
core::ptr::write_volatile(0x40007414u32 as *mut u32, reg);
}
}
}
}
pub mod dhr12l2 {
pub mod dacc2dhr {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007418u32 as *const u32) >> 4) & 0xFFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007418u32 as *const u32);
reg &= 0xFFFF000Fu32;
reg |= (val & 0xFFF) << 4;
core::ptr::write_volatile(0x40007418u32 as *mut u32, reg);
}
}
}
}
pub mod dhr8r2 {
pub mod dacc2dhr {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x4000741Cu32 as *const u32) & 0xFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x4000741Cu32 as *const u32);
reg &= 0xFFFFFF00u32;
reg |= val & 0xFF;
core::ptr::write_volatile(0x4000741Cu32 as *mut u32, reg);
}
}
}
}
pub mod dhr12rd {
pub mod dacc1dhr {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40007420u32 as *const u32) & 0xFFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007420u32 as *const u32);
reg &= 0xFFFFF000u32;
reg |= val & 0xFFF;
core::ptr::write_volatile(0x40007420u32 as *mut u32, reg);
}
}
}
pub mod dacc2dhr {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007420u32 as *const u32) >> 16) & 0xFFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007420u32 as *const u32);
reg &= 0xF000FFFFu32;
reg |= (val & 0xFFF) << 16;
core::ptr::write_volatile(0x40007420u32 as *mut u32, reg);
}
}
}
}
pub mod dhr12ld {
pub mod dacc1dhr {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007424u32 as *const u32) >> 4) & 0xFFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007424u32 as *const u32);
reg &= 0xFFFF000Fu32;
reg |= (val & 0xFFF) << 4;
core::ptr::write_volatile(0x40007424u32 as *mut u32, reg);
}
}
}
pub mod dacc2dhr {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007424u32 as *const u32) >> 20) & 0xFFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007424u32 as *const u32);
reg &= 0xFFFFFu32;
reg |= (val & 0xFFF) << 20;
core::ptr::write_volatile(0x40007424u32 as *mut u32, reg);
}
}
}
}
pub mod dhr8rd {
pub mod dacc1dhr {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40007428u32 as *const u32) & 0xFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007428u32 as *const u32);
reg &= 0xFFFFFF00u32;
reg |= val & 0xFF;
core::ptr::write_volatile(0x40007428u32 as *mut u32, reg);
}
}
}
pub mod dacc2dhr {
pub fn get() -> u32 {
unsafe {
(core::ptr::read_volatile(0x40007428u32 as *const u32) >> 8) & 0xFF
}
}
pub fn set(val: u32) {
unsafe {
let mut reg = core::ptr::read_volatile(0x40007428u32 as *const u32);
reg &= 0xFFFF00FFu32;
reg |= (val & 0xFF) << 8;
core::ptr::write_volatile(0x40007428u32 as *mut u32, reg);
}
}
}
}
pub mod dor1 {
pub mod dacc1dor {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x4000742Cu32 as *const u32) & 0xFFF
}
}
}
}
pub mod dor2 {
pub mod dacc2dor {
pub fn get() -> u32 {
unsafe {
core::ptr::read_volatile(0x40007430u32 as *const u32) & 0xFFF
}
}
}
}
|
#[doc = "Register `TDH2R` reader"]
pub type R = crate::R<TDH2R_SPEC>;
#[doc = "Register `TDH2R` writer"]
pub type W = crate::W<TDH2R_SPEC>;
#[doc = "Field `DATA4` reader - DATA4"]
pub type DATA4_R = crate::FieldReader;
#[doc = "Field `DATA4` writer - DATA4"]
pub type DATA4_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `DATA5` reader - DATA5"]
pub type DATA5_R = crate::FieldReader;
#[doc = "Field `DATA5` writer - DATA5"]
pub type DATA5_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `DATA6` reader - DATA6"]
pub type DATA6_R = crate::FieldReader;
#[doc = "Field `DATA6` writer - DATA6"]
pub type DATA6_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `DATA7` reader - DATA7"]
pub type DATA7_R = crate::FieldReader;
#[doc = "Field `DATA7` writer - DATA7"]
pub type DATA7_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bits 0:7 - DATA4"]
#[inline(always)]
pub fn data4(&self) -> DATA4_R {
DATA4_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - DATA5"]
#[inline(always)]
pub fn data5(&self) -> DATA5_R {
DATA5_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - DATA6"]
#[inline(always)]
pub fn data6(&self) -> DATA6_R {
DATA6_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - DATA7"]
#[inline(always)]
pub fn data7(&self) -> DATA7_R {
DATA7_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - DATA4"]
#[inline(always)]
#[must_use]
pub fn data4(&mut self) -> DATA4_W<TDH2R_SPEC, 0> {
DATA4_W::new(self)
}
#[doc = "Bits 8:15 - DATA5"]
#[inline(always)]
#[must_use]
pub fn data5(&mut self) -> DATA5_W<TDH2R_SPEC, 8> {
DATA5_W::new(self)
}
#[doc = "Bits 16:23 - DATA6"]
#[inline(always)]
#[must_use]
pub fn data6(&mut self) -> DATA6_W<TDH2R_SPEC, 16> {
DATA6_W::new(self)
}
#[doc = "Bits 24:31 - DATA7"]
#[inline(always)]
#[must_use]
pub fn data7(&mut self) -> DATA7_W<TDH2R_SPEC, 24> {
DATA7_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 = "mailbox data high register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tdh2r::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 [`tdh2r::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TDH2R_SPEC;
impl crate::RegisterSpec for TDH2R_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`tdh2r::R`](R) reader structure"]
impl crate::Readable for TDH2R_SPEC {}
#[doc = "`write(|w| ..)` method takes [`tdh2r::W`](W) writer structure"]
impl crate::Writable for TDH2R_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets TDH2R to value 0"]
impl crate::Resettable for TDH2R_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
extern crate chrono;
use chrono::{DateTime, Datelike, TimeZone, Utc};
use std::cmp;
/// This trait defines functions which allow for year calculations between two dates. As
/// the standard DateTime, Date, and Duration types in chrono are unable to do this (due to
/// complications with leap-years, etc.), a utility function must be added to calculate the
/// years between two DateTimes separately.
pub trait YearCalculations {
/// Returns the number of years between Self and another DateTime as an integer.
fn years_since<Tz2: TimeZone>(&self, b: &DateTime<Tz2>) -> i32;
}
fn cmp_month_day(a_utc: &DateTime<Utc>, b_utc: &DateTime<Utc>) -> i32 {
match a_utc.month().cmp(&b_utc.month()) {
cmp::Ordering::Greater => 0,
cmp::Ordering::Less => -1,
cmp::Ordering::Equal => match a_utc.day().cmp(&b_utc.day()) {
cmp::Ordering::Greater | cmp::Ordering::Equal => 0,
cmp::Ordering::Less => -1,
}
}
}
impl<Tz> YearCalculations for DateTime<Tz> where Tz: TimeZone {
fn years_since<Tz2: TimeZone>(&self, b: &DateTime<Tz2>) -> i32 {
let me_utc = self.with_timezone(&Utc);
let b_utc = b.with_timezone(&Utc);
let base_years = me_utc.year() - b_utc.year();
match base_years.cmp(&0) {
cmp::Ordering::Equal => 0,
cmp::Ordering::Greater => base_years + cmp_month_day(&me_utc, &b_utc),
cmp::Ordering::Less => base_years - cmp_month_day(&me_utc, &b_utc),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Format of fn name = test_years_ymd_xyz where
/// x = year (b = before, a = after, s = same)
/// y = year (b = before, a = after, s = same)
/// z = year (b = before, a = after, s = same)
#[test]
fn test_years_ymd_bbb() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-01-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 8);
}
#[test]
fn test_years_ymd_bba() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-01-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 8);
}
#[test]
fn test_years_ymd_bbs() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-01-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 8);
}
#[test]
fn test_years_ymd_bab() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-05-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 7);
}
#[test]
fn test_years_ymd_baa() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-05-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 7);
}
#[test]
fn test_years_ymd_bas() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-05-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 7);
}
#[test]
fn test_years_ymd_bsb() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-03-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 8);
}
#[test]
fn test_years_ymd_bsa() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-03-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 7);
}
#[test]
fn test_years_ymd_bss() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2010-03-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 8);
}
#[test]
fn test_years_ymd_abb() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-01-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -12);
}
#[test]
fn test_years_ymd_aba() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-01-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -12);
}
#[test]
fn test_years_ymd_abs() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-01-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -12);
}
#[test]
fn test_years_ymd_aab() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-06-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -11);
}
#[test]
fn test_years_ymd_aaa() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-06-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -11);
}
#[test]
fn test_years_ymd_aas() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-06-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -11);
}
#[test]
fn test_years_ymd_asb() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-03-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -12);
}
#[test]
fn test_years_ymd_asa() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-03-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -11);
}
#[test]
fn test_years_ymd_ass() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2030-03-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), -12);
}
#[test]
fn test_years_ymd_sbb() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-01-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
#[test]
fn test_years_ymd_sba() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-01-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
#[test]
fn test_years_ymd_sbs() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-01-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
#[test]
fn test_years_ymd_sab() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-06-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
#[test]
fn test_years_ymd_saa() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-06-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
#[test]
fn test_years_ymd_sas() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-06-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
#[test]
fn test_years_ymd_ssb() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-03-11T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
#[test]
fn test_years_ymd_ssa() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-03-21T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
#[test]
fn test_years_ymd_sss() {
let test_date1 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
let test_date2 = DateTime::parse_from_rfc3339("2018-03-15T12:00:00Z").unwrap();
assert_eq!(test_date1.years_since(&test_date2), 0);
}
}
|
//! Link: https://adventofcode.com/2019/day/6
//! Day 6: Universal Orbit Map
//!
//! You've landed at the Universal Orbit Map facility on Mercury.
//! Because navigation in space often involves transferring between orbits,
//! the orbit maps here are useful for finding efficient routes between,
//! for example, you and Santa.
//! You download a map of the local orbits (your puzzle input).
//!
//! Except for the universal Center of Mass (COM),
//! every object in space is in orbit around exactly one other object.
use std::str::FromStr;
use std::collections::HashMap;
#[derive(Debug, Fail)]
enum NodeParseError {
#[fail(display = "invalid side count for `{}`", input)]
InvalidSideCount {
input: String,
},
}
struct Node(String, String);
impl FromStr for Node {
type Err = NodeParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let sides: Vec<&str> = s.split(')').collect();
if sides.len() != 2 {
Err(NodeParseError::InvalidSideCount{input: s.to_owned()})
} else {
Ok(Node { 0: sides[0].to_owned(), 1: sides[1].to_owned() })
}
}
}
#[derive(Default, Debug)]
struct Map(HashMap<String, Vec<String>>);
impl Map {
fn from<'a>(&'a self, origin: &'a str) -> HashMap<&'a str, i32> {
let mut result = HashMap::new();
let mut queue = std::collections::VecDeque::new();
result.insert(origin, 0);
queue.push_back(origin);
while let Some(u) = queue.pop_front() {
let dist = *result.get(u).expect("ohno");
for v in self.0.get(u).iter().flat_map(|e| e.iter()) {
result.entry(v).or_insert_with(|| { queue.push_back(v); dist + 1 });
}
}
result
}
}
#[aoc_generator(day6)]
fn input_generator(input: &str) -> Option<Map> {
input
.split_whitespace()
.map(|x| x.parse::<Node>())
.try_fold(Map::default(), |mut map: Map, n: Result<Node, NodeParseError>| {
match n {
Ok(Node(a, b)) => {
map.0.entry(a.clone()).or_insert_with(|| vec![]).push(b.clone());
map.0.entry(b.clone()).or_insert_with(|| vec![]).push(a.clone());
Some(map)
},
Err(_) => None,
}
})
}
// What is the total number of direct and indirect orbits in your map data?
#[aoc(day6, part1, Map)]
fn solve_part1_map(input: &Map) -> i32 {
input.from("COM").values().sum()
}
// What is the minimum number of orbital transfers required
// to move from the object YOU are orbiting to the object SAN is orbiting?
#[aoc(day6, part2, Map)]
fn solve_part2_map(input: &Map) -> i32 {
(*input.from("YOU").get("SAN").unwrap() - 2)
}
#[cfg(test)]
mod tests {
use super::*;
struct SubRun {
pub origin: String,
pub target: String,
pub expected_success: bool,
pub expected_distance: i32,
}
struct Run {
pub input: String,
pub origin: String,
pub expected_sum: i32,
pub subs: Vec<SubRun>,
}
#[test]
fn day6_examples() -> Result<(), std::option::NoneError> {
let runs = vec![
Run{
input: "COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L".to_owned(),
origin: "COM".to_owned(),
expected_sum: 42,
subs: vec![
SubRun{
origin: "COM".to_owned(),
target: "D".to_owned(),
expected_success: true,
expected_distance: 1,
},
]
},
Run{
input: "COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L\nK)YOU\nI)SAN".to_owned(),
origin: "COM".to_owned(),
expected_sum: 54,
subs: vec![
SubRun{
origin: "YOU".to_owned(),
target: "SAN".to_owned(),
expected_success: true,
expected_distance: 4,
},
]
}
];
for (index, run) in runs.iter().enumerate() {
let input = input_generator(run.input.as_str())?;
let distances = input.from(run.origin.as_str());
assert_eq!(run.expected_sum, distances.values().sum(),
"Run #{}, sum check", index);
for (sub_index, sub_run) in run.subs.iter().enumerate() {
let from_origin = input.from(sub_run.origin.as_str());
let target = from_origin.get(sub_run.target.as_str());
assert_eq!(sub_run.expected_success, target.is_some(),
"Run #{}, #{}, success check", index, sub_index);
assert_eq!(sub_run.expected_distance, (*target.unwrap_or(&0) - 2),
"Run #{}, #{}, distance check", index, sub_index);
}
}
Ok(())
}
} |
//! Inter-Integrated Circuit (I2C) bus
//!
//! This is a master-mode-only implementation of I2C.
//!
//! Take care to note that the `write` and `write_read` methods accept an address argument that is
//! _not shifted on your behalf_.
//!
//! ```
//! use stm32l0x1_hal;
//!
//! let d = stm32l0x1_hal::stm32l0x1::Peripherals::take().unwrap();
//! let i2c = d.I2C;
//! let mut flash = d.FLASH.constrain();
//! let mut pwr = d.PWR.constrain();
//! let mut rcc = d.RCC.constrain().freeze(&mut flash, &mut pwr);
//!
//! let gpiob = gpio::B::new(d.GPIOB, &mut self.rcc.iop);
//!
//! let i2c_sda = gpiob.PB7.into_output::<OpenDrain, PullUp>().into_alt_fun::<AF1>();
//! i2c_sda.set_pin_speed(PinSpeed::VeryHigh);
//!
//! let i2c_scl = gpiob.PB6.into_output::<OpenDrain, PullUp>().into_alt_fun::<AF1>();
//! i2c_scl.set_pin_speed(PinSpeed::VeryHigh);
//!
//! let i2c_addr = 0x32 << 1; // <-- !!! you must shift your address accordingly
//!
//! let mut i2c = i2c::I2c::i2c1(
//! i2c1,
//! (i2c_scl, i2c_sda),
//! i2c::I2cClkSrc::HSI16,
//! 0x00303D5B, // timing_reg
//! &mut rcc.apb1,
//! &mut rcc.ccipr,
//! );
//!
//! i2c.write(i2c_addr, &[0x00, (0x1 << 6) as u8]).unwrap();
//! let result = i2c.write_read(i2c_addr, &[0x01]).unwrap();
//! ```
use crate::rcc::{APB1, CCIPR};
use crate::stm32l0x1::I2C1;
use hal::blocking::i2c::{Write, WriteRead};
#[doc(hidden)]
mod private {
/// The Sealed trait prevents other crates from implementing helper traits used by this one
pub trait Sealed {}
}
/// Available clock sources for I2C modules
pub enum I2cClkSrc {
/// APB1
PCLK1,
/// High-speed internal 16 MHz
HSI16,
/// SYSCLK
Sysclk,
}
/// I2C error
#[derive(Debug)]
pub enum Error {
/// Bus error
Bus,
/// Arbitration loss
Arbitration,
// Overrun, // slave mode only
// Pec, // SMBUS mode only
// Timeout, // SMBUS mode only
// Alert, // SMBUS mode only
#[doc(hidden)]
_Extensible,
}
#[doc(hidden)]
/// SCL pin marker trait
///
/// Note: this trait SHALL NOT be implemented, and should be considered Sealed
pub unsafe trait SclPin<I2C> {}
#[doc(hidden)]
/// SDA pin marker trait
///
/// Note: this trait SHALL NOT be implemented, and should be considered Sealed
pub unsafe trait SdaPin<I2C> {}
#[cfg(any(feature = "STM32L011x3", feature = "STM32L011x4"))]
/// I2C pin definitions for the STM32L011x3/4 family
pub mod stm32l011x3_4;
#[cfg(any(feature = "STM32L031x4", feature = "STM32L031x6"))]
/// I2C pin definitions for the STM32L031x4/6 family
pub mod stm32l031x4_6;
/// I2C peripheral operating in master mode
pub struct I2c<I2C, PINS> {
i2c: I2C,
pins: PINS,
}
macro_rules! busy_wait {
($i2c:expr, $flag:ident) => {
loop {
let isr = $i2c.isr.read();
if isr.berr().bit_is_set() {
return Err(Error::Bus);
} else if isr.arlo().bit_is_set() {
return Err(Error::Arbitration);
} else if isr.$flag().bit_is_set() {
break;
} else {
// try again
}
}
};
}
macro_rules! hal {
($($I2CX:ident: ($i2cX:ident, $i2cXen:ident, $i2cXrst:ident, $i2cXsel:ident),)+) => {
$(
impl<SCL, SDA> I2c<$I2CX, (SCL, SDA)> {
/// Create a new I2C peripheral in master mode
///
/// Note: You'll undoubtedly notice that this function takes a `timing_reg` value
/// instead of a reference to the clocks and a desired bus frequency.
/// Implementation of the calculations for the various clocking and delay values is
/// not complete (read: I can't seem to make it work). Until then, using the value
/// generated by STM32CubeMX is recommended.
//pub fn $i2cX<'p, 'f, VDD: 'p, VCORE: 'p, RTC: 'p, HZ>(
pub fn $i2cX(
i2c: $I2CX,
pins: (SCL, SDA),
//freq: HZ,
clk_src: I2cClkSrc,
//clk_ctx: &ClockContext<'p, 'f, VDD, VCORE, RTC>,
timing_reg: u32,
apb1: &mut APB1,
ccipr: &mut CCIPR,
) -> Self where
SCL: SclPin<$I2CX>,
SDA: SdaPin<$I2CX>,
//HZ: Into<Hertz>,
{
apb1.enr().modify(|_, w| w.$i2cXen().set_bit());
while apb1.enr().read().$i2cXen().bit_is_clear() {}
i2c.cr1.write(|w| w.pe().clear_bit());
/*
let (i2cclk_f, sel0_bit, sel1_bit) = match clk_src {
I2cClkSrc::PCLK1 => (clk_ctx.apb1().0, false, false),
I2cClkSrc::Sysclk => (clk_ctx.sysclk().0, false, true),
I2cClkSrc::HSI16 => (match clk_ctx.hsi16().as_ref() {
Some(f) => f.0,
None => panic!("hsi16 disabled but selected for i2c"),
}, true, true),
};
*/
let sel_bits = match clk_src {
//let (sel1_bit, sel0_bit) = match clk_src {
I2cClkSrc::PCLK1 => 0b00,
I2cClkSrc::Sysclk => 0b01,
I2cClkSrc::HSI16 => 0b10,
};
ccipr.inner().modify(|_,w| unsafe { w.$i2cXsel().bits(sel_bits) });
/*
let freq = freq.into().0;
//assert!(freq <= 100_000);
// TODO review compliance with the timing requirements of I2C
// t_I2CCLK = 1 / PCLK1
// t_PRESC = (PRESC + 1) * t_I2CCLK
// t_SCLL = (SCLL + 1) * t_PRESC
// t_SCLH = (SCLH + 1) * t_PRESC
//
// t_SYNC1 + t_SYNC2 > 4 * t_I2CCLK
// t_SCL ~= t_SYNC1 + t_SYNC2 + t_SCLL + t_SCLH
let ratio = i2cclk_f / freq - 4;
let (presc, scll, sclh, sdadel, scldel) = if freq > 100_000 {
// fast-mode or fast-mode plus
// here we pick SCLL + 1 = 2 * (SCLH + 1)
let presc = ratio / 387;
let sclh = ((ratio / (presc + 1)) - 3) / 3;
let scll = 2 * (sclh + 1) - 1;
let (sdadel, scldel) = if freq > 400_000 {
// fast-mode plus
let sdadel = 0;
let scldel = i2cclk_f / 4_000_000 / (presc + 1) - 1;
(sdadel, scldel)
} else {
// fast-mode
let sdadel = i2cclk_f / 8_000_000 / (presc + 1);
let scldel = i2cclk_f / 2_000_000 / (presc + 1) - 1;
(sdadel, scldel)
};
(presc, scll, sclh, sdadel, scldel)
} else {
// standard-mode
// here we pick SCLL = SCLH
let presc = ratio / 514;
let sclh = ((ratio / (presc + 1)) - 2) / 2;
let scll = sclh;
let sdadel = i2cclk_f / 2_000_000 / (presc + 1);
let scldel = i2cclk_f / 800_000 / (presc + 1) - 1;
(presc, scll, sclh, sdadel, scldel)
};
let presc = presc as u8;
assert!(presc < 16);
let scldel = scldel as u8;
assert!(scldel < 16);
let sdadel = sdadel as u8;
assert!(sdadel < 16);
let sclh = sclh as u8;
let scll = scll as u8;
// Configure for "fast mode" (400 KHz)
i2c.timingr.write(|w| unsafe {
w.presc()
.bits(presc)
.scll()
.bits(scll)
.sclh()
.bits(sclh)
.sdadel()
.bits(sdadel)
.scldel()
.bits(scldel)
});
*/
i2c.timingr.write(|w| unsafe { w.bits(timing_reg) });
i2c.cr2.modify(|_,w| w./*autoend().set_bit().*/nack().set_bit());
i2c.cr1.modify(|_,w| w.anfoff().clear_bit());
// Enable the peripheral
i2c.cr1.write(|w| w.pe().set_bit());
I2c { i2c, pins }
}
/// Releases the I2C peripheral and associated pins
///
/// This does not de-initialize the I2C in any way!
pub fn free(self) -> ($I2CX, (SCL, SDA)) {
(self.i2c, self.pins)
}
}
impl<PINS> Write for I2c<$I2CX, PINS> {
type Error = Error;
fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Error> {
// TODO support transfers of more than 255 bytes
assert!(bytes.len() < 256 && bytes.len() > 0);
// START and prepare to send `bytes`
self.i2c.cr2.write(|w| w
.sadd()
.bits(addr as u16)
.rd_wrn()
.clear_bit()
.nbytes()
.bits(bytes.len() as u8)
.start()
.set_bit()
.autoend()
.set_bit()
);
for byte in bytes {
// Wait until we are allowed to send data (START has been ACKed or last byte
// when through)
busy_wait!(self.i2c, txis);
// put byte on the wire
self.i2c.txdr.write(|w| w.txdata().bits(*byte));
}
// Wait until the last transmission is finished ???
// busy_wait!(self.i2c, busy);
// automatic STOP
Ok(())
}
}
impl<PINS> WriteRead for I2c<$I2CX, PINS> {
type Error = Error;
fn write_read(
&mut self,
addr: u8,
bytes: &[u8],
buffer: &mut [u8],
) -> Result<(), Error> {
// TODO support transfers of more than 255 bytes
assert!(bytes.len() < 256 && bytes.len() > 0);
assert!(buffer.len() < 256 && buffer.len() > 0);
// TODO do we have to explicitly wait here if the bus is busy (e.g. another
// master is communicating)?
// START and prepare to send `bytes`
self.i2c.cr2.write(|w| w
.sadd()
.bits(addr as u16)
.rd_wrn()
.clear_bit()
.nbytes()
.bits(bytes.len() as u8)
.start()
.set_bit()
.autoend()
.clear_bit()
);
for byte in bytes {
// Wait until we are allowed to send data (START has been ACKed or last byte
// when through)
busy_wait!(self.i2c, txis);
// put byte on the wire
self.i2c.txdr.write(|w| w.txdata().bits(*byte));
}
// Wait until the last transmission is finished
busy_wait!(self.i2c, tc);
// reSTART and prepare to receive bytes into `buffer`
self.i2c.cr2.write(|w| w
.sadd()
.bits(addr as u16)
.rd_wrn()
.set_bit()
.nbytes()
.bits(buffer.len() as u8)
.start()
.set_bit()
.autoend()
.set_bit()
);
for byte in buffer {
// Wait until we have received something
busy_wait!(self.i2c, rxne);
*byte = self.i2c.rxdr.read().rxdata().bits();
}
// automatic STOP
Ok(())
}
}
)+
}
}
hal! {
I2C1: (i2c1, i2c1en, i2c1rst, i2c1sel),
}
|
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;
use futures::channel::mpsc;
use futures::sink::Sink;
use futures::stream::Stream;
use futures::{ready, SinkExt, StreamExt};
use bytes::Bytes;
use failure::Error;
use crate::{Connection, PackChan, SenderSink, SrtCongestCtrl};
type BoxConnStream = Pin<Box<dyn Stream<Item = Result<(Connection, PackChan), Error>> + Send>>;
pub struct StreamerServer {
server: BoxConnStream,
channels: Vec<mpsc::Sender<(Instant, Bytes)>>,
}
impl StreamerServer {
pub fn new(
server: impl Stream<Item = Result<(Connection, PackChan), Error>> + Send + 'static,
) -> Self {
StreamerServer {
server: server.boxed(),
channels: vec![], // TODO: research lengths
}
}
}
impl Sink<(Instant, Bytes)> for StreamerServer {
type Error = Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
for i in &mut self.channels {
if let Err(e) = ready!(i.poll_ready(cx)) {
return Poll::Ready(Err(Error::from(e)));
}
}
Poll::Ready(Ok(()))
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
for i in &mut self.channels {
if let Err(e) = ready!(Pin::new(i).poll_close(cx)) {
return Poll::Ready(Err(Error::from(e)));
}
}
Poll::Ready(Ok(()))
}
fn start_send(mut self: Pin<&mut Self>, item: (Instant, Bytes)) -> Result<(), Error> {
for i in &mut self.channels {
i.start_send(item.clone())?;
}
Ok(())
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
for i in &mut self.channels {
let _ = Pin::new(i).poll_flush(cx)?;
}
loop {
let (conn, chan) = ready!(Pin::new(&mut self.server).poll_next(cx))
.expect("Multiplexer stream ended, strange")
.expect("Multiplex server return Err");
let mut sender = SenderSink::new(chan, SrtCongestCtrl, conn.settings, conn.handshake);
let (tx, rx) = mpsc::channel(100);
self.channels.push(tx);
// TODO: remove from the channel list when finished
tokio::spawn(async move {
sender.send_all(&mut rx.map(Ok)).await.unwrap();
sender.close().await.unwrap();
});
}
}
}
|
//! The Equinox stochastic photon mapper, see the README for more information.
#![allow(clippy::module_inception)]
#![forbid(unsafe_code, while_true)]
mod device {
pub mod camera;
pub mod device;
pub mod display;
pub mod environment;
pub mod geometry;
pub mod instance;
pub mod integrator;
pub mod lens_flare;
pub mod material;
pub mod raster;
}
mod engine {
pub mod framebuffer;
pub mod shader;
pub mod texture;
pub mod uniform_buffer;
pub mod vertex_array;
}
mod scene {
pub mod aperture;
pub mod bounding_box;
pub mod camera;
pub mod dirty;
pub mod display;
pub mod environment;
pub mod geometry;
pub mod instance;
pub mod integrator;
pub mod material;
pub mod metadata;
pub mod raster;
pub mod scene;
}
pub use device::{
camera::*, device::*, display::*, environment::*, geometry::*, instance::*, integrator::*,
lens_flare::*, material::*, raster::*,
};
pub use engine::{framebuffer::*, shader::*, texture::*, uniform_buffer::*, vertex_array::*};
pub use scene::{
aperture::*, bounding_box::*, camera::*, dirty::*, display::*, environment::*, geometry::*,
instance::*, integrator::*, material::*, metadata::*, raster::*, scene::*,
};
/// WebGL shaders from the `shader` directory.
///
/// This module is autogenerated by the crate build script which will handle all
/// GLSL preprocessing such as expanding #includes and adding file/line markers.
pub mod shader {
include!(concat!(env!("OUT_DIR"), "/glsl_shaders.rs"));
}
use cgmath::{prelude::*, Basis3, Vector3};
use js_sys::{Array, Error, Function, Uint8Array};
use serde::{de::DeserializeOwned, Serialize};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::WebGl2RenderingContext;
/// WASM wrapper for a scene.
#[wasm_bindgen]
#[derive(Debug, Default)]
pub struct WebScene {
scene: Scene,
}
#[wasm_bindgen]
impl WebScene {
/// Creates a new empty scene.
#[wasm_bindgen(constructor)]
pub fn new() -> WebScene {
Self::default()
}
pub fn json(&self) -> Result<JsValue, JsValue> {
as_json(&self.scene)
}
pub fn raster_width(&self) -> u32 {
self.scene.raster.width
}
pub fn raster_height(&self) -> u32 {
self.scene.raster.height
}
pub fn name(&self) -> String {
self.scene.metadata.name.clone()
}
/// Reconfigures the scene using the provided scene JSON data.
///
/// This method will attempt to dirty the least amount of scene data
/// possible, which should make later device updates more efficient.
pub fn set_json(&mut self, json: &JsValue) -> Result<(), JsValue> {
let temporary: Scene = from_json(json)?;
temporary.validate()?;
self.scene.patch_from_other(temporary);
Ok(())
}
/// Returns all assets which are referenced in this scene.
pub fn assets(&self) -> Array {
self.scene
.assets()
.into_iter()
.map(ToOwned::to_owned)
.map(JsValue::from)
.collect()
}
/// Applies a camera-space translation to the camera position.
pub fn move_camera(&mut self, dx: f32, dy: f32, dz: f32) {
let mut direction: Vector3<f32> = self.scene.camera.direction.into();
let mut up_vector: Vector3<f32> = self.scene.camera.up_vector.into();
direction = direction.normalize();
up_vector = up_vector.normalize();
let xfm = Basis3::look_at(direction, up_vector).invert();
let rotated_dir = xfm.rotate_vector([dx, dy, dz].into());
self.scene.camera.position[0] += rotated_dir[0];
self.scene.camera.position[1] += rotated_dir[1];
self.scene.camera.position[2] += rotated_dir[2];
}
#[allow(clippy::float_cmp)]
pub fn set_camera_direction(&mut self, x: f32, y: f32, z: f32) {
if self.scene.camera.direction != [x, y, z] {
self.scene.camera.direction = [x, y, z];
}
}
}
fn as_json<T: Serialize>(value: &T) -> Result<JsValue, JsValue> {
Ok(JsValue::from_serde(value).map_err(|e| Error::new(&e.to_string()))?)
}
fn from_json<T: DeserializeOwned>(json: &JsValue) -> Result<T, JsValue> {
Ok(json.into_serde().map_err(|e| Error::new(&e.to_string()))?)
}
/// WASM wrapper for a device.
#[wasm_bindgen]
pub struct WebDevice {
device: Device,
}
#[wasm_bindgen]
impl WebDevice {
#[wasm_bindgen(constructor)]
pub fn new(context: &WebGl2RenderingContext) -> Result<WebDevice, JsValue> {
Ok(Self {
device: Device::new(context)?,
})
}
pub fn texture_compression(&mut self) -> Result<JsValue, JsValue> {
Ok(JsValue::from_serde(&self.device.texture_compression()).unwrap())
}
/// Returns whether updating the device with a scene may be time-consuming.
pub fn is_expensive_update(&mut self, scene: &WebScene) -> Result<bool, JsValue> {
Ok(self.device.is_update_expensive(&scene.scene)?)
}
/// Updates the device with a scene, returning true if an update occurred.
pub fn update(&mut self, scene: &mut WebScene, assets: &Function) -> Result<bool, JsValue> {
Ok(self.device.update(&mut scene.scene, |asset| {
let asset_data = assets.call1(&JsValue::NULL, &JsValue::from(asset))?;
if asset_data.is_null() || asset_data.is_undefined() {
return Err(Error::new("failed to fetch asset"));
}
if let Some(buffer) = asset_data.dyn_ref::<Uint8Array>() {
Ok(buffer.to_vec())
} else {
Err(Error::new("asset callback did not return Uint8Array"))
}
})?)
}
/// Refines the render using the SPPN integrator.
pub fn refine(&mut self) -> Result<(), JsValue> {
Ok(self.device.refine()?)
}
/// Presents the current SPPM integrator render.
pub fn present(&mut self) -> Result<(), JsValue> {
Ok(self.device.present()?)
}
/// Returns the number of photons traced by the SPPM integrator.
pub fn sppm_photons(&self) -> f64 {
self.device.state.photon_count as f64
}
/// Returns the number of passes performed by the SPPM integrator.
pub fn sppm_passes(&self) -> u32 {
self.device.state.current_pass
}
/// Signals to the device that its WebGL context has been lost.
pub fn context_lost(&mut self) {
self.device.context_lost();
}
}
#[allow(dead_code)]
mod build_metadata {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
/// Returns a version string for the WASM module.
#[wasm_bindgen]
pub fn version() -> String {
format!(
"Equinox v{} ({}) built with {}",
build_metadata::PKG_VERSION,
build_metadata::GIT_VERSION.unwrap(),
build_metadata::RUSTC_VERSION,
)
}
/// Returns licensing information for the WASM module.
#[wasm_bindgen]
pub fn licensing() -> String {
lies::licenses_text!().to_owned()
}
/// Configures browser logging functionality.
#[wasm_bindgen]
pub fn initialize_logging() {
console_error_panic_hook::set_once();
let _ = console_log::init();
}
|
// These are for making everything in `src/commands/*`
// available in `src/main.rs` via `mod commands;`.
// (Pssst, don't forget to `use` them as well.)
pub mod about;
pub mod date;
pub mod embed;
pub mod fortune;
pub mod git;
pub mod hmm;
pub mod math;
pub mod noice;
pub mod projects;
pub mod quit;
pub mod rng;
pub mod wipltrn;
pub mod ww;
|
use super::*;
use crate::helpers::SolomonBuilder;
use crate::solomon::{SolomonProblem, SolomonSolution};
use std::sync::Arc;
use vrp_core::construction::heuristics::InsertionContext;
use vrp_core::solver::mutation::{Recreate, RecreateWithCheapest};
use vrp_core::solver::population::Elitism;
use vrp_core::solver::RefinementContext;
use vrp_core::utils::Environment;
#[test]
fn can_write_solomon_solution() {
let environment = Arc::new(Environment::default());
let problem = Arc::new(
SolomonBuilder::new()
.set_title("Trivial problem")
.set_vehicle((1, 10))
.add_customer((0, 0, 0, 0, 0, 1000, 1))
.add_customer((1, 1, 0, 1, 5, 1000, 5))
.build()
.read_solomon()
.unwrap(),
);
let mut refinement_ctx = RefinementContext::new(
problem.clone(),
Box::new(Elitism::new(problem.clone(), environment.random.clone(), 1, 1)),
environment.clone(),
None,
);
let mut buffer = String::new();
let writer = unsafe { BufWriter::new(buffer.as_mut_vec()) };
RecreateWithCheapest::default()
.run(&mut refinement_ctx, InsertionContext::new(problem.clone(), environment))
.solution
.to_solution(problem.extras.clone())
.write_solomon(writer)
.unwrap();
assert_eq!(buffer, "Solution\nRoute 1: 1\n");
}
|
pub use wasm_bindgen::{self, prelude::*, JsCast};
pub mod element;
mod dom;
mod console;
mod futures_signals_ext;
pub use futures_signals_ext::{MutableExt, MutableVecExt};
pub use element::*;
pub use dom::{window, document};
pub use futures_signals::{
self,
map_mut,
map_ref,
signal::{Mutable, Signal, SignalExt},
signal_vec::{MutableVec, SignalVec, SignalVecExt},
signal_map::{MutableBTreeMap, SignalMap, SignalMapExt},
};
pub use dominator::{self, Dom, DomBuilder, events, traits::StaticEvent};
pub use paste;
pub use console::log;
#[cfg(feature = "panic_hook")]
pub use console_error_panic_hook;
#[cfg(feature = "static_ref")]
pub use static_ref_macro::static_ref;
#[cfg(feature = "static_ref")]
pub use once_cell;
#[cfg(feature = "clone")]
pub use enclose::enc as clone;
#[cfg(feature = "small_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[cfg(feature = "fast_alloc")]
compile_error!("Do you know a fast allocator working in Wasm?");
// #[cfg(feature = "tracing_alloc")]
// #[global_allocator]
// static GLOBAL_ALLOCATOR: wasm_tracing_allocator::WasmTracingAllocator<std::alloc::System> = wasm_tracing_allocator::WasmTracingAllocator(std::alloc::System);
#[cfg(feature = "fmt")]
pub use ufmt::{self, uDebug, uDisplay, uWrite, uwrite, uwriteln};
#[cfg(feature = "fmt")]
pub use lexical::{self, WriteIntegerOptions, WriteFloatOptions, NumberFormat};
#[cfg(not(feature = "fmt"))]
pub use std::format as format;
#[cfg(feature = "fmt")]
#[macro_export]
macro_rules! format {
($($arg:tt)*) => {{
let mut text = String::new();
$crate::ufmt::uwrite!(&mut text, $($arg)*).unwrap_throw();
text
}}
}
pub trait FlagSet {}
pub trait FlagNotSet {}
#[macro_export]
macro_rules! make_flags {
($($flag:ident),*) => {
$(paste::paste!{
#[derive(Default)]
pub struct [<$flag FlagSet>];
#[derive(Default)]
pub struct [<$flag FlagNotSet>];
impl $crate::FlagSet for [<$flag FlagSet>] {}
impl $crate::FlagNotSet for [<$flag FlagNotSet>] {}
})*
}
}
pub fn start_app<'a, E: Element>(browser_element_id: impl Into<Option<&'a str>>, view_root: impl FnOnce() -> E) {
#[cfg(feature = "panic_hook")]
#[cfg(debug_assertions)]
console_error_panic_hook::set_once();
let parent = browser_element_id
.into()
// @TODO we need a better error message
.map(dominator::get_id)
.unwrap_or_else(|| dominator::body().unchecked_into());
dominator::append_dom(&parent, view_root().into_raw_element().into_dom());
}
|
use crate::rvals::{Result, SteelVal};
// TODO
pub const fn _new_void() -> SteelVal {
SteelVal::Void
}
// TODO
pub const fn _new_true() -> SteelVal {
SteelVal::BoolV(true)
}
// TODO
pub const fn _new_false() -> SteelVal {
SteelVal::BoolV(false)
}
#[derive(Debug)]
pub struct Env {
pub(crate) bindings_vec: Vec<SteelVal>,
}
pub trait MacroEnv {
fn validate_identifier(&self, name: &str) -> bool;
}
impl Env {
pub fn extract(&self, idx: usize) -> Option<SteelVal> {
self.bindings_vec.get(idx).cloned()
}
/// top level global env has no parent
pub fn root() -> Self {
Env {
bindings_vec: Vec::new(),
}
}
/// Search starting from the current environment
/// for `idx`, looking through the parent chain in order.
///
/// if found, return that value
///
/// Otherwise, error with `FreeIdentifier`
// #[inline]
pub fn repl_lookup_idx(&self, idx: usize) -> Result<SteelVal> {
Ok(self.bindings_vec[idx].clone())
}
#[inline]
pub fn repl_define_idx(&mut self, idx: usize, val: SteelVal) {
if idx < self.bindings_vec.len() {
self.bindings_vec[idx] = val;
} else {
self.bindings_vec.push(val);
assert_eq!(self.bindings_vec.len() - 1, idx);
}
}
pub fn repl_set_idx(&mut self, idx: usize, val: SteelVal) -> Result<SteelVal> {
let output = self.bindings_vec[idx].clone();
self.bindings_vec[idx] = val;
Ok(output)
}
#[inline]
pub fn add_root_value(&mut self, idx: usize, val: SteelVal) {
// self.bindings_map.insert(idx, val);
self.repl_define_idx(idx, val);
}
}
|
use crate::http::client::Client;
use std::borrow::Borrow;
use crate::api::models::lock::Lock;
use crate::api::models::transaction::Transaction;
use crate::api::models::wallet::Wallet;
use crate::api::Result;
use std::collections::HashMap;
pub struct Wallets {
client: Client,
}
impl Wallets {
pub fn new(client: Client) -> Wallets {
Wallets { client }
}
pub async fn all(&mut self) -> Result<Vec<Wallet>> {
self.all_params(Vec::<(String, String)>::new()).await
}
pub async fn all_params<I, K, V>(&mut self, parameters: I) -> Result<Vec<Wallet>>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
self.client.get_with_params("wallets", parameters).await
}
pub async fn top(&mut self) -> Result<Vec<Wallet>> {
self.top_params(Vec::<(String, String)>::new()).await
}
pub async fn top_params<I, K, V>(&mut self, parameters: I) -> Result<Vec<Wallet>>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
self.client.get_with_params("wallets/top", parameters).await
}
pub async fn show(&mut self, id: &str) -> Result<Wallet> {
let endpoint = format!("wallets/{}", id);
self.client.get(&endpoint).await
}
pub async fn transactions(&mut self, id: &str) -> Result<Vec<Transaction>> {
self.transactions_params(id, Vec::<(String, String)>::new())
.await
}
pub async fn transactions_params<I, K, V>(
&mut self,
id: &str,
parameters: I,
) -> Result<Vec<Transaction>>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
let endpoint = format!("wallets/{}/transactions", id);
self.client.get_with_params(&endpoint, parameters).await
}
pub async fn sent_transactions(&mut self, id: &str) -> Result<Vec<Transaction>> {
self.sent_transactions_params(id, Vec::<(String, String)>::new())
.await
}
pub async fn sent_transactions_params<I, K, V>(
&mut self,
id: &str,
parameters: I,
) -> Result<Vec<Transaction>>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
let endpoint = format!("wallets/{}/transactions/sent", id);
self.client.get_with_params(&endpoint, parameters).await
}
pub async fn received_transactions(&mut self, id: &str) -> Result<Vec<Transaction>> {
self.received_transactions_params(id, Vec::<(String, String)>::new())
.await
}
pub async fn received_transactions_params<I, K, V>(
&mut self,
id: &str,
parameters: I,
) -> Result<Vec<Transaction>>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
let endpoint = format!("wallets/{}/transactions/received", id);
self.client.get_with_params(&endpoint, parameters).await
}
pub async fn votes(&mut self, id: &str) -> Result<Vec<Transaction>> {
let endpoint = format!("wallets/{}/votes", id);
self.client.get(&endpoint).await
}
pub async fn search<I, K, V>(
&mut self,
payload: HashMap<&str, &str>,
parameters: I,
) -> Result<Vec<Wallet>>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
self.client
.post_with_params("wallets/search", payload, parameters)
.await
}
pub async fn locks(&mut self, id: &str) -> Result<Vec<Lock>> {
let endpoint = format!("wallets/{}/locks", id);
self.client.get(&endpoint).await
}
}
|
use super::*;
use crate::request_options::LeaseId;
use crate::util::HeaderMapExt;
use crate::*;
use crate::{RequestId, SessionToken};
use chrono::{DateTime, FixedOffset, Utc};
use http::header::{DATE, ETAG, LAST_MODIFIED};
#[cfg(feature = "enable_hyper")]
use http::status::StatusCode;
use http::HeaderMap;
#[cfg(feature = "enable_hyper")]
use hyper::{Body, Client, Request};
use std::str::FromStr;
pub fn lease_id_from_headers(headers: &HeaderMap) -> Result<LeaseId, Error> {
get_from_headers(headers, LEASE_ID)
}
pub fn request_id_from_headers(headers: &HeaderMap) -> Result<RequestId, Error> {
get_from_headers(headers, REQUEST_ID)
}
pub fn client_request_id_from_headers_optional(headers: &HeaderMap) -> Option<String> {
headers.get_as_str(CLIENT_REQUEST_ID).map(|s| s.to_owned())
}
pub fn last_modified_from_headers_optional(
headers: &HeaderMap,
) -> Result<Option<DateTime<Utc>>, Error> {
get_option_from_headers(headers, LAST_MODIFIED.as_str())
}
pub fn rfc2822_from_headers_mandatory(
headers: &HeaderMap,
header_name: &str,
) -> Result<DateTime<Utc>, Error> {
let date = get_str_from_headers(headers, header_name)?;
let date = parse_date_from_rfc2822(date)?;
let date = DateTime::from_utc(date.naive_utc(), Utc);
Ok(date)
}
pub fn last_modified_from_headers(headers: &HeaderMap) -> Result<DateTime<Utc>, Error> {
rfc2822_from_headers_mandatory(headers, LAST_MODIFIED.as_str())
}
pub fn continuation_token_from_headers_optional(
headers: &HeaderMap,
) -> Result<Option<String>, Error> {
if let Some(hc) = headers.get(CONTINUATION) {
Ok(Some(hc.to_str()?.to_owned()))
} else {
Ok(None)
}
}
pub fn utc_date_from_rfc2822(date: &str) -> Result<DateTime<Utc>, Error> {
let date = parse_date_from_rfc2822(date)?;
Ok(DateTime::from_utc(date.naive_utc(), Utc))
}
pub fn date_from_headers(headers: &HeaderMap) -> Result<DateTime<Utc>, Error> {
let date = get_str_from_headers(headers, DATE.as_str())?;
let date = parse_date_from_rfc2822(date)?;
let date = DateTime::from_utc(date.naive_utc(), Utc);
Ok(date)
}
pub fn sku_name_from_headers(headers: &HeaderMap) -> Result<String, Error> {
let sku_name = get_str_from_headers(headers, SKU_NAME)?;
Ok(sku_name.to_owned())
}
pub fn account_kind_from_headers(headers: &HeaderMap) -> Result<String, Error> {
let account_kind = get_str_from_headers(headers, ACCOUNT_KIND)?;
Ok(account_kind.to_owned())
}
pub fn etag_from_headers_optional(headers: &HeaderMap) -> Result<Option<String>, Error> {
if headers.contains_key(ETAG) {
Ok(Some(etag_from_headers(headers)?))
} else {
Ok(None)
}
}
pub fn etag_from_headers(headers: &HeaderMap) -> Result<String, Error> {
get_str_from_headers(headers, ETAG.as_str()).map(ToOwned::to_owned)
}
pub fn lease_time_from_headers(headers: &HeaderMap) -> Result<u8, Error> {
get_from_headers(headers, LEASE_TIME)
}
#[cfg(not(feature = "azurite_workaround"))]
pub fn delete_type_permanent_from_headers(headers: &HeaderMap) -> Result<bool, Error> {
get_from_headers(headers, DELETE_TYPE_PERMANENT)
}
#[cfg(feature = "azurite_workaround")]
pub fn delete_type_permanent_from_headers(headers: &HeaderMap) -> Result<Option<bool>, Error> {
get_option_from_headers(headers, DELETE_TYPE_PERMANENT)
}
pub fn sequence_number_from_headers(headers: &HeaderMap) -> Result<u64, Error> {
get_from_headers(headers, BLOB_SEQUENCE_NUMBER)
}
pub fn session_token_from_headers(headers: &HeaderMap) -> Result<SessionToken, Error> {
get_str_from_headers(headers, SESSION_TOKEN).map(ToOwned::to_owned)
}
pub fn server_from_headers(headers: &HeaderMap) -> Result<&str, Error> {
get_str_from_headers(headers, SERVER)
}
pub fn version_from_headers(headers: &HeaderMap) -> Result<&str, Error> {
get_str_from_headers(headers, VERSION)
}
pub fn request_server_encrypted_from_headers(headers: &HeaderMap) -> Result<bool, Error> {
get_from_headers(headers, REQUEST_SERVER_ENCRYPTED)
}
pub fn content_type_from_headers(headers: &HeaderMap) -> Result<&str, Error> {
get_str_from_headers(headers, http::header::CONTENT_TYPE.as_str())
}
pub fn item_count_from_headers(headers: &HeaderMap) -> Result<u32, Error> {
get_from_headers(headers, ITEM_COUNT)
}
#[cfg(feature = "enable_hyper")]
pub async fn perform_http_request(
client: &Client<hyper_rustls::HttpsConnector<hyper::client::HttpConnector>>,
req: Request<Body>,
expected_status: StatusCode,
) -> Result<String, Error> {
debug!("req == {:?}", req);
let res = client
.request(req)
.await
.map_err(HttpError::ExecuteRequestError)?;
check_status_extract_body_2(res, expected_status).await
}
pub fn get_str_from_headers<'a>(headers: &'a HeaderMap, key: &str) -> Result<&'a str, Error> {
Ok(headers
.get(key)
.ok_or_else(|| Error::HeaderNotFound(key.to_owned()))?
.to_str()?)
}
pub fn get_from_headers<T: std::str::FromStr>(headers: &HeaderMap, key: &str) -> Result<T, Error>
where
T: std::str::FromStr,
T::Err: Into<ParsingError>,
{
get_str_from_headers(headers, key)?
.parse()
.map_err(|e: T::Err| Error::ParsingError(e.into()))
}
pub fn get_option_from_headers<T>(headers: &HeaderMap, key: &str) -> Result<Option<T>, Error>
where
T: std::str::FromStr,
T::Err: Into<ParsingError>,
{
match headers.get(key) {
Some(header) => Ok(Some(
header
.to_str()?
.parse()
.map_err(|e: T::Err| Error::ParsingError(e.into()))?,
)),
None => Ok(None),
}
}
pub fn parse_date_from_str(date: &str, fmt: &str) -> Result<DateTime<FixedOffset>, ParsingError> {
DateTime::parse_from_str(date, fmt).map_err(ParsingError::ParseDateTimeError)
}
pub fn parse_date_from_rfc2822(date: &str) -> Result<DateTime<FixedOffset>, ParsingError> {
DateTime::parse_from_rfc2822(date).map_err(ParsingError::ParseDateTimeError)
}
pub fn parse_int<F>(s: &str) -> Result<F, ParsingError>
where
F: FromStr<Err = std::num::ParseIntError>,
{
FromStr::from_str(s).map_err(ParsingError::ParseIntError)
}
|
use regex::Regex;
use std::env;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
fn read_ignoring_utf_errors(path: &PathBuf) -> String {
let mut f =
File::open(path).unwrap_or_else(|_| panic!("McFly error: {:?} file not found", &path));
let mut buffer = Vec::new();
f.read_to_end(&mut buffer)
.unwrap_or_else(|_| panic!("McFly error: Unable to read from {:?}", &path));
String::from_utf8_lossy(&buffer).to_string()
}
#[allow(clippy::if_same_then_else)]
fn has_leading_timestamp(line: &str) -> bool {
let mut matched_chars = 0;
for (index, c) in line.chars().enumerate() {
if index == 0 && c == '#' {
matched_chars += 1;
} else if index > 0 && index < 11 && (c.is_digit(10)) {
matched_chars += 1;
} else if index > 11 {
break;
}
}
matched_chars == 11
}
pub fn history_file_path() -> PathBuf {
let path = PathBuf::from(env::var("HISTFILE").unwrap_or_else(|err| {
panic!(format!(
"McFly error: Please ensure HISTFILE is set for your shell ({})",
err
))
}));
fs::canonicalize(&path).unwrap_or_else(|err| {
panic!(format!(
"McFly error: The contents of $HISTFILE appear invalid ({})",
err
))
})
}
pub fn full_history(path: &PathBuf) -> Vec<String> {
let history_contents = read_ignoring_utf_errors(&path);
let zsh_timestamp_and_duration_regex = Regex::new(r"^: \d+:\d+;").unwrap();
history_contents
.split('\n')
.filter(|line| !has_leading_timestamp(line) && !line.is_empty())
.map(|line| zsh_timestamp_and_duration_regex.replace(line, ""))
.map(String::from)
.collect::<Vec<String>>()
}
pub fn last_history_line(path: &PathBuf) -> Option<String> {
// Could switch to https://github.com/mikeycgto/rev_lines
full_history(path).last().map(|s| s.trim().to_string())
}
pub fn delete_last_history_entry_if_search(path: &PathBuf, debug: bool) {
let history_contents = read_ignoring_utf_errors(&path);
let mut lines = history_contents
.split('\n')
.map(String::from)
.collect::<Vec<String>>();
if !lines.is_empty() && lines[lines.len() - 1].is_empty() {
lines.pop();
}
let starts_with_mcfly = Regex::new(r"^(: \d+:\d+;)?#mcfly:").unwrap();
if lines.is_empty() || !starts_with_mcfly.is_match(&lines[lines.len() - 1]) {
return; // Abort if empty or the last line isn't a comment.
}
if debug {
println!("McFly: Removed {:?} from file {:?}", lines.pop(), &path);
} else {
lines.pop();
}
if !lines.is_empty() && has_leading_timestamp(&lines[lines.len() - 1]) {
lines.pop();
}
lines.push(String::from("")); // New line at end of file expected by bash.
fs::write(&path, lines.join("\n"))
.unwrap_or_else(|_| panic!("McFly error: Unable to update {:?}", &path));
}
pub fn delete_lines(path: &PathBuf, command: &str) {
let history_contents = read_ignoring_utf_errors(&path);
let zsh_timestamp_and_duration_regex = Regex::new(r"^: \d+:\d+;").unwrap();
let lines = history_contents
.split('\n')
.map(String::from)
.filter(|cmd| !command.eq(&zsh_timestamp_and_duration_regex.replace(cmd, "")))
.collect::<Vec<String>>();
fs::write(&path, lines.join("\n"))
.unwrap_or_else(|_| panic!("McFly error: Unable to update {:?}", &path));
}
pub fn append_history_entry(
command: &str,
when_run: Option<i64>,
path: &PathBuf,
zsh_extended_history: bool,
debug: bool,
) {
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open(path)
.unwrap_or_else(|err| {
panic!(format!(
"McFly error: please make sure HISTFILE exists ({})",
err
))
});
if debug {
println!("McFly: Appended '{}' to file {:?}", command, &path);
}
if zsh_extended_history {
let when = when_run.unwrap_or(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_else(|err| panic!(format!("McFly error: Time went backwards ({})", err)))
.as_secs() as i64,
);
if let Err(e) = writeln!(file, ": {}:0;{}", when, command) {
eprintln!("Couldn't append to file {:?}: {}", &path, e);
}
} else {
if let Err(e) = writeln!(file, "{}", command) {
eprintln!("Couldn't append to file {:?}: {}", &path, e);
}
}
}
#[cfg(test)]
mod tests {
use super::has_leading_timestamp;
#[test]
fn has_leading_timestamp_works() {
assert_eq!(false, has_leading_timestamp("abc"));
assert_eq!(false, has_leading_timestamp("#abc"));
assert_eq!(false, has_leading_timestamp("#123456"));
assert_eq!(true, has_leading_timestamp("#1234567890"));
assert_eq!(false, has_leading_timestamp("#123456789"));
assert_eq!(false, has_leading_timestamp("# 1234567890"));
assert_eq!(false, has_leading_timestamp("1234567890"));
assert_eq!(false, has_leading_timestamp("hello 1234567890"));
}
}
|
mod asm;
mod bus;
mod cpu;
mod dec;
mod isa;
mod mon;
mod sys;
fn main() {
// syntax brevity for Assembler args
use asm::{branch, label, val, Operand::*};
// assemble a nonsense demo program using diverse instructions
let org: u16 = 0x1234;
let mut asm = asm::Assembler::new();
asm.org(org)
.ldx(Imm(0xFF))
.txs()
.lda(Imm(0xAA))
.ldx(Imm(0x10))
.ldy(Imm(0xAA))
.lsr(A)
.ora(Imm(0x00))
.pha()
.lda(Imm(0xFF))
.pla()
.php()
.sec()
.plp()
.rol(A)
.ror(A)
.label("loop")
.inx()
.iny()
.adc(Abs(val(org + 2)))
.sbc(Imm(0x44))
.asl(A)
.lda(IndY(0x01))
.and(XInd(0x00))
.bit(Z(0x00))
.bcc(Rel(branch("branch_to")))
.bcs(Rel(branch("branch_to")))
.beq(Rel(branch("branch_to")))
.bmi(Rel(branch("branch_to")))
.bne(Rel(branch("branch_to")))
.bpl(Rel(branch("branch_to")))
.bvc(Rel(branch("branch_to")))
.bvs(Rel(branch("branch_to")))
.nop()
.label("branch_to")
.sta(AbsX(val(0x0000)))
.stx(ZY(0x10))
.sty(ZX(0x20))
.tax()
.tay()
.tsx()
.txa()
.txs()
.tya()
.sec()
.sed()
.sei()
.clc()
.cld()
.cli()
.clv()
.cmp(AbsX(label("message")))
.cpx(Imm(0x12))
.cpy(Imm(0x34))
.dec(Z(0x00))
.dex()
.dey()
.eor(AbsY(val(0x8000)))
.inc(ZX(0x80))
.jsr(Abs(label("subroutine")))
.jmp(Abs(label("loop")))
.jmp(Abs(val(0)))
.brk()
.label("message")
.data("Hello world!\nHow are you?\n".into())
.label("subroutine")
.rts()
.label("interrupt")
.rti()
.print_listing();
let mut sys = sys::Sys::new();
// preload program to RAM
sys.bus.load(asm.org, asm.assemble().unwrap());
// set reset vector to program address
sys.bus.write(0xFFFC, asm.org as u8);
sys.bus.write(0xFFFD, (asm.org >> 8) as u8);
sys.reset();
// run some instructions
for _ in 0..80 {
sys.step();
}
}
|
//! Encoding of a binary [`Context`].
//!
//! ```text
//!
//! +------------------+-----------------+-----------------+
//! | | | |
//! | Transaction Id | Current Layer | Current State |
//! | (Hash) | (u64) | (State) |
//! | | | |
//! | 32 bytes | 8 bytes | 32 bytes |
//! | | (Big-Endian) | |
//! | | | |
//! +------------------+-----------------+-----------------+
//!
//! ```
use std::io::Cursor;
use svm_types::{Context, Layer};
use crate::{ReadExt, WriteExt};
/// Returns the number of bytes required to hold a binary [`Context`].
pub const fn byte_size() -> usize {
32 + 8 + 32
}
/// Encodes a binary [`Context`] of a transaction.
pub fn encode(context: &Context, w: &mut Vec<u8>) {
w.write_tx_id(context.tx_id());
w.write_u64_be(context.layer().0);
w.write_state(context.state());
}
/// Decodes a binary [`Context`] of a transaction.
///
/// Returns the decoded [`Context`],
/// On failure, returns [`std::io::Result`].
pub fn decode(cursor: &mut Cursor<&[u8]>) -> std::io::Result<Context> {
let tx_id = cursor.read_tx_id()?;
let layer = cursor.read_u64_be()?;
let state = cursor.read_state()?;
let context = Context::new(tx_id, Layer(layer), state);
Ok(context)
}
|
use crate::accounts_index::{AccountMapEntry, IsCached, WriteAccountMapEntry};
use solana_sdk::pubkey::Pubkey;
use std::collections::{
hash_map::{Entry, Keys},
HashMap,
};
use std::fmt::Debug;
type K = Pubkey;
// one instance of this represents one bin of the accounts index.
#[derive(Debug, Default)]
pub struct InMemAccountsIndex<T: IsCached> {
// backing store
map: HashMap<Pubkey, AccountMapEntry<T>>,
}
impl<T: IsCached> InMemAccountsIndex<T> {
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
pub fn entry(&mut self, pubkey: Pubkey) -> Entry<K, AccountMapEntry<T>> {
self.map.entry(pubkey)
}
pub fn items(&self) -> Vec<(K, AccountMapEntry<T>)> {
self.map.iter().map(|(k, v)| (*k, v.clone())).collect()
}
pub fn keys(&self) -> Keys<K, AccountMapEntry<T>> {
self.map.keys()
}
pub fn get(&self, key: &K) -> Option<AccountMapEntry<T>> {
self.map.get(key).cloned()
}
pub fn remove(&mut self, key: &K) {
self.map.remove(key);
}
// If the slot list for pubkey exists in the index and is empty, remove the index entry for pubkey and return true.
// Return false otherwise.
pub fn remove_if_slot_list_empty(&mut self, pubkey: Pubkey) -> bool {
if let Entry::Occupied(index_entry) = self.map.entry(pubkey) {
if index_entry.get().slot_list.read().unwrap().is_empty() {
index_entry.remove();
return true;
}
}
false
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
// return None if item was created new
// if entry for pubkey already existed, return Some(entry). Caller needs to call entry.update.
pub fn insert_new_entry_if_missing_with_lock(
&mut self,
pubkey: Pubkey,
new_entry: AccountMapEntry<T>,
) -> Option<(WriteAccountMapEntry<T>, T, Pubkey)> {
let account_entry = self.map.entry(pubkey);
match account_entry {
Entry::Occupied(account_entry) => Some((
WriteAccountMapEntry::from_account_map_entry(account_entry.get().clone()),
// extract the new account_info from the unused 'new_entry'
new_entry.slot_list.write().unwrap().remove(0).1,
*account_entry.key(),
)),
Entry::Vacant(account_entry) => {
account_entry.insert(new_entry);
None
}
}
}
}
|
use super::sched::*;
use crate::lib::*;
global_asm!(include_str!("../arch/riscv/kernel/head.S"));
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Context {
pub regs: thread_struct,
pub status: u64,
pub epc: u64,
}
extern "C" {
fn trap_m();
fn trap_s();
}
global_asm!(include_str!("../arch/riscv/kernel/entry.S"));
pub static mut TICKS: usize = 0;
pub fn timer_init() {
set_next_timeout();
w_mtvec(trap_m as u64);
w_mstatus(r_mstatus() | MSTATUS_MIE);
}
fn set_next_timeout() {
const CLINT_MTIME: u64 = 0x200bff8;
const CLINT_MTIMECMP: u64 = 0x2004000;
const INTERVAL: u64 = 10000000;
unsafe {
*(CLINT_MTIMECMP as *mut u64) = *(CLINT_MTIME as *const u64) + INTERVAL;
}
}
#[no_mangle]
pub extern "C" fn machine_trap_handler(context: &mut Context) {
let mcause = r_mcause();
//println!("machine_trap_handler {} epc {:x}", mcause, context.epc);
const M_TIMER_INTERRUPT: u64 = (1 << 63) | 7;
const S_ECALL: u64 = 9;
if mcause == M_TIMER_INTERRUPT {
w_mip(r_mip() | MIP_STIP);
w_sie(r_sie() | SIE_STIE);
w_mie(r_mie() & !MIE_MTIE);
} else if mcause == S_ECALL {
set_next_timeout();
w_mie(r_mie() | MIE_MTIE);
context.epc += 4;
} else {
panic!("unknown machine trap: mcause {}", mcause);
}
}
#[no_mangle]
pub extern "C" fn supervisor_trap_handler(context: &mut Context) {
let scause = r_scause();
let stval = r_stval();
// println!("supervisor_trap_handler {} epc {:x}", scause, context.epc);
const S_TIMER_INTERRUPT: u64 = (1 << 63) | 5;
const ECALL_U: u64 = 8;
const ECALL_S: u64 = 9;
const INSTRUCTION_PGFAULT: u64 = 12;
const LOAD_PGFAULT: u64 = 13;
const STORE_PGFAULT: u64 = 15;
if scause == S_TIMER_INTERRUPT {
unsafe {
TICKS += 1;
SCHED.do_timer(context);
w_sie(r_sie() & !SIE_STIE);
llvm_asm!("ecall");
}
} else if scause == ECALL_U {
println!("Environment call from U-mode: {}", stval);
} else if scause == ECALL_S {
println!("Environment call from S-mode: {}", stval);
} else if scause == INSTRUCTION_PGFAULT {
println!(
"Instruction page fault: faulting virtual address {:x}",
stval
);
} else if scause == LOAD_PGFAULT {
println!("Load page fault: faulting virtual address {:x}", stval);
} else if scause == STORE_PGFAULT {
println!("Store/AMO page fault: faulting virtual address {:x}", stval);
} else {
panic!(
"unknown supervisor trap: scause {} stval {:x}",
scause, stval
);
}
}
pub fn trap_init() {
w_stvec(trap_s as u64);
w_sstatus(r_sstatus() | SSTATUS_SIE);
}
|
#[doc = "Register `HSEM_IPIDR` reader"]
pub type R = crate::R<HSEM_IPIDR_SPEC>;
#[doc = "Field `IPID` reader - IPID"]
pub type IPID_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - IPID"]
#[inline(always)]
pub fn ipid(&self) -> IPID_R {
IPID_R::new(self.bits)
}
}
#[doc = "HSEM IP identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hsem_ipidr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct HSEM_IPIDR_SPEC;
impl crate::RegisterSpec for HSEM_IPIDR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`hsem_ipidr::R`](R) reader structure"]
impl crate::Readable for HSEM_IPIDR_SPEC {}
#[doc = "`reset()` method sets HSEM_IPIDR to value 0x0010_0072"]
impl crate::Resettable for HSEM_IPIDR_SPEC {
const RESET_VALUE: Self::Ux = 0x0010_0072;
}
|
//! Build keyboard events.
mod event;
pub use event::Event;
pub use iced_core::keyboard::{KeyCode, ModifiersState};
|
use super::*;
pub use V8::Private;
impl Private {
pub fn for_api(name: &str) -> Local<Private> {
unsafe {
V8::Private_ForApi(Isolate::raw(), V8::String::new_from_slice(name).into()).into()
}
}
}
|
use htmldsl::attributes;
use htmldsl::elements;
use htmldsl::styles;
use htmldsl::units;
use htmldsl::{TagRenderableIntoElement, TagRenderableStyleSetter};
use crate::models;
pub fn maybe_append<T>(mut vec: Vec<T>, maybe: Option<T>) -> Vec<T> {
match maybe {
Some(v) => {
vec.push(v);
vec
}
None => vec,
}
}
fn current_selection_marker<'a>() -> elements::Img<'a> {
elements::Img::style_less_with_src("/images/marker.png".to_string())
}
fn absolute_hover<'a, T: TagRenderableStyleSetter<'a>>(element: T) -> T {
element.add_style(vec![
&styles::Display::Block,
&styles::Position::Absolute,
&styles::Top {
value: units::Number::Length(0, units::Length::Pixel),
},
&styles::Left {
value: units::Number::Length(0, units::Length::Pixel),
},
])
}
impl models::Terrain {
pub fn into_html<'a>(self) -> elements::Img<'a> {
elements::Img::style_less_with_src(format!("/images/{}.png", self.image_name()))
}
fn image_name(&self) -> String {
match self {
models::Terrain::Grass => "grass",
models::Terrain::Dirt => "dirt",
models::Terrain::Rock => "rock",
}
.into()
}
}
impl models::Character {
pub fn into_html<'a>(self) -> elements::Img<'a> {
elements::Img::style_less_with_src(format!("/images/{}.png", self.image_name()))
}
fn image_name(&self) -> String {
match self {
models::Character::Knight => "knight",
models::Character::Mage => "mage",
models::Character::Thief => "thief",
}
.into()
}
}
impl models::Map {
pub fn into_html<'a, T: Iterator<Item = (&'a (u32, u32), elements::Img<'static>)>>(
&self,
overlay_elements: T,
current_selection: Option<(u32, u32)>,
) -> htmldsl::Element {
let (max_x, max_y) = self.maxes();
let mut empty_rendered_map: Vec<
Vec<(models::Terrain, Option<elements::Img<'static>>, bool)>,
> = (0..max_y)
.into_iter()
.map(|_| {
(0..max_x)
.into_iter()
.map(|_| (self.default_terrain.clone(), None, false))
.collect()
})
.collect();
for ((x, y), terrain) in self.specified_terrain.iter() {
empty_rendered_map[(max_y - *y - 1) as usize][*x as usize].0 = terrain.clone();
}
for (&(x, y), overlay_img) in overlay_elements.into_iter() {
empty_rendered_map[(max_y - y - 1) as usize][x as usize].1 = Some(overlay_img);
}
match current_selection {
Some((x, y)) => empty_rendered_map[(max_y - y - 1) as usize][x as usize].2 = true,
None => (),
};
elements::Table::style_less(
None,
elements::Tbody::style_less(
empty_rendered_map
.into_iter()
.map(|row| {
elements::Tr::style_less(
row.into_iter()
.map(|data| {
elements::Td::style_less(vec![elements::Div::style_less(
maybe_append(
maybe_append(
vec![data
.0
.into_html()
.add_style(vec![&styles::Display::Block])
.into_element()],
data.1.map(|x| absolute_hover(x).into_element()),
),
if data.2 {
Some(
absolute_hover(current_selection_marker())
.into_element(),
)
} else {
None
},
),
)
.add_style(vec![&styles::Position::Relative])
.into_element()])
})
.collect(),
)
})
.collect(),
),
)
.into_element()
}
}
impl models::Game {
pub fn into_html(&self, edit: bool) -> htmldsl::Element {
let terrain = self.map.at(&self.current_selection);
let o_character = self.character_at(&self.current_selection);
let hover_info = elements::Div::style_less(vec![
elements::P::style_less(maybe_append(
vec![
terrain.clone().into_html().into_element(),
htmldsl::text("Terrain: "),
htmldsl::text(terrain.display_string()),
],
if edit {
Some(build_terrain_adding_buttons(self.id).into_element())
} else {
None
},
))
.into_element(),
elements::P::style_less(maybe_append(
vec![
o_character
.clone()
.map_or(current_selection_marker().into_element(), |x| {
x.into_html().into_element()
}),
htmldsl::text("Character: "),
htmldsl::text(match o_character {
Some(v) => v.display_string(),
None => "--".into(),
}),
],
if edit {
Some(build_character_adding_buttons(self.id).into_element())
} else {
None
},
))
.into_element(),
])
.add_style(vec![
&styles::Display::InlineBlock,
&styles::Width {
value: units::NumberOrAuto::Number(units::Number::Length(
200,
units::Length::Pixel,
)),
},
&styles::Height {
value: units::NumberOrAuto::Number(units::Number::Length(
300,
units::Length::Pixel,
)),
},
&styles::Border {
style: units::BorderStyle::Solid,
},
])
.into_element();
elements::Table::style_less(
None,
elements::Tbody::style_less(vec![elements::Tr::style_less(vec![
elements::Td::style_less(vec![self.map.into_html(
self.characters
.iter()
.map(|(k, v)| (k, v.clone().into_html())),
Some(self.current_selection),
)]),
elements::Td::style_less(vec![hover_info]),
])]),
)
.into_element()
}
}
fn build_terrain_adding_buttons<'a>(game_id: u32) -> elements::Div<'a> {
elements::Div::style_less(
models::Terrain::all_values()
.into_iter()
.map(|x| {
elements::Form {
formmethod: attributes::Formmethod {
inner: units::FormmethodValue::Post,
},
action: Some(attributes::Action {
value: units::SourceValue::new(format!(
"/games/{}/edit/terrain/{}",
game_id,
x.url_frag_string()
)),
}),
inputs: Vec::new(),
button: elements::Button::style_less(x.into_html().into_element()),
styles: attributes::StyleAttr::new(vec![&styles::Display::Inline]),
}
.into_element()
})
.chain(
vec![elements::Form {
formmethod: attributes::Formmethod {
inner: units::FormmethodValue::Post,
},
action: Some(attributes::Action {
value: units::SourceValue::new(format!(
"/games/{}/edit/unset/terrain",
game_id,
)),
}),
inputs: Vec::new(),
button: elements::Button::style_less(htmldsl::text("delete")),
styles: attributes::StyleAttr::new(vec![&styles::Display::Inline]),
}
.into_element()]
.into_iter(),
)
.collect(),
)
}
fn build_character_adding_buttons<'a>(game_id: u32) -> elements::Div<'a> {
elements::Div::style_less(
models::Character::all_values()
.into_iter()
.map(|x| {
elements::Form {
formmethod: attributes::Formmethod {
inner: units::FormmethodValue::Post,
},
action: Some(attributes::Action {
value: units::SourceValue::new(format!(
"/games/{}/edit/character/{}",
game_id,
x.url_frag_string()
)),
}),
inputs: Vec::new(),
button: elements::Button::style_less(x.into_html().into_element()),
styles: attributes::StyleAttr::new(vec![&styles::Display::Inline]),
}
.into_element()
})
.chain(
vec![elements::Form {
formmethod: attributes::Formmethod {
inner: units::FormmethodValue::Post,
},
action: Some(attributes::Action {
value: units::SourceValue::new(format!(
"/games/{}/edit/unset/character",
game_id,
)),
}),
inputs: Vec::new(),
button: elements::Button::style_less(htmldsl::text("delete")),
styles: attributes::StyleAttr::new(vec![&styles::Display::Inline]),
}
.into_element()]
.into_iter(),
)
.collect(),
)
}
pub fn cursor_form_button(game_id: u32, dir: models::Direction, edit: bool) -> htmldsl::Element {
let (url_frag, symbol) = dir.form_strings();
elements::Form {
formmethod: attributes::Formmethod {
inner: units::FormmethodValue::Post,
},
action: Some(attributes::Action {
value: units::SourceValue::new(if edit {
format!("/games/{}/edit/cursor/{}", game_id, url_frag)
} else {
format!("/games/{}/cursor/{}", game_id, url_frag)
}),
}),
inputs: Vec::new(),
button: elements::Button::style_less(htmldsl::text(symbol)),
styles: attributes::StyleAttr::new(vec![&styles::Display::Inline]),
}
.into_element()
}
|
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
// This file was auto-created by LmcpGen. Modifications will be overwritten.
use avtas::lmcp::{Error, ErrorType, Lmcp, LmcpSubscription, SrcLoc, Struct, StructInfo};
use std::fmt::Debug;
#[derive(Clone, Debug, Default)]
#[repr(C)]
pub struct TaskOption {
pub task_id: i64,
pub option_id: i64,
pub eligible_entities: Vec<i64>,
pub cost: i64,
pub start_location: Box<::afrl::cmasi::location3d::Location3DT>,
pub start_heading: f32,
pub end_location: Box<::afrl::cmasi::location3d::Location3DT>,
pub end_heading: f32,
}
impl PartialEq for TaskOption {
fn eq(&self, _other: &TaskOption) -> bool {
true
&& &self.task_id == &_other.task_id
&& &self.option_id == &_other.option_id
&& &self.eligible_entities == &_other.eligible_entities
&& &self.cost == &_other.cost
&& &self.start_location == &_other.start_location
&& &self.start_heading == &_other.start_heading
&& &self.end_location == &_other.end_location
&& &self.end_heading == &_other.end_heading
}
}
impl LmcpSubscription for TaskOption {
fn subscription() -> &'static str { "uxas.messages.task.TaskOption" }
}
impl Struct for TaskOption {
fn struct_info() -> StructInfo {
StructInfo {
exist: 1,
series: 6149757930721443840u64,
version: 7,
struct_ty: 20,
}
}
}
impl Lmcp for TaskOption {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
let mut pos = 0;
{
let x = Self::struct_info().ser(buf)?;
pos += x;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.task_id.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.option_id.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.eligible_entities.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.cost.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.start_location.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.start_heading.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.end_location.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.end_heading.ser(r)?;
pos += writeb;
}
Ok(pos)
}
fn deser(buf: &[u8]) -> Result<(TaskOption, usize), Error> {
let mut pos = 0;
let (si, u) = StructInfo::deser(buf)?;
pos += u;
if si == TaskOption::struct_info() {
let mut out: TaskOption = Default::default();
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.task_id = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.option_id = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<i64>, usize) = Lmcp::deser(r)?;
out.eligible_entities = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.cost = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Box<::afrl::cmasi::location3d::Location3DT>, usize) = Lmcp::deser(r)?;
out.start_location = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.start_heading = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Box<::afrl::cmasi::location3d::Location3DT>, usize) = Lmcp::deser(r)?;
out.end_location = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (f32, usize) = Lmcp::deser(r)?;
out.end_heading = x;
pos += readb;
}
Ok((out, pos))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
let mut size = 15;
size += self.task_id.size();
size += self.option_id.size();
size += self.eligible_entities.size();
size += self.cost.size();
size += self.start_location.size();
size += self.start_heading.size();
size += self.end_location.size();
size += self.end_heading.size();
size
}
}
pub trait TaskOptionT: Debug + Send {
fn as_uxas_messages_task_task_option(&self) -> Option<&TaskOption> { None }
fn as_mut_uxas_messages_task_task_option(&mut self) -> Option<&mut TaskOption> { None }
fn task_id(&self) -> i64;
fn task_id_mut(&mut self) -> &mut i64;
fn option_id(&self) -> i64;
fn option_id_mut(&mut self) -> &mut i64;
fn eligible_entities(&self) -> &Vec<i64>;
fn eligible_entities_mut(&mut self) -> &mut Vec<i64>;
fn cost(&self) -> i64;
fn cost_mut(&mut self) -> &mut i64;
fn start_location(&self) -> &Box<::afrl::cmasi::location3d::Location3DT>;
fn start_location_mut(&mut self) -> &mut Box<::afrl::cmasi::location3d::Location3DT>;
fn start_heading(&self) -> f32;
fn start_heading_mut(&mut self) -> &mut f32;
fn end_location(&self) -> &Box<::afrl::cmasi::location3d::Location3DT>;
fn end_location_mut(&mut self) -> &mut Box<::afrl::cmasi::location3d::Location3DT>;
fn end_heading(&self) -> f32;
fn end_heading_mut(&mut self) -> &mut f32;
}
impl Clone for Box<TaskOptionT> {
fn clone(&self) -> Box<TaskOptionT> {
if let Some(x) = TaskOptionT::as_uxas_messages_task_task_option(self.as_ref()) {
Box::new(x.clone())
} else {
unreachable!()
}
}
}
impl Default for Box<TaskOptionT> {
fn default() -> Box<TaskOptionT> { Box::new(TaskOption::default()) }
}
impl PartialEq for Box<TaskOptionT> {
fn eq(&self, other: &Box<TaskOptionT>) -> bool {
if let (Some(x), Some(y)) =
(TaskOptionT::as_uxas_messages_task_task_option(self.as_ref()),
TaskOptionT::as_uxas_messages_task_task_option(other.as_ref())) {
x == y
} else {
false
}
}
}
impl Lmcp for Box<TaskOptionT> {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
if let Some(x) = TaskOptionT::as_uxas_messages_task_task_option(self.as_ref()) {
x.ser(buf)
} else {
unreachable!()
}
}
fn deser(buf: &[u8]) -> Result<(Box<TaskOptionT>, usize), Error> {
let (si, _) = StructInfo::deser(buf)?;
if si == TaskOption::struct_info() {
let (x, readb) = TaskOption::deser(buf)?;
Ok((Box::new(x), readb))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
if let Some(x) = TaskOptionT::as_uxas_messages_task_task_option(self.as_ref()) {
x.size()
} else {
unreachable!()
}
}
}
impl TaskOptionT for TaskOption {
fn as_uxas_messages_task_task_option(&self) -> Option<&TaskOption> { Some(self) }
fn as_mut_uxas_messages_task_task_option(&mut self) -> Option<&mut TaskOption> { Some(self) }
fn task_id(&self) -> i64 { self.task_id }
fn task_id_mut(&mut self) -> &mut i64 { &mut self.task_id }
fn option_id(&self) -> i64 { self.option_id }
fn option_id_mut(&mut self) -> &mut i64 { &mut self.option_id }
fn eligible_entities(&self) -> &Vec<i64> { &self.eligible_entities }
fn eligible_entities_mut(&mut self) -> &mut Vec<i64> { &mut self.eligible_entities }
fn cost(&self) -> i64 { self.cost }
fn cost_mut(&mut self) -> &mut i64 { &mut self.cost }
fn start_location(&self) -> &Box<::afrl::cmasi::location3d::Location3DT> { &self.start_location }
fn start_location_mut(&mut self) -> &mut Box<::afrl::cmasi::location3d::Location3DT> { &mut self.start_location }
fn start_heading(&self) -> f32 { self.start_heading }
fn start_heading_mut(&mut self) -> &mut f32 { &mut self.start_heading }
fn end_location(&self) -> &Box<::afrl::cmasi::location3d::Location3DT> { &self.end_location }
fn end_location_mut(&mut self) -> &mut Box<::afrl::cmasi::location3d::Location3DT> { &mut self.end_location }
fn end_heading(&self) -> f32 { self.end_heading }
fn end_heading_mut(&mut self) -> &mut f32 { &mut self.end_heading }
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::*;
impl Arbitrary for TaskOption {
fn arbitrary<G: Gen>(_g: &mut G) -> TaskOption {
TaskOption {
task_id: Arbitrary::arbitrary(_g),
option_id: Arbitrary::arbitrary(_g),
eligible_entities: Arbitrary::arbitrary(_g),
cost: Arbitrary::arbitrary(_g),
start_location: Box::new(::afrl::cmasi::location3d::Location3D::arbitrary(_g)),
start_heading: Arbitrary::arbitrary(_g),
end_location: Box::new(::afrl::cmasi::location3d::Location3D::arbitrary(_g)),
end_heading: Arbitrary::arbitrary(_g),
}
}
}
quickcheck! {
fn serializes(x: TaskOption) -> Result<TestResult, Error> {
use std::u16;
if x.eligible_entities.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
Ok(TestResult::from_bool(sx == x.size()))
}
fn roundtrips(x: TaskOption) -> Result<TestResult, Error> {
use std::u16;
if x.eligible_entities.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
let (y, sy) = TaskOption::deser(&buf)?;
Ok(TestResult::from_bool(sx == sy && x == y))
}
}
}
|
use std::sync::{
Arc,
atomic::{
Ordering,
AtomicUsize
}
};
use crossbeam::{
queue::ArrayQueue,
channel::{
self,
Sender,
Receiver
}
};
#[derive(PartialEq, Debug)]
pub enum DonationResult {
Donated,
NotDonated
}
#[derive(Clone)]
pub struct BeggarPool<T>
where
T: Clone
{
workers_registered: Arc<AtomicUsize>,
beggar_senders: Arc<Vec<Sender<T>>>,
beggar_receivers: Arc<Vec<Receiver<T>>>,
beggar_queue: Arc<ArrayQueue<usize>>
}
impl<T> BeggarPool<T>
where
T: Clone
{
pub fn new(num_workers: usize) -> Self
{
let mut beggar_senders = Vec::with_capacity(num_workers);
let mut beggar_receivers = Vec::with_capacity(num_workers);
let beggar_queue = Arc::new(ArrayQueue::new(num_workers));
for _ in 0..num_workers {
let (sender, receiver) = channel::bounded(1);
beggar_senders.push(sender);
beggar_receivers.push(receiver);
}
Self { workers_registered: Arc::new(AtomicUsize::new(0)), beggar_senders: Arc::new(beggar_senders), beggar_receivers: Arc::new(beggar_receivers), beggar_queue }
}
pub fn register(&mut self) -> usize {
self.workers_registered.fetch_add(1, Ordering::Relaxed)
}
pub fn beg_work(&self, id: usize) -> Option<T> {
match self.beggar_queue.push(id) {
Ok(_) => self.beggar_receivers[id].recv().ok(),
_ => None
}
}
pub fn donate_work(&self, work: &T) -> DonationResult {
match self.beggar_queue.pop().map(|id| self.beggar_senders[id].send(work.clone())) {
Ok(_) => DonationResult::Donated,
_ => DonationResult::NotDonated
}
}
pub fn is_ready(&self) -> bool {
!self.beggar_queue.is_empty()
}
} |
#[doc = "Register `WTCR` reader"]
pub type R = crate::R<WTCR_SPEC>;
#[doc = "Register `WTCR` writer"]
pub type W = crate::W<WTCR_SPEC>;
#[doc = "Field `IMODE` reader - IMODE"]
pub type IMODE_R = crate::FieldReader;
#[doc = "Field `IMODE` writer - IMODE"]
pub type IMODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `IDTR` reader - IDTR"]
pub type IDTR_R = crate::BitReader;
#[doc = "Field `IDTR` writer - IDTR"]
pub type IDTR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ISIZE` reader - ISIZE"]
pub type ISIZE_R = crate::FieldReader;
#[doc = "Field `ISIZE` writer - ISIZE"]
pub type ISIZE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `ADMODE` reader - ADMODE"]
pub type ADMODE_R = crate::FieldReader;
#[doc = "Field `ADMODE` writer - ADMODE"]
pub type ADMODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `ADDTR` reader - ADDTR"]
pub type ADDTR_R = crate::BitReader;
#[doc = "Field `ADDTR` writer - ADDTR"]
pub type ADDTR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ADSIZE` reader - ADSIZE"]
pub type ADSIZE_R = crate::FieldReader;
#[doc = "Field `ADSIZE` writer - ADSIZE"]
pub type ADSIZE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `ABMODE` reader - ABMODE"]
pub type ABMODE_R = crate::FieldReader;
#[doc = "Field `ABMODE` writer - ABMODE"]
pub type ABMODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `ABDTR` reader - ABDTR"]
pub type ABDTR_R = crate::BitReader;
#[doc = "Field `ABDTR` writer - ABDTR"]
pub type ABDTR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ABSIZE` reader - ABSIZE"]
pub type ABSIZE_R = crate::FieldReader;
#[doc = "Field `ABSIZE` writer - ABSIZE"]
pub type ABSIZE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `DMODE` reader - DMODE"]
pub type DMODE_R = crate::FieldReader;
#[doc = "Field `DMODE` writer - DMODE"]
pub type DMODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `DDTR` reader - DDTR"]
pub type DDTR_R = crate::BitReader;
#[doc = "Field `DDTR` writer - DDTR"]
pub type DDTR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DQSE` reader - DQSE"]
pub type DQSE_R = crate::BitReader;
#[doc = "Field `DQSE` writer - DQSE"]
pub type DQSE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:2 - IMODE"]
#[inline(always)]
pub fn imode(&self) -> IMODE_R {
IMODE_R::new((self.bits & 7) as u8)
}
#[doc = "Bit 3 - IDTR"]
#[inline(always)]
pub fn idtr(&self) -> IDTR_R {
IDTR_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bits 4:5 - ISIZE"]
#[inline(always)]
pub fn isize(&self) -> ISIZE_R {
ISIZE_R::new(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 8:10 - ADMODE"]
#[inline(always)]
pub fn admode(&self) -> ADMODE_R {
ADMODE_R::new(((self.bits >> 8) & 7) as u8)
}
#[doc = "Bit 11 - ADDTR"]
#[inline(always)]
pub fn addtr(&self) -> ADDTR_R {
ADDTR_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bits 12:13 - ADSIZE"]
#[inline(always)]
pub fn adsize(&self) -> ADSIZE_R {
ADSIZE_R::new(((self.bits >> 12) & 3) as u8)
}
#[doc = "Bits 16:18 - ABMODE"]
#[inline(always)]
pub fn abmode(&self) -> ABMODE_R {
ABMODE_R::new(((self.bits >> 16) & 7) as u8)
}
#[doc = "Bit 19 - ABDTR"]
#[inline(always)]
pub fn abdtr(&self) -> ABDTR_R {
ABDTR_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bits 20:21 - ABSIZE"]
#[inline(always)]
pub fn absize(&self) -> ABSIZE_R {
ABSIZE_R::new(((self.bits >> 20) & 3) as u8)
}
#[doc = "Bits 24:26 - DMODE"]
#[inline(always)]
pub fn dmode(&self) -> DMODE_R {
DMODE_R::new(((self.bits >> 24) & 7) as u8)
}
#[doc = "Bit 27 - DDTR"]
#[inline(always)]
pub fn ddtr(&self) -> DDTR_R {
DDTR_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 29 - DQSE"]
#[inline(always)]
pub fn dqse(&self) -> DQSE_R {
DQSE_R::new(((self.bits >> 29) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - IMODE"]
#[inline(always)]
#[must_use]
pub fn imode(&mut self) -> IMODE_W<WTCR_SPEC, 0> {
IMODE_W::new(self)
}
#[doc = "Bit 3 - IDTR"]
#[inline(always)]
#[must_use]
pub fn idtr(&mut self) -> IDTR_W<WTCR_SPEC, 3> {
IDTR_W::new(self)
}
#[doc = "Bits 4:5 - ISIZE"]
#[inline(always)]
#[must_use]
pub fn isize(&mut self) -> ISIZE_W<WTCR_SPEC, 4> {
ISIZE_W::new(self)
}
#[doc = "Bits 8:10 - ADMODE"]
#[inline(always)]
#[must_use]
pub fn admode(&mut self) -> ADMODE_W<WTCR_SPEC, 8> {
ADMODE_W::new(self)
}
#[doc = "Bit 11 - ADDTR"]
#[inline(always)]
#[must_use]
pub fn addtr(&mut self) -> ADDTR_W<WTCR_SPEC, 11> {
ADDTR_W::new(self)
}
#[doc = "Bits 12:13 - ADSIZE"]
#[inline(always)]
#[must_use]
pub fn adsize(&mut self) -> ADSIZE_W<WTCR_SPEC, 12> {
ADSIZE_W::new(self)
}
#[doc = "Bits 16:18 - ABMODE"]
#[inline(always)]
#[must_use]
pub fn abmode(&mut self) -> ABMODE_W<WTCR_SPEC, 16> {
ABMODE_W::new(self)
}
#[doc = "Bit 19 - ABDTR"]
#[inline(always)]
#[must_use]
pub fn abdtr(&mut self) -> ABDTR_W<WTCR_SPEC, 19> {
ABDTR_W::new(self)
}
#[doc = "Bits 20:21 - ABSIZE"]
#[inline(always)]
#[must_use]
pub fn absize(&mut self) -> ABSIZE_W<WTCR_SPEC, 20> {
ABSIZE_W::new(self)
}
#[doc = "Bits 24:26 - DMODE"]
#[inline(always)]
#[must_use]
pub fn dmode(&mut self) -> DMODE_W<WTCR_SPEC, 24> {
DMODE_W::new(self)
}
#[doc = "Bit 27 - DDTR"]
#[inline(always)]
#[must_use]
pub fn ddtr(&mut self) -> DDTR_W<WTCR_SPEC, 27> {
DDTR_W::new(self)
}
#[doc = "Bit 29 - DQSE"]
#[inline(always)]
#[must_use]
pub fn dqse(&mut self) -> DQSE_W<WTCR_SPEC, 29> {
DQSE_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 = "WTCR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wtcr::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 [`wtcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct WTCR_SPEC;
impl crate::RegisterSpec for WTCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`wtcr::R`](R) reader structure"]
impl crate::Readable for WTCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`wtcr::W`](W) writer structure"]
impl crate::Writable for WTCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets WTCR to value 0"]
impl crate::Resettable for WTCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::fs;
use std::slice;
use tensorflow::Graph;
use tensorflow::SavedModelBundle;
use tensorflow::SessionOptions;
use tensorflow::SessionRunArgs;
use tensorflow::Tensor;
fn main() {
// 加载模型
let export_dir = "pys/resnet50";
let mut graph = Graph::new();
let opts = SessionOptions::new();
let sm = SavedModelBundle::load(&opts, &["serve"], &mut graph, export_dir).unwrap();
// 加载测试图片
// 新建推理请求
let op = graph
.operation_by_name_required("serving_default_input_1")
.unwrap();
let request = read_request();
let mut step = SessionRunArgs::new();
step.add_feed(&op, 0, &request);
for op in graph.operation_iter() {
println!(">>> {:?}", op.name());
}
let output_op = graph
.operation_by_name_required("StatefulPartitionedCall")
.unwrap();
step.add_target(&output_op);
let output_t = step.request_fetch(&output_op, 0);
sm.session.run(&mut step).unwrap();
let output: Tensor<f32> = step.fetch(output_t).unwrap();
println!("{:?}", output);
}
fn read_request() -> Tensor<f32> {
let data = fs::read("pys/request").unwrap();
let data =
unsafe { slice::from_raw_parts(data.as_ptr() as *const f32, data.len() / 4 as usize) };
Tensor::new(&[1, 224, 224, 3]).with_values(&data).unwrap()
}
|
mod add;
mod generate;
mod report;
mod run;
mod update;
pub use add::*;
pub use generate::*;
pub use report::*;
pub use run::*;
pub use update::*;
|
#![no_main]
#![no_std]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::{entry, interrupt};
#[entry]
fn foo() -> ! {
loop {}
}
#[interrupt] //~ ERROR failed to resolve: use of undeclared crate or module `interrupt`
fn USART1() {}
|
#[doc = "Register `TIM12_CCER` reader"]
pub type R = crate::R<TIM12_CCER_SPEC>;
#[doc = "Register `TIM12_CCER` writer"]
pub type W = crate::W<TIM12_CCER_SPEC>;
#[doc = "Field `CC1E` reader - CC1E"]
pub type CC1E_R = crate::BitReader;
#[doc = "Field `CC1E` writer - CC1E"]
pub type CC1E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC1P` reader - CC1P"]
pub type CC1P_R = crate::BitReader;
#[doc = "Field `CC1P` writer - CC1P"]
pub type CC1P_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC1NP` reader - CC1NP"]
pub type CC1NP_R = crate::BitReader;
#[doc = "Field `CC1NP` writer - CC1NP"]
pub type CC1NP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC2E` reader - CC2E"]
pub type CC2E_R = crate::BitReader;
#[doc = "Field `CC2E` writer - CC2E"]
pub type CC2E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC2P` reader - CC2P"]
pub type CC2P_R = crate::BitReader;
#[doc = "Field `CC2P` writer - CC2P"]
pub type CC2P_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CC2NP` reader - CC2NP"]
pub type CC2NP_R = crate::BitReader;
#[doc = "Field `CC2NP` writer - CC2NP"]
pub type CC2NP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - CC1E"]
#[inline(always)]
pub fn cc1e(&self) -> CC1E_R {
CC1E_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - CC1P"]
#[inline(always)]
pub fn cc1p(&self) -> CC1P_R {
CC1P_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 3 - CC1NP"]
#[inline(always)]
pub fn cc1np(&self) -> CC1NP_R {
CC1NP_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - CC2E"]
#[inline(always)]
pub fn cc2e(&self) -> CC2E_R {
CC2E_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - CC2P"]
#[inline(always)]
pub fn cc2p(&self) -> CC2P_R {
CC2P_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 7 - CC2NP"]
#[inline(always)]
pub fn cc2np(&self) -> CC2NP_R {
CC2NP_R::new(((self.bits >> 7) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - CC1E"]
#[inline(always)]
#[must_use]
pub fn cc1e(&mut self) -> CC1E_W<TIM12_CCER_SPEC, 0> {
CC1E_W::new(self)
}
#[doc = "Bit 1 - CC1P"]
#[inline(always)]
#[must_use]
pub fn cc1p(&mut self) -> CC1P_W<TIM12_CCER_SPEC, 1> {
CC1P_W::new(self)
}
#[doc = "Bit 3 - CC1NP"]
#[inline(always)]
#[must_use]
pub fn cc1np(&mut self) -> CC1NP_W<TIM12_CCER_SPEC, 3> {
CC1NP_W::new(self)
}
#[doc = "Bit 4 - CC2E"]
#[inline(always)]
#[must_use]
pub fn cc2e(&mut self) -> CC2E_W<TIM12_CCER_SPEC, 4> {
CC2E_W::new(self)
}
#[doc = "Bit 5 - CC2P"]
#[inline(always)]
#[must_use]
pub fn cc2p(&mut self) -> CC2P_W<TIM12_CCER_SPEC, 5> {
CC2P_W::new(self)
}
#[doc = "Bit 7 - CC2NP"]
#[inline(always)]
#[must_use]
pub fn cc2np(&mut self) -> CC2NP_W<TIM12_CCER_SPEC, 7> {
CC2NP_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 = "TIM12 capture/compare enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim12_ccer::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 [`tim12_ccer::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TIM12_CCER_SPEC;
impl crate::RegisterSpec for TIM12_CCER_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`tim12_ccer::R`](R) reader structure"]
impl crate::Readable for TIM12_CCER_SPEC {}
#[doc = "`write(|w| ..)` method takes [`tim12_ccer::W`](W) writer structure"]
impl crate::Writable for TIM12_CCER_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets TIM12_CCER to value 0"]
impl crate::Resettable for TIM12_CCER_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::faucet_config;
use base64::decode;
use faucet_config::{load_faucet_conf, FaucetConf};
use faucet_proto::proto::faucet::{
create_sg_faucet, FaucetRequest as FaucetRequestProto, SgFaucet,
};
use faucet_proto::FaucetRequest;
use grpc_helpers::{provide_grpc_response, spawn_service_thread_with_drop_closure, ServerHandle};
use libra_config::config::ConsensusKeyPair;
use libra_crypto::ed25519::*;
use libra_logger::prelude::*;
use sgchain::star_chain_client::{ChainClient, StarChainClient};
use std::path::PathBuf;
use std::{clone::Clone, convert::TryFrom, fs, sync::Arc};
use tokio::runtime::Runtime;
pub struct FaucetNode {}
impl FaucetNode {
pub fn load_and_run() -> ServerHandle {
let current_dir = PathBuf::from("./");
let faucet_conf = load_faucet_conf(format!(
"{}/{}",
fs::canonicalize(¤t_dir)
.expect("path err.")
.to_str()
.expect("str err."),
"sgfaucet/faucet-service"
));
Self::run(faucet_conf)
}
pub fn run(faucet_conf: FaucetConf) -> ServerHandle {
let (host, port) = faucet_conf.server();
let faucet_service = SgFaucetService::new(faucet_conf);
spawn_service_thread_with_drop_closure(
create_sg_faucet(faucet_service.clone()),
host,
port,
"faucet",
Some(100_000_000),
move || {
// shutdown_receiver.recv().expect(
// "Failed to receive on shutdown channel when storage service was dropped",
// )
},
)
}
}
#[derive(Clone)]
pub struct SgFaucetService {
chain_client: StarChainClient,
key_pair: Arc<Ed25519PrivateKey>,
}
impl SgFaucetService {
pub fn new(faucet_conf: FaucetConf) -> Self {
let (host, port) = faucet_conf.chain();
let chain_client = StarChainClient::new(host.as_str(), port as u32);
let pri_file = faucet_conf.pri_file().expect("pri key is none.");
let key_base64 =
decode(&fs::read(pri_file).expect("read pri file err.")).expect("base64 decode err.");
let pri_key =
Ed25519PrivateKey::try_from(key_base64.as_ref()).expect("Ed25519PrivateKey parse err.");
// let key_pair = generate_keypair::load_key_from_file(
// pri_file,
// ).expect("Faucet account key is required to generate config");
let key_pair = ConsensusKeyPair::load(pri_key)
.take_private()
.expect("pri key is none.");
SgFaucetService {
chain_client,
key_pair: Arc::new(key_pair),
}
}
}
impl SgFaucet for SgFaucetService {
fn faucet(
&mut self,
ctx: ::grpcio::RpcContext,
req: FaucetRequestProto,
sink: ::grpcio::UnarySink<()>,
) {
let faucet_req = FaucetRequest::try_from(req).expect("parse err.");
let mut rt = Runtime::new().expect("faucet runtime err.");
let chain_client = self.chain_client.clone();
let mut can_faucet = false;
let exist_flag = chain_client.account_exist(&faucet_req.address, None);
if !exist_flag {
can_faucet = true;
} else {
let account_state = chain_client.get_account_state(faucet_req.address, None);
match account_state {
Ok(account) => match account.get_account_resource() {
Some(a_r) => {
if a_r.balance() < 10_000_000 {
can_faucet = true;
}
}
None => {
can_faucet = true;
}
},
Err(e) => {
warn!("{:?}", e);
}
}
}
if can_faucet {
let f = async move {
chain_client
.faucet_with_sender(
None,
self.key_pair.as_ref(),
faucet_req.address,
faucet_req.amount,
)
.await
};
rt.block_on(f).expect("faucet err.");
}
provide_grpc_response(Ok(()), ctx, sink);
}
}
|
use log::error;
use rand::Rng;
use serenity::{
framework::standard::{macros::command, Args, CommandResult},
model::channel::Message,
prelude::*,
};
#[command]
#[description = "Bot will generate a random number between min and max and reply with the result."]
#[usage = "min max"]
#[example = "-999 999"]
fn rng(ctx: &mut Context, msg: &Message, args: Args) -> CommandResult {
fn min_and_max(mut a: Args) -> (i64, i64) {
let min = a.single::<i64>().unwrap_or(9223372036854775807);
let max = a.single::<i64>().unwrap_or(9223372036854775807);
(min, max)
}
let (min, max) = min_and_max(args);
let message: String = "Could not generate a random number, please try again.".to_string();
if min == 9223372036854775807 {
let message_specific: String = "The min value supplied is invalid.".to_string();
error!("{}", message_specific);
msg.channel_id.say(&ctx.http, message_specific)?;
msg.channel_id.say(&ctx.http, message)?;
return Ok(());
} else if max == 9223372036854775807 {
let message_specific: String = "The max value supplied is invalid.".to_string();
error!("{}", message_specific);
msg.channel_id.say(&ctx.http, message_specific)?;
msg.channel_id.say(&ctx.http, message)?;
return Ok(());
} else if min == max {
let message_specific: String =
"The min value must not be equal to, or greater than, the max value.".to_string();
error!("{}", message_specific);
msg.channel_id.say(&ctx.http, message_specific)?;
msg.channel_id.say(&ctx.http, message)?;
return Ok(());
} else if min > max {
let message_specific: String =
"The min value must be lower than the max value.".to_string();
error!("{}", message_specific);
msg.channel_id.say(&ctx.http, message_specific)?;
msg.channel_id.say(&ctx.http, message)?;
return Ok(());
}
let random_number = rand::thread_rng().gen_range(min, max);
if let Err(why) = msg.channel_id.say(&ctx.http, &random_number.to_string()) {
error!("Could not send randomly generated number because: {}", why);
msg.channel_id.say(
&ctx.http,
"Could not generate a random number, please try again.",
)?;
}
Ok(())
}
|
fn main() {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let nums = line
.trim()
.split_whitespace()
.into_iter()
.map(|c| c.parse::<f64>().unwrap())
.collect::<Vec<_>>();
println!(
"{}",
((nums[0] - nums[2]).powf(2.0) + (nums[1] - nums[3]).powf(2.0)).sqrt()
)
}
|
#[macro_use]
extern crate lazy_static;
extern crate regex;
use regex::Regex;
use std::cmp::{max, min};
const INPUT: &str = include_str!("../input.txt");
struct Reindeer {
name: String,
speed: u32,
duration: u32,
rest: u32,
}
impl Reindeer {
fn from_str(input: &str) -> Self {
lazy_static! {
static ref RE_REINDEER: Regex = Regex::new(r"(?P<name>[a-zA-Z]+)[^0-9]+(?P<speed>[0-9]+)[^0-9]+(?P<duration>[0-9]+)[^0-9]+(?P<rest>[0-9]+)[^0-9]+").unwrap();
}
match RE_REINDEER.captures(input) {
Some(cap) => {
let name = cap
.name("name")
.map_or(String::from(""), |m| String::from(m.as_str()));
let speed = cap
.name("speed")
.map_or(0u32, |m| m.as_str().parse::<u32>().unwrap());
let duration = cap
.name("duration")
.map_or(0u32, |m| m.as_str().parse::<u32>().unwrap());
let rest = cap
.name("rest")
.map_or(0u32, |m| m.as_str().parse::<u32>().unwrap());
Reindeer {
name,
speed,
duration,
rest,
}
}
None => {
panic!("Couldn't parse reindeer: {}", input);
}
}
}
fn distance_travelled(&self, seconds: u32) -> u32 {
// distance travelled during full cycles
((seconds / (self.duration + self.rest)) * self.duration * self.speed)
// distance travelled in the remaining time
+ min(seconds % (self.duration + self.rest), self.duration) * self.speed
}
}
fn format_input(input_str: &str) -> Vec<Reindeer> {
let mut result: Vec<Reindeer> = Vec::new();
for line in input_str.lines() {
result.push(Reindeer::from_str(line));
}
result
}
fn solve_part_1(input_str: &str) -> u32 {
let reindeers: Vec<Reindeer> = format_input(input_str);
let mut results: Vec<(String, u32)> = Vec::new();
let mut result: u32 = 0;
for reindeer in reindeers {
results.push((reindeer.name.clone(), reindeer.distance_travelled(2503)));
}
for (_, dst) in results {
if dst > result {
result = dst;
}
}
result
}
fn solve_part_2(input_str: &str) -> u32 {
let reindeers: Vec<Reindeer> = format_input(input_str);
let mut scores: Vec<u32> = Vec::new();
for _ in 0..reindeers.len() {
scores.push(0);
}
for t in 1..=2503 {
let mut distance: Vec<u32> = Vec::new();
let mut temp: u32 = 0u32;
for r in 0..reindeers.len() {
let dst: u32 = reindeers[r].distance_travelled(t);
distance.push(dst);
temp = max(temp, dst);
}
for r in 0..reindeers.len() {
if distance[r] == temp {
scores[r] += 1;
}
}
}
*scores.iter().max().unwrap()
}
fn main() {
println!("Answer part 1: {}", solve_part_1(INPUT));
println!("Answer part 2: {}", solve_part_2(INPUT));
}
|
use std::fmt;
#[derive(Clone, Copy, Debug)]
pub struct ChunkHeader {
offset: u64,
header_size: u16,
chunk_size: u32,
chunk_type: u16,
}
impl ChunkHeader {
pub fn new(offset: u64, header_size: u16, chunk_size: u32, chunk_type: u16) -> Self {
Self {
offset,
header_size,
chunk_size,
chunk_type,
}
}
pub fn get_offset(&self) -> u64 {
self.offset
}
pub fn get_header_size(&self) -> u16 {
self.header_size
}
pub fn get_data_offset(&self) -> u64 {
self.offset + u64::from(self.header_size)
}
pub fn get_chunk_end(&self) -> u64 {
self.offset + u64::from(self.chunk_size)
}
pub fn absolute(&self, relative: u64) -> u64 {
let absolute = self.offset + relative;
if absolute > self.get_chunk_end() {
panic!("Requested a relative value out of bounds");
}
absolute
}
pub fn get_token(&self) -> u16 {
self.chunk_type
}
}
impl fmt::Display for ChunkHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"(Token:{:X}; Start: {}; Data: {}; End {})",
self.chunk_type,
self.offset,
self.get_data_offset(),
self.get_chunk_end()
)
}
}
#[cfg(test)]
mod tests {
use super::ChunkHeader;
#[test]
pub fn it_returns_data_offset() {
let chunk = ChunkHeader::new(4000, 8, 16, 0);
assert_eq!(4008, chunk.get_data_offset());
}
#[test]
pub fn it_returns_chunk_end() {
let chunk = ChunkHeader::new(4000, 8, 16, 0);
assert_eq!(4016, chunk.get_chunk_end());
}
#[test]
#[should_panic]
pub fn it_panics_from_relative_out_of_bound() {
let chunk = ChunkHeader::new(4000, 8, 500, 0);
chunk.absolute(510);
}
#[test]
pub fn it_returns_absolute_offsets_from_relative_ones() {
let chunk = ChunkHeader::new(4000, 8, 500, 0);
let res = chunk.absolute(490);
assert_eq!(4490, res);
}
}
|
use SafeWrapper;
use ir::{User, Instruction, Value, TerminatorInst, Block};
use sys;
use std::ptr;
/// A conditional or unconditional branch.
pub struct BranchInst<'ctx>(TerminatorInst<'ctx>);
impl<'ctx> BranchInst<'ctx>
{
/// Creates an unconditional branch.
pub fn unconditional(destination: &Block) -> Self {
unsafe { BranchInst::new(None, destination, None) }
}
/// Creates a conditional branch.
///
/// At least one of `on_true` or `on_false` must be specified.
pub fn conditional(condition: &Value,
on_true: &Block,
on_false: Option<&Block>) -> Self {
unsafe { BranchInst::new(Some(condition), on_true, on_false) }
}
/// Creates a new branch.
unsafe fn new(condition: Option<&Value>,
on_true: &Block,
on_false: Option<&Block>) -> Self {
let condition = condition.map(Value::inner).unwrap_or(ptr::null_mut());
let on_false = on_false.map(|b| b.inner()).unwrap_or(ptr::null_mut());
let inner = sys::LLVMRustCreateBranchInst(on_true.inner(), on_false, condition);
wrap_value!(inner => User => Instruction => TerminatorInst => BranchInst)
}
}
impl_subtype!(BranchInst => TerminatorInst);
#[cfg(test)]
mod test
{
use ir;
#[test]
fn can_create_unconditional() {
let context = ir::Context::new();
let bb = ir::Block::new(&context);
ir::BranchInst::unconditional(&bb);
}
#[test]
fn can_create_conditional() {
let context = ir::Context::new();
let bb = ir::Block::new(&context);
let t = ir::ConstantInt::boolean_true(&context);
ir::BranchInst::conditional(&t, &bb, None);
}
#[test]
fn can_create_conditional_else() {
let context = ir::Context::new();
let bbtrue = ir::Block::new(&context);
let bbfalse = ir::Block::new(&context);
let t = ir::ConstantInt::boolean_true(&context);
ir::BranchInst::conditional(&t, &bbtrue, Some(&bbfalse));
}
}
|
#![deny(
missing_debug_implementations,
trivial_numeric_casts,
unstable_features,
unused_import_braces,
unused_qualifications
)]
extern crate clap;
extern crate notify;
extern crate hyper;
extern crate futures;
extern crate tempdir;
extern crate reqwest;
extern crate pbr;
extern crate libflate;
extern crate tar;
extern crate sha1;
extern crate sha2;
extern crate digest;
extern crate toml;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate handlebars;
extern crate unicode_categories;
extern crate indexmap;
extern crate websocket;
extern crate regex;
extern crate walkdir;
extern crate base_x;
extern crate parity_wasm;
#[macro_use]
extern crate log;
extern crate rustc_demangle;
extern crate env_logger;
extern crate cargo_metadata;
extern crate ansi_term;
extern crate semver;
extern crate memmap;
use std::process::exit;
use std::env;
use clap::{
Arg,
App,
AppSettings,
SubCommand
};
#[allow(dead_code)]
mod app_dirs;
mod cargo_shim;
#[macro_use]
mod utils;
mod http_utils;
mod config;
mod package;
mod build;
mod deployment;
mod error;
mod wasm;
mod wasm_gc;
mod wasm_inline_js;
mod wasm_export_main;
mod wasm_export_table;
mod wasm_hook_grow;
mod wasm_runtime;
mod wasm_context;
mod wasm_intrinsics;
mod wasm_js_export;
mod emscripten;
mod test_chromium;
mod chrome_devtools;
mod cmd_build;
mod cmd_start;
mod cmd_test;
mod cmd_deploy;
mod cmd_prepare_emscripten;
fn add_shared_build_params< 'a, 'b >( app: App< 'a, 'b > ) -> App< 'a, 'b > {
return app
.arg(
Arg::with_name( "package" )
.short( "p" )
.long( "package" )
.help( "Package to build" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "features" )
.long( "features" )
.help( "Space-separated list of features to also build" )
.value_name( "FEATURES" )
.takes_value( true )
)
.arg(
Arg::with_name( "all-features" )
.long( "all-features" )
.help( "Build all available features" )
// Technically Cargo doesn't treat it as conflicting,
// but it seems less confusing to *not* allow these together.
.conflicts_with_all( &[ "features", "no-default-features" ] )
)
.arg(
Arg::with_name( "no-default-features" )
.long( "no-default-features" )
.help( "Do not build the `default` feature" )
)
.arg(
Arg::with_name( "use-system-emscripten" )
.long( "use-system-emscripten" )
.help( "Won't try to download Emscripten; will always use the system one" )
)
.arg(
Arg::with_name( "release" )
.long( "release" )
.help( "Build artifacts in release mode, with optimizations" )
)
.arg(
Arg::with_name( "target" )
.long( "target" )
.takes_value( true )
.value_name( "TRIPLE" )
.help( "Build for the target [default: asmjs-unknown-emscripten]" )
.possible_values( &[ "asmjs-unknown-emscripten", "wasm32-unknown-emscripten", "wasm32-unknown-unknown" ] )
.conflicts_with_all( &["target-asmjs-emscripten", "target-webasm-emscripten", "target-webasm"] )
)
.arg(
Arg::with_name( "verbose" )
.short( "v" )
.long( "verbose" )
.help( "Use verbose output" )
)
// These three are legacy options kept for compatibility.
.arg(
Arg::with_name( "target-asmjs-emscripten" )
.long( "target-asmjs-emscripten" )
.help( "Generate asmjs through Emscripten (default)" )
.overrides_with_all( &["target-webasm-emscripten", "target-webasm"] )
.hidden( true )
)
.arg(
Arg::with_name( "target-webasm-emscripten" )
.long( "target-webasm-emscripten" )
.help( "Generate webasm through Emscripten" )
.overrides_with_all( &["target-asmjs-emscripten", "target-webasm"] )
.hidden( true )
)
.arg(
Arg::with_name( "target-webasm" )
.long( "target-webasm" )
.help( "Generates webasm through Rust's native backend (HIGHLY EXPERIMENTAL!)" )
.overrides_with_all( &["target-asmjs-emscripten", "target-webasm-emscripten"] )
.hidden( true )
);
}
fn main() {
if let Ok( value ) = env::var( "CARGO_WEB_LOG" ) {
let mut builder = env_logger::Builder::new();
builder.parse( &value );
builder.init();
}
let args = {
// To allow running both as 'cargo-web' and as 'cargo web'.
let mut args = env::args();
let mut filtered_args = Vec::new();
filtered_args.push( args.next().unwrap() );
match args.next() {
None => {},
#[cfg(any(unix))]
Some( ref arg ) if filtered_args[ 0 ].ends_with( "cargo-web" ) && arg == "web" => {},
#[cfg(any(windows))]
Some( ref arg ) if filtered_args[ 0 ].ends_with( "cargo-web.exe" ) && arg == "web" => {},
Some( arg ) => filtered_args.push( arg )
}
filtered_args.extend( args );
filtered_args
};
let mut build_subcommand =
SubCommand::with_name( "build" )
.about( "Compile a local package and all of its dependencies" )
.arg(
Arg::with_name( "lib" )
.long( "lib" )
.help( "Build only this package's library" )
)
.arg(
Arg::with_name( "bin" )
.long( "bin" )
.help( "Build only the specified binary" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "example" )
.long( "example" )
.help( "Build only the specified example" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "test" )
.long( "test" )
.help( "Build only the specified test target" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "bench" )
.long( "bench" )
.help( "Build only the specified benchmark target" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "message-format" )
.long( "message-format" )
.help( "Selects the stdout output format" )
.value_name( "FMT" )
.takes_value( true )
.default_value( "human" )
.possible_values( &[
"human",
"json"
])
)
.arg(
Arg::with_name( "runtime" )
.long( "runtime" )
.takes_value( true )
.value_name( "RUNTIME" )
.help( "Selects the type of JavaScript runtime which will be generated; valid only for the `wasm32-unknown-unknown` target" )
.possible_values( &["standalone", "experimental-only-loader"] )
.default_value_if(
"target", Some( "wasm32-unknown-unknown" ),
"standalone"
)
.hidden( true ) // This is experimental for now.
);
let mut test_subcommand =
SubCommand::with_name( "test" )
.about( "Compiles and runs tests" )
.arg(
Arg::with_name( "no-run" )
.long( "no-run" )
.help( "Compile, but don't run tests" )
)
.arg(
Arg::with_name( "nodejs" )
.long( "nodejs" )
.help( "Uses Node.js to run the tests" )
)
.arg(
Arg::with_name( "passthrough" )
.help( "-- followed by anything will pass the arguments to the test runner")
.multiple( true )
.takes_value( true )
.last( true )
);
let mut start_subcommand =
SubCommand::with_name( "start" )
.about( "Runs an embedded web server serving the built project" )
.arg(
Arg::with_name( "bin" )
.long( "bin" )
.help( "Build only the specified binary" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "example" )
.long( "example" )
.help( "Serves the specified example" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "test" )
.long( "test" )
.help( "Build only the specified test target" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "bench" )
.long( "bench" )
.help( "Build only the specified benchmark target" )
.value_name( "NAME" )
.takes_value( true )
)
.arg(
Arg::with_name( "host" )
.long( "host" )
.help( "Bind the server to this address, default `localhost`")
.value_name( "HOST" )
.takes_value( true )
)
.arg(
Arg::with_name( "port" )
.long( "port" )
.help( "Bind the server to this port, default 8000" )
.value_name( "PORT" )
.takes_value( true )
)
.arg(
Arg::with_name( "auto-reload" )
.long( "auto-reload" )
.help( "Will try to automatically reload the page on rebuild" )
);
let mut deploy_subcommand =
SubCommand::with_name( "deploy" )
.about( "Deploys your project so that its ready to be served statically" );
let prepare_emscripten_subcommand =
SubCommand::with_name( "prepare-emscripten" )
.about( "Fetches and installs prebuilt Emscripten packages" );
build_subcommand = add_shared_build_params( build_subcommand );
test_subcommand = add_shared_build_params( test_subcommand );
start_subcommand = add_shared_build_params( start_subcommand );
deploy_subcommand = add_shared_build_params( deploy_subcommand );
let matches = App::new( "cargo-web" )
.version( env!( "CARGO_PKG_VERSION" ) )
.setting( AppSettings::SubcommandRequiredElseHelp )
.setting( AppSettings::VersionlessSubcommands )
.subcommand( build_subcommand )
.subcommand( test_subcommand )
.subcommand( start_subcommand )
.subcommand( deploy_subcommand )
.subcommand( prepare_emscripten_subcommand )
.get_matches_from( args );
let result = if let Some( matches ) = matches.subcommand_matches( "build" ) {
cmd_build::command_build( matches )
} else if let Some( matches ) = matches.subcommand_matches( "test" ) {
cmd_test::command_test( matches )
} else if let Some( matches ) = matches.subcommand_matches( "start" ) {
cmd_start::command_start( matches )
} else if let Some( matches ) = matches.subcommand_matches( "deploy" ) {
cmd_deploy::command_deploy( matches )
} else if let Some( _ ) = matches.subcommand_matches( "prepare-emscripten" ) {
cmd_prepare_emscripten::command_prepare_emscripten()
} else {
return;
};
match result {
Ok( _ ) => {},
Err( error ) => {
eprintln!( "error: {}", error );
exit( 101 );
}
}
}
|
//! Get info on your direct messages.
use rtm::{Cursor, Im, Message, ThreadInfo};
use timestamp::Timestamp;
/// Close a direct message channel.
///
/// Wraps https://api.slack.com/methods/im.close
#[derive(Clone, Debug, Serialize, new)]
pub struct CloseRequest {
/// Direct message channel to close.
pub channel: ::DmId,
}
/// Fetches history of messages and events from direct message channel.
///
/// Wraps https://api.slack.com/methods/im.history
#[derive(Clone, Debug, Serialize, new)]
pub struct HistoryRequest {
/// Direct message channel to fetch history for.
pub channel: ::DmId,
/// End of time range of messages to include in results.
#[new(default)]
pub latest: Option<::Timestamp>,
/// Start of time range of messages to include in results.
#[new(default)]
pub oldest: Option<::Timestamp>,
/// Include messages with latest or oldest timestamp in results.
#[new(default)]
pub inclusive: Option<bool>,
/// Number of messages to return, between 1 and 1000.
#[new(default)]
pub count: Option<u32>,
/// Include unread_count_display in the output?
#[new(default)]
pub unreads: Option<bool>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HistoryResponse {
ok: bool,
pub has_more: Option<bool>,
pub latest: Option<String>,
#[serde(default)]
pub messages: Vec<Message>,
pub is_limited: Option<bool>,
}
/// Lists direct message channels for the calling user.
///
/// Wraps https://api.slack.com/methods/im.list
#[derive(Clone, Debug, Serialize, new)]
pub struct ListRequest {
/// Paginate through collections of data by setting the `cursor` parameter to a `next_cursor` attribute returned by a previous request's `response_metadata`. Default value fetches the first "page" of the collection. See pagination for more detail.
#[new(default)]
pub cursor: Option<Cursor>,
/// The maximum number of items to return. Fewer than the requested number of items may be returned, even if the end of the users list hasn't been reached.
#[new(default)]
pub limit: Option<u32>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ListResponse {
ok: bool,
#[serde(default)]
pub ims: Vec<Im>,
}
/// Sets the read cursor in a direct message channel.
///
/// Wraps https://api.slack.com/methods/im.mark
#[derive(Clone, Debug, Serialize, new)]
pub struct MarkRequest {
/// Direct message channel to set reading cursor in.
pub channel: ::DmId,
/// Timestamp of the most recently seen message.
pub ts: Timestamp,
}
/// Opens a direct message channel.
///
/// Wraps https://api.slack.com/methods/im.open
#[derive(Clone, Debug, Serialize, new)]
pub struct OpenRequest {
/// User to open a direct message channel with.
pub user: ::UserId,
/// Boolean, indicates you want the full IM channel definition in the response.
#[new(default)]
pub return_im: Option<bool>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct OpenResponse {
ok: bool,
pub channel: Option<Im>,
}
/// Retrieve a thread of messages posted to a direct message conversation
///
/// Wraps https://api.slack.com/methods/im.replies
#[derive(Clone, Debug, Serialize, new)]
pub struct RepliesRequest {
/// Direct message channel to fetch thread from
pub channel: ::DmId,
/// Unique identifier of a thread's parent message
pub thread_ts: Timestamp,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RepliesResponse {
ok: bool,
pub messages: Option<Vec<Message>>,
pub thread_info: Option<ThreadInfo>,
}
|
fn revrot(s: &str, c: usize) -> String {
if s.len() < c || s.is_empty() || c == 0 { return "".to_string() }
let (cur, rest) = s.split_at(c);
let sum: u32 = cur.chars().map(|c| c.to_digit(10).unwrap().pow(3)).sum();
let result = match sum % 2 {
0 => cur.chars().rev().collect(),
_ => String::from(&cur[1..]) + &cur[0..1]
};
result + &revrot(rest, c)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_revrot() {
assert_eq!(revrot("1234", 0), "");
assert_eq!(revrot("", 5), "");
assert_eq!(revrot("1234", 5), "");
assert_eq!(revrot("1234", 2), "2143");
assert_eq!(revrot("131246", 3), "311642");
}
fn testing(s: &str, c: usize, exp: &str) -> () {
assert_eq!(&revrot(s, c), exp)
}
#[test]
fn basics_revrot() {
testing("1234", 0, "");
testing("", 0, "");
testing("1234", 5, "");
let s = "733049910872815764";
testing(s, 5, "330479108928157");
let s = "73304991087281576455176044327690580265896";
testing(s, 8, "1994033775182780067155464327690480265895");
}
}
|
#[doc = "Register `SR` reader"]
pub type R = crate::R<SR_SPEC>;
#[doc = "Field `TAMP1F` reader - TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the TAMP1 input."]
pub type TAMP1F_R = crate::BitReader;
#[doc = "Field `TAMP2F` reader - TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the TAMP2 input."]
pub type TAMP2F_R = crate::BitReader;
#[doc = "Field `ITAMP3F` reader - LSE monitoring tamper detection flag This flag is set by hardware when a tamper detection event is detected on the internal tamper 3."]
pub type ITAMP3F_R = crate::BitReader;
#[doc = "Field `ITAMP4F` reader - HSE monitoring tamper detection flag This flag is set by hardware when a tamper detection event is detected on the internal tamper 4."]
pub type ITAMP4F_R = crate::BitReader;
#[doc = "Field `ITAMP5F` reader - RTC calendar overflow tamper detection flag This flag is set by hardware when a tamper detection event is detected on the internal tamper 5."]
pub type ITAMP5F_R = crate::BitReader;
#[doc = "Field `ITAMP6F` reader - ST manufacturer readout tamper detection flag This flag is set by hardware when a tamper detection event is detected on the internal tamper 6."]
pub type ITAMP6F_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the TAMP1 input."]
#[inline(always)]
pub fn tamp1f(&self) -> TAMP1F_R {
TAMP1F_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the TAMP2 input."]
#[inline(always)]
pub fn tamp2f(&self) -> TAMP2F_R {
TAMP2F_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 18 - LSE monitoring tamper detection flag This flag is set by hardware when a tamper detection event is detected on the internal tamper 3."]
#[inline(always)]
pub fn itamp3f(&self) -> ITAMP3F_R {
ITAMP3F_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - HSE monitoring tamper detection flag This flag is set by hardware when a tamper detection event is detected on the internal tamper 4."]
#[inline(always)]
pub fn itamp4f(&self) -> ITAMP4F_R {
ITAMP4F_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - RTC calendar overflow tamper detection flag This flag is set by hardware when a tamper detection event is detected on the internal tamper 5."]
#[inline(always)]
pub fn itamp5f(&self) -> ITAMP5F_R {
ITAMP5F_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - ST manufacturer readout tamper detection flag This flag is set by hardware when a tamper detection event is detected on the internal tamper 6."]
#[inline(always)]
pub fn itamp6f(&self) -> ITAMP6F_R {
ITAMP6F_R::new(((self.bits >> 21) & 1) != 0)
}
}
#[doc = "TAMP status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SR_SPEC;
impl crate::RegisterSpec for SR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`sr::R`](R) reader structure"]
impl crate::Readable for SR_SPEC {}
#[doc = "`reset()` method sets SR to value 0"]
impl crate::Resettable for SR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b7133593f835927b8046/libraries/eosiolib/contracts/eosio/action.hpp#L249-L274>
use alloc::string::{String, ToString};
use alloc::{format, vec};
use alloc::vec::Vec;
use core::str::FromStr;
use codec::{Encode, Decode};
use crate::{
AccountName, ActionName, Asset, Digest, NumBytes,
PermissionLevel, Read, SerializeData, Write
};
#[cfg(feature = "std")]
use serde::{
Serialize, Deserialize,
de::Error as DeError,
ser::{Error as SerError, Serializer, SerializeStruct}
};
/// This is the packed representation of an action along with meta-data about
/// the authorization levels.
#[derive(Clone, Debug, Read, Write, NumBytes, PartialEq, Default, Encode, Decode, Digest, SerializeData)]
#[eosio_core_root_path = "crate"]
#[repr(C)]
pub struct Action {
/// Name of the account the action is intended for
pub account: AccountName,
/// Name of the action
pub name: ActionName,
/// List of permissions that authorize this action
pub authorization: Vec<PermissionLevel>,
/// Payload data
pub data: Vec<u8>,
}
#[cfg(feature = "std")]
impl<'de> serde::Deserialize<'de> for Action {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::de::Deserializer<'de>
{
#[derive(Debug)]
struct VisitorAction;
impl<'de> serde::de::Visitor<'de> for VisitorAction
{
type Value = Action;
fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "string or a struct, but this is: {:?}", self)
}
fn visit_map<D>(self, mut map: D) -> Result<Self::Value, D::Error>
where D: serde::de::MapAccess<'de>,
{
let mut account = AccountName::default();
let mut name = ActionName::default();
let mut authorization: Vec<PermissionLevel> = vec![];
let mut data: Vec<u8> = vec![];
while let Some(field) = map.next_key()? {
match field {
"account" => {
account = map.next_value()?;
}
"name" => {
name = map.next_value()?;
}
"authorization" => {
authorization= map.next_value()?;
}
"hex_data" => {
let val: String= map.next_value()?;
data = hex::decode(val).map_err(D::Error::custom)?;
}
_ => {
let _: serde_json::Value = map.next_value()?;
continue;
}
}
}
let action = Action {
account,
name,
authorization,
data,
};
Ok(action)
}
}
deserializer.deserialize_any(VisitorAction)
}
}
impl Action {
pub fn new(account: AccountName, name: ActionName, authorization: Vec<PermissionLevel>, data: Vec<u8>) -> Self {
Action { account, name, authorization, data }
}
pub fn from_str<T: AsRef<str>, S: SerializeData>(
account: T,
name: T,
authorization: Vec<PermissionLevel>,
action_data: S
) -> crate::Result<Self> {
let account = FromStr::from_str(account.as_ref()).map_err(crate::Error::from)?;
let name = FromStr::from_str(name.as_ref()).map_err(crate::Error::from)?;
let data = action_data.to_serialize_data()?;
Ok(Action { account, name, authorization, data })
}
pub fn transfer<T: AsRef<str>>(from: T, to: T, quantity: T, memo: T) -> crate::Result<Action> {
let permission_level = PermissionLevel::from_str(from.as_ref(), "active")?;
let action_transfer = ActionTransfer::from_str(from, to, quantity, memo)?;
Action::from_str(
"eosio.token",
"transfer",
vec![permission_level],
action_transfer
)
}
}
impl core::fmt::Display for Action {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "account: {}\n\
name: {}\n\
authorization: {}\n\
hex_data: {}",
self.account,
self.name,
self.authorization.iter().map(|item| format!("{}", item)).collect::<String>(),
hex::encode(&self.data),
)
}
}
#[cfg(feature = "std")]
impl serde::ser::Serialize for Action {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
let mut state = serializer.serialize_struct("Action", 5)?;
state.serialize_field("account", &self.account)?;
state.serialize_field("name", &self.name)?;
state.serialize_field("authorization", &self.authorization)?;
state.serialize_field("hex_data", &hex::encode(&self.data))?;
match (self.account.to_string().as_str(), self.name.to_string().as_str()) {
("eosio.token", "transfer") => {
let data = ActionTransfer::read(&self.data, &mut 0).map_err(|_| S::Error::custom("Action read from data failed."))?;
state.serialize_field("data", &data)?;
},
_ => {}
}
state.end()
}
}
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Read, Write, NumBytes, Default, SerializeData)]
#[eosio_core_root_path = "crate"]
pub struct ActionTransfer {
pub from: AccountName,
pub to: AccountName,
pub quantity: Asset,
pub memo: String,
}
impl ActionTransfer {
pub fn new(from: AccountName, to: AccountName, quantity: Asset, memo: String) -> Self {
ActionTransfer { from, to, quantity, memo }
}
pub fn from_str<T: AsRef<str>>(from: T, to: T, quantity: T, memo: T) -> crate::Result<Self> {
let from = FromStr::from_str(from.as_ref()).map_err(crate::Error::from)?;
let to = FromStr::from_str(to.as_ref()).map_err(crate::Error::from)?;
let quantity = FromStr::from_str(quantity.as_ref()).map_err(crate::Error::from)?;
let memo = memo.as_ref().to_string();
Ok(ActionTransfer { from, to, quantity, memo })
}
}
pub trait ToAction: Write + NumBytes {
const NAME: u64;
#[inline]
fn to_action(
&self,
account: AccountName,
authorization: Vec<PermissionLevel>,
) -> crate::Result<Action> {
let mut data = vec![0_u8; self.num_bytes()];
self.write(&mut data, &mut 0).map_err(crate::Error::BytesWriteError)?;
Ok(Action {
account,
name: Self::NAME.into(),
authorization,
data,
})
}
}
#[cfg(test)]
mod tests {
use hex;
use super::*;
#[test]
fn action_hash_should_work() {
let action = Action {
account: FromStr::from_str("eosio.token").unwrap(),
name: FromStr::from_str("issue").unwrap(),
authorization: vec![PermissionLevel {
actor: FromStr::from_str("eosio").unwrap(),
permission: FromStr::from_str("active").unwrap(),
}],
data: hex::decode("0000000000ea305500625e5a1809000004454f530000000004696e6974").unwrap(),
};
let hash = action.digest().unwrap();
assert_eq!(hash, "0221f3da945a3de738cdb744f7963a6a3486097ab42436d1f4e13a1ade502bb9".into());
}
#[test]
fn action_transfer_serialize_should_work() {
let action = Action::transfer("testa", "testb", "1.0000 EOS", "a memo").ok().unwrap();
let data = action.to_serialize_data();
assert!(data.is_ok());
let data = data.unwrap();
assert_eq!(
hex::encode(data),
"00a6823403ea3055000000572d3ccdcd01000000000093b1ca00000000a8ed323227000000000093b1ca000000008093b1ca102700000000000004454f53000000000661206d656d6f"
);
}
#[test]
fn action_deserialize_should_be_ok() {
let action_str = r#"
{
"account": "eosio.token",
"name": "transfer",
"authorization": [
{
"actor": "junglefaucet",
"permission": "active"
}
],
"data": {
"from": "junglefaucet",
"receiver": "megasuper333",
"stake_net_quantity": "1.0000 EOS",
"stake_cpu_quantity": "1.0000 EOS",
"transfer": 1
},
"hex_data": "9015d266a9c8a67e30c6b8aa6a6c989240420f000000000004454f5300000000134e657720425020526567697374726174696f6e"
}"#;
let action: Result<Action, _> = serde_json::from_str(action_str);
assert!(action.is_ok());
let hash = action.unwrap().digest().unwrap();
assert_eq!(hash, "eaa3b4bf845a1b41668ab7ca49fb5644fc91a6c0156dfd33911b4ec69d2e41d6".into())
}
}
|
extern crate failure;
#[macro_use]
extern crate failure_derive;
#[macro_use]
extern crate nom;
#[macro_use]
extern crate log;
pub mod errors;
pub mod keywords;
pub mod parser;
pub mod scc;
pub mod types;
|
//! `StatusReporter` is to expose the necessary operational information
//! to the outside world.
use crate::prelude::*;
use std::convert::TryFrom;
/// # Required features
///
/// This function requires the `status-report` feature of the `delay_timer`
/// crate to be enabled.
#[derive(Debug, Clone)]
pub struct StatusReporter {
inner: AsyncReceiver<PublicEvent>,
}
impl StatusReporter {
pub fn get_public_event(&self) -> AnyResult<PublicEvent> {
let event = self.inner.try_recv()?;
Ok(event)
}
pub(crate) fn new(inner: AsyncReceiver<PublicEvent>) -> Self {
Self { inner }
}
}
#[derive(Debug, Copy, Clone)]
pub enum PublicEvent {
RemoveTask(u64),
RunningTask(u64, i64),
FinishTask(u64, i64),
}
impl TryFrom<&TimerEvent> for PublicEvent {
type Error = &'static str;
fn try_from(timer_event: &TimerEvent) -> Result<Self, Self::Error> {
match timer_event {
TimerEvent::RemoveTask(task_id) => Ok(PublicEvent::RemoveTask(*task_id)),
TimerEvent::AppendTaskHandle(_, delay_task_handler_box) => {
Ok(PublicEvent::RunningTask(delay_task_handler_box.get_task_id(), delay_task_handler_box.get_record_id()))
}
TimerEvent::FinishTask(task_id, record_id, _) => {
Ok(PublicEvent::FinishTask(*task_id, *record_id))
}
_ => Err("PublicEvent only accepts timer_event some variant( RemoveTask, CancelTask ,FinishTask )!"),
}
}
}
impl PublicEvent {
pub fn get_task_id(&self) -> u64 {
match self {
PublicEvent::RemoveTask(ref task_id) => *task_id,
PublicEvent::RunningTask(ref task_id, _) => *task_id,
PublicEvent::FinishTask(ref task_id, _) => *task_id,
}
}
pub fn get_record_id(&self) -> Option<i64> {
match self {
PublicEvent::RemoveTask(_) => None,
PublicEvent::RunningTask(_,ref record_id) => Some(*record_id),
PublicEvent::FinishTask(_,ref record_id) => Some(*record_id),
}
}
}
|
#[doc = "Register `IOPRSTR` reader"]
pub type R = crate::R<IOPRSTR_SPEC>;
#[doc = "Register `IOPRSTR` writer"]
pub type W = crate::W<IOPRSTR_SPEC>;
#[doc = "Field `GPIOARST` reader - I/O port A reset This bit is set and cleared by software."]
pub type GPIOARST_R = crate::BitReader;
#[doc = "Field `GPIOARST` writer - I/O port A reset This bit is set and cleared by software."]
pub type GPIOARST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOBRST` reader - I/O port B reset This bit is set and cleared by software."]
pub type GPIOBRST_R = crate::BitReader;
#[doc = "Field `GPIOBRST` writer - I/O port B reset This bit is set and cleared by software."]
pub type GPIOBRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOCRST` reader - I/O port C reset This bit is set and cleared by software."]
pub type GPIOCRST_R = crate::BitReader;
#[doc = "Field `GPIOCRST` writer - I/O port C reset This bit is set and cleared by software."]
pub type GPIOCRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIODRST` reader - I/O port D reset This bit is set and cleared by software."]
pub type GPIODRST_R = crate::BitReader;
#[doc = "Field `GPIODRST` writer - I/O port D reset This bit is set and cleared by software."]
pub type GPIODRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOFRST` reader - I/O port F reset This bit is set and cleared by software."]
pub type GPIOFRST_R = crate::BitReader;
#[doc = "Field `GPIOFRST` writer - I/O port F reset This bit is set and cleared by software."]
pub type GPIOFRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - I/O port A reset This bit is set and cleared by software."]
#[inline(always)]
pub fn gpioarst(&self) -> GPIOARST_R {
GPIOARST_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - I/O port B reset This bit is set and cleared by software."]
#[inline(always)]
pub fn gpiobrst(&self) -> GPIOBRST_R {
GPIOBRST_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - I/O port C reset This bit is set and cleared by software."]
#[inline(always)]
pub fn gpiocrst(&self) -> GPIOCRST_R {
GPIOCRST_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - I/O port D reset This bit is set and cleared by software."]
#[inline(always)]
pub fn gpiodrst(&self) -> GPIODRST_R {
GPIODRST_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 5 - I/O port F reset This bit is set and cleared by software."]
#[inline(always)]
pub fn gpiofrst(&self) -> GPIOFRST_R {
GPIOFRST_R::new(((self.bits >> 5) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - I/O port A reset This bit is set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpioarst(&mut self) -> GPIOARST_W<IOPRSTR_SPEC, 0> {
GPIOARST_W::new(self)
}
#[doc = "Bit 1 - I/O port B reset This bit is set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpiobrst(&mut self) -> GPIOBRST_W<IOPRSTR_SPEC, 1> {
GPIOBRST_W::new(self)
}
#[doc = "Bit 2 - I/O port C reset This bit is set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpiocrst(&mut self) -> GPIOCRST_W<IOPRSTR_SPEC, 2> {
GPIOCRST_W::new(self)
}
#[doc = "Bit 3 - I/O port D reset This bit is set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpiodrst(&mut self) -> GPIODRST_W<IOPRSTR_SPEC, 3> {
GPIODRST_W::new(self)
}
#[doc = "Bit 5 - I/O port F reset This bit is set and cleared by software."]
#[inline(always)]
#[must_use]
pub fn gpiofrst(&mut self) -> GPIOFRST_W<IOPRSTR_SPEC, 5> {
GPIOFRST_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 = "RCC I/O port reset register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ioprstr::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 [`ioprstr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IOPRSTR_SPEC;
impl crate::RegisterSpec for IOPRSTR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ioprstr::R`](R) reader structure"]
impl crate::Readable for IOPRSTR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ioprstr::W`](W) writer structure"]
impl crate::Writable for IOPRSTR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets IOPRSTR to value 0"]
impl crate::Resettable for IOPRSTR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
println!("--output--");
if let Some(arg) = std::env::args().skip(1).next() {
println!("Argument: {}", arg);
}
|
use crate::prelude::*;
pub fn visibility_system(world: &mut World) {
let player_entity = world.resource_entity::<Player>().ok();
for (entity, (viewshed, pos)) in world.query::<(&mut Viewshed, &Position)>().into_iter() {
if viewshed.dirty {
if let Some((_, map)) = world.query::<&mut TileMap>().into_iter().next() {
update_viewshed(viewshed, pos, map);
// If this is the player, reveal what they can see
if Some(entity) == player_entity {
apply_viewshed_to_map(viewshed, map);
}
}
}
}
}
fn update_viewshed(viewshed: &mut Viewshed, pos: &Position, map: &TileMap) {
viewshed.dirty = false;
viewshed.visible_tiles.clear();
viewshed.visible_tiles = field_of_view(pos.to_point(), viewshed.range, &*map);
viewshed
.visible_tiles
.retain(|p| p.x >= 0 && p.x < map.get_width() && p.y >= 0 && p.y < map.get_height());
}
fn apply_viewshed_to_map(viewshed: &mut Viewshed, map: &mut TileMap) {
map.clear_visible_tiles();
for vis in viewshed.visible_tiles.iter() {
map.set_tile_revealed(vis.x, vis.y);
map.set_tile_visible(vis.x, vis.y);
}
}
|
#[doc = "Register `AHB3RSTR` reader"]
pub type R = crate::R<AHB3RSTR_SPEC>;
#[doc = "Register `AHB3RSTR` writer"]
pub type W = crate::W<AHB3RSTR_SPEC>;
#[doc = "Field `MDMARST` reader - MDMA block reset"]
pub type MDMARST_R = crate::BitReader<MDMARST_A>;
#[doc = "MDMA block reset\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MDMARST_A {
#[doc = "1: Reset the selected module"]
Reset = 1,
}
impl From<MDMARST_A> for bool {
#[inline(always)]
fn from(variant: MDMARST_A) -> Self {
variant as u8 != 0
}
}
impl MDMARST_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<MDMARST_A> {
match self.bits {
true => Some(MDMARST_A::Reset),
_ => None,
}
}
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn is_reset(&self) -> bool {
*self == MDMARST_A::Reset
}
}
#[doc = "Field `MDMARST` writer - MDMA block reset"]
pub type MDMARST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MDMARST_A>;
impl<'a, REG, const O: u8> MDMARST_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Reset the selected module"]
#[inline(always)]
pub fn reset(self) -> &'a mut crate::W<REG> {
self.variant(MDMARST_A::Reset)
}
}
#[doc = "Field `DMA2DRST` reader - DMA2D block reset"]
pub use MDMARST_R as DMA2DRST_R;
#[doc = "Field `JPGDECRST` reader - JPGDEC block reset"]
pub use MDMARST_R as JPGDECRST_R;
#[doc = "Field `FMCRST` reader - FMC block reset"]
pub use MDMARST_R as FMCRST_R;
#[doc = "Field `QSPIRST` reader - QUADSPI and QUADSPI delay block reset"]
pub use MDMARST_R as QSPIRST_R;
#[doc = "Field `SDMMC1RST` reader - SDMMC1 and SDMMC1 delay block reset"]
pub use MDMARST_R as SDMMC1RST_R;
#[doc = "Field `CPURST` reader - CPU reset"]
pub use MDMARST_R as CPURST_R;
#[doc = "Field `DMA2DRST` writer - DMA2D block reset"]
pub use MDMARST_W as DMA2DRST_W;
#[doc = "Field `JPGDECRST` writer - JPGDEC block reset"]
pub use MDMARST_W as JPGDECRST_W;
#[doc = "Field `FMCRST` writer - FMC block reset"]
pub use MDMARST_W as FMCRST_W;
#[doc = "Field `QSPIRST` writer - QUADSPI and QUADSPI delay block reset"]
pub use MDMARST_W as QSPIRST_W;
#[doc = "Field `SDMMC1RST` writer - SDMMC1 and SDMMC1 delay block reset"]
pub use MDMARST_W as SDMMC1RST_W;
#[doc = "Field `CPURST` writer - CPU reset"]
pub use MDMARST_W as CPURST_W;
impl R {
#[doc = "Bit 0 - MDMA block reset"]
#[inline(always)]
pub fn mdmarst(&self) -> MDMARST_R {
MDMARST_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 4 - DMA2D block reset"]
#[inline(always)]
pub fn dma2drst(&self) -> DMA2DRST_R {
DMA2DRST_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - JPGDEC block reset"]
#[inline(always)]
pub fn jpgdecrst(&self) -> JPGDECRST_R {
JPGDECRST_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 12 - FMC block reset"]
#[inline(always)]
pub fn fmcrst(&self) -> FMCRST_R {
FMCRST_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 14 - QUADSPI and QUADSPI delay block reset"]
#[inline(always)]
pub fn qspirst(&self) -> QSPIRST_R {
QSPIRST_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 16 - SDMMC1 and SDMMC1 delay block reset"]
#[inline(always)]
pub fn sdmmc1rst(&self) -> SDMMC1RST_R {
SDMMC1RST_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 31 - CPU reset"]
#[inline(always)]
pub fn cpurst(&self) -> CPURST_R {
CPURST_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - MDMA block reset"]
#[inline(always)]
#[must_use]
pub fn mdmarst(&mut self) -> MDMARST_W<AHB3RSTR_SPEC, 0> {
MDMARST_W::new(self)
}
#[doc = "Bit 4 - DMA2D block reset"]
#[inline(always)]
#[must_use]
pub fn dma2drst(&mut self) -> DMA2DRST_W<AHB3RSTR_SPEC, 4> {
DMA2DRST_W::new(self)
}
#[doc = "Bit 5 - JPGDEC block reset"]
#[inline(always)]
#[must_use]
pub fn jpgdecrst(&mut self) -> JPGDECRST_W<AHB3RSTR_SPEC, 5> {
JPGDECRST_W::new(self)
}
#[doc = "Bit 12 - FMC block reset"]
#[inline(always)]
#[must_use]
pub fn fmcrst(&mut self) -> FMCRST_W<AHB3RSTR_SPEC, 12> {
FMCRST_W::new(self)
}
#[doc = "Bit 14 - QUADSPI and QUADSPI delay block reset"]
#[inline(always)]
#[must_use]
pub fn qspirst(&mut self) -> QSPIRST_W<AHB3RSTR_SPEC, 14> {
QSPIRST_W::new(self)
}
#[doc = "Bit 16 - SDMMC1 and SDMMC1 delay block reset"]
#[inline(always)]
#[must_use]
pub fn sdmmc1rst(&mut self) -> SDMMC1RST_W<AHB3RSTR_SPEC, 16> {
SDMMC1RST_W::new(self)
}
#[doc = "Bit 31 - CPU reset"]
#[inline(always)]
#[must_use]
pub fn cpurst(&mut self) -> CPURST_W<AHB3RSTR_SPEC, 31> {
CPURST_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 = "RCC AHB3 Reset Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb3rstr::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 [`ahb3rstr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB3RSTR_SPEC;
impl crate::RegisterSpec for AHB3RSTR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb3rstr::R`](R) reader structure"]
impl crate::Readable for AHB3RSTR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb3rstr::W`](W) writer structure"]
impl crate::Writable for AHB3RSTR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB3RSTR to value 0"]
impl crate::Resettable for AHB3RSTR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[cfg(target_os = "linux")]
fn are_you_on_linux() {
println!("You are running linux!")
}
#[cfg(not(target_os = "linux"))]
fn are_you_on_linux() {
println!("You are *not* running linux!")
}
mod tests {
use crate::cfg::are_you_on_linux;
#[test]
fn main() {
are_you_on_linux();
println!("Are you sure?");
if cfg!(target_os = "linux") {
println!("It's linux");
} else {
println!("It's not linux!");
}
}
} |
use std::io::{stdout, Read, Write};
use std::fs::File;
use indicatif::{ProgressBar, ProgressStyle};
use curl::easy::{Easy, List};
use memmap::MmapOptions;
use serde_json::Value as JSONValue;
use error::OpenstackError;
use client::Response;
pub fn upload_to_object_store(
file: &mut File,
object_store_url: &str,
token: &str,
) -> Result<Response, OpenstackError> {
let mut headers = List::new();
headers.append(&format!("X-Auth-Token: {}", token))?;
let mut data = Vec::new();
let mut easy = Easy::new();
easy.url(object_store_url)?;
easy.upload(true)?;
easy.http_headers(headers)?;
easy.progress(true)?;
let mut remote_headers = vec![];
{
let progress_bar = make_progress_bar(file.metadata()?.len());
let mut transfer = easy.transfer();
transfer.progress_function(|_a, _b, _c, d| {
if d as u32 != 0 {
progress_bar.set_position(d as u64);
}
true
})?;
transfer
.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
})?;
transfer.header_function(|header| {
remote_headers.push(String::from_utf8(header.to_vec()).unwrap_or(String::from(" : ")));
true
})?;
transfer.read_function(|into| Ok(file.read(into).unwrap()))?;
transfer.perform()?;
progress_bar.finish();
}
// println!("{:?}", String::from_utf8(data).unwrap_or(String::from("")));
// Ok(String::from_utf8(data).unwrap_or(String::from("")))
let response_data = JSONValue::String(String::from_utf8(data).unwrap_or(String::from("")));
Ok(Response{0: response_data, 1: easy.response_code()?, 2: remote_headers})
}
pub fn download_from_object_store(
file: &mut File,
object_store_url: &str,
token: &str,
) -> Result<Response, OpenstackError> {
let mut headers = List::new();
headers.append(&format!("X-Auth-Token: {}", token))?;
// let urlpath = &format!("{}/{}/{}", object_store_url, container, name);
let urlpath = object_store_url;
let mut easy = Easy::new();
easy.url(urlpath)?;
easy.get(true)?;
easy.http_headers(headers)?;
easy.progress(true)?;
let mut remote_headers = vec![];
{
let progress_bar = make_progress_bar(0);
let mut transfer = easy.transfer();
transfer.progress_function(|a, b, _c, _d| {
if a as u32 != 0 {
progress_bar.set_length(a as u64);
progress_bar.set_position(b as u64);
}
true
})?;
transfer.write_function(|data| Ok(file.write(data).unwrap()))?;
transfer.header_function(|header| {
remote_headers.push(String::from_utf8(header.to_vec()).unwrap_or(String::from(" : ")));
true
})?;
transfer.perform()?;
progress_bar.finish();
}
let statuscode = easy.response_code()?;
// Ok((String::from(""), statuscode))
let response_data = JSONValue::String(String::from(""));
Ok(Response{0: response_data, 1: easy.response_code()?, 2: remote_headers})
}
pub fn upload_to_object_store_dynamic_large_objects(
file: &File,
name: &str,
container: &str,
object_store_url: &str,
token: &str,
parts: usize,
skip_first: usize,
) -> Result<Response, OpenstackError> {
let fileurl = object_store_url;
let mut headers = List::new();
headers.append(&format!("X-Auth-Token: {}", token))?;
let mut easy = Easy::new();
easy.url(fileurl)?;
easy.upload(true)?;
easy.http_headers(headers)?;
easy.write_function(|into| Ok(stdout().write(into).unwrap()))?;
easy.perform()?;
let mut responses = Vec::new();
let mut success = true;
{
let mmap = unsafe { MmapOptions::new().map(file)? };
let amount = (mmap.len() as f32 / (parts as f32 - 0.1)) as usize;
let chuckies = mmap.chunks(amount).skip(skip_first);
for (index, mut chunk) in chuckies.enumerate() {
let response = upload_part(&mut chunk, index, fileurl, token)?;
if !response.is_success() {
success = false;
responses.push(response);
break;
}
responses.push(response);
}
}
if success == true {
set_dynamic_manifest(fileurl, container, name, token)?;
}
match success {
true => Ok(responses[responses.len()-1].clone()),
false => Ok(responses[0].clone()),
}
}
pub fn open_file(filename: &str) -> Result<File, OpenstackError> {
let filepath = is_file(filename)?;
Ok(File::open(filepath)?)
}
pub fn create_file(filename: &str) -> Result<File, OpenstackError> {
make_sure_folder_exists(filename)?;
Ok(File::create(filename)?)
}
fn is_file(filename: &str) -> Result<std::path::PathBuf, OpenstackError> {
let filepath = std::path::PathBuf::from(filename);
if !filepath.is_file() {
return Err(
OpenstackError::new(&format!("'{}' does not exist", filename))
);
}
Ok(filepath)
}
fn make_sure_folder_exists(filename: &str) -> Result<(), OpenstackError> {
let filepath = std::path::PathBuf::from(filename);
let parent = match filepath.parent(){
Some(x) => x.to_path_buf(),
None => return Ok(())
};
std::fs::DirBuilder::new().recursive(true).create(parent)?;
Ok(())
}
fn make_objectstore_url(store_url: &str, container: &str, filename: &str) -> String {
format!("{}/{}/{}", store_url, container, filename)
}
fn set_dynamic_manifest(
fileurl: &str,
container: &str,
filename: &str,
token: &str,
) -> Result<(String, u32), OpenstackError> {
let mut headers = List::new();
headers.append(&format!("X-Auth-Token: {}", token))?;
headers.append(&format!("X-Object-Manifest: {}/{}/", container, filename))?;
let mut data = Vec::new();
let mut easy = Easy::new();
easy.url(&fileurl)?;
easy.upload(true)?;
easy.http_headers(headers)?;
{
let mut transfer = easy.transfer();
transfer.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
})?;
transfer.perform()?;
}
Ok((
String::from_utf8(data).unwrap_or(String::from("")),
easy.response_code()?,
))
}
fn upload_part(
chunk: &mut &[u8],
index: usize,
fileurl: &str,
token: &str,
) -> Result<Response, OpenstackError> {
let mut headers = List::new();
headers.append(&format!("X-Auth-Token: {}", token))?;
let mut data = Vec::new();
let mut easy = Easy::new();
easy.url(&format!("{}/{:08}", fileurl, index))?;
easy.upload(true)?;
easy.progress(true)?;
easy.http_headers(headers)?;
let mut remote_headers = vec![];
{
let progress_bar = make_progress_bar(chunk.len() as u64);
let mut transfer = easy.transfer();
transfer.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
})?;
transfer.progress_function(|_a, _b, _c, d| {
if d as u32 != 0 {
progress_bar.set_position(d as u64);
}
true
})?;
transfer.header_function(|header| {
remote_headers.push(String::from_utf8(header.to_vec()).unwrap_or(String::from(" : ")));
true
})?;
transfer.read_function(|into| Ok(chunk.read(into).unwrap()))?;
transfer.perform()?;
progress_bar.finish();
}
Ok(Response{
0: JSONValue::String(String::from_utf8(data).unwrap_or(String::from(""))),
1: easy.response_code()?,
2: remote_headers,
})
}
pub fn make_progress_bar(length: u64) -> ProgressBar{
let progress_bar = ProgressBar::new(length);
progress_bar.set_style(
ProgressStyle::default_bar()
.template("[{elapsed_precise}] {wide_bar:.cyan/blue} {bytes:>7}/{total_bytes:7}"),
);
progress_bar
} |
use ndarray::prelude::*;
use ndarray_rand::rand::{thread_rng, Rng};
use ndarray_rand::rand_distr::WeightedIndex;
use ndarray_stats::QuantileExt;
use crate::rl::prelude::*;
/// Allows Agents to be trained using a genetic algorithm
pub trait Evolve {
fn mutate(&mut self, mutation_rate: f64);
fn crossover(&self, other: &Self) -> Self;
}
/// Trains Agent by making it compete against different versions of itself,
/// and setting the Agent as the best Agent in each generation.
pub struct GeneticAlgorithm {
agent_amount: usize,
mutation_rate: f64,
}
impl GeneticAlgorithm {
pub fn new(agent_amount: usize, mutation_rate: f64) -> Self {
Self {
agent_amount,
mutation_rate,
}
}
/// use scores to generate new generation using survival of the fittest
fn new_generation<AC, AG>(
&mut self,
old_generation: Vec<&AG>,
scores: &Array1<Reward>,
) -> Vec<AG>
where
AC: Action,
AG: Agent<AC> + Evolve,
{
assert_eq!(
scores.len(),
self.agent_amount,
"scores length must match agent amount"
);
let min_score = scores.min().expect("failed to get min score");
let max_score = scores.min().expect("failed to get max score");
let weights = match min_score == max_score {
true => Array1::ones(scores.len()),
false => scores - *min_score,
};
let weighted_dist = WeightedIndex::new(&weights).unwrap();
let mut new_generation = vec![];
let mut rng = thread_rng();
for _ in 0..self.agent_amount {
let parents_indices: Vec<usize> =
(&mut rng).sample_iter(&weighted_dist).take(2).collect();
let a0 = &old_generation[parents_indices[0]];
let a1 = &old_generation[parents_indices[1]];
let mut child = a0.crossover(a1);
child.mutate(self.mutation_rate);
new_generation.push(child);
}
new_generation
}
}
impl<AC, AG> Trainer<AC, AG> for GeneticAlgorithm
where
AC: Action,
AG: Agent<AC> + Evolve,
{
fn train<'a, E: Environment<AC>>(
&mut self,
agent: &'a mut AG,
env: &E,
epochs: usize,
verbose: bool,
) {
// create multiple agents and an env for each one
let mut agents = vec![agent.clone(); self.agent_amount];
let mut envs = vec![env.clone(); self.agent_amount];
// run epochs
let max_reward = env.max_reward();
for e in 0..epochs {
let mut scores = Array1::zeros(self.agent_amount);
// evaluate each agent
for (i, (agent, environment)) in agents.iter_mut().zip(envs.iter_mut()).enumerate() {
let mut score = 0.;
environment.reset();
while !environment.is_done() && score < max_reward {
let action = agent.act(&environment.observe());
let reward = environment.step(&action);
score += reward;
}
scores[i] = score;
}
if verbose {
println!(
"epoch {} | max score: {} | avg scores: {} | min score: {}",
e,
scores.max().unwrap(),
scores.sum() / self.agent_amount as f32,
scores.min().unwrap()
);
}
// update agent as the best agent of the current generation
*agent = agents[scores.argmax().unwrap()].clone();
// spawn new generation
agents = self.new_generation(agents.iter().collect(), &scores);
// HILLCLIMBING: save the best agent from each generation
agents[0] = agent.clone();
}
}
}
#[cfg(test)]
mod tests {
use crate::neuron::activations::{linear, relu, sigmoid};
use crate::neuron::layers::Layer;
use crate::neuron::networks::Network;
use crate::neuron::transfers::dense;
use crate::rl::agents::NeuroEvolutionAgent;
use crate::rl::environments::JumpEnvironment;
use crate::rl::trainers::genetic_algorithm::GeneticAlgorithm;
use super::*;
#[test]
fn test_neuro_evolution_learner() {
let env = JumpEnvironment::new(10);
let env_observation_space = env.observation_space();
let env_action_space = env.action_space();
let l1 = Layer::new(3, env_observation_space, dense(), relu());
let l2 = Layer::new(4, 3, dense(), sigmoid());
let l3 = Layer::new(env_action_space, 4, dense(), linear());
let network_layers = vec![l1, l2, l3];
let mut agent = NeuroEvolutionAgent::new(Network::new(network_layers));
let agent_amount = 10;
let mutation_rate = 0.01;
let mut learner = GeneticAlgorithm::new(agent_amount, mutation_rate);
let epochs = 10;
learner.train(&mut agent, &env, epochs, false);
}
}
|
#[doc = "Register `BTR` reader"]
pub type R = crate::R<BTR_SPEC>;
#[doc = "Register `BTR` writer"]
pub type W = crate::W<BTR_SPEC>;
#[doc = "Field `BRP` reader - BRP"]
pub type BRP_R = crate::FieldReader<u16>;
#[doc = "Field `BRP` writer - BRP"]
pub type BRP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 10, O, u16>;
#[doc = "Field `TS1` reader - TS1"]
pub type TS1_R = crate::FieldReader;
#[doc = "Field `TS1` writer - TS1"]
pub type TS1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `TS2` reader - TS2"]
pub type TS2_R = crate::FieldReader;
#[doc = "Field `TS2` writer - TS2"]
pub type TS2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `SJW` reader - SJW"]
pub type SJW_R = crate::FieldReader;
#[doc = "Field `SJW` writer - SJW"]
pub type SJW_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `LBKM` reader - LBKM"]
pub type LBKM_R = crate::BitReader;
#[doc = "Field `LBKM` writer - LBKM"]
pub type LBKM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SILM` reader - SILM"]
pub type SILM_R = crate::BitReader;
#[doc = "Field `SILM` writer - SILM"]
pub type SILM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:9 - BRP"]
#[inline(always)]
pub fn brp(&self) -> BRP_R {
BRP_R::new((self.bits & 0x03ff) as u16)
}
#[doc = "Bits 16:19 - TS1"]
#[inline(always)]
pub fn ts1(&self) -> TS1_R {
TS1_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 20:22 - TS2"]
#[inline(always)]
pub fn ts2(&self) -> TS2_R {
TS2_R::new(((self.bits >> 20) & 7) as u8)
}
#[doc = "Bits 24:25 - SJW"]
#[inline(always)]
pub fn sjw(&self) -> SJW_R {
SJW_R::new(((self.bits >> 24) & 3) as u8)
}
#[doc = "Bit 30 - LBKM"]
#[inline(always)]
pub fn lbkm(&self) -> LBKM_R {
LBKM_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - SILM"]
#[inline(always)]
pub fn silm(&self) -> SILM_R {
SILM_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:9 - BRP"]
#[inline(always)]
#[must_use]
pub fn brp(&mut self) -> BRP_W<BTR_SPEC, 0> {
BRP_W::new(self)
}
#[doc = "Bits 16:19 - TS1"]
#[inline(always)]
#[must_use]
pub fn ts1(&mut self) -> TS1_W<BTR_SPEC, 16> {
TS1_W::new(self)
}
#[doc = "Bits 20:22 - TS2"]
#[inline(always)]
#[must_use]
pub fn ts2(&mut self) -> TS2_W<BTR_SPEC, 20> {
TS2_W::new(self)
}
#[doc = "Bits 24:25 - SJW"]
#[inline(always)]
#[must_use]
pub fn sjw(&mut self) -> SJW_W<BTR_SPEC, 24> {
SJW_W::new(self)
}
#[doc = "Bit 30 - LBKM"]
#[inline(always)]
#[must_use]
pub fn lbkm(&mut self) -> LBKM_W<BTR_SPEC, 30> {
LBKM_W::new(self)
}
#[doc = "Bit 31 - SILM"]
#[inline(always)]
#[must_use]
pub fn silm(&mut self) -> SILM_W<BTR_SPEC, 31> {
SILM_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 = "CAN_BTR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`btr::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 [`btr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct BTR_SPEC;
impl crate::RegisterSpec for BTR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`btr::R`](R) reader structure"]
impl crate::Readable for BTR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`btr::W`](W) writer structure"]
impl crate::Writable for BTR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets BTR to value 0"]
impl crate::Resettable for BTR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
pub use generated::*;
use crate::demo::message::bspdecal::*;
use crate::demo::message::classinfo::*;
use crate::demo::message::gameevent::*;
use crate::demo::message::packetentities::*;
use crate::demo::message::setconvar::*;
use crate::demo::message::stringtable::*;
use crate::demo::message::tempentities::*;
use crate::demo::message::usermessage::*;
use crate::demo::message::voice::*;
use crate::demo::parser::{Encode, ParseBitSkip};
use crate::{Parse, ParserState, Result, Stream};
use bitbuffer::{BitRead, BitWrite, BitWriteStream, LittleEndian};
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
pub mod bspdecal;
pub mod classinfo;
pub mod gameevent;
pub mod generated;
pub mod packetentities;
pub mod setconvar;
pub mod stringtable;
pub mod tempentities;
pub mod usermessage;
pub mod voice;
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(
BitRead, BitWrite, Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr,
)]
#[repr(u8)]
#[discriminant_bits = 6]
pub enum MessageType {
Empty = 0,
File = 2,
NetTick = 3,
StringCmd = 4,
SetConVar = 5,
SignOnState = 6,
Print = 7,
ServerInfo = 8,
ClassInfo = 10,
SetPause = 11,
CreateStringTable = 12,
UpdateStringTable = 13,
VoiceInit = 14,
VoiceData = 15,
ParseSounds = 17,
SetView = 18,
FixAngle = 19,
BspDecal = 21,
UserMessage = 23,
EntityMessage = 24,
GameEvent = 25,
PacketEntities = 26,
TempEntities = 27,
PreFetch = 28,
Menu = 29,
GameEventList = 30,
GetCvarValue = 31,
CmdKeyValues = 32,
}
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
#[serde(bound(deserialize = "'a: 'static"))]
#[serde(tag = "type")]
pub enum Message<'a> {
Empty,
File(FileMessage),
NetTick(NetTickMessage),
StringCmd(StringCmdMessage),
SetConVar(SetConVarMessage),
SignOnState(SignOnStateMessage),
Print(PrintMessage),
ServerInfo(Box<ServerInfoMessage>),
ClassInfo(ClassInfoMessage),
SetPause(SetPauseMessage),
CreateStringTable(CreateStringTableMessage<'a>),
UpdateStringTable(UpdateStringTableMessage<'a>),
VoiceInit(VoiceInitMessage),
VoiceData(VoiceDataMessage<'a>),
ParseSounds(ParseSoundsMessage<'a>),
SetView(SetViewMessage),
FixAngle(FixAngleMessage),
BspDecal(BSPDecalMessage),
UserMessage(UserMessage<'a>),
EntityMessage(EntityMessage<'a>),
GameEvent(GameEventMessage),
PacketEntities(PacketEntitiesMessage),
TempEntities(TempEntitiesMessage),
PreFetch(PreFetchMessage),
Menu(MenuMessage<'a>),
GameEventList(GameEventListMessage),
GetCvarValue(GetCvarValueMessage),
CmdKeyValues(CmdKeyValuesMessage<'a>),
}
impl<'a> Parse<'a> for Message<'a> {
fn parse(stream: &mut Stream<'a>, state: &ParserState) -> Result<Self> {
let message_type = MessageType::parse(stream, state)?;
Self::from_type(message_type, stream, state)
}
}
impl<'a> Message<'a> {
pub fn get_message_type(&self) -> MessageType {
match self {
Message::Empty => MessageType::Empty,
Message::File(_) => MessageType::File,
Message::NetTick(_) => MessageType::NetTick,
Message::StringCmd(_) => MessageType::StringCmd,
Message::SetConVar(_) => MessageType::SetConVar,
Message::SignOnState(_) => MessageType::SignOnState,
Message::Print(_) => MessageType::Print,
Message::ServerInfo(_) => MessageType::ServerInfo,
Message::ClassInfo(_) => MessageType::ClassInfo,
Message::SetPause(_) => MessageType::SetPause,
Message::CreateStringTable(_) => MessageType::CreateStringTable,
Message::UpdateStringTable(_) => MessageType::UpdateStringTable,
Message::VoiceInit(_) => MessageType::VoiceInit,
Message::VoiceData(_) => MessageType::VoiceData,
Message::ParseSounds(_) => MessageType::ParseSounds,
Message::SetView(_) => MessageType::SetView,
Message::FixAngle(_) => MessageType::FixAngle,
Message::BspDecal(_) => MessageType::BspDecal,
Message::UserMessage(_) => MessageType::UserMessage,
Message::EntityMessage(_) => MessageType::EntityMessage,
Message::GameEvent(_) => MessageType::GameEvent,
Message::PacketEntities(_) => MessageType::PacketEntities,
Message::TempEntities(_) => MessageType::TempEntities,
Message::PreFetch(_) => MessageType::PreFetch,
Message::Menu(_) => MessageType::Menu,
Message::GameEventList(_) => MessageType::GameEventList,
Message::GetCvarValue(_) => MessageType::GetCvarValue,
Message::CmdKeyValues(_) => MessageType::CmdKeyValues,
}
}
pub fn from_type(
message_type: MessageType,
stream: &mut Stream<'a>,
state: &ParserState,
) -> Result<Self> {
Ok(match message_type {
MessageType::Empty => Message::Empty,
MessageType::File => Message::File(FileMessage::parse(stream, state)?),
MessageType::NetTick => Message::NetTick(NetTickMessage::parse(stream, state)?),
MessageType::StringCmd => Message::StringCmd(StringCmdMessage::parse(stream, state)?),
MessageType::SetConVar => Message::SetConVar(SetConVarMessage::parse(stream, state)?),
MessageType::SignOnState => {
Message::SignOnState(SignOnStateMessage::parse(stream, state)?)
}
MessageType::Print => Message::Print(PrintMessage::parse(stream, state)?),
MessageType::ServerInfo => {
Message::ServerInfo(Box::new(ServerInfoMessage::parse(stream, state)?))
}
MessageType::ClassInfo => Message::ClassInfo(ClassInfoMessage::parse(stream, state)?),
MessageType::SetPause => Message::SetPause(SetPauseMessage::parse(stream, state)?),
MessageType::CreateStringTable => {
Message::CreateStringTable(CreateStringTableMessage::parse(stream, state)?)
}
MessageType::UpdateStringTable => {
Message::UpdateStringTable(UpdateStringTableMessage::parse(stream, state)?)
}
MessageType::VoiceInit => Message::VoiceInit(VoiceInitMessage::parse(stream, state)?),
MessageType::VoiceData => Message::VoiceData(VoiceDataMessage::parse(stream, state)?),
MessageType::ParseSounds => {
Message::ParseSounds(ParseSoundsMessage::parse(stream, state)?)
}
MessageType::SetView => Message::SetView(SetViewMessage::parse(stream, state)?),
MessageType::FixAngle => Message::FixAngle(FixAngleMessage::parse(stream, state)?),
MessageType::BspDecal => Message::BspDecal(BSPDecalMessage::parse(stream, state)?),
MessageType::UserMessage => Message::UserMessage(UserMessage::parse(stream, state)?),
MessageType::EntityMessage => {
Message::EntityMessage(EntityMessage::parse(stream, state)?)
}
MessageType::GameEvent => Message::GameEvent(GameEventMessage::parse(stream, state)?),
MessageType::PacketEntities => {
Message::PacketEntities(PacketEntitiesMessage::parse(stream, state)?)
}
MessageType::TempEntities => {
Message::TempEntities(TempEntitiesMessage::parse(stream, state)?)
}
MessageType::PreFetch => Message::PreFetch(PreFetchMessage::parse(stream, state)?),
MessageType::Menu => Message::Menu(MenuMessage::parse(stream, state)?),
MessageType::GameEventList => {
Message::GameEventList(GameEventListMessage::parse(stream, state)?)
}
MessageType::GetCvarValue => {
Message::GetCvarValue(GetCvarValueMessage::parse(stream, state)?)
}
MessageType::CmdKeyValues => {
Message::CmdKeyValues(CmdKeyValuesMessage::parse(stream, state)?)
}
})
}
pub fn skip_type(
message_type: MessageType,
stream: &mut Stream,
state: &ParserState,
) -> Result<()> {
match message_type {
MessageType::Empty => Ok(()),
MessageType::File => FileMessage::parse_skip(stream, state),
MessageType::NetTick => NetTickMessage::parse_skip(stream, state),
MessageType::StringCmd => StringCmdMessage::parse_skip(stream, state),
MessageType::SetConVar => SetConVarMessage::parse_skip(stream, state),
MessageType::SignOnState => SignOnStateMessage::parse_skip(stream, state),
MessageType::Print => PrintMessage::parse_skip(stream, state),
MessageType::ServerInfo => ServerInfoMessage::parse_skip(stream, state),
MessageType::ClassInfo => ClassInfoMessage::parse_skip(stream, state),
MessageType::SetPause => SetPauseMessage::parse_skip(stream, state),
MessageType::CreateStringTable => CreateStringTableMessage::parse_skip(stream, state),
MessageType::UpdateStringTable => UpdateStringTableMessage::parse_skip(stream, state),
MessageType::VoiceInit => VoiceInitMessage::parse_skip(stream, state),
MessageType::VoiceData => VoiceDataMessage::parse_skip(stream, state),
MessageType::ParseSounds => ParseSoundsMessage::parse_skip(stream, state),
MessageType::SetView => SetViewMessage::parse_skip(stream, state),
MessageType::FixAngle => FixAngleMessage::parse_skip(stream, state),
MessageType::BspDecal => BSPDecalMessage::parse_skip(stream, state),
MessageType::UserMessage => UserMessage::parse_skip(stream, state),
MessageType::EntityMessage => EntityMessage::parse_skip(stream, state),
MessageType::GameEvent => GameEventMessage::parse_skip(stream, state),
MessageType::PacketEntities => PacketEntitiesMessage::parse_skip(stream, state),
MessageType::TempEntities => TempEntitiesMessage::parse_skip(stream, state),
MessageType::PreFetch => PreFetchMessage::parse_skip(stream, state),
MessageType::Menu => MenuMessage::parse_skip(stream, state),
MessageType::GameEventList => GameEventListMessage::parse_skip(stream, state),
MessageType::GetCvarValue => GetCvarValueMessage::parse_skip(stream, state),
MessageType::CmdKeyValues => CmdKeyValuesMessage::parse_skip(stream, state),
}
}
}
impl Encode for Message<'_> {
fn encode(&self, stream: &mut BitWriteStream<LittleEndian>, state: &ParserState) -> Result<()> {
match self {
Message::Empty => Ok(()),
Message::File(message) => message.encode(stream, state),
Message::NetTick(message) => message.encode(stream, state),
Message::StringCmd(message) => message.encode(stream, state),
Message::SetConVar(message) => message.encode(stream, state),
Message::SignOnState(message) => message.encode(stream, state),
Message::Print(message) => message.encode(stream, state),
Message::ServerInfo(message) => message.encode(stream, state),
Message::ClassInfo(message) => message.encode(stream, state),
Message::SetPause(message) => message.encode(stream, state),
Message::CreateStringTable(message) => message.encode(stream, state),
Message::UpdateStringTable(message) => message.encode(stream, state),
Message::VoiceInit(message) => message.encode(stream, state),
Message::VoiceData(message) => message.encode(stream, state),
Message::ParseSounds(message) => message.encode(stream, state),
Message::SetView(message) => message.encode(stream, state),
Message::FixAngle(message) => message.encode(stream, state),
Message::BspDecal(message) => message.encode(stream, state),
Message::UserMessage(message) => message.encode(stream, state),
Message::EntityMessage(message) => message.encode(stream, state),
Message::GameEvent(message) => message.encode(stream, state),
Message::PacketEntities(message) => message.encode(stream, state),
Message::TempEntities(message) => message.encode(stream, state),
Message::PreFetch(message) => message.encode(stream, state),
Message::Menu(message) => message.encode(stream, state),
Message::GameEventList(message) => message.encode(stream, state),
Message::GetCvarValue(message) => message.encode(stream, state),
Message::CmdKeyValues(message) => message.encode(stream, state),
}
}
}
|
#[doc = "Writer for register RPR"]
pub type W = crate::W<u32, super::RPR>;
#[doc = "Register RPR `reset()`'s with value 0xff"]
impl crate::ResetValue for super::RPR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xff
}
}
#[doc = "Write proxy for field `PRIORITY`"]
pub struct PRIORITY_W<'a> {
w: &'a mut W,
}
impl<'a> PRIORITY_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 3)) | (((value as u32) & 0x1f) << 3);
self.w
}
}
impl W {
#[doc = "Bits 3:7 - current running priority on the CPU interface"]
#[inline(always)]
pub fn priority(&mut self) -> PRIORITY_W {
PRIORITY_W { w: self }
}
}
|
use crate::PyProjectToml;
use anyhow::{bail, format_err, Context, Result};
use fs_err as fs;
use indexmap::IndexMap;
use pep440_rs::{Version, VersionSpecifiers};
use pep508_rs::{MarkerExpression, MarkerOperator, MarkerTree, MarkerValue, Requirement};
use pyproject_toml::License;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::str;
use std::str::FromStr;
/// The metadata required to generate the .dist-info directory
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct WheelMetadata {
/// Python Package Metadata 2.1
pub metadata21: Metadata21,
/// The `[console_scripts]` for the entry_points.txt
pub scripts: HashMap<String, String>,
/// The name of the module can be distinct from the package name, mostly
/// because package names normally contain minuses while module names
/// have underscores. The package name is part of metadata21
pub module_name: String,
}
/// Python Package Metadata 2.1 as specified in
/// https://packaging.python.org/specifications/core-metadata/
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub struct Metadata21 {
// Mandatory fields
pub metadata_version: String,
pub name: String,
pub version: Version,
// Optional fields
pub platform: Vec<String>,
pub supported_platform: Vec<String>,
pub summary: Option<String>,
pub description: Option<String>,
pub description_content_type: Option<String>,
pub keywords: Option<String>,
pub home_page: Option<String>,
pub download_url: Option<String>,
pub author: Option<String>,
pub author_email: Option<String>,
pub maintainer: Option<String>,
pub maintainer_email: Option<String>,
pub license: Option<String>,
// https://peps.python.org/pep-0639/#license-file-multiple-use
pub license_files: Vec<PathBuf>,
pub classifiers: Vec<String>,
pub requires_dist: Vec<Requirement>,
pub provides_dist: Vec<String>,
pub obsoletes_dist: Vec<String>,
pub requires_python: Option<VersionSpecifiers>,
pub requires_external: Vec<String>,
pub project_url: IndexMap<String, String>,
pub provides_extra: Vec<String>,
pub scripts: IndexMap<String, String>,
pub gui_scripts: IndexMap<String, String>,
pub entry_points: IndexMap<String, IndexMap<String, String>>,
}
impl Metadata21 {
/// Initializes with name, version and otherwise the defaults
pub fn new(name: String, version: Version) -> Self {
Self {
metadata_version: "2.1".to_string(),
name,
version,
platform: vec![],
supported_platform: vec![],
summary: None,
description: None,
description_content_type: None,
keywords: None,
home_page: None,
download_url: None,
author: None,
author_email: None,
maintainer: None,
maintainer_email: None,
license: None,
license_files: vec![],
classifiers: vec![],
requires_dist: vec![],
provides_dist: vec![],
obsoletes_dist: vec![],
requires_python: None,
requires_external: vec![],
project_url: Default::default(),
provides_extra: vec![],
scripts: Default::default(),
gui_scripts: Default::default(),
entry_points: Default::default(),
}
}
}
const PLAINTEXT_CONTENT_TYPE: &str = "text/plain; charset=UTF-8";
const GFM_CONTENT_TYPE: &str = "text/markdown; charset=UTF-8; variant=GFM";
/// Guess a Description-Content-Type based on the file extension,
/// defaulting to plaintext if extension is unknown or empty.
///
/// See https://packaging.python.org/specifications/core-metadata/#description-content-type
fn path_to_content_type(path: &Path) -> String {
path.extension()
.map_or(String::from(PLAINTEXT_CONTENT_TYPE), |ext| {
let ext = ext.to_string_lossy().to_lowercase();
let type_str = match ext.as_str() {
"rst" => "text/x-rst; charset=UTF-8",
"md" => GFM_CONTENT_TYPE,
"markdown" => GFM_CONTENT_TYPE,
_ => PLAINTEXT_CONTENT_TYPE,
};
String::from(type_str)
})
}
impl Metadata21 {
/// Merge metadata with pyproject.toml, where pyproject.toml takes precedence
///
/// pyproject_dir must be the directory containing pyproject.toml
pub fn merge_pyproject_toml(
&mut self,
pyproject_dir: impl AsRef<Path>,
pyproject_toml: &PyProjectToml,
) -> Result<()> {
let pyproject_dir = pyproject_dir.as_ref();
if let Some(project) = &pyproject_toml.project {
self.name = project.name.clone();
if let Some(version) = &project.version {
self.version = version.clone();
}
if let Some(description) = &project.description {
self.summary = Some(description.clone());
}
match &project.readme {
Some(pyproject_toml::ReadMe::RelativePath(readme_path)) => {
let readme_path = pyproject_dir.join(readme_path);
let description = Some(fs::read_to_string(&readme_path).context(format!(
"Failed to read readme specified in pyproject.toml, which should be at {}",
readme_path.display()
))?);
self.description = description;
self.description_content_type = Some(path_to_content_type(&readme_path));
}
Some(pyproject_toml::ReadMe::Table {
file,
text,
content_type,
}) => {
if file.is_some() && text.is_some() {
bail!("file and text fields of 'project.readme' are mutually-exclusive, only one of them should be specified");
}
if let Some(readme_path) = file {
let readme_path = pyproject_dir.join(readme_path);
let description = Some(fs::read_to_string(&readme_path).context(format!(
"Failed to read readme specified in pyproject.toml, which should be at {}",
readme_path.display()
))?);
self.description = description;
}
if let Some(description) = text {
self.description = Some(description.clone());
}
self.description_content_type = content_type.clone();
}
None => {}
}
if let Some(requires_python) = &project.requires_python {
self.requires_python = Some(requires_python.clone());
}
if let Some(license) = &project.license {
match license {
// TODO: switch to License-Expression core metadata, see https://peps.python.org/pep-0639/#add-license-expression-field
License::String(license_expr) => self.license = Some(license_expr.clone()),
License::Table { file, text } => match (file, text) {
(Some(_), Some(_)) => {
bail!("file and text fields of 'project.license' are mutually-exclusive, only one of them should be specified");
}
(Some(license_path), None) => {
let license_path = pyproject_dir.join(license_path);
self.license_files.push(license_path);
}
(None, Some(license_text)) => self.license = Some(license_text.clone()),
(None, None) => {}
},
}
}
// Until PEP 639 is approved with metadata 2.3, we can assume a
// dynamic license-files (also awaiting full 2.2 metadata support)
// We're already emitting the License-Files metadata without issue.
// license-files.globs = ["LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*"]
let license_include_targets = ["LICEN[CS]E*", "COPYING*", "NOTICE*", "AUTHORS*"];
let escaped_manifest_string = glob::Pattern::escape(pyproject_dir.to_str().unwrap());
let escaped_manifest_path = Path::new(&escaped_manifest_string);
for pattern in license_include_targets.iter() {
for license_path in
glob::glob(&escaped_manifest_path.join(pattern).to_string_lossy())?
.filter_map(Result::ok)
{
// if the pyproject.toml specified the license file,
// then we won't list it as automatically included
if !self.license_files.contains(&license_path) {
eprintln!("📦 Including license file \"{}\"", license_path.display());
self.license_files.push(license_path);
}
}
}
if let Some(authors) = &project.authors {
let mut names = Vec::with_capacity(authors.len());
let mut emails = Vec::with_capacity(authors.len());
for author in authors {
match (&author.name, &author.email) {
(Some(name), Some(email)) => {
emails.push(format!("{name} <{email}>"));
}
(Some(name), None) => {
names.push(name.as_str());
}
(None, Some(email)) => {
emails.push(email.clone());
}
(None, None) => {}
}
}
if !names.is_empty() {
self.author = Some(names.join(", "));
}
if !emails.is_empty() {
self.author_email = Some(emails.join(", "));
}
}
if let Some(maintainers) = &project.maintainers {
let mut names = Vec::with_capacity(maintainers.len());
let mut emails = Vec::with_capacity(maintainers.len());
for maintainer in maintainers {
match (&maintainer.name, &maintainer.email) {
(Some(name), Some(email)) => {
emails.push(format!("{name} <{email}>"));
}
(Some(name), None) => {
names.push(name.as_str());
}
(None, Some(email)) => {
emails.push(email.clone());
}
(None, None) => {}
}
}
if !names.is_empty() {
self.maintainer = Some(names.join(", "));
}
if !emails.is_empty() {
self.maintainer_email = Some(emails.join(", "));
}
}
if let Some(keywords) = &project.keywords {
self.keywords = Some(keywords.join(","));
}
if let Some(classifiers) = &project.classifiers {
self.classifiers = classifiers.clone();
}
if let Some(urls) = &project.urls {
self.project_url = urls.clone();
}
if let Some(dependencies) = &project.dependencies {
self.requires_dist = dependencies.clone();
}
if let Some(dependencies) = &project.optional_dependencies {
// Transform the extra -> deps map into the PEP 508 style `dep ; extras = ...` style
for (extra, deps) in dependencies {
self.provides_extra.push(extra.clone());
for dep in deps {
let mut dep = dep.clone();
// Keep in sync with `develop()`!
let new_extra = MarkerTree::Expression(MarkerExpression {
l_value: MarkerValue::Extra,
operator: MarkerOperator::Equal,
r_value: MarkerValue::QuotedString(extra.to_string()),
});
if let Some(existing) = dep.marker.take() {
dep.marker = Some(MarkerTree::And(vec![existing, new_extra]));
} else {
dep.marker = Some(new_extra);
}
self.requires_dist.push(dep);
}
}
}
if let Some(scripts) = &project.scripts {
self.scripts = scripts.clone();
}
if let Some(gui_scripts) = &project.gui_scripts {
self.gui_scripts = gui_scripts.clone();
}
if let Some(entry_points) = &project.entry_points {
// Raise error on ambiguous entry points: https://www.python.org/dev/peps/pep-0621/#entry-points
if entry_points.contains_key("console_scripts") {
bail!("console_scripts is not allowed in project.entry-points table");
}
if entry_points.contains_key("gui_scripts") {
bail!("gui_scripts is not allowed in project.entry-points table");
}
self.entry_points = entry_points.clone();
}
}
Ok(())
}
/// Uses a Cargo.toml to create the metadata for python packages
///
/// manifest_path must be the directory, not the file
pub fn from_cargo_toml(
manifest_path: impl AsRef<Path>,
cargo_metadata: &cargo_metadata::Metadata,
) -> Result<Metadata21> {
let package = cargo_metadata
.root_package()
.context("Expected cargo to return metadata with root_package")?;
let authors = package.authors.join(", ");
let author_email = if authors.contains('@') {
Some(authors.clone())
} else {
None
};
let mut description: Option<String> = None;
let mut description_content_type: Option<String> = None;
// See https://packaging.python.org/specifications/core-metadata/#description
// and https://doc.rust-lang.org/cargo/reference/manifest.html#the-readme-field
if package.readme == Some("false".into()) {
// > You can suppress this behavior by setting this field to false
} else if let Some(ref readme) = package.readme {
let readme_path = manifest_path.as_ref().join(readme);
description = Some(fs::read_to_string(&readme_path).context(format!(
"Failed to read Readme specified in Cargo.toml, which should be at {}",
readme_path.display()
))?);
description_content_type = Some(path_to_content_type(&readme_path));
} else {
// > If no value is specified for this field, and a file named
// > README.md, README.txt or README exists in the package root
// Even though it's not what cargo does, we also search for README.rst
// since it's still popular in the python world
for readme_guess in ["README.md", "README.txt", "README.rst", "README"] {
let guessed_readme = manifest_path.as_ref().join(readme_guess);
if guessed_readme.exists() {
let context = format!(
"Readme at {} exists, but can't be read",
guessed_readme.display()
);
description = Some(fs::read_to_string(&guessed_readme).context(context)?);
description_content_type = Some(path_to_content_type(&guessed_readme));
break;
}
}
};
let name = package.name.clone();
let mut project_url = IndexMap::new();
if let Some(repository) = package.repository.as_ref() {
project_url.insert("Source Code".to_string(), repository.clone());
}
let license_files = if let Some(license_file) = package.license_file.as_ref() {
vec![manifest_path.as_ref().join(license_file)]
} else {
Vec::new()
};
let version = Version::from_str(&package.version.to_string()).map_err(|err| {
format_err!(
"Rust version used in Cargo.toml is not a valid python version: {}. \
Note that rust uses [SemVer](https://semver.org/) while python uses \
[PEP 440](https://peps.python.org/pep-0440/), which have e.g. some differences \
when declaring prereleases.",
err
)
})?;
let metadata = Metadata21 {
// name, version and metadata_version are added through Metadata21::new()
// Mapped from cargo metadata
summary: package.description.clone(),
description,
description_content_type,
keywords: if package.keywords.is_empty() {
None
} else {
Some(package.keywords.join(","))
},
home_page: package.homepage.clone(),
download_url: None,
// Cargo.toml has no distinction between author and author email
author: if package.authors.is_empty() {
None
} else {
Some(authors)
},
author_email,
license: package.license.clone(),
license_files,
project_url,
..Metadata21::new(name, version)
};
Ok(metadata)
}
/// Formats the metadata into a list where keys with multiple values
/// become multiple single-valued key-value pairs. This format is needed for the pypi
/// uploader and for the METADATA file inside wheels
pub fn to_vec(&self) -> Vec<(String, String)> {
let mut fields = vec![
("Metadata-Version", self.metadata_version.clone()),
("Name", self.name.clone()),
("Version", self.version.to_string()),
];
let mut add_vec = |name, values: &[String]| {
for i in values {
fields.push((name, i.clone()));
}
};
add_vec("Platform", &self.platform);
add_vec("Supported-Platform", &self.supported_platform);
add_vec("Classifier", &self.classifiers);
add_vec(
"Requires-Dist",
&self
.requires_dist
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>(),
);
add_vec("Provides-Dist", &self.provides_dist);
add_vec("Obsoletes-Dist", &self.obsoletes_dist);
add_vec("Requires-External", &self.requires_external);
add_vec("Provides-Extra", &self.provides_extra);
let license_files: Vec<String> = self
.license_files
.iter()
.map(|path| path.file_name().unwrap().to_str().unwrap().to_string())
.collect();
add_vec("License-File", &license_files);
let mut add_option = |name, value: &Option<String>| {
if let Some(some) = value.clone() {
fields.push((name, some));
}
};
add_option("Summary", &self.summary);
add_option("Keywords", &self.keywords);
add_option("Home-Page", &self.home_page);
add_option("Download-URL", &self.download_url);
add_option("Author", &self.author);
add_option("Author-email", &self.author_email);
add_option("Maintainer", &self.maintainer);
add_option("Maintainer-email", &self.maintainer_email);
add_option("License", &self.license.as_deref().map(fold_header));
add_option(
"Requires-Python",
&self
.requires_python
.as_ref()
.map(|requires_python| requires_python.to_string()),
);
add_option("Description-Content-Type", &self.description_content_type);
// Project-URL is special
// "A string containing a browsable URL for the project and a label for it, separated by a comma."
// `Project-URL: Bug Tracker, http://bitbucket.org/tarek/distribute/issues/`
for (key, value) in self.project_url.iter() {
fields.push(("Project-URL", format!("{key}, {value}")))
}
// Description shall be last, so we can ignore RFC822 and just put the description
// in the body
// The borrow checker doesn't like us using add_option here
if let Some(description) = &self.description {
fields.push(("Description", description.clone()));
}
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect()
}
/// Writes the format for the metadata file inside wheels
pub fn to_file_contents(&self) -> Result<String> {
let mut fields = self.to_vec();
let mut out = "".to_string();
let body = match fields.last() {
Some((key, description)) if key == "Description" => {
let desc = description.clone();
fields.pop().unwrap();
Some(desc)
}
Some((_, _)) => None,
None => None,
};
for (key, value) in fields {
writeln!(out, "{key}: {value}")?;
}
if let Some(body) = body {
writeln!(out, "\n{body}")?;
}
Ok(out)
}
/// Returns the distribution name according to PEP 427, Section "Escaping
/// and Unicode"
pub fn get_distribution_escaped(&self) -> String {
let re = Regex::new(r"[^\w\d.]+").unwrap();
re.replace_all(&self.name, "_").to_string()
}
/// Returns the version encoded according to PEP 427, Section "Escaping
/// and Unicode"
pub fn get_version_escaped(&self) -> String {
self.version.to_string().replace('-', "_")
}
/// Returns the name of the .dist-info directory as defined in the wheel specification
pub fn get_dist_info_dir(&self) -> PathBuf {
PathBuf::from(format!(
"{}-{}.dist-info",
&self.get_distribution_escaped(),
&self.get_version_escaped()
))
}
}
/// Fold long header field according to RFC 5322 section 2.2.3
/// https://datatracker.ietf.org/doc/html/rfc5322#section-2.2.3
fn fold_header(text: &str) -> String {
let mut result = String::with_capacity(text.len());
let options = textwrap::Options::new(78)
.initial_indent("")
.subsequent_indent("\t");
for (i, line) in textwrap::wrap(text, options).iter().enumerate() {
if i > 0 {
result.push_str("\r\n");
}
let line = line.trim_end();
if line.is_empty() {
result.push('\t');
} else {
result.push_str(line);
}
}
result
}
#[cfg(test)]
mod test {
use super::*;
use cargo_metadata::MetadataCommand;
use expect_test::{expect, Expect};
use indoc::indoc;
use pretty_assertions::assert_eq;
fn assert_metadata_from_cargo_toml(
readme: &str,
cargo_toml: &str,
expected: Expect,
) -> Metadata21 {
let crate_dir = tempfile::tempdir().unwrap();
let crate_path = crate_dir.path();
let manifest_path = crate_path.join("Cargo.toml");
fs::create_dir(crate_path.join("src")).unwrap();
fs::write(crate_path.join("src/lib.rs"), "").unwrap();
let readme_path = crate_path.join("README.md");
fs::write(&readme_path, readme.as_bytes()).unwrap();
let readme_path = if cfg!(windows) {
readme_path.to_str().unwrap().replace('\\', "/")
} else {
readme_path.to_str().unwrap().to_string()
};
let toml_with_path = cargo_toml.replace("REPLACE_README_PATH", &readme_path);
fs::write(&manifest_path, toml_with_path).unwrap();
let cargo_metadata = MetadataCommand::new()
.manifest_path(manifest_path)
.exec()
.unwrap();
let metadata = Metadata21::from_cargo_toml(crate_path, &cargo_metadata).unwrap();
let actual = metadata.to_file_contents().unwrap();
expected.assert_eq(&actual);
// get_dist_info_dir test checks against hard-coded values - check that they are as expected in the source first
assert!(
cargo_toml.contains("name = \"info-project\"")
&& cargo_toml.contains("version = \"0.1.0\""),
"cargo_toml name and version string do not match hardcoded values, test will fail",
);
metadata
}
#[test]
fn test_metadata_from_cargo_toml() {
let readme = indoc!(
r#"
# Some test package
This is the readme for a test package
"#
);
let cargo_toml = indoc!(
r#"
[package]
authors = ["konstin <konstin@mailbox.org>"]
name = "info-project"
version = "0.1.0"
description = "A test project"
homepage = "https://example.org"
readme = "REPLACE_README_PATH"
keywords = ["ffi", "test"]
[lib]
crate-type = ["cdylib"]
name = "pyo3_pure"
"#
);
let expected = expect![[r#"
Metadata-Version: 2.1
Name: info-project
Version: 0.1.0
Summary: A test project
Keywords: ffi,test
Home-Page: https://example.org
Author: konstin <konstin@mailbox.org>
Author-email: konstin <konstin@mailbox.org>
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
# Some test package
This is the readme for a test package
"#]];
assert_metadata_from_cargo_toml(readme, cargo_toml, expected);
}
#[test]
fn test_path_to_content_type() {
for (filename, expected) in &[
("r.md", GFM_CONTENT_TYPE),
("r.markdown", GFM_CONTENT_TYPE),
("r.mArKdOwN", GFM_CONTENT_TYPE),
("r.rst", "text/x-rst; charset=UTF-8"),
("r.somethingelse", PLAINTEXT_CONTENT_TYPE),
("r", PLAINTEXT_CONTENT_TYPE),
] {
let result = path_to_content_type(&PathBuf::from(filename));
assert_eq!(
&result.as_str(),
expected,
"Wrong content type for file '{}'. Expected '{}', got '{}'",
filename,
expected,
result
);
}
}
#[test]
fn test_merge_metadata_from_pyproject_toml() {
let manifest_dir = PathBuf::from("test-crates").join("pyo3-pure");
let cargo_metadata = MetadataCommand::new()
.manifest_path(manifest_dir.join("Cargo.toml"))
.exec()
.unwrap();
let mut metadata = Metadata21::from_cargo_toml(&manifest_dir, &cargo_metadata).unwrap();
let pyproject_toml = PyProjectToml::new(manifest_dir.join("pyproject.toml")).unwrap();
metadata
.merge_pyproject_toml(&manifest_dir, &pyproject_toml)
.unwrap();
assert_eq!(
metadata.summary,
Some("Implements a dummy function in Rust".to_string())
);
assert_eq!(
metadata.description,
Some(fs_err::read_to_string("test-crates/pyo3-pure/README.md").unwrap())
);
assert_eq!(metadata.classifiers, &["Programming Language :: Rust"]);
assert_eq!(
metadata.maintainer_email,
Some("messense <messense@icloud.com>".to_string())
);
assert_eq!(metadata.scripts["get_42"], "pyo3_pure:DummyClass.get_42");
assert_eq!(
metadata.gui_scripts["get_42_gui"],
"pyo3_pure:DummyClass.get_42"
);
assert_eq!(metadata.provides_extra, &["test"]);
assert_eq!(
metadata.requires_dist,
&[
Requirement::from_str("attrs; extra == 'test'",).unwrap(),
Requirement::from_str("boltons; (sys_platform == 'win32') and extra == 'test'")
.unwrap(),
]
);
assert_eq!(metadata.license.as_ref().unwrap(), "MIT");
let license_file = &metadata.license_files[0];
assert_eq!(license_file.file_name().unwrap(), "LICENSE");
let content = metadata.to_file_contents().unwrap();
let pkginfo: Result<python_pkginfo::Metadata, _> = content.parse();
assert!(pkginfo.is_ok());
}
#[test]
fn test_merge_metadata_from_pyproject_toml_with_customized_python_source_dir() {
let manifest_dir = PathBuf::from("test-crates").join("pyo3-mixed-py-subdir");
let cargo_metadata = MetadataCommand::new()
.manifest_path(manifest_dir.join("Cargo.toml"))
.exec()
.unwrap();
let mut metadata = Metadata21::from_cargo_toml(&manifest_dir, &cargo_metadata).unwrap();
let pyproject_toml = PyProjectToml::new(manifest_dir.join("pyproject.toml")).unwrap();
metadata
.merge_pyproject_toml(&manifest_dir, &pyproject_toml)
.unwrap();
// defined in Cargo.toml
assert_eq!(
metadata.summary,
Some("Implements a dummy function combining rust and python".to_string())
);
// defined in pyproject.toml
assert_eq!(metadata.scripts["get_42"], "pyo3_mixed_py_subdir:get_42");
}
#[test]
fn test_implicit_readme() {
let manifest_dir = PathBuf::from("test-crates").join("pyo3-mixed");
let cargo_metadata = MetadataCommand::new()
.manifest_path(manifest_dir.join("Cargo.toml"))
.exec()
.unwrap();
let metadata = Metadata21::from_cargo_toml(&manifest_dir, &cargo_metadata).unwrap();
assert!(metadata.description.unwrap().starts_with("# pyo3-mixed"));
assert_eq!(
metadata.description_content_type.unwrap(),
"text/markdown; charset=UTF-8; variant=GFM"
);
}
#[test]
fn test_merge_metadata_from_pyproject_dynamic_license_test() {
let manifest_dir = PathBuf::from("test-crates").join("license-test");
let cargo_metadata = MetadataCommand::new()
.manifest_path(manifest_dir.join("Cargo.toml"))
.exec()
.unwrap();
let mut metadata = Metadata21::from_cargo_toml(&manifest_dir, &cargo_metadata).unwrap();
let pyproject_toml = PyProjectToml::new(manifest_dir.join("pyproject.toml")).unwrap();
metadata
.merge_pyproject_toml(&manifest_dir, &pyproject_toml)
.unwrap();
// verify Cargo.toml value came through
assert_eq!(metadata.license.as_ref().unwrap(), "MIT");
// verify we have the total number of expected licenses
assert_eq!(4, metadata.license_files.len());
// Verify pyproject.toml license = {file = ...} worked
assert_eq!(metadata.license_files[0], manifest_dir.join("LICENCE.txt"));
// Verify the default licenses were included
assert_eq!(metadata.license_files[1], manifest_dir.join("LICENSE"));
assert_eq!(metadata.license_files[2], manifest_dir.join("NOTICE.md"));
assert_eq!(metadata.license_files[3], manifest_dir.join("AUTHORS.txt"));
}
}
|
#[allow(unused_imports)]
#[macro_use]
extern crate clap;
#[allow(unused_imports)]
#[macro_use]
extern crate failure;
use failure::Error;
extern crate config;
extern crate serde;
#[allow(unused_imports)]
#[macro_use]
extern crate serde_derive;
extern crate serde_yaml;
extern crate ubackup;
use ubackup::Settings;
use std::fs::File;
use std::path::Path;
fn main() -> Result<(), Error> {
let cli = clap_app!(uBackup =>
(version: crate_version!())
(author: crate_authors!("\n"))
(about: crate_description!())
(@arg config: -c --config +takes_value "Config file (yml)")
(@group q =>
(@arg quiet: -q --quiet "Quiet")
(@arg verbose: -v --verbose "Verbose")
)
(@group r =>
(@arg dryrun: -d --dryrun "Dry (don't run)")
(@arg run: -r --run "Run")
)
);
let cli: clap::ArgMatches = cli.get_matches();
let config_file = cli.value_of("config").unwrap_or("config.yaml");
let config_path = Path::new(config_file);
if !config_path.exists() {
println!("Creating default config at {}.", config_file);
return Ok(serde_yaml::to_writer(
File::create(config_path)?,
&Settings::new(None)?,
)?);
}
let mut settings = Settings::new(Some(config_file))?;
if cli.is_present("quiet") {
settings.config.quiet = true;
}
if cli.is_present("verbose") {
settings.config.quiet = false;
}
if cli.is_present("dryrun") {
settings.config.dryrun = true;
}
if cli.is_present("run") {
settings.config.dryrun = false;
}
let [successes, errors, copied, skiped]: [u32; 4] = ubackup::backup(settings.clone())?;
println!(
"{} successes, {} errors, {} copies, {} skips",
successes, errors, copied, skiped
);
Ok(())
}
|
//! This is a platform agnostic Rust driver for the HDC2080, HDC2021 and
//! HDC2010 low-power humidity and temperature digital sensor using
//! the [`embedded-hal`] traits.
//!
//! [`embedded-hal`]: https://github.com/rust-embedded/embedded-hal
//!
//! This driver allows you to:
//! - Set the measurement mode. Temperature only or temperature and humidity. See: [`set_measurement_mode()`].
//! - Make one shot measurement. See: [`read()`].
//! - Read the data and interrupt status. See: [`status()`].
//! - Trigger a software reset. See: [`software_reset()`].
//! - Read the manufacturer ID. See: [`manufacturer_id()`].
//! - Read the device ID. See: [`device_id()`].
//!
//! [`set_measurement_mode()`]: struct.Hdc20xx.html#method.set_measurement_mode
//! [`read()`]: struct.Hdc20xx.html#method.read
//! [`status()`]: struct.Hdc20xx.html#method.status
//! [`software_reset()`]: struct.Hdc20xx.html#method.software_reset
//! [`manufacturer_id()`]: struct.Hdc20xx.html#method.manufacturer_id
//! [`device_id()`]: struct.Hdc20xx.html#method.device_id
//!
//! <!-- TODO
//! [Introductory blog post](TODO)
//! -->
//!
//! ## The devices
//!
//! The HDC2080 device is an integrated humidity and temperature sensor that
//! provides high accuracy measurements with very low power consumption in a
//! small DFN package. The capacitive-based sensor includes new integrated
//! digital features and a heating element to dissipate condensation and moisture.
//!
//! The HDC2080 digital features include programmable interrupt thresholds to
//! provide alerts and system wake-ups without requiring a microcontroller to
//! be continuously monitoring the system. Combined with programmable sampling
//! intervals, a low power consumption, and a support for a 1.8-V supply voltage,
//! the HDC2080 is designed for battery-operated systems.
//!
//! This driver is compatible with HDC2080, HDC2021 and HDC2010.
//!
//! Datasheets: [HDC2080](https://www.ti.com/lit/ds/symlink/hdc2080.pdf), [HDC2021](https://www.ti.com/lit/ds/symlink/hdc2021.pdf), [HDC2010](https://www.ti.com/lit/ds/symlink/hdc2010.pdf)
//!
//! ## Usage examples (see also examples folder)
//!
//! To use this driver, import this crate and an `embedded_hal` implementation,
//! then instantiate the device.
//!
//! Please find additional examples using hardware in this repository: [driver-examples]
//!
//! [driver-examples]: https://github.com/eldruin/driver-examples
//!
//! ### Make a one-shot temperature and humidity measurement
//!
//! ```no_run
//! use embedded_hal::blocking::delay::DelayMs;
//! use hdc20xx::{Hdc20xx, SlaveAddr};
//! use linux_embedded_hal::{Delay, I2cdev};
//!
//! let mut delay = Delay {};
//! let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! let address = SlaveAddr::default();
//! let mut sensor = Hdc20xx::new(dev, address);
//! loop {
//! loop {
//! let result = sensor.read();
//! match result {
//! Err(nb::Error::WouldBlock) => delay.delay_ms(100_u8),
//! Err(e) => {
//! println!("Error! {:?}", e);
//! }
//! Ok(data) => {
//! println!(
//! "Temperature: {:2}°C, Humidity: {:2}%",
//! data.temperature,
//! data.humidity.unwrap()
//! );
//! }
//! }
//! }
//! }
//! ```
//!
//! ### Use an alternative address
//!
//! ```no_run
//! use hdc20xx::{Hdc20xx, SlaveAddr};
//! use linux_embedded_hal::I2cdev;
//!
//! let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! let address = SlaveAddr::Alternative(true);
//! let sensor = Hdc20xx::new(dev, address);
//! ```
//!
//! ### Configure measuring only the temperature
//!
//! ```no_run
//! use hdc20xx::{Hdc20xx, MeasurementMode, SlaveAddr};
//! use linux_embedded_hal::I2cdev;
//!
//! let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! let address = SlaveAddr::default();
//! let mut sensor = Hdc20xx::new(dev, address);
//! sensor.set_measurement_mode(MeasurementMode::TemperatureOnly).unwrap();
//! ```
//!
//! ### Read the manufacturer and device ID
//!
//! ```no_run
//! use hdc20xx::{Hdc20xx, SlaveAddr};
//! use linux_embedded_hal::I2cdev;
//!
//! let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! let address = SlaveAddr::default();
//! let mut sensor = Hdc20xx::new(dev, address);
//! let manuf_id = sensor.manufacturer_id().unwrap();
//! let dev_id = sensor.device_id().unwrap();
//! println!(
//! "Manufacturer ID: {}, Device ID: {}",
//! manuf_id, dev_id
//! );
//! ```
//!
//! ### Read the data and interrupt status
//!
//! ```no_run
//! use hdc20xx::{Hdc20xx, SlaveAddr};
//! use linux_embedded_hal::I2cdev;
//!
//! let dev = I2cdev::new("/dev/i2c-1").unwrap();
//! let address = SlaveAddr::default();
//! let mut sensor = Hdc20xx::new(dev, address);
//! let status = sensor.status().unwrap();
//! println!("Status: {:?}", status);
//! ```
//!
#![deny(unsafe_code, missing_docs)]
#![no_std]
use core::marker::PhantomData;
mod device_impl;
mod types;
pub use crate::types::{Error, Measurement, MeasurementMode, SlaveAddr, Status};
mod register_address;
use crate::register_address::{BitFlags, Register, BASE_ADDR};
/// HDC2080, HDC2021 and HDC2010 device driver
#[derive(Debug)]
pub struct Hdc20xx<I2C, MODE> {
i2c: I2C,
address: u8,
meas_config: Config,
was_measurement_started: bool,
_mode: PhantomData<MODE>,
}
#[derive(Debug, Default, Clone, Copy)]
struct Config {
bits: u8,
}
/// Mode marker
pub mod mode {
/// One shot measurement mode
pub struct OneShot(());
/// Continuous measurement mode
pub struct Continuous(());
}
mod private {
use super::mode;
pub trait Sealed {}
impl Sealed for mode::OneShot {}
impl Sealed for mode::Continuous {}
}
|
use cgmath::Vector2;
pub const SCREEN_SIZE: Vector2<u32> = Vector2 {
x: 1024,
y: 768,
};
pub const GAME_SIZE: Vector2<u32> = Vector2 {
x: 1024,
y: 768,
};
|
use super::*;
/// A planning element.
///
/// # Semantics
///
/// Contains the deadline, scheduled and closed timestamps for a headline. All are optional.
///
/// # Syntax
///
/// Planning lines are context-free.
///
/// ```text
/// KEYWORD: TIMESTAMP
/// ```
///
/// `KEYWORD` is one of `DEADLINE`, `SCHEDULED` or `CLOSED`. Planning can be repeated but one
/// keywords can only be used once. The order doesn't matter.
///
/// `TIMESTAMP` is a [`objects::Timestamp`].
///
/// Consecutive planning items are aggregated into one.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Planning {
pub closed: Option<objects::Timestamp>,
pub deadline: Option<objects::Timestamp>,
pub scheduled: Option<objects::Timestamp>,
}
|
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::{
convert, fmt, mem,
net::{Ipv4Addr, Ipv6Addr},
str,
sync::Arc,
};
use chrono::prelude::*;
use chrono_tz::Tz;
use either::Either;
use crate::types::{
column::datetime64::to_datetime,
decimal::{Decimal, NoBits},
DateConverter, DateTimeType, Enum16, Enum8, HasSqlType, SqlType,
};
use uuid::Uuid;
pub(crate) type AppDateTime = DateTime<Tz>;
pub(crate) type AppDate = Date<Tz>;
/// Client side representation of a value of Clickhouse column.
#[derive(Clone, Debug)]
pub enum Value {
UInt8(u8),
UInt16(u16),
UInt32(u32),
UInt64(u64),
Int8(i8),
Int16(i16),
Int32(i32),
Int64(i64),
String(Arc<Vec<u8>>),
Float32(f32),
Float64(f64),
Date(u16, Tz),
DateTime(u32, Tz),
DateTime64(i64, (u32, Tz)),
ChronoDateTime(DateTime<Tz>),
Ipv4([u8; 4]),
Ipv6([u8; 16]),
Uuid([u8; 16]),
Nullable(Either<&'static SqlType, Box<Value>>),
Array(&'static SqlType, Arc<Vec<Value>>),
Decimal(Decimal),
Enum8(Vec<(String, i8)>, Enum8),
Enum16(Vec<(String, i16)>, Enum16),
Map(
&'static SqlType,
&'static SqlType,
Arc<HashMap<Value, Value>>,
),
}
impl Hash for Value {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Self::String(s) => s.hash(state),
Self::Int8(i) => i.hash(state),
Self::Int16(i) => i.hash(state),
Self::Int32(i) => i.hash(state),
Self::Int64(i) => i.hash(state),
Self::UInt8(i) => i.hash(state),
Self::UInt16(i) => i.hash(state),
Self::UInt32(i) => i.hash(state),
Self::UInt64(i) => i.hash(state),
_ => unimplemented!(),
}
}
}
impl Eq for Value {}
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Value::UInt8(a), Value::UInt8(b)) => *a == *b,
(Value::UInt16(a), Value::UInt16(b)) => *a == *b,
(Value::UInt32(a), Value::UInt32(b)) => *a == *b,
(Value::UInt64(a), Value::UInt64(b)) => *a == *b,
(Value::Int8(a), Value::Int8(b)) => *a == *b,
(Value::Int16(a), Value::Int16(b)) => *a == *b,
(Value::Int32(a), Value::Int32(b)) => *a == *b,
(Value::Int64(a), Value::Int64(b)) => *a == *b,
(Value::String(a), Value::String(b)) => *a == *b,
(Value::Float32(a), Value::Float32(b)) => *a == *b,
(Value::Float64(a), Value::Float64(b)) => *a == *b,
(Value::Date(a, tz_a), Value::Date(b, tz_b)) => {
let time_a = tz_a.timestamp(i64::from(*a) * 24 * 3600, 0);
let time_b = tz_b.timestamp(i64::from(*b) * 24 * 3600, 0);
time_a.date() == time_b.date()
}
(Value::DateTime(a, tz_a), Value::DateTime(b, tz_b)) => {
let time_a = tz_a.timestamp(i64::from(*a), 0);
let time_b = tz_b.timestamp(i64::from(*b), 0);
time_a == time_b
}
(Value::ChronoDateTime(a), Value::ChronoDateTime(b)) => *a == *b,
(Value::Nullable(a), Value::Nullable(b)) => *a == *b,
(Value::Array(ta, a), Value::Array(tb, b)) => *ta == *tb && *a == *b,
(Value::Decimal(a), Value::Decimal(b)) => *a == *b,
(Value::Enum8(values_a, val_a), Value::Enum8(values_b, val_b)) => {
*values_a == *values_b && *val_a == *val_b
}
(Value::Enum16(values_a, val_a), Value::Enum16(values_b, val_b)) => {
*values_a == *values_b && *val_a == *val_b
}
(Value::Ipv4(a), Value::Ipv4(b)) => *a == *b,
(Value::Ipv6(a), Value::Ipv6(b)) => *a == *b,
(Value::Uuid(a), Value::Uuid(b)) => *a == *b,
(Value::DateTime64(a, (prec_a, tz_a)), Value::DateTime64(b, (prec_b, tz_b))) => {
// chrono has no "variable-precision" offset method. As a
// fallback, we always use `timestamp_nanos` and multiply by
// the correct value.
#[rustfmt::skip]
const MULTIPLIERS: [i64; 10] = [
1_000_000_000, // 1 s is 10^9 nanos
100_000_000,
10_000_000,
1_000_000, // 1 ms is 10^6 nanos
100_000,
10_000,
1_000, // 1 µs is 10^3 nanos
100,
10,
1, // 1 ns is 1 nanos!
];
// The precision must be in the [0 - 9] range. As such, the
// following indexing can not fail.
prec_a == prec_b
&& tz_a.timestamp_nanos(a * MULTIPLIERS[*prec_a as usize])
== tz_b.timestamp_nanos(b * MULTIPLIERS[*prec_b as usize])
}
_ => false,
}
}
}
impl Value {
pub(crate) fn default(sql_type: SqlType) -> Value {
match sql_type {
SqlType::UInt8 => Value::UInt8(0),
SqlType::UInt16 => Value::UInt16(0),
SqlType::UInt32 => Value::UInt32(0),
SqlType::UInt64 => Value::UInt64(0),
SqlType::Int8 => Value::Int8(0),
SqlType::Int16 => Value::Int16(0),
SqlType::Int32 => Value::Int32(0),
SqlType::Int64 => Value::Int64(0),
SqlType::String => Value::String(Arc::new(Vec::default())),
SqlType::FixedString(str_len) => Value::String(Arc::new(vec![0_u8; str_len])),
SqlType::Float32 => Value::Float32(0.0),
SqlType::Float64 => Value::Float64(0.0),
SqlType::Date => 0_u16.to_date(Tz::Zulu).into(),
SqlType::DateTime(DateTimeType::DateTime64(_, _)) => {
Value::DateTime64(0, (1, Tz::Zulu))
}
SqlType::SimpleAggregateFunction(_, nested) => Value::default(nested.clone()),
SqlType::DateTime(_) => 0_u32.to_date(Tz::Zulu).into(),
SqlType::Nullable(inner) => Value::Nullable(Either::Left(inner)),
SqlType::Array(inner) => Value::Array(inner, Arc::new(Vec::default())),
SqlType::Decimal(precision, scale) => Value::Decimal(Decimal {
underlying: 0,
precision,
scale,
nobits: NoBits::N64,
}),
SqlType::Ipv4 => Value::Ipv4([0_u8; 4]),
SqlType::Ipv6 => Value::Ipv6([0_u8; 16]),
SqlType::Uuid => Value::Uuid([0_u8; 16]),
SqlType::Enum8(values) => Value::Enum8(values, Enum8(0)),
SqlType::Enum16(values) => Value::Enum16(values, Enum16(0)),
SqlType::Map(k, v) => Value::Map(k, v, Arc::new(HashMap::default())),
}
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Value::UInt8(ref v) => fmt::Display::fmt(v, f),
Value::UInt16(ref v) => fmt::Display::fmt(v, f),
Value::UInt32(ref v) => fmt::Display::fmt(v, f),
Value::UInt64(ref v) => fmt::Display::fmt(v, f),
Value::Int8(ref v) => fmt::Display::fmt(v, f),
Value::Int16(ref v) => fmt::Display::fmt(v, f),
Value::Int32(ref v) => fmt::Display::fmt(v, f),
Value::Int64(ref v) => fmt::Display::fmt(v, f),
Value::String(ref v) => match str::from_utf8(v) {
Ok(s) => fmt::Display::fmt(s, f),
Err(_) => write!(f, "{:?}", v),
},
Value::Float32(ref v) => fmt::Display::fmt(v, f),
Value::Float64(ref v) => fmt::Display::fmt(v, f),
Value::DateTime(u, tz) if f.alternate() => {
let time = tz.timestamp(i64::from(*u), 0);
fmt::Display::fmt(&time, f)
}
Value::DateTime(u, tz) => {
let time = tz.timestamp(i64::from(*u), 0);
write!(f, "{}", time.to_rfc2822())
}
Value::DateTime64(value, params) => {
let (precision, tz) = params;
let time = to_datetime(*value, *precision, *tz);
write!(f, "{}", time.to_rfc2822())
}
Value::ChronoDateTime(time) => {
write!(f, "{}", time.to_rfc2822())
}
Value::Date(v, tz) if f.alternate() => {
let time = tz.timestamp(i64::from(*v) * 24 * 3600, 0);
let date = time.date();
fmt::Display::fmt(&date, f)
}
Value::Date(v, tz) => {
let time = tz.timestamp(i64::from(*v) * 24 * 3600, 0);
let date = time.date();
fmt::Display::fmt(&date.format("%Y-%m-%d"), f)
}
Value::Nullable(v) => match v {
Either::Left(_) => write!(f, "NULL"),
Either::Right(data) => data.fmt(f),
},
Value::Array(_, vs) => {
let cells: Vec<String> = vs.iter().map(|v| format!("{}", v)).collect();
write!(f, "[{}]", cells.join(", "))
}
Value::Decimal(v) => fmt::Display::fmt(v, f),
Value::Ipv4(v) => {
write!(f, "{}", decode_ipv4(v))
}
Value::Ipv6(v) => {
write!(f, "{}", decode_ipv6(v))
}
Value::Uuid(v) => {
let mut buffer = *v;
buffer[..8].reverse();
buffer[8..].reverse();
match Uuid::from_slice(&buffer) {
Ok(uuid) => write!(f, "{}", uuid),
Err(e) => write!(f, "{}", e),
}
}
Value::Enum8(ref _v1, ref v2) => write!(f, "Enum8, {}", v2),
Value::Enum16(ref _v1, ref v2) => write!(f, "Enum16, {}", v2),
Value::Map(_, _, hm) => {
let cells: Vec<String> = hm
.iter()
.map(|(k, v)| format!("key=>{} value=>{}", k, v))
.collect();
write!(f, "[{}]", cells.join(", "))
}
}
}
}
impl From<Value> for SqlType {
fn from(source: Value) -> Self {
match source {
Value::UInt8(_) => SqlType::UInt8,
Value::UInt16(_) => SqlType::UInt16,
Value::UInt32(_) => SqlType::UInt32,
Value::UInt64(_) => SqlType::UInt64,
Value::Int8(_) => SqlType::Int8,
Value::Int16(_) => SqlType::Int16,
Value::Int32(_) => SqlType::Int32,
Value::Int64(_) => SqlType::Int64,
Value::String(_) => SqlType::String,
Value::Float32(_) => SqlType::Float32,
Value::Float64(_) => SqlType::Float64,
Value::Date(_, _) => SqlType::Date,
Value::DateTime(_, _) => SqlType::DateTime(DateTimeType::DateTime32),
Value::ChronoDateTime(_) => SqlType::DateTime(DateTimeType::DateTime32),
Value::Nullable(d) => match d {
Either::Left(t) => SqlType::Nullable(t),
Either::Right(inner) => {
let sql_type = SqlType::from(inner.as_ref().to_owned());
SqlType::Nullable(sql_type.into())
}
},
Value::Array(t, _) => SqlType::Array(t),
Value::Decimal(v) => SqlType::Decimal(v.precision, v.scale),
Value::Ipv4(_) => SqlType::Ipv4,
Value::Ipv6(_) => SqlType::Ipv6,
Value::Uuid(_) => SqlType::Uuid,
Value::Enum8(values, _) => SqlType::Enum8(values),
Value::Enum16(values, _) => SqlType::Enum16(values),
Value::DateTime64(_, params) => {
let (precision, tz) = params;
SqlType::DateTime(DateTimeType::DateTime64(precision, tz))
}
Value::Map(k, v, _) => SqlType::Map(k, v),
}
}
}
impl<T> From<Option<T>> for Value
where
Value: From<T>,
T: HasSqlType,
{
fn from(value: Option<T>) -> Value {
match value {
None => {
let default_type: SqlType = T::get_sql_type();
Value::Nullable(Either::Left(default_type.into()))
}
Some(inner) => Value::Nullable(Either::Right(Box::new(inner.into()))),
}
}
}
macro_rules! value_from {
( $( $t:ty : $k:ident ),* ) => {
$(
impl convert::From<$t> for Value {
fn from(v: $t) -> Value {
Value::$k(v.into())
}
}
)*
};
}
macro_rules! value_array_from {
( $( $t:ty : $k:ident ),* ) => {
$(
impl convert::From<Vec<$t>> for Value {
fn from(v: Vec<$t>) -> Self {
Value::Array(
SqlType::$k.into(),
Arc::new(v.into_iter().map(|s| s.into()).collect())
)
}
}
)*
};
}
impl From<AppDate> for Value {
fn from(v: AppDate) -> Value {
Value::Date(u16::get_days(v), v.timezone())
}
}
impl From<Enum8> for Value {
fn from(v: Enum8) -> Value {
Value::Enum8(Vec::new(), v)
}
}
impl From<Enum16> for Value {
fn from(v: Enum16) -> Value {
Value::Enum16(Vec::new(), v)
}
}
impl From<AppDateTime> for Value {
fn from(v: AppDateTime) -> Value {
Value::ChronoDateTime(v)
}
}
impl From<DateTime<Utc>> for Value {
fn from(v: DateTime<Utc>) -> Value {
Value::DateTime(v.timestamp() as u32, Tz::UTC)
}
}
impl From<String> for Value {
fn from(v: String) -> Value {
Value::String(Arc::new(v.into_bytes()))
}
}
impl From<Vec<u8>> for Value {
fn from(v: Vec<u8>) -> Value {
Value::String(Arc::new(v))
}
}
impl From<&[u8]> for Value {
fn from(v: &[u8]) -> Value {
Value::String(Arc::new(v.to_vec()))
}
}
impl From<Vec<String>> for Value {
fn from(v: Vec<String>) -> Self {
Value::Array(
SqlType::String.into(),
Arc::new(v.into_iter().map(|s| s.into()).collect())
)
}
}
impl From<Uuid> for Value {
fn from(v: Uuid) -> Value {
let mut buffer = *v.as_bytes();
buffer[..8].reverse();
buffer[8..].reverse();
Value::Uuid(buffer)
}
}
impl From<bool> for Value {
fn from(v: bool) -> Value {
Value::UInt8(if v { 1 } else { 0 })
}
}
impl<K, V> From<HashMap<K, V>> for Value
where
K: Into<Value> + HasSqlType,
V: Into<Value> + HasSqlType,
{
fn from(hm: HashMap<K, V>) -> Self {
let mut res = HashMap::with_capacity(hm.capacity());
for (k, v) in hm {
res.insert(k.into(), v.into());
}
Self::Map(
K::get_sql_type().clone().into(),
V::get_sql_type().clone().into(),
Arc::new(res),
)
}
}
value_from! {
u8: UInt8,
u16: UInt16,
u32: UInt32,
u64: UInt64,
i8: Int8,
i16: Int16,
i32: Int32,
i64: Int64,
f32: Float32,
f64: Float64,
Decimal: Decimal,
[u8; 4]: Ipv4,
[u8; 16]: Ipv6
}
value_array_from! {
u16: UInt16,
u32: UInt32,
u64: UInt64,
i8: Int8,
i16: Int16,
i32: Int32,
i64: Int64,
f32: Float32,
f64: Float64
}
impl<'a> From<&'a str> for Value {
fn from(v: &'a str) -> Self {
let bytes: Vec<u8> = v.as_bytes().into();
Value::String(Arc::new(bytes))
}
}
impl From<Value> for String {
fn from(mut v: Value) -> Self {
if let Value::String(ref mut x) = &mut v {
let mut tmp = Arc::new(Vec::new());
mem::swap(x, &mut tmp);
if let Ok(result) = str::from_utf8(tmp.as_ref()) {
return result.into();
}
}
let from = SqlType::from(v);
panic!("Can't convert Value::{} into String.", from);
}
}
impl From<Value> for Vec<u8> {
fn from(v: Value) -> Self {
match v {
Value::String(bs) => bs.to_vec(),
_ => {
let from = SqlType::from(v);
panic!("Can't convert Value::{} into Vec<u8>.", from)
}
}
}
}
macro_rules! from_value {
( $( $t:ty : $k:ident ),* ) => {
$(
impl convert::From<Value> for $t {
fn from(v: Value) -> $t {
if let Value::$k(x) = v {
return x;
}
let from = SqlType::from(v);
panic!("Can't convert Value::{} into {}", from, stringify!($t))
}
}
)*
};
}
impl From<Value> for AppDate {
fn from(v: Value) -> AppDate {
if let Value::Date(x, tz) = v {
let time = tz.timestamp(i64::from(x) * 24 * 3600, 0);
return time.date();
}
let from = SqlType::from(v);
panic!("Can't convert Value::{} into {}", from, "AppDate")
}
}
impl From<Value> for AppDateTime {
fn from(v: Value) -> AppDateTime {
match v {
Value::DateTime(u, tz) => tz.timestamp(i64::from(u), 0),
Value::DateTime64(u, params) => {
let (precision, tz) = params;
to_datetime(u, precision, tz)
}
Value::ChronoDateTime(dt) => dt,
_ => {
let from = SqlType::from(v);
panic!("Can't convert Value::{} into {}", from, "DateTime<Tz>")
}
}
}
}
from_value! {
u8: UInt8,
u16: UInt16,
u32: UInt32,
u64: UInt64,
i8: Int8,
i16: Int16,
i32: Int32,
i64: Int64,
f32: Float32,
f64: Float64,
[u8; 4]: Ipv4
}
pub(crate) fn decode_ipv4(octets: &[u8; 4]) -> Ipv4Addr {
let mut buffer = *octets;
buffer.reverse();
Ipv4Addr::from(buffer)
}
pub(crate) fn decode_ipv6(octets: &[u8; 16]) -> Ipv6Addr {
Ipv6Addr::from(*octets)
}
#[cfg(test)]
mod test {
use super::*;
use chrono_tz::Tz::{self, UTC};
use std::fmt;
use rand::{
distributions::{Distribution, Standard},
random,
};
use crate::{Block, row};
fn test_into_t<T>(v: Value, x: &T)
where
Value: convert::Into<T>,
T: PartialEq + fmt::Debug,
{
let a: T = v.into();
assert_eq!(a, *x);
}
fn test_from_rnd<T>()
where
Value: convert::Into<T> + convert::From<T>,
T: PartialEq + fmt::Debug + Clone,
Standard: Distribution<T>,
{
for _ in 0..100 {
let value = random::<T>();
test_into_t::<T>(Value::from(value.clone()), &value);
}
}
fn test_from_t<T>(value: &T)
where
Value: convert::Into<T> + convert::From<T>,
T: PartialEq + fmt::Debug + Clone,
{
test_into_t::<T>(Value::from(value.clone()), value);
}
macro_rules! test_type {
( $( $k:ident : $t:ty ),* ) => {
$(
#[test]
fn $k() {
test_from_rnd::<$t>();
}
)*
};
}
test_type! {
test_u8: u8,
test_u16: u16,
test_u32: u32,
test_u64: u64,
test_i8: i8,
test_i16: i16,
test_i32: i32,
test_i64: i64,
test_f32: f32,
test_f64: f64,
test_ipv4: [u8; 4]
}
#[test]
fn test_string() {
test_from_t(&"284222f9-aba2-4b05-bcf5-e4e727fe34d1".to_string());
}
#[test]
fn test_from_u32() {
let v = Value::UInt32(32);
let u: u32 = u32::from(v);
assert_eq!(u, 32);
}
#[test]
fn test_uuid() {
let uuid = Uuid::parse_str("936da01f-9abd-4d9d-80c7-02af85c822a8").unwrap();
let v = Value::from(uuid);
assert_eq!(v.to_string(), "936da01f-9abd-4d9d-80c7-02af85c822a8");
}
#[test]
fn test_from_datetime_utc() {
let date_time_value: DateTime<Utc> = Utc.ymd(2014, 7, 8).and_hms(14, 0, 0);
let v = Value::from(date_time_value);
assert_eq!(
v,
Value::DateTime(date_time_value.timestamp() as u32, Tz::UTC)
);
}
#[test]
fn test_from_date() {
let date_value: Date<Tz> = UTC.ymd(2016, 10, 22);
let date_time_value: DateTime<Tz> = UTC.ymd(2014, 7, 8).and_hms(14, 0, 0);
let d: Value = Value::from(date_value);
let dt: Value = date_time_value.into();
assert_eq!(
Value::Date(u16::get_days(date_value), date_value.timezone()),
d
);
assert_eq!(Value::ChronoDateTime(date_time_value), dt);
}
#[test]
fn test_boolean() {
let v = Value::from(false);
let w = Value::from(true);
assert_eq!(v, Value::UInt8(0));
assert_eq!(w, Value::UInt8(1));
}
#[test]
fn test_string_from() {
let v = Value::String(Arc::new(b"df47a455-bb3c-4bd6-b2f2-a24be3db36ab".to_vec()));
let u = String::from(v);
assert_eq!("df47a455-bb3c-4bd6-b2f2-a24be3db36ab".to_string(), u);
}
#[test]
fn test_into_string() {
let v = Value::String(Arc::new(b"d2384838-dfe8-43ea-b1f7-63fb27b91088".to_vec()));
let u: String = v.into();
assert_eq!("d2384838-dfe8-43ea-b1f7-63fb27b91088".to_string(), u);
}
#[test]
fn test_into_vec() {
let v = Value::String(Arc::new(vec![1, 2, 3]));
let u: Vec<u8> = v.into();
assert_eq!(vec![1, 2, 3], u);
}
#[test]
fn test_display() {
assert_eq!("42".to_string(), format!("{}", Value::UInt8(42)));
assert_eq!("42".to_string(), format!("{}", Value::UInt16(42)));
assert_eq!("42".to_string(), format!("{}", Value::UInt32(42)));
assert_eq!("42".to_string(), format!("{}", Value::UInt64(42)));
assert_eq!("42".to_string(), format!("{}", Value::Int8(42)));
assert_eq!("42".to_string(), format!("{}", Value::Int16(42)));
assert_eq!("42".to_string(), format!("{}", Value::Int32(42)));
assert_eq!("42".to_string(), format!("{}", Value::Int64(42)));
assert_eq!(
"text".to_string(),
format!("{}", Value::String(Arc::new(b"text".to_vec())))
);
assert_eq!(
"\u{1}\u{2}\u{3}".to_string(),
format!("{}", Value::String(Arc::new(vec![1, 2, 3])))
);
assert_eq!(
"NULL".to_string(),
format!("{}", Value::Nullable(Either::Left(SqlType::UInt8.into())))
);
assert_eq!(
"42".to_string(),
format!(
"{}",
Value::Nullable(Either::Right(Box::new(Value::UInt8(42))))
)
);
assert_eq!(
"[1, 2, 3]".to_string(),
format!(
"{}",
Value::Array(
SqlType::Int32.into(),
Arc::new(vec![Value::Int32(1), Value::Int32(2), Value::Int32(3)])
)
)
);
}
#[test]
fn test_default_fixed_str() {
for n in 0_usize..1000_usize {
let actual = Value::default(SqlType::FixedString(n));
let actual_str: String = actual.into();
assert_eq!(actual_str.len(), n);
for ch in actual_str.as_bytes() {
assert_eq!(*ch, 0_u8);
}
}
}
#[test]
fn test_size_of() {
use std::mem;
assert_eq!(56, mem::size_of::<[Value; 1]>());
}
#[test]
fn test_from_some() {
assert_eq!(
Value::from(Some(1_u32)),
Value::Nullable(Either::Right(Value::UInt32(1).into()))
);
assert_eq!(
Value::from(Some("text")),
Value::Nullable(Either::Right(Value::String(b"text".to_vec().into()).into()))
);
assert_eq!(
Value::from(Some(3.1)),
Value::Nullable(Either::Right(Value::Float64(3.1).into()))
);
let date_time_val = UTC.ymd(2019, 1, 1).and_hms(0, 0, 0);
assert_eq!(
Value::from(Some(date_time_val)),
Value::Nullable(Either::Right(Value::ChronoDateTime(date_time_val).into()))
);
}
#[test]
fn test_value_array_from() {
let mut block = Block::with_capacity(5);
block.push(row! {
u16: vec![1_u16, 2, 3],
u32: vec![1_u32, 2, 3],
u64: vec![1_u64, 2, 3],
i8: vec![1_i8, 2, 3],
i16: vec![1_i16, 2, 3],
i32: vec![1_i32, 2, 3],
i64: vec![1_i64, 2, 3],
f32: vec![1_f32, 2.0, 3.0],
f64: vec![1_f64, 2.0, 3.0],
}).unwrap();
assert_eq!(block.row_count(), 1);
assert_eq!(block.column_count(), 9);
}
}
|
/// Tile in the Minesweeper grid, packed into a single byte.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(super) struct PackedTile(pub(super) u8);
impl Default for PackedTile {
fn default() -> Self {
Tile::default().pack()
}
}
impl PackedTile {
/// Unpacks the `Tile` from a single byte.
pub(super) fn unpack(self) -> Tile {
if self.0 == '!' as u8 {
Tile::Mine
} else if self.0 == ' ' as u8 {
Tile::Number(0)
} else if self.0 <= '9' as u8 {
Tile::Number(self.0 - '0' as u8)
} else if self.0 < 0x60 {
Tile::Number(self.0 - 'A' as u8 + 10)
} else {
Tile::Covered(
FlagState::from((self.0 >> 2) & 0b11),
HiddenState::from(self.0 & 0b11),
)
}
}
}
/// Tile in the Minesweeper grid.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Tile {
/// Covered tile.
Covered(FlagState, HiddenState),
/// Revealed safe tile.
Number(u8),
/// Revealed mine tile.
Mine,
}
impl Default for Tile {
fn default() -> Self {
Tile::Covered(FlagState::default(), HiddenState::default())
}
}
impl Tile {
/// Packs the tile into a single byte.
pub(super) fn pack(self) -> PackedTile {
match self {
Tile::Covered(f, h) => PackedTile(0x60 | (f as u8) << 2 | h as u8),
Tile::Number(0) => PackedTile(' ' as u8),
Tile::Number(n) if n < 10 => PackedTile(n + '0' as u8),
Tile::Number(n) => PackedTile(n - 10 + 'A' as u8),
Tile::Mine => PackedTile('!' as u8),
}
}
/// Toggles flag on the tile.
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn toggle_flag(self) -> Tile {
match self {
Tile::Covered(f, h) => {
let new_f = match f {
FlagState::None => FlagState::Flag,
FlagState::Flag => FlagState::None,
FlagState::Question => FlagState::None,
};
Tile::Covered(new_f, h)
}
_ => self,
}
}
/// Returns `true` if the tile is a mine or `false` if it might not be.
pub fn is_mine(self) -> bool {
match self {
Tile::Covered(_, HiddenState::Mine) => true,
Tile::Mine => true,
_ => false,
}
}
/// Returns `true` if the tile is a flag or a revealed mine.
pub fn is_assumed_mine(self) -> bool {
match self {
Tile::Covered(FlagState::Flag, _) => true,
Tile::Mine => true,
_ => false,
}
}
}
/// Flag or question mark annotation added by the player.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum FlagState {
/// No player annotation.
None = 0,
/// Flag annotation.
Flag = 1,
/// Question mark annotation.
Question = 2,
}
impl Default for FlagState {
fn default() -> Self {
FlagState::None
}
}
impl From<u8> for FlagState {
fn from(x: u8) -> Self {
match x & 0b11 {
0 => FlagState::None,
1 => FlagState::Flag,
2 => FlagState::Question,
_ => panic!("Invalid FlagState"),
}
}
}
/// Underlying state hidden from the player.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum HiddenState {
/// Possibly a mine, depending on hidden information.
Unknown = 0,
/// Definitely safe, based on information revealed to the player.
Safe = 1,
/// Definitely a mine, based on information revealed to the player.
Mine = 2,
}
impl Default for HiddenState {
fn default() -> Self {
HiddenState::Unknown
}
}
impl From<u8> for HiddenState {
fn from(x: u8) -> Self {
match x & 0b11 {
0 => HiddenState::Unknown,
1 => HiddenState::Safe,
2 => HiddenState::Mine,
_ => panic!("Invalid HiddenState"),
}
}
}
#[cfg(test)]
#[test]
fn test_packed_tile() {
let tiles: &[Tile] = &[
Tile::Mine,
Tile::Covered(FlagState::None, HiddenState::Unknown),
Tile::Covered(FlagState::None, HiddenState::Safe),
Tile::Covered(FlagState::None, HiddenState::Mine),
Tile::Covered(FlagState::Flag, HiddenState::Unknown),
Tile::Covered(FlagState::Flag, HiddenState::Safe),
Tile::Covered(FlagState::Flag, HiddenState::Mine),
Tile::Covered(FlagState::Question, HiddenState::Unknown),
Tile::Covered(FlagState::Question, HiddenState::Safe),
Tile::Covered(FlagState::Question, HiddenState::Mine),
];
for &t in tiles {
assert_eq!(t, t.pack().unpack());
}
for n in 0..32 {
let t = Tile::Number(n);
assert_eq!(t, t.pack().unpack());
}
}
|
use common::error::Error;
use common::result::Result;
#[derive(Debug, Clone)]
pub struct Synopsis {
synopsis: String,
}
impl Synopsis {
pub fn new<S: Into<String>>(synopsis: S) -> Result<Self> {
let synopsis = synopsis.into();
if synopsis.len() < 4 {
return Err(Error::new("synopsis", "too_short"));
}
Ok(Synopsis { synopsis })
}
pub fn value(&self) -> &str {
&self.synopsis
}
}
impl ToString for Synopsis {
fn to_string(&self) -> String {
self.value().to_owned()
}
}
|
/*
SPDX-License-Identifier: Apache-2.0 OR MIT
Copyright 2020 The arboard contributors
The project to which this file belongs is licensed under either of
the Apache 2.0 or the MIT license at the licensee's choice. The terms
and conditions of the chosen license apply to this file.
*/
use super::common::{Error, ImageData};
use core_graphics::color_space::CGColorSpace;
use core_graphics::image::CGImage;
use core_graphics::{
base::{kCGBitmapByteOrderDefault, kCGImageAlphaLast, kCGRenderingIntentDefault, CGFloat},
data_provider::{CGDataProvider, CustomData},
};
use objc::runtime::{Class, Object, BOOL, NO};
use objc::{msg_send, sel, sel_impl};
use objc_foundation::{INSArray, INSObject, INSString};
use objc_foundation::{NSArray, NSDictionary, NSObject, NSString};
use objc_id::{Id, Owned};
use std::io::Cursor;
use std::mem::transmute;
// required to bring NSPasteboard into the path of the class-resolver
#[link(name = "AppKit", kind = "framework")]
extern "C" {}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct NSSize {
pub width: CGFloat,
pub height: CGFloat,
}
#[derive(Debug, Clone)]
struct PixelArray {
data: Vec<u8>,
}
impl CustomData for PixelArray {
unsafe fn ptr(&self) -> *const u8 {
self.data.as_ptr()
}
unsafe fn len(&self) -> usize {
self.data.len()
}
}
/// Returns an NSImage object on success.
fn image_from_pixels(
pixels: Vec<u8>,
width: usize,
height: usize,
) -> Result<Id<NSObject>, Box<dyn std::error::Error>> {
let colorspace = CGColorSpace::create_device_rgb();
let bitmap_info: u32 = kCGBitmapByteOrderDefault | kCGImageAlphaLast;
let pixel_data: Box<Box<dyn CustomData>> = Box::new(Box::new(PixelArray { data: pixels }));
let provider = unsafe { CGDataProvider::from_custom_data(pixel_data) };
let rendering_intent = kCGRenderingIntentDefault;
let cg_image = CGImage::new(
width,
height,
8,
32,
4 * width,
&colorspace,
bitmap_info,
&provider,
false,
rendering_intent,
);
let size = NSSize { width: width as CGFloat, height: height as CGFloat };
let nsimage_class = Class::get("NSImage").ok_or("Class::get(\"NSImage\")")?;
let image: Id<NSObject> = unsafe { Id::from_ptr(msg_send![nsimage_class, alloc]) };
let () = unsafe { msg_send![image, initWithCGImage:cg_image size:size] };
Ok(image)
}
pub struct OSXClipboardContext {
pasteboard: Id<Object>,
}
impl OSXClipboardContext {
pub(crate) fn new() -> Result<OSXClipboardContext, Error> {
let cls = Class::get("NSPasteboard")
.ok_or(Error::Unknown { description: "Class::get(\"NSPasteboard\")".into() })?;
let pasteboard: *mut Object = unsafe { msg_send![cls, generalPasteboard] };
if pasteboard.is_null() {
return Err(Error::Unknown {
description: "NSPasteboard#generalPasteboard returned null".into(),
});
}
let pasteboard: Id<Object> = unsafe { Id::from_ptr(pasteboard) };
Ok(OSXClipboardContext { pasteboard })
}
pub(crate) fn get_text(&mut self) -> Result<String, Error> {
let string_class: Id<NSObject> = {
let cls: Id<Class> = unsafe { Id::from_ptr(class("NSString")) };
unsafe { transmute(cls) }
};
let classes: Id<NSArray<NSObject, Owned>> = NSArray::from_vec(vec![string_class]);
let options: Id<NSDictionary<NSObject, NSObject>> = NSDictionary::new();
let string_array: Id<NSArray<NSString>> = unsafe {
let obj: *mut NSArray<NSString> =
msg_send![self.pasteboard, readObjectsForClasses:&*classes options:&*options];
if obj.is_null() {
//return Err("pasteboard#readObjectsForClasses:options: returned null".into());
return Err(Error::ContentNotAvailable);
}
Id::from_ptr(obj)
};
if string_array.count() == 0 {
//Err("pasteboard#readObjectsForClasses:options: returned empty".into())
Err(Error::ContentNotAvailable)
} else {
Ok(string_array[0].as_str().to_owned())
}
}
pub(crate) fn set_text(&mut self, data: String) -> Result<(), Error> {
let string_array = NSArray::from_vec(vec![NSString::from_str(&data)]);
let _: usize = unsafe { msg_send![self.pasteboard, clearContents] };
let success: bool = unsafe { msg_send![self.pasteboard, writeObjects: string_array] };
if success {
Ok(())
} else {
Err(Error::Unknown { description: "NSPasteboard#writeObjects: returned false".into() })
}
}
// fn get_binary_contents(&mut self) -> Result<Option<ClipboardContent>, Box<dyn std::error::Error>> {
// let string_class: Id<NSObject> = {
// let cls: Id<Class> = unsafe { Id::from_ptr(class("NSString")) };
// unsafe { transmute(cls) }
// };
// let image_class: Id<NSObject> = {
// let cls: Id<Class> = unsafe { Id::from_ptr(class("NSImage")) };
// unsafe { transmute(cls) }
// };
// let url_class: Id<NSObject> = {
// let cls: Id<Class> = unsafe { Id::from_ptr(class("NSURL")) };
// unsafe { transmute(cls) }
// };
// let classes = vec![url_class, image_class, string_class];
// let classes: Id<NSArray<NSObject, Owned>> = NSArray::from_vec(classes);
// let options: Id<NSDictionary<NSObject, NSObject>> = NSDictionary::new();
// let contents: Id<NSArray<NSObject>> = unsafe {
// let obj: *mut NSArray<NSObject> =
// msg_send![self.pasteboard, readObjectsForClasses:&*classes options:&*options];
// if obj.is_null() {
// return Err(err("pasteboard#readObjectsForClasses:options: returned null"));
// }
// Id::from_ptr(obj)
// };
// if contents.count() == 0 {
// Ok(None)
// } else {
// let obj = &contents[0];
// if obj.is_kind_of(Class::get("NSString").unwrap()) {
// let s: &NSString = unsafe { transmute(obj) };
// Ok(Some(ClipboardContent::Utf8(s.as_str().to_owned())))
// } else if obj.is_kind_of(Class::get("NSImage").unwrap()) {
// let tiff: &NSArray<NSObject> = unsafe { msg_send![obj, TIFFRepresentation] };
// let len: usize = unsafe { msg_send![tiff, length] };
// let bytes: *const u8 = unsafe { msg_send![tiff, bytes] };
// let vec = unsafe { std::slice::from_raw_parts(bytes, len) };
// // Here we copy the entire &[u8] into a new owned `Vec`
// // Is there another way that doesn't copy multiple megabytes?
// Ok(Some(ClipboardContent::Tiff(vec.into())))
// } else if obj.is_kind_of(Class::get("NSURL").unwrap()) {
// let s: &NSString = unsafe { msg_send![obj, absoluteString] };
// Ok(Some(ClipboardContent::Utf8(s.as_str().to_owned())))
// } else {
// // let cls: &Class = unsafe { msg_send![obj, class] };
// // println!("{}", cls.name());
// Err(err("pasteboard#readObjectsForClasses:options: returned unknown class"))
// }
// }
// }
pub(crate) fn get_image(&mut self) -> Result<ImageData, Error> {
let image_class: Id<NSObject> = {
let cls: Id<Class> = unsafe { Id::from_ptr(class("NSImage")) };
unsafe { transmute(cls) }
};
let classes = vec![image_class];
let classes: Id<NSArray<NSObject, Owned>> = NSArray::from_vec(classes);
let options: Id<NSDictionary<NSObject, NSObject>> = NSDictionary::new();
let contents: Id<NSArray<NSObject>> = unsafe {
let obj: *mut NSArray<NSObject> =
msg_send![self.pasteboard, readObjectsForClasses:&*classes options:&*options];
if obj.is_null() {
return Err(Error::ContentNotAvailable);
}
Id::from_ptr(obj)
};
let result;
if contents.count() == 0 {
result = Err(Error::ContentNotAvailable);
} else {
let obj = &contents[0];
if obj.is_kind_of(Class::get("NSImage").unwrap()) {
let tiff: &NSArray<NSObject> = unsafe { msg_send![obj, TIFFRepresentation] };
let len: usize = unsafe { msg_send![tiff, length] };
let bytes: *const u8 = unsafe { msg_send![tiff, bytes] };
let slice = unsafe { std::slice::from_raw_parts(bytes, len) };
let data_cursor = Cursor::new(slice);
let reader = image::io::Reader::with_format(data_cursor, image::ImageFormat::Tiff);
let width;
let height;
let pixels;
match reader.decode() {
Ok(img) => {
let rgba = img.into_rgba();
let (w, h) = rgba.dimensions();
width = w;
height = h;
pixels = rgba.into_raw();
}
Err(_) => return Err(Error::ConversionFailure),
};
let data = ImageData {
width: width as usize,
height: height as usize,
bytes: pixels.into(),
};
result = Ok(data);
} else {
// let cls: &Class = unsafe { msg_send![obj, class] };
// println!("{}", cls.name());
result = Err(Error::ContentNotAvailable);
}
}
result
}
pub(crate) fn set_image(&mut self, data: ImageData) -> Result<(), Error> {
let pixels = data.bytes.into();
let image = image_from_pixels(pixels, data.width, data.height)
.map_err(|_| Error::ConversionFailure)?;
let objects: Id<NSArray<NSObject, Owned>> = NSArray::from_vec(vec![image]);
let _: usize = unsafe { msg_send![self.pasteboard, clearContents] };
let success: BOOL = unsafe { msg_send![self.pasteboard, writeObjects: objects] };
if success == NO {
return Err(Error::Unknown {
description:
"Failed to write the image to the pasteboard (`writeObjects` returned NO)."
.into(),
});
}
Ok(())
}
}
// this is a convenience function that both cocoa-rs and
// glutin define, which seems to depend on the fact that
// Option::None has the same representation as a null pointer
#[inline]
pub fn class(name: &str) -> *mut Class {
unsafe { transmute(Class::get(name)) }
}
|
use crate::{BoxFuture, Result};
pub trait Init<'a, P>: Sized + Send + Sync {
fn init(provider: &'a P) -> BoxFuture<'a, Result<Self>>;
}
|
use crate::{NumBytes, Read, Write};
/// TODO Read, Write, `NumBytes` needs a custom implementation based on `fixed_bytes`
#[derive(Read, Write, NumBytes, Default, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[eosio_core_root_path = "crate"]
pub struct Checksum160([u8; 20]);
impl Checksum160 {
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub const fn to_bytes(&self) -> [u8; 20] {
self.0
}
}
impl From<[u8; 20]> for Checksum160 {
#[inline]
fn from(value: [u8; 20]) -> Self {
Self(value)
}
}
impl From<Checksum160> for [u8; 20] {
#[inline]
fn from(value: Checksum160) -> Self {
value.0
}
}
|
///// chapter 4 "structuring data and matching patterns"
///// program section:
//
fn main() {
let magic_numbers = vec![7_i32, 42, 47, 45, 54];
///// only the items 42, 47 and 45
//
let slc = &magic_numbers[1..4];
println!("{:?}", slc);
}
///// output should be:
/*
*/// end of output
|
pub fn build_message(opt_name: Option<&str>) -> String {
let name = opt_name.unwrap_or("World");
return format!("Hello {}!", name);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_message_none() {
let message = build_message(None);
assert_eq!(message, "Hello World!");
}
#[test]
fn build_message_some() {
let message = build_message(Some("MyName"));
assert_eq!(message, "Hello MyName!");
}
}
|
use webrender::api::units::LayoutPixel;
use webrender::api::*;
use rpdf_document::Page;
use rpdf_graphics::{text, GraphicsObject};
use super::text::FontRenderContext;
pub struct PageRenderer<'a> {
page: &'a Page,
}
impl<'a> PageRenderer<'a> {
pub fn new(page: &'a Page) -> Self {
Self { page }
}
fn render_text(
&mut self,
scale: euclid::TypedScale<f32, LayoutPixel, LayoutPixel>,
api: &RenderApi,
builder: &mut DisplayListBuilder,
txn: &mut Transaction,
space_and_clip: &SpaceAndClipInfo,
font_context: &mut FontRenderContext<'a>,
text_object: &'a text::TextObject,
) {
for text_fragment in text_object.fragments.iter() {
let mut transform = euclid::TypedTransform2D::from_untyped(&text_fragment.transform);
transform.m32 = self.page.height() as f32 - transform.m32;
if let Some(font) = self.page.font(&text_fragment.font_name) {
font_context.load_font(api, txn, &text_fragment.font_name, font);
} else {
// skip text fragments that don't have font data
continue;
};
let font_size = text_fragment.font_size * scale.get();
let font_instance_key =
font_context.load_font_instance(api, txn, &text_fragment.font_name, font_size);
let mut glyph_instances = Vec::with_capacity(text_fragment.glyphs.len());
for text_glyph in text_fragment.glyphs.iter() {
let mut point = euclid::TypedPoint2D::from_untyped(&text_glyph.origin);
point.y = self.page.height() as f32 - point.y;
glyph_instances.push(GlyphInstance {
index: text_glyph.index,
point: scale.transform_point(&point),
});
}
let size = euclid::TypedSize2D::<f32, LayoutPixel>::new(self.page.width() as f32, 60.0);
let rect = euclid::TypedRect::<f32, LayoutPixel>::new(
euclid::TypedPoint2D::<f32, LayoutPixel>::new(0.0, -30.0),
size,
);
let transformed_rect = scale.transform_rect(&transform.transform_rect(&rect));
log::trace!("push text {:?} {:?}", glyph_instances, transformed_rect);
builder.push_text(
&LayoutPrimitiveInfo::new(transformed_rect),
space_and_clip,
&glyph_instances,
font_instance_key,
ColorF::BLACK,
None,
);
}
}
pub fn render(
&mut self,
scale: euclid::TypedScale<f32, LayoutPixel, LayoutPixel>,
api: &RenderApi,
builder: &mut DisplayListBuilder,
txn: &mut Transaction,
space_and_clip: &SpaceAndClipInfo,
font_context: &mut FontRenderContext<'a>,
) {
for graphics_object in self.page.graphics_objects() {
match graphics_object {
GraphicsObject::Text(text_object) => self.render_text(
scale,
api,
builder,
txn,
space_and_clip,
font_context,
text_object,
),
}
}
}
}
|
#[doc = "Register `CR1` reader"]
pub type R = crate::R<CR1_SPEC>;
#[doc = "Register `CR1` writer"]
pub type W = crate::W<CR1_SPEC>;
#[doc = "Field `LPDS` reader - Low-power deep sleep"]
pub type LPDS_R = crate::BitReader;
#[doc = "Field `LPDS` writer - Low-power deep sleep"]
pub type LPDS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PDDS` reader - Power down deepsleep"]
pub type PDDS_R = crate::BitReader<PDDS_A>;
#[doc = "Power down deepsleep\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PDDS_A {
#[doc = "0: Enter Stop mode when the CPU enters deepsleep"]
StopMode = 0,
#[doc = "1: Enter Standby mode when the CPU enters deepsleep"]
StandbyMode = 1,
}
impl From<PDDS_A> for bool {
#[inline(always)]
fn from(variant: PDDS_A) -> Self {
variant as u8 != 0
}
}
impl PDDS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PDDS_A {
match self.bits {
false => PDDS_A::StopMode,
true => PDDS_A::StandbyMode,
}
}
#[doc = "Enter Stop mode when the CPU enters deepsleep"]
#[inline(always)]
pub fn is_stop_mode(&self) -> bool {
*self == PDDS_A::StopMode
}
#[doc = "Enter Standby mode when the CPU enters deepsleep"]
#[inline(always)]
pub fn is_standby_mode(&self) -> bool {
*self == PDDS_A::StandbyMode
}
}
#[doc = "Field `PDDS` writer - Power down deepsleep"]
pub type PDDS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PDDS_A>;
impl<'a, REG, const O: u8> PDDS_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Enter Stop mode when the CPU enters deepsleep"]
#[inline(always)]
pub fn stop_mode(self) -> &'a mut crate::W<REG> {
self.variant(PDDS_A::StopMode)
}
#[doc = "Enter Standby mode when the CPU enters deepsleep"]
#[inline(always)]
pub fn standby_mode(self) -> &'a mut crate::W<REG> {
self.variant(PDDS_A::StandbyMode)
}
}
#[doc = "Field `CSBF` reader - Clear standby flag"]
pub type CSBF_R = crate::BitReader;
#[doc = "Field `CSBF` writer - Clear standby flag"]
pub type CSBF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PVDE` reader - Power voltage detector enable"]
pub type PVDE_R = crate::BitReader;
#[doc = "Field `PVDE` writer - Power voltage detector enable"]
pub type PVDE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PLS` reader - PVD level selection"]
pub type PLS_R = crate::FieldReader;
#[doc = "Field `PLS` writer - PVD level selection"]
pub type PLS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `DBP` reader - Disable backup domain write protection"]
pub type DBP_R = crate::BitReader;
#[doc = "Field `DBP` writer - Disable backup domain write protection"]
pub type DBP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FPDS` reader - Flash power down in Stop mode"]
pub type FPDS_R = crate::BitReader;
#[doc = "Field `FPDS` writer - Flash power down in Stop mode"]
pub type FPDS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LPUDS` reader - Low-power regulator in deepsleep under-drive mode"]
pub type LPUDS_R = crate::BitReader;
#[doc = "Field `LPUDS` writer - Low-power regulator in deepsleep under-drive mode"]
pub type LPUDS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MRUDS` reader - Main regulator in deepsleep under-drive mode"]
pub type MRUDS_R = crate::BitReader;
#[doc = "Field `MRUDS` writer - Main regulator in deepsleep under-drive mode"]
pub type MRUDS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ADCDC1` reader - ADCDC1"]
pub type ADCDC1_R = crate::BitReader;
#[doc = "Field `ADCDC1` writer - ADCDC1"]
pub type ADCDC1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `VOS` reader - Regulator voltage scaling output selection"]
pub type VOS_R = crate::FieldReader<VOS_A>;
#[doc = "Regulator voltage scaling output selection\n\nValue on reset: 3"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum VOS_A {
#[doc = "1: Scale 3 mode"]
Scale3 = 1,
#[doc = "2: Scale 2 mode"]
Scale2 = 2,
#[doc = "3: Scale 1 mode (reset value)"]
Scale1 = 3,
}
impl From<VOS_A> for u8 {
#[inline(always)]
fn from(variant: VOS_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for VOS_A {
type Ux = u8;
}
impl VOS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<VOS_A> {
match self.bits {
1 => Some(VOS_A::Scale3),
2 => Some(VOS_A::Scale2),
3 => Some(VOS_A::Scale1),
_ => None,
}
}
#[doc = "Scale 3 mode"]
#[inline(always)]
pub fn is_scale3(&self) -> bool {
*self == VOS_A::Scale3
}
#[doc = "Scale 2 mode"]
#[inline(always)]
pub fn is_scale2(&self) -> bool {
*self == VOS_A::Scale2
}
#[doc = "Scale 1 mode (reset value)"]
#[inline(always)]
pub fn is_scale1(&self) -> bool {
*self == VOS_A::Scale1
}
}
#[doc = "Field `VOS` writer - Regulator voltage scaling output selection"]
pub type VOS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, VOS_A>;
impl<'a, REG, const O: u8> VOS_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Scale 3 mode"]
#[inline(always)]
pub fn scale3(self) -> &'a mut crate::W<REG> {
self.variant(VOS_A::Scale3)
}
#[doc = "Scale 2 mode"]
#[inline(always)]
pub fn scale2(self) -> &'a mut crate::W<REG> {
self.variant(VOS_A::Scale2)
}
#[doc = "Scale 1 mode (reset value)"]
#[inline(always)]
pub fn scale1(self) -> &'a mut crate::W<REG> {
self.variant(VOS_A::Scale1)
}
}
#[doc = "Field `ODEN` reader - Over-drive enable"]
pub type ODEN_R = crate::BitReader;
#[doc = "Field `ODEN` writer - Over-drive enable"]
pub type ODEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ODSWEN` reader - Over-drive switching enabled"]
pub type ODSWEN_R = crate::BitReader;
#[doc = "Field `ODSWEN` writer - Over-drive switching enabled"]
pub type ODSWEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UDEN` reader - Under-drive enable in stop mode"]
pub type UDEN_R = crate::FieldReader;
#[doc = "Field `UDEN` writer - Under-drive enable in stop mode"]
pub type UDEN_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
impl R {
#[doc = "Bit 0 - Low-power deep sleep"]
#[inline(always)]
pub fn lpds(&self) -> LPDS_R {
LPDS_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Power down deepsleep"]
#[inline(always)]
pub fn pdds(&self) -> PDDS_R {
PDDS_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 3 - Clear standby flag"]
#[inline(always)]
pub fn csbf(&self) -> CSBF_R {
CSBF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Power voltage detector enable"]
#[inline(always)]
pub fn pvde(&self) -> PVDE_R {
PVDE_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bits 5:7 - PVD level selection"]
#[inline(always)]
pub fn pls(&self) -> PLS_R {
PLS_R::new(((self.bits >> 5) & 7) as u8)
}
#[doc = "Bit 8 - Disable backup domain write protection"]
#[inline(always)]
pub fn dbp(&self) -> DBP_R {
DBP_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Flash power down in Stop mode"]
#[inline(always)]
pub fn fpds(&self) -> FPDS_R {
FPDS_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Low-power regulator in deepsleep under-drive mode"]
#[inline(always)]
pub fn lpuds(&self) -> LPUDS_R {
LPUDS_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Main regulator in deepsleep under-drive mode"]
#[inline(always)]
pub fn mruds(&self) -> MRUDS_R {
MRUDS_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 13 - ADCDC1"]
#[inline(always)]
pub fn adcdc1(&self) -> ADCDC1_R {
ADCDC1_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bits 14:15 - Regulator voltage scaling output selection"]
#[inline(always)]
pub fn vos(&self) -> VOS_R {
VOS_R::new(((self.bits >> 14) & 3) as u8)
}
#[doc = "Bit 16 - Over-drive enable"]
#[inline(always)]
pub fn oden(&self) -> ODEN_R {
ODEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - Over-drive switching enabled"]
#[inline(always)]
pub fn odswen(&self) -> ODSWEN_R {
ODSWEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bits 18:19 - Under-drive enable in stop mode"]
#[inline(always)]
pub fn uden(&self) -> UDEN_R {
UDEN_R::new(((self.bits >> 18) & 3) as u8)
}
}
impl W {
#[doc = "Bit 0 - Low-power deep sleep"]
#[inline(always)]
#[must_use]
pub fn lpds(&mut self) -> LPDS_W<CR1_SPEC, 0> {
LPDS_W::new(self)
}
#[doc = "Bit 1 - Power down deepsleep"]
#[inline(always)]
#[must_use]
pub fn pdds(&mut self) -> PDDS_W<CR1_SPEC, 1> {
PDDS_W::new(self)
}
#[doc = "Bit 3 - Clear standby flag"]
#[inline(always)]
#[must_use]
pub fn csbf(&mut self) -> CSBF_W<CR1_SPEC, 3> {
CSBF_W::new(self)
}
#[doc = "Bit 4 - Power voltage detector enable"]
#[inline(always)]
#[must_use]
pub fn pvde(&mut self) -> PVDE_W<CR1_SPEC, 4> {
PVDE_W::new(self)
}
#[doc = "Bits 5:7 - PVD level selection"]
#[inline(always)]
#[must_use]
pub fn pls(&mut self) -> PLS_W<CR1_SPEC, 5> {
PLS_W::new(self)
}
#[doc = "Bit 8 - Disable backup domain write protection"]
#[inline(always)]
#[must_use]
pub fn dbp(&mut self) -> DBP_W<CR1_SPEC, 8> {
DBP_W::new(self)
}
#[doc = "Bit 9 - Flash power down in Stop mode"]
#[inline(always)]
#[must_use]
pub fn fpds(&mut self) -> FPDS_W<CR1_SPEC, 9> {
FPDS_W::new(self)
}
#[doc = "Bit 10 - Low-power regulator in deepsleep under-drive mode"]
#[inline(always)]
#[must_use]
pub fn lpuds(&mut self) -> LPUDS_W<CR1_SPEC, 10> {
LPUDS_W::new(self)
}
#[doc = "Bit 11 - Main regulator in deepsleep under-drive mode"]
#[inline(always)]
#[must_use]
pub fn mruds(&mut self) -> MRUDS_W<CR1_SPEC, 11> {
MRUDS_W::new(self)
}
#[doc = "Bit 13 - ADCDC1"]
#[inline(always)]
#[must_use]
pub fn adcdc1(&mut self) -> ADCDC1_W<CR1_SPEC, 13> {
ADCDC1_W::new(self)
}
#[doc = "Bits 14:15 - Regulator voltage scaling output selection"]
#[inline(always)]
#[must_use]
pub fn vos(&mut self) -> VOS_W<CR1_SPEC, 14> {
VOS_W::new(self)
}
#[doc = "Bit 16 - Over-drive enable"]
#[inline(always)]
#[must_use]
pub fn oden(&mut self) -> ODEN_W<CR1_SPEC, 16> {
ODEN_W::new(self)
}
#[doc = "Bit 17 - Over-drive switching enabled"]
#[inline(always)]
#[must_use]
pub fn odswen(&mut self) -> ODSWEN_W<CR1_SPEC, 17> {
ODSWEN_W::new(self)
}
#[doc = "Bits 18:19 - Under-drive enable in stop mode"]
#[inline(always)]
#[must_use]
pub fn uden(&mut self) -> UDEN_W<CR1_SPEC, 18> {
UDEN_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 = "power control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr1::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 [`cr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CR1_SPEC;
impl crate::RegisterSpec for CR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cr1::R`](R) reader structure"]
impl crate::Readable for CR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cr1::W`](W) writer structure"]
impl crate::Writable for CR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CR1 to value 0xc000"]
impl crate::Resettable for CR1_SPEC {
const RESET_VALUE: Self::Ux = 0xc000;
}
|
#[doc = "Register `TIM7_CR1` reader"]
pub type R = crate::R<TIM7_CR1_SPEC>;
#[doc = "Register `TIM7_CR1` writer"]
pub type W = crate::W<TIM7_CR1_SPEC>;
#[doc = "Field `CEN` reader - Counter enable CEN is cleared automatically in one-pulse mode, when an update event occurs."]
pub type CEN_R = crate::BitReader;
#[doc = "Field `CEN` writer - Counter enable CEN is cleared automatically in one-pulse mode, when an update event occurs."]
pub type CEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UDIS` reader - Update disable This bit is set and cleared by software to enable/disable UEV event generation. Counter overflow/underflow Setting the UG bit Update generation through the slave mode controller Buffered registers are then loaded with their preload values."]
pub type UDIS_R = crate::BitReader;
#[doc = "Field `UDIS` writer - Update disable This bit is set and cleared by software to enable/disable UEV event generation. Counter overflow/underflow Setting the UG bit Update generation through the slave mode controller Buffered registers are then loaded with their preload values."]
pub type UDIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `URS` reader - Update request source This bit is set and cleared by software to select the UEV event sources. Counter overflow/underflow Setting the UG bit Update generation through the slave mode controller"]
pub type URS_R = crate::BitReader;
#[doc = "Field `URS` writer - Update request source This bit is set and cleared by software to select the UEV event sources. Counter overflow/underflow Setting the UG bit Update generation through the slave mode controller"]
pub type URS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OPM` reader - One-pulse mode"]
pub type OPM_R = crate::BitReader;
#[doc = "Field `OPM` writer - One-pulse mode"]
pub type OPM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ARPE` reader - Auto-reload preload enable"]
pub type ARPE_R = crate::BitReader;
#[doc = "Field `ARPE` writer - Auto-reload preload enable"]
pub type ARPE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UIFREMAP` reader - UIF status bit remapping"]
pub type UIFREMAP_R = crate::BitReader;
#[doc = "Field `UIFREMAP` writer - UIF status bit remapping"]
pub type UIFREMAP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DITHEN` reader - Dithering enable Note: The DITHEN bit can only be modified when CEN bit is reset."]
pub type DITHEN_R = crate::BitReader;
#[doc = "Field `DITHEN` writer - Dithering enable Note: The DITHEN bit can only be modified when CEN bit is reset."]
pub type DITHEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Counter enable CEN is cleared automatically in one-pulse mode, when an update event occurs."]
#[inline(always)]
pub fn cen(&self) -> CEN_R {
CEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Update disable This bit is set and cleared by software to enable/disable UEV event generation. Counter overflow/underflow Setting the UG bit Update generation through the slave mode controller Buffered registers are then loaded with their preload values."]
#[inline(always)]
pub fn udis(&self) -> UDIS_R {
UDIS_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Update request source This bit is set and cleared by software to select the UEV event sources. Counter overflow/underflow Setting the UG bit Update generation through the slave mode controller"]
#[inline(always)]
pub fn urs(&self) -> URS_R {
URS_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - One-pulse mode"]
#[inline(always)]
pub fn opm(&self) -> OPM_R {
OPM_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 7 - Auto-reload preload enable"]
#[inline(always)]
pub fn arpe(&self) -> ARPE_R {
ARPE_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 11 - UIF status bit remapping"]
#[inline(always)]
pub fn uifremap(&self) -> UIFREMAP_R {
UIFREMAP_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - Dithering enable Note: The DITHEN bit can only be modified when CEN bit is reset."]
#[inline(always)]
pub fn dithen(&self) -> DITHEN_R {
DITHEN_R::new(((self.bits >> 12) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Counter enable CEN is cleared automatically in one-pulse mode, when an update event occurs."]
#[inline(always)]
#[must_use]
pub fn cen(&mut self) -> CEN_W<TIM7_CR1_SPEC, 0> {
CEN_W::new(self)
}
#[doc = "Bit 1 - Update disable This bit is set and cleared by software to enable/disable UEV event generation. Counter overflow/underflow Setting the UG bit Update generation through the slave mode controller Buffered registers are then loaded with their preload values."]
#[inline(always)]
#[must_use]
pub fn udis(&mut self) -> UDIS_W<TIM7_CR1_SPEC, 1> {
UDIS_W::new(self)
}
#[doc = "Bit 2 - Update request source This bit is set and cleared by software to select the UEV event sources. Counter overflow/underflow Setting the UG bit Update generation through the slave mode controller"]
#[inline(always)]
#[must_use]
pub fn urs(&mut self) -> URS_W<TIM7_CR1_SPEC, 2> {
URS_W::new(self)
}
#[doc = "Bit 3 - One-pulse mode"]
#[inline(always)]
#[must_use]
pub fn opm(&mut self) -> OPM_W<TIM7_CR1_SPEC, 3> {
OPM_W::new(self)
}
#[doc = "Bit 7 - Auto-reload preload enable"]
#[inline(always)]
#[must_use]
pub fn arpe(&mut self) -> ARPE_W<TIM7_CR1_SPEC, 7> {
ARPE_W::new(self)
}
#[doc = "Bit 11 - UIF status bit remapping"]
#[inline(always)]
#[must_use]
pub fn uifremap(&mut self) -> UIFREMAP_W<TIM7_CR1_SPEC, 11> {
UIFREMAP_W::new(self)
}
#[doc = "Bit 12 - Dithering enable Note: The DITHEN bit can only be modified when CEN bit is reset."]
#[inline(always)]
#[must_use]
pub fn dithen(&mut self) -> DITHEN_W<TIM7_CR1_SPEC, 12> {
DITHEN_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u16) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "TIM7 control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim7_cr1::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 [`tim7_cr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TIM7_CR1_SPEC;
impl crate::RegisterSpec for TIM7_CR1_SPEC {
type Ux = u16;
}
#[doc = "`read()` method returns [`tim7_cr1::R`](R) reader structure"]
impl crate::Readable for TIM7_CR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`tim7_cr1::W`](W) writer structure"]
impl crate::Writable for TIM7_CR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets TIM7_CR1 to value 0"]
impl crate::Resettable for TIM7_CR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Code Expressions.
use std::fmt;
use std::rc::Rc;
// TODO: Use real things instead of scaffolding.
//use crate::ir::immediates::{Imm64, Offset32};
//use crate::ir::{ExternalName, Type};
//use crate::isa::TargetIsa;
#[derive(Clone, Debug, Hash, Eq, PartialEq, Copy)]
pub enum Type {
I32,
I64,
}
pub type Offset32 = i32;
pub type Imm64 = i64;
pub type ExternalName = String;
pub trait TargetIsa {
fn pointer_type(&self) -> Type;
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::I32 => write!(f, "i32"),
Self::I64 => write!(f, "i64"),
}
}
}
/// A "code expression", which is an expression which can be expanded into code
/// or interpreted directly.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub enum CodeExpr {
/// Value is the address of the VM context struct.
VMContext,
/// The value of a symbol, which is a name which will be resolved to an
/// actual value later (eg. by linking).
///
/// For now, symbolic values always have pointer type, and represent
/// addresses, however in the future they could be used to represent other
/// things as well.
Symbol {
/// The symbolic name.
name: ExternalName,
/// Offset from the symbol. This can be used instead of IAddImm to represent folding an
/// offset into a symbol.
offset: Imm64,
/// Will this symbol be defined nearby, such that it will always be a certain distance
/// away, after linking? If so, references to it can avoid going through a GOT. Note that
/// symbols meant to be preemptible cannot be colocated.
colocated: bool,
},
/// Add an immediate constant to a value.
IAddImm {
/// The base value.
base: Rc<CodeExpr>,
/// Offset to be added to the value.
offset: Imm64,
/// The type of the iadd.
result_type: Type,
},
/// Load a value from memory.
///
/// The `base` expression is the address of a memory location to load from.
/// The memory must be accessible, and naturally aligned to hold a value of
/// the type.
Load {
/// The base pointer.
base: Rc<CodeExpr>,
/// Offset added to the base pointer before doing the load.
offset: Offset32,
/// Type of the loaded value.
result_type: Type,
/// Specifies whether the memory that this refers to is readonly, allowing for the
/// elimination of redundant loads.
readonly: bool,
},
/// A function call.
Call {
/// The expression to call. May be a `Symbol` for a direct call, or
/// other kinds of expression for indirect calls.
callee: Rc<CodeExpr>,
/// Arguments to pass to the call.
args: Vec<CodeExpr>,
/// The result type of the call.
result_type: Type,
},
/// An "if-then-else".
IfElse {
/// The boolean condition.
condition: Rc<CodeExpr>,
/// Expression to execute if `condition` is true.
then: Rc<CodeExpr>,
/// Expression to execute if `condition` is false.
else_: Rc<CodeExpr>,
},
}
impl CodeExpr {
/// Assume that `self` is an `CodeExpr::Symbol` and return its name.
pub fn symbol_name(&self) -> &ExternalName {
match *self {
Self::Symbol { ref name, .. } => name,
_ => panic!("only symbols have names"),
}
}
/// Return the type of this expression.
pub fn result_type(&self, isa: &dyn TargetIsa) -> Type {
match *self {
Self::VMContext { .. } | Self::Symbol { .. } => isa.pointer_type(),
Self::IAddImm { result_type, .. }
| Self::Load { result_type, .. }
| Self::Call { result_type, .. } => result_type,
Self::IfElse {
condition: _,
ref then,
ref else_,
} => {
let result = then.result_type(isa);
assert_eq!(result, else_.result_type(isa));
result
}
}
}
}
impl fmt::Display for CodeExpr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::VMContext => write!(f, "vmctx"),
Self::Symbol {
ref name,
offset,
colocated,
} => {
write!(
f,
"symbol {}{}",
if colocated { "colocated " } else { "" },
name
)?;
let offset_val: i64 = offset.into();
if offset_val > 0 {
write!(f, "+")?;
}
if offset_val != 0 {
write!(f, "{}", offset)?;
}
Ok(())
}
Self::IAddImm {
result_type,
ref base,
offset,
} => write!(f, "iadd_imm.{}({}, {})", result_type, base, offset),
Self::Load {
ref base,
offset,
result_type,
readonly,
} => write!(
f,
"load.{} notrap aligned {}({}+{})",
result_type,
if readonly { "readonly " } else { "" },
base,
offset
),
Self::Call {
ref callee,
ref args,
result_type,
} => write!(
f,
"call.{}({}, {})",
result_type,
callee,
args.iter()
.map(|arg| format!("{}", arg))
.collect::<Vec<_>>()
.join(", ")
),
Self::IfElse {
ref condition,
ref then,
ref else_,
} => write!(f, "if {} {{ {} }} else {{ {} }}", condition, then, else_),
}
}
}
|
extern crate hostname;
extern crate bufstream;
use std::error::Error;
use std::net::TcpStream;
use std::io::{self, Write, BufRead, stderr};
use bufstream::BufStream;
use std::time::{SystemTime, UNIX_EPOCH};
use std::fs::OpenOptions;
enum SmtpState {
INIT,
READY,
MAIL,
RCPT,
DATA,
}
#[derive(Debug, PartialEq)]
struct ReceiveMail {
pub mail_from: String,
pub rcpt_to: String,
pub data: String,
}
impl ReceiveMail {
pub fn init() -> ReceiveMail {
ReceiveMail {
mail_from: String::new(),
rcpt_to: String::new(),
data: String::new(),
}
}
}
#[derive(Debug, PartialEq)]
struct SmtpReply {
pub code: u16,
pub message: String,
}
pub fn main() {
println!("hello, here is receiver.");
}
pub fn handler(stream: &mut BufStream<TcpStream>) -> io::Result<()> {
stream.write(b"220 hostname ESMTP smtpd-rs\n")?;
stream.flush()?;
let mut state = SmtpState::INIT;
let mut _mail = ReceiveMail::init();
loop {
state = match &state {
SmtpState::INIT => {
let mut line = String::new();
if let Err(err) = stream.read_line(&mut line) {
print_error(&err);
panic!("error: {}", err);
}
println!("line {:?}", line.trim());
let _cmd;
match line.trim().split_whitespace().nth(0) {
Some(s) => _cmd = s,
None => {
stream.write(format!("555 5.5.2 Syntax error. - smtpd-rs\n").as_bytes())?;
stream.flush()?;
continue;
}
};
println!("command {}", _cmd);
match dispatch(&line.trim().to_string()) {
Some(_reply) => {
let _code = &_reply.code;
let _message: &str = &_reply.message;
stream.write(&_message.as_bytes())?;
stream.flush()?;
}
None => {
/* abort. */
stream.write(b"disconnect.")?;
stream.flush()?;
panic!();
}
}
match &_cmd {
&"HELO" => SmtpState::READY,
&"EHLO" => SmtpState::READY,
&"RSET" => SmtpState::READY,
&"QUIT" => {
/* abort. */
stream.write(b"disconnect.\n")?;
stream.flush()?;
panic!();
}
_ => SmtpState::INIT,
}
}
SmtpState::READY => {
let mut line = String::new();
if let Err(err) = stream.read_line(&mut line) {
print_error(&err);
panic!("error: {}", err);
}
println!("line {:?}", line.trim());
let _cmd;
match line.trim().split_whitespace().nth(0) {
Some(s) => _cmd = s,
None => {
stream.write(b"555 5.5.2 Syntax error. - smtpd-rs")?;
stream.flush()?;
continue;
}
};
println!("command {}", _cmd);
match dispatch(&line.trim().to_string()) {
Some(_reply) => {
let _code = &_reply.code;
let _message: &str = &_reply.message;
stream.write(&_message.as_bytes())?;
stream.flush()?;
_mail.mail_from = match line.trim().split_whitespace().nth(1) {
Some(s) => {
let _param = String::from(s);
let (_from, _addr) = _param.split_at(5); // "FROM:" is 5
println!("_from {}, _addr {}", _from, _addr);
if _from.to_uppercase().to_string() != "FROM:" {
String::new()
} else {
_addr.to_string()
}
}
None => String::new(),
};
}
None => {
/* abort. */
stream.write(b"disconnect.")?;
stream.flush()?;
panic!();
}
}
match &_cmd {
&"MAIL" => SmtpState::MAIL,
&"RSET" => SmtpState::READY,
&"QUIT" => {
/* abort. */
stream.write(b"disconnect.\n")?;
stream.flush()?;
panic!();
}
_ => SmtpState::READY,
}
}
SmtpState::MAIL => {
let mut line = String::new();
if let Err(err) = stream.read_line(&mut line) {
print_error(&err);
panic!("error: {}", err);
}
println!("line {:?}", line.trim());
let _cmd;
match line.trim().split_whitespace().nth(0) {
Some(s) => _cmd = s,
None => {
stream.write(b"555 5.5.2 Syntax error. - smtpd-rs")?;
stream.flush()?;
continue;
}
};
println!("command {}", _cmd);
match dispatch(&line.trim().to_string()) {
Some(_reply) => {
let _code = &_reply.code;
let _message: &str = &_reply.message;
stream.write(&_message.as_bytes())?;
stream.flush()?;
_mail.rcpt_to = match line.trim().split_whitespace().nth(1) {
Some(s) => {
let _param = String::from(s);
let (_to, _addr) = _param.split_at(3); // "TO:" is 5
println!("_to {}, _addr {}", _to, _addr);
if _to.to_uppercase().to_string() != "TO:" {
String::new()
} else {
_addr.to_string()
}
}
None => String::new(),
};
}
None => {
/* abort. */
stream.write(b"disconnect.")?;
stream.flush()?;
panic!();
}
}
match &_cmd {
&"RCPT" => SmtpState::RCPT,
&"RSET" => SmtpState::READY,
&"QUIT" => {
/* abort. */
stream.write(b"disconnect.\n")?;
stream.flush()?;
panic!();
}
_ => SmtpState::MAIL,
}
}
SmtpState::RCPT => {
let mut line = String::new();
if let Err(err) = stream.read_line(&mut line) {
print_error(&err);
panic!("error: {}", err);
}
println!("line {:?}", line.trim());
let _cmd;
match line.trim().split_whitespace().nth(0) {
Some(s) => _cmd = s,
None => {
stream.write(b"555 5.5.2 Syntax error. - smtpd-rs")?;
stream.flush()?;
continue;
}
};
println!("command {}", _cmd);
match dispatch(&line.trim().to_string()) {
Some(_reply) => {
let _code = &_reply.code;
let _message: &str = &_reply.message;
stream.write(&_message.as_bytes())?;
stream.flush()?;
}
None => {
/* abort. */
stream.write(b"disconnect.\n")?;
stream.flush()?;
panic!();
}
}
match &_cmd {
&"DATA" => SmtpState::DATA,
&"RSET" => SmtpState::READY,
&"QUIT" => {
/* abort. */
stream.write(b"disconnect.\n")?;
stream.flush()?;
panic!();
}
_ => SmtpState::RCPT,
}
}
SmtpState::DATA => {
let mut _data = Vec::<String>::new();
loop {
let mut _l = String::new();
if let Err(e) = stream.read_line(&mut _l) {
print_error(&e);
continue;
}
println!("line {:?}", _l.trim());
if _l.trim().to_string() == "." { break; }
if _l.trim().to_string() == ".." {
_data.push(".".to_string());
continue;
}
_data.push(_l);
}
_mail.data = _data.concat();
if _mail.mail_from.is_empty() {
println!("mail from is empty.");
stream.write(format!("451 Reequested action aborted. FROM address is empty.\n").as_bytes())?;
stream.flush()?;
} else if _mail.rcpt_to.is_empty() {
println!("rcpt to is empty.");
stream.write(format!("451 Reequested action aborted.RCPT address is empty.\n").as_bytes())?;
stream.flush()?;
} else if _mail.data.is_empty() {
println!("data is empty.");
stream.write(format!("451 Reequested action aborted. DATA context is empty.\n").as_bytes())?;
stream.flush()?;
} else {
println!("write mail. {:?}", _mail);
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH).unwrap();
let _filename = format!("tests/Maildir/new/mail.{:?}", since_the_epoch);
println!("filename {}", _filename);
{
let mut _file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(_filename).expect("file create");
_file.write_fmt(format_args!("Return-Path: {}\n", &_mail.mail_from)).unwrap();
_file.write_fmt(format_args!("Delivered-To: {}\n", &_mail.rcpt_to)).unwrap();
_file.write_all(&_mail.data.as_bytes()).unwrap();
}
stream.write(format!("250 OK\n").as_bytes())?;
stream.flush()?;
}
SmtpState::READY
}
}
}
}
fn dispatch(command: &String) -> Option<SmtpReply> {
let mut command_split = command.trim().split_whitespace();
let _cmd = command_split.next();
/* minimum implementation (see RFC5321 4.5.1) */
match _cmd {
Some("EHLO") => {
let param1 = command_split.next();
println!("param1 {:?}", param1);
let reply;
match param1 {
None => {
reply = SmtpReply {
code: 555,
message: format!("5.5.2 Syntax error. - smtpd-rs\n"),
}
}
Some(param1) => {
if command_split.next() != None {
reply = SmtpReply {
code: 555,
message: format!("5.5.2 Syntax error. - smtpd-rs\n"),
};
} else {
reply = SmtpReply {
code: 250,
message: format!("ok at your service {:?}\n", param1),
};
}
}
}
Some(reply)
}
Some("HELO") => {
let param1 = command_split.next();
println!("param1 {:?}", param1);
let reply;
match param1 {
None => {
reply = SmtpReply {
code: 555,
message: format!("5.5.2 Syntax error. - smtpd-rs\n"),
}
}
Some(param1) => {
if command_split.next() != None {
reply = SmtpReply {
code: 555,
message: format!("5.5.2 Syntax error. - smtpd-rs\n"),
};
} else {
reply = SmtpReply {
code: 250,
message: format!("ok at your service {:?}\n", param1),
};
}
}
}
Some(reply)
}
Some("MAIL") => {
let from_address = command_split.next();
println!("{:?}", from_address);
let reply = SmtpReply {
code: 250,
message: format!("2.1.0 OK - smtpd-rs\n"),
};
Some(reply)
}
Some("RCPT") => {
let rcpt_address = command_split.next();
println!("{:?}", rcpt_address);
let reply = SmtpReply {
code: 250,
message: format!("2.1.0 OK - smtpd-rs\n"),
};
Some(reply)
}
Some("DATA") => {
let reply = SmtpReply {
code: 354,
message: format!("Start mail input; end with <CRLF>.<CRLF>\n"),
};
Some(reply)
}
Some("RSET") => {
let reply = SmtpReply {
code: 250,
message: format!("2.1.0 OK - smtpd-rs\n"),
};
Some(reply)
}
Some("NOOP") => {
let reply = SmtpReply {
code: 250,
message: format!("2.1.0 OK - smtpd-rs\n"),
};
Some(reply)
}
Some("QUIT") => {
let reply = SmtpReply {
code: 221,
message: format!("Closing connection. Good bye.\n"),
};
Some(reply)
}
Some("VRFY") => {
let reply = SmtpReply {
code: 250,
message: format!("2.1.0 OK - smtpd-rs\n"),
};
Some(reply)
}
_ => {
let reply = SmtpReply {
code: 555,
message: format!(r"5.5.2 Syntax error. - smtpd-rs\n"),
};
Some(reply)
}
}
}
fn print_error(mut err: &Error) {
let _ = writeln!(stderr(), "error: {}", err);
while let Some(cause) = err.cause() {
let _ = writeln!(stderr(), "caused by: {}", cause);
err = cause;
}
}
#[test]
fn test_handler() {}
#[test]
fn test_dispatch() {
assert_eq!(dispatch(&"EHLO localhost".to_string()), Some(SmtpReply { code: 250, message: "ok at your service \"localhost\"\n".parse().unwrap() }));
assert_eq!(dispatch(&"HELO localhost".to_string()), Some(SmtpReply { code: 250, message: "ok at your service \"localhost\"\n".parse().unwrap() }));
assert_eq!(dispatch(&"MAIL FROM:postmaster@example.com".to_string()), Some(SmtpReply { code: 250, message: "2.1.0 OK - smtpd-rs\n".parse().unwrap() }));
assert_eq!(dispatch(&"RCPT TO:postmaster@example.com".to_string()), Some(SmtpReply { code: 250, message: "2.1.0 OK - smtpd-rs\n".parse().unwrap() }));
assert_eq!(dispatch(&"DATA".to_string()), Some(SmtpReply { code: 354, message: "Start mail input; end with <CRLF>.<CRLF>\n".parse().unwrap() }));
assert_eq!(dispatch(&"RSET".to_string()), Some(SmtpReply { code: 250, message: "2.1.0 OK - smtpd-rs\n".parse().unwrap() }));
assert_eq!(dispatch(&"NOOP".to_string()), Some(SmtpReply { code: 250, message: "2.1.0 OK - smtpd-rs\n".parse().unwrap() }));
assert_eq!(dispatch(&"QUIT".to_string()), Some(SmtpReply { code: 221, message: "Closing connection. Good bye.\n".to_string() }));
assert_eq!(dispatch(&"VRFY".to_string()), Some(SmtpReply { code: 250, message: "2.1.0 OK - smtpd-rs\n".parse().unwrap() }));
assert_eq!(dispatch(&"blahblahblah".to_string()), Some(SmtpReply { code: 555, message: r"5.5.2 Syntax error. - smtpd-rs\n".to_string() }));
}
|
use std::fs::File;
use std::io::Write;
fn main() {
// 1バイトずつ書き出す
let path = "sample.txt" ;
let mut file = File::create( path )
.expect("file not found.");
let s = "hello rust world.\n";
for it in s.as_bytes() {
file.write(&[*it])
.expect("cannot write.");
let ch = *it ; // 実体を取得
let ary = [ch]; // 配列に直す
file.write(&ary) // 参照を渡す
.expect("cannot write.");
}
}
fn _main() {
// write!マクロで書き出す
let path = "sample.txt" ;
let mut file = File::create( path )
.expect("file not found.");
write!( file, "hello rust world.\n")
.expect("cannot write.");
// write メソッドで書き出す
// [u8] のバイト配列なので、b で修飾する
let path = "sample2.txt" ;
let mut file = File::create( path )
.expect("file not found.");
file.write( b"hello rust world.\n")
.expect("cannot write.");
// &str 型を [u8] に直して渡しても良い
let path = "sample3.txt" ;
let mut file = File::create( path )
.expect("file not found.");
let s = "hello rust world.\n";
file.write(s.as_bytes())
.expect("cannot write.");
// 1バイトずつ書き出す
let path = "sample4.txt" ;
let mut file = File::create( path )
.expect("file not found.");
let s = "hello rust world.\n";
for i in s.as_bytes() {
file.write(&[*i])
.expect("cannot write.");
}
// std::io::Result を利用する
println!("call sub function.");
sub( "sample5.txt" ) ;
}
// 戻り値に std::io::Result を利用すると、
// .except 部分を ? を使って短く書ける
fn sub( path: &str ) -> std::io::Result<()> {
let mut file = File::create( path )? ;
file.write( b"hello rust world.\n")? ;
Ok(())
}
|
pub use rusqlite_types::*;
|
use itertools::Itertools;
use std::collections::HashMap;
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum Tile {
Empty,
Wall,
Block,
Paddle,
Ball,
}
impl Tile {
fn new(tile_id: i64) -> Tile {
match tile_id {
0 => Tile::Empty,
1 => Tile::Wall,
2 => Tile::Block,
3 => Tile::Paddle,
4 => Tile::Ball,
_ => panic!("bad tile"),
}
}
fn draw(self) -> char {
match self {
Tile::Empty => ' ',
Tile::Wall => '#',
Tile::Block => '.',
Tile::Paddle => '_',
Tile::Ball => 'o',
}
}
}
pub struct Game {
computer: super::intcode::Computer,
display: HashMap<(i64, i64), Tile>,
score: i64,
}
impl Game {
pub fn new(input: &str) -> Game {
let mut computer = super::intcode::Computer::load(input);
let display: HashMap<(i64, i64), Tile> = HashMap::new();
computer.run();
Game {
computer: computer,
display: display,
score: 0,
}
}
pub fn play(&mut self) {
loop {
self.computer.run_with_input(0);
self.read_output();
self.draw();
}
}
fn read_output(&mut self) {
for (x, y, tile_id) in self.computer.outputs.iter().tuples() {
if (*x, *y) == (-1, 0) {
self.score = *tile_id
} else {
self.display.insert((*x, *y), Tile::new(*tile_id));
}
}
self.computer.outputs = vec![];
}
pub fn draw(&self) {
println!("Score: {}", self.score);
println!("Blocks: {}", self.display.iter().filter(|(_,tile)| **tile == Tile::Block).count());
for y in 0..20 {
for x in 0..44 {
print!("{}", self.display[&(x, y)].draw())
}
println!();
}
}
}
|
use structopt::StructOpt;
use std::path::PathBuf;
#[derive(Debug, StructOpt)]
#[structopt(name = "Pyschedelic image generator", about = "Generate random psychedelic images")]
pub struct Opt {
#[structopt(short = "s", long = "set-wallpaper")]
pub wallpaper: bool,
#[structopt(short = "w", long = "width", default_value = "1920")]
pub width: u32,
#[structopt(short = "h", long = "height", default_value = "1080")]
pub height: u32,
#[structopt(short = "n", long = "num", default_value = "10")]
pub num: usize,
#[structopt(parse(from_os_str), short = "p", long = "path", default_value = "images")]
pub path: PathBuf
} |
fn main() {
let some_number = Some(5);
let some_string = Some("a string");
// Using none requires telling the compiler the type
let absent_number: Option<i32> = None;
let x: i8 = 5;
let y: Option<i8> = Some(5);
// Can't add an i8 to an Option<i8>
// the trait `std::ops::Add<std::option::Option<i8>>` is not implemented for `i8`
// you have to convert Option<T> to T
// let sum = x + y;
}
|
#![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 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 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 Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")]
pub is_data_action: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplayValue>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplayValue {
#[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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PipelineTemplateDefinitionListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PipelineTemplateDefinition>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PipelineTemplateDefinition {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inputs: Vec<InputDescriptor>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InputDescriptor {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "type")]
pub type_: input_descriptor::Type,
#[serde(rename = "possibleValues", default, skip_serializing_if = "Vec::is_empty")]
pub possible_values: Vec<InputValue>,
}
pub mod input_descriptor {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
String,
SecureString,
Int,
Bool,
Authorization,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InputValue {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(rename = "displayValue", default, skip_serializing_if = "Option::is_none")]
pub display_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Pipeline {
#[serde(flatten)]
pub resource: Resource,
pub properties: PipelineProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PipelineProperties {
#[serde(rename = "pipelineId", default, skip_serializing_if = "Option::is_none")]
pub pipeline_id: Option<i64>,
pub organization: OrganizationReference,
pub project: ProjectReference,
#[serde(rename = "bootstrapConfiguration")]
pub bootstrap_configuration: BootstrapConfiguration,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OrganizationReference {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProjectReference {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BootstrapConfiguration {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repository: Option<CodeRepository>,
pub template: PipelineTemplate,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CodeRepository {
#[serde(rename = "repositoryType")]
pub repository_type: code_repository::RepositoryType,
pub id: String,
#[serde(rename = "defaultBranch")]
pub default_branch: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub authorization: Option<Authorization>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<serde_json::Value>,
}
pub mod code_repository {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RepositoryType {
#[serde(rename = "gitHub")]
GitHub,
#[serde(rename = "vstsGit")]
VstsGit,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Authorization {
#[serde(rename = "authorizationType")]
pub authorization_type: authorization::AuthorizationType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
}
pub mod authorization {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AuthorizationType {
#[serde(rename = "personalAccessToken")]
PersonalAccessToken,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PipelineTemplate {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: 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 tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PipelineUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PipelineListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Pipeline>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
|
use std::str;
use std::io::BufRead;
use std::collections::HashMap;
use quick_xml::{XmlReader, Element, Event};
use error::Error;
use extension::{Extension, ExtensionMap};
pub trait FromXml: Sized {
fn from_xml<R: ::std::io::BufRead>(mut reader: XmlReader<R>,
element: Element)
-> Result<(Self, XmlReader<R>), Error>;
}
macro_rules! try_reader {
($e:expr, $reader:ident) => (match $e {
Ok(v) => v,
Err(err) => return (Err(err.into()), $reader),
})
}
macro_rules! element_text {
($reader:ident) => ({
let text = ::fromxml::element_text($reader);
$reader = text.1;
try!(text.0)
})
}
macro_rules! skip_element {
($reader:ident) => ({
let result = ::fromxml::skip_element($reader);
$reader = result.1;
try!(result.0)
})
}
macro_rules! parse_extension {
($reader:ident, $element:ident, $ns:ident, $name:ident, $extensions:expr) => ({
let result = ::fromxml::parse_extension($reader, &$element, $ns, $name, &mut $extensions);
$reader = result.1;
try!(result.0)
})
}
pub fn element_text<R: BufRead>(mut reader: XmlReader<R>)
-> (Result<Option<String>, Error>, XmlReader<R>) {
let mut content: Option<String> = None;
while let Some(e) = reader.next() {
match e {
Ok(Event::Start(_)) => {
let result = skip_element(reader);
reader = result.1;
try_reader!(result.0, reader);
}
Ok(Event::End(_)) => {
break;
}
Ok(Event::CData(element)) => {
let text = element.content();
content = Some(try_reader!(str::from_utf8(text), reader).to_string());
}
Ok(Event::Text(element)) => {
let text = try_reader!(element.unescaped_content(), reader);
content = Some(try_reader!(String::from_utf8(text.into_owned()), reader));
}
Err(err) => return (Err(err.into()), reader),
_ => {}
}
}
(Ok(content), reader)
}
pub fn skip_element<R: BufRead>(mut reader: XmlReader<R>) -> (Result<(), Error>, XmlReader<R>) {
while let Some(e) = reader.next() {
match e {
Ok(Event::Start(_)) => {
let result = skip_element(reader);
reader = result.1;
try_reader!(result.0, reader);
}
Ok(Event::End(_)) => {
return (Ok(()), reader);
}
Err(err) => return (Err(err.into()), reader),
_ => {}
}
}
(Err(Error::EOF), reader)
}
pub fn extension_name(element: &Element) -> Option<(&[u8], &[u8])> {
let split = element.name().splitn(2, |b| *b == b':').collect::<Vec<_>>();
if split.len() == 2 {
let ns = unsafe { split.get_unchecked(0) };
if ns != b"" && ns != b"rss" && ns != b"rdf" {
return Some((ns, unsafe { split.get_unchecked(1) }));
}
}
None
}
pub fn parse_extension<R: BufRead>(mut reader: XmlReader<R>,
element: &Element,
ns: &[u8],
name: &[u8],
extensions: &mut ExtensionMap)
-> (Result<(), Error>, XmlReader<R>) {
let ns = try_reader!(str::from_utf8(ns), reader);
let name = try_reader!(str::from_utf8(name), reader);
let ext = parse_extension_element(reader, element);
reader = ext.1;
let ext = try_reader!(ext.0, reader);
if !extensions.contains_key(ns) {
extensions.insert(ns.to_string(), HashMap::new());
}
let map = match extensions.get_mut(ns) {
Some(map) => map,
None => unreachable!(),
};
let ext = {
if let Some(list) = map.get_mut(name) {
list.push(ext);
None
} else {
Some(ext)
}
};
if let Some(ext) = ext {
map.insert(name.to_string(), vec![ext]);
}
(Ok(()), reader)
}
fn parse_extension_element<R: BufRead>(mut reader: XmlReader<R>,
element: &Element)
-> (Result<Extension, Error>, XmlReader<R>) {
let mut children = HashMap::<String, Vec<Extension>>::new();
let mut attrs = HashMap::<String, String>::new();
let mut content = None;
for attr in element.attributes().with_checks(false).unescaped() {
if let Ok(attr) = attr {
let key = try_reader!(str::from_utf8(attr.0), reader);
let value = try_reader!(str::from_utf8(&attr.1), reader);
attrs.insert(key.to_string(), value.to_string());
}
}
while let Some(e) = reader.next() {
match e {
Ok(Event::Start(element)) => {
let child = parse_extension_element(reader, &element);
reader = child.1;
let ext = try_reader!(child.0, reader);
let name = {
let split = element.name().splitn(2, |b| *b == b':').collect::<Vec<_>>();
if split.len() == 2 {
try_reader!(str::from_utf8(unsafe { split.get_unchecked(1) }), reader)
} else {
try_reader!(str::from_utf8(unsafe { split.get_unchecked(0) }), reader)
}
};
let ext = {
if let Some(list) = children.get_mut(name) {
list.push(ext);
None
} else {
Some(ext)
}
};
if let Some(ext) = ext {
children.insert(name.to_string(), vec![ext]);
}
}
Ok(Event::End(element)) => {
return (Ok(Extension {
name: try_reader!(str::from_utf8(element.name()), reader).to_string(),
value: content,
attrs: attrs,
children: children,
}), reader)
}
Ok(Event::CData(element)) => {
let text = element.content();
content = Some(try_reader!(str::from_utf8(text), reader).to_string());
}
Ok(Event::Text(element)) => {
let text = try_reader!(element.unescaped_content(), reader);
content = Some(try_reader!(String::from_utf8(text.into_owned()), reader));
}
Err(err) => return (Err(err.into()), reader),
_ => {}
}
}
(Err(Error::EOF), reader)
}
|
use std::{thread, time};
pub use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::{Cursor, Seek, SeekFrom};
use std::collections::HashMap;
pub use spacepacket::SpacePacket;
extern crate sys_info;
use serde_json;
use Config;
pub enum HkCmds {
ShutdownCommand,
SleepCommand{interval: u16},
RawCommand{raw: Vec<u8>},
}
fn send_hk_ps_list(tlm_send: &std::sync::mpsc::Sender<Vec<u8>>, &sequence_number: &u16, &apid: &u16) {
let mut map = HashMap::new();
map.insert("query", "{ps {pid,cmd}}");
let client = reqwest::blocking::Client::new();
let ps_list = match client.post("http://127.0.0.1:8030/").json(&map).send() {
Ok(n) => match n.text() {
Ok(n) => n,
Err(_e) => {
let ps_info = serde_json::json!( { "data": { "processInfo": { "pid": "unknown", "cmd": "unknown" } } });
let string_version = ps_info.to_string().to_owned();
string_version
}
},
Err(_e) => serde_json::json!( { "data": { "processInfo": { "pid": "unknown", "cmd": "unknown" } } }).to_string().to_owned(),
};
// eprintln!("Housekeeping task results:");
eprintln!("{:#?}", ps_list);
let payload = ps_list.as_bytes();
let sp : SpacePacket = SpacePacket{ apid: apid,
sec_hdr_flag: 0,
version: 0,
packet_type: 0,
seq_flags: 3,
seq_num: sequence_number,
data_len: (payload.len() as u16) -1,
payload: payload.to_vec() };
let telemetry_data = sp.to_vec();
let _result = tlm_send.send( telemetry_data );
}
fn send_hk_data( tlm_send: &std::sync::mpsc::Sender<Vec<u8>>, &sequence_number: &u16, &apid: &u16) {
// send_hk_ps_list( tlm_send, &sequence_number, &apid);
let mut map = HashMap::new();
map.insert("query", "{memInfo{total,available,free}}");
let client = reqwest::blocking::Client::new();
let memory_stats = match client.post("http://127.0.0.1:8030/").json(&map).send() {
Ok(n) => match n.text() {
Ok(n) => n,
Err(_e) => {
let json_mem_info = serde_json::json!( { "data": { "memInfo": { "total": "unknown", "free": "unknown" } } });
let string_version = json_mem_info.to_string().to_owned();
string_version
}
},
Err(_e) => {
let json_mem_info = serde_json::json!( { "data": { "memInfo": { "total": "unknown", "free": "unknown" } } });
let string_version = json_mem_info.to_string().to_owned();
string_version
},
};
eprintln!("{:#?}", memory_stats);
let mut payload = memory_stats;
let disk_info = sys_info::disk_info();
let (disk_total, disk_free) = match disk_info {
Ok(n) => {
eprintln!("Disk total: {}, Dis free: {}", n.total, n.free);
(n.total, n.free)
// payload.write_u64::<BigEndian>(n.total).unwrap();
// payload.write_u64::<BigEndian>(n.free).unwrap();
},
Err(_e)=> {
eprintln!("Unable to get disk info");
( 0, 0)
// payload.write_u64::<BigEndian>(0).unwrap();
// payload.write_u64::<BigEndian>(0).unwrap();
},
};
let json_disk_info = serde_json::json!( { "data": { "diskInfo": { "total": disk_total, "free": disk_free } } });
let string_version = json_disk_info.to_string();
payload.push_str(&string_version);
eprintln!("{:#?}", payload);
let payload = payload.as_bytes();
// let payload = string_version.as_bytes();
// let mem_info = sys_info::mem_info();
// let (mem_total, mem_free) = match mem_info {
// Ok(n) => {
// eprintln!("Mem total: {}, Mem free: {}", n.total, n.free);
// payload.write_u64::<BigEndian>(n.total).unwrap();
// payload.write_u64::<BigEndian>(n.free).unwrap();
// (n.total, n.free)
// },
// Err(_e)=> {
// eprintln!("Unable to get Mem info");
// payload.write_u64::<BigEndian>(0).unwrap();
// payload.write_u64::<BigEndian>(0).unwrap();
// (0, 0)
// },
// };
let sp : SpacePacket = SpacePacket{ apid: apid,
sec_hdr_flag: 0,
version: 0,
packet_type: 0,
seq_flags: 3,
seq_num: sequence_number,
data_len: (payload.len() as u16) -1,
payload: payload.to_vec() };
let telemetry_data = sp.to_vec();
let _result = tlm_send.send( telemetry_data );
}
pub fn do_housekeeping( service_config: Config, tlm_send: std::sync::mpsc::Sender<Vec<u8>>, cmd_rx: std::sync::mpsc::Receiver<HkCmds>, _response_tx: std::sync::mpsc::Sender<Vec<u8>>) {
let sleep_interval = time::Duration::from_millis(service_config.housekeeping.wakeup_interval as u64 *1000);
let mut housekeeping_interval = time::Duration::new(service_config.housekeeping.poll_interval as u64, 0);
let apid = service_config.housekeeping.apid;
let mut now = time::Instant::now();
let mut sequence_number:u16 = 0;
loop {
thread::sleep(sleep_interval);
let result = cmd_rx.try_recv();
match result {
Ok(n) => {
// eprintln!("Housekeeping received a new command");
match n {
HkCmds::SleepCommand{interval} => {
eprintln!("now should sleep for {}", interval);
housekeeping_interval = time::Duration::from_millis( interval as u64);
},
HkCmds::ShutdownCommand => {
return;
}
HkCmds::RawCommand{raw: bytes} => {
let mut rdr = Cursor::new(bytes);
match rdr.seek(SeekFrom::Start(6)) {
Ok(_n) => (),
Err(_e) => { eprintln!("Bad HK command"); continue; },
}
let cmd = rdr.read_u8().unwrap();
eprintln!("new cmd is {}", cmd);
if cmd == 2 {
let delay = rdr.read_u16::<BigEndian>().unwrap();
eprintln!("New delay value is {}", delay);
housekeeping_interval = time::Duration::new( delay as u64, 0);
}
else if cmd == 101 {
send_hk_ps_list( &tlm_send, &sequence_number, &apid);
sequence_number += 1;
}
}
}
},
Err(_e) => (),
};
if now.elapsed() >= housekeeping_interval {
eprintln!("Its time to clean house");
now = time::Instant::now();
send_hk_data( &tlm_send, &sequence_number, &apid);
sequence_number += 1;
}
}
}
|
use crate::object::*;
use crate::value::*;
use crate::vtable::*;
use crate::*;
pub static ARRAY_VTBL: VTable = VTable {
element_size: 8,
instance_size: 0,
parent: None,
lookup_fn: Some(array_lookup),
index_fn: None,
calc_size_fn: Some(determine_array_size),
apply_fn: None,
destroy_fn: None,
set_fn: Some(array_set),
trace_fn: Some(trace_array),
set_index_fn: None,
};
pub fn array_lookup(vm: &VM, this: Ref<Obj>, key: Value) -> WaffleResult {
let this = this.cast::<Array>();
if key == vm.length {
return WaffleResult::okay(Value::new_int(this.len() as _));
} else if key.is_number() {
let idx = key.to_number().trunc() as usize;
if idx < this.len() {
return WaffleResult::okay(this.get_at(idx));
} else {
WaffleResult::okay(Value::undefined())
}
} else {
WaffleResult::okay(Value::undefined())
}
}
pub fn array_set(_: &VM, this: Ref<Obj>, key: Value, value: Value) -> WaffleResult {
if !key.is_number() {
return WaffleResult::okay(Value::new_bool(false));
}
let mut this = this.cast::<Array>();
let idx = key.to_number().trunc() as usize;
if idx < this.len() {
this.set_at(idx, value);
WaffleResult::okay(Value::new_bool(true))
} else {
WaffleResult::okay(Value::new_bool(false))
}
}
pub fn trace_array(arr: Ref<Obj>, trace: &mut dyn FnMut(*const Ref<Obj>)) {
let arr = arr.cast::<Array>();
debug_assert!(arr.vtable as *const VTable == &ARRAY_VTBL as *const _);
for i in 0..arr.len() {
let item = arr.get_at(i);
if item.is_cell() {
trace(item.as_cell_ref());
}
}
}
fn determine_array_size(obj: Ref<Obj>) -> usize {
let handle: Ref<Array> = obj.cast();
let calc = Header::size() as usize
+ std::mem::size_of::<usize>()
+ std::mem::size_of::<usize>()
+ handle.vtable.element_size * handle.len() as usize;
calc
}
pub static STRING_VTBL: VTable = VTable {
element_size: std::mem::size_of::<WaffleString>(),
instance_size: 0,
parent: None,
lookup_fn: None,
index_fn: None,
calc_size_fn: None,
apply_fn: None,
destroy_fn: None,
set_fn: None,
trace_fn: None,
set_index_fn: None,
};
|
use std::{mem, ptr};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use super::avl;
use super::block_ptr::BlockPtr;
use super::dvaddr::DVAddr;
use super::from_bytes::FromBytes;
use super::lzjb;
use super::uberblock::Uberblock;
use super::zfs;
pub const NUM_TYPES: usize = 6;
pub const NUM_TASKQ_TYPES: usize = 4;
pub struct Reader {
pub disk: File,
}
impl Reader {
// TODO: Error handling
pub fn read(&mut self, start: usize, length: usize) -> Vec<u8> {
let mut ret: Vec<u8> = vec![0; length*512];
self.disk.seek(SeekFrom::Start(start as u64 * 512));
self.disk.read(&mut ret);
ret
}
pub fn write(&mut self, block: usize, data: &[u8; 512]) {
self.disk.seek(SeekFrom::Start(block as u64 * 512));
self.disk.write(data);
}
pub fn read_dva(&mut self, dva: &DVAddr) -> Vec<u8> {
self.read(dva.sector() as usize, dva.asize() as usize)
}
pub fn read_block(&mut self, block_ptr: &BlockPtr) -> Result<Vec<u8>, &'static str> {
let data = self.read_dva(&block_ptr.dvas[0]);
match block_ptr.compression() {
2 => {
// compression off
Ok(data)
}
1 | 3 => {
// lzjb compression
let mut decompressed = vec![0; (block_ptr.lsize()*512) as usize];
lzjb::LzjbDecoder::new(&data).read(&mut decompressed);
Ok(decompressed)
}
_ => Err("Error: not enough bytes"),
}
}
/*
pub fn read_type<T: FromBytes>(&mut self, block_ptr: &BlockPtr) -> Result<T, &'static str> {
self.read_block(block_ptr).and_then(|data| T::from_bytes(&data[..]))
}
*/
pub fn read_type_array<T: FromBytes>(&mut self,
block_ptr: &BlockPtr,
offset: usize)
-> Result<T, String> {
self.read_block(block_ptr).map_err(|x| x.to_owned()).and_then(|data| T::from_bytes(&data[offset * mem::size_of::<T>()..]).map_err(|x| x.to_owned()))
}
pub fn uber(&mut self) -> Result<Uberblock, &'static str> {
let mut newest_uberblock: Option<Uberblock> = None;
for i in 0..128 {
if let Ok(uberblock) = Uberblock::from_bytes(&self.read(256 + i * 2, 2)) {
let newest = match newest_uberblock {
Some(previous) => {
if uberblock.txg > previous.txg {
// Found a newer uberblock
true
} else {
false
}
}
// No uberblock yet, so first one we find is the newest
None => true,
};
if newest {
newest_uberblock = Some(uberblock);
}
}
}
match newest_uberblock {
Some(uberblock) => Ok(uberblock),
None => Err("Failed to find valid uberblock"),
}
}
}
/// ZIOO priority
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Priority {
/// Non-queued IO
Now,
/// Synchronous read
SyncRead,
/// Synchronous write
SyncWrite,
/// Log write
LogWrite,
/// Cache fills
CacheFill,
/// Deduplication table prefetch
DTP,
/// Free
Free,
/// Asynchronous read
AsyncRead,
/// Asynchronous write
AsyncWrite,
/// Resilver
Resilver,
/// Scrub
Scrub,
}
/// ZIO task
#[derive(Copy, Clone, PartialEq)]
pub enum Type {
/// Nothin'
Null,
/// Read
Read,
/// Write
Write,
/// Free data
Free,
/// Claim data
Claim,
/// IO control (VDev modifications etc.)
IoCtl,
}
enum Stage {
/// RWFCI
Open = 1 << 0,
/// R....
ReadBpInit = 1 << 1,
/// ..F..
FreeBpInit = 1 << 2,
/// RWF..
IssueAsync = 1 << 3,
/// .W...
WriteBpInit = 1 << 4,
/// .W...
ChecksumGenerate = 1 << 5,
/// .W...
NopWrite = 1 << 6,
/// R....
DdtReadStart = 1 << 7,
/// R....
DdtReadDone = 1 << 8,
/// .W...
DdtWrite = 1 << 9,
/// ..F..
DdtFree = 1 << 10,
/// RWFC.
GangAssemble = 1 << 11,
/// RWFC.
GangIssue = 1 << 12,
/// .W...
DvaAllocate = 1 << 13,
/// ..F..
DvaFree = 1 << 14,
/// ...C.
DvaClaim = 1 << 15,
/// RWFCI
Ready = 1 << 16,
/// RW..I
VdevIoStart = 1 << 17,
/// RW..I
VdevIoDone = 1 << 18,
/// RW..I
VdevIoAssess = 1 << 19,
/// R....
ChecksumVerify = 1 << 20,
/// RWFCI
Done = 1 << 21,
}
/// Taskq type
pub enum TaskqType {
/// An "issue"
Issue,
/// An high-priority "issue"
IssueHigh,
/// Interrupt
Interrupt,
/// High-priority interrupt
InterruptHigh,
}
#[derive(Copy, Clone, PartialEq)]
enum PipelineFlow {
Continue = 0x100,
Stop = 0x101,
}
#[derive(Copy, Clone, PartialEq)]
enum Flag {
/// Must be equal for two zios to aggregate
DontAggregate = 1 << 0,
IoRepair = 1 << 1,
SelfHeal = 1 << 2,
Resilver = 1 << 3,
Scrub = 1 << 4,
ScanThread = 1 << 5,
Physical = 1 << 6,
/// Inherited by ddt, gang, or vdev children.
CanFail = 1 << 7,
Speculative = 1 << 8,
ConfigWriter = 1 << 9,
DontRetry = 1 << 10,
DontCache = 1 << 11,
NoData = 1 << 12,
InduceDamage = 1 << 13,
/// Vdev inherited (from children)
IoRetry = 1 << 14,
Probe = 1 << 15,
TryHard = 1 << 16,
Optional = 1 << 17,
/// Non-inherited
DontQueue = 1 << 18,
DontPropagate = 1 << 19,
IoBypass = 1 << 20,
IoRewrite = 1 << 21,
Raw = 1 << 22,
GangChild = 1 << 23,
DdtChild = 1 << 24,
GodFather = 1 << 25,
NopWrite = 1 << 26,
ReExecuted = 1 << 27,
Delegated = 1 << 28,
FastWrite = 1 << 29,
}
#[derive(Copy, Clone, PartialEq)]
enum Child {
Vdev = 0,
Gang,
Ddt,
Logical,
}
#[repr(u8)]
enum WaitType {
Ready = 0,
Done,
}
|
mod connections;
mod connection;
pub use self::connections::*;
pub use self::connection::*;
|
use crate::binds::BindCount;
use crate::binds::{BindsInternal, CollectBinds};
use crate::from::FromClause;
use crate::{filter::Filter, WriteSql};
use extend::ext;
use std::fmt::{self, Write};
#[derive(Debug, Clone)]
pub enum Join<T> {
Known {
kind: JoinKind,
from: FromClause<T>,
filter: Filter,
},
RawWithKind(String),
Raw(String),
}
impl<T> Join<T> {
pub fn raw(sql: &str) -> JoinOn<T> {
JoinOn::Raw(sql.to_string())
}
pub fn cast_to<K>(self) -> Join<K> {
match self {
Join::Known { kind, from, filter } => Join::Known {
kind,
from: from.cast_to::<K>(),
filter,
},
Join::RawWithKind(sql) => Join::RawWithKind(sql),
Join::Raw(sql) => Join::Raw(sql),
}
}
}
impl<T> WriteSql for &Join<T> {
fn write_sql<W: Write>(self, f: &mut W, bind_count: &mut BindCount) -> fmt::Result {
match self {
Join::Known { kind, from, filter } => {
kind.write_sql(f, bind_count)?;
from.write_sql(f, bind_count)?;
write!(f, " ON ")?;
filter.write_sql(f, bind_count)?;
}
Join::RawWithKind(sql) => {
write!(f, "{}", sql)?;
}
Join::Raw(sql) => {
write!(f, "{}", sql)?;
}
}
Ok(())
}
}
impl<T> CollectBinds for Join<T> {
fn collect_binds(&self, binds: &mut BindsInternal) {
match self {
Join::Known {
kind: _,
from,
filter,
} => {
from.collect_binds(binds);
filter.collect_binds(binds);
}
Join::RawWithKind(_) => {}
Join::Raw(_) => {}
}
}
}
impl<T> CollectBinds for Vec<Join<T>> {
fn collect_binds(&self, binds: &mut BindsInternal) {
for join in self {
join.collect_binds(binds)
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum JoinKind {
Default,
Inner,
Outer,
}
impl WriteSql for &JoinKind {
fn write_sql<W: Write>(self, f: &mut W, _: &mut BindCount) -> fmt::Result {
match self {
JoinKind::Default => write!(f, "JOIN ")?,
JoinKind::Inner => write!(f, "INNER JOIN ")?,
JoinKind::Outer => write!(f, "OUTER JOIN ")?,
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub enum JoinOn<T> {
Known { from: FromClause<T>, filter: Filter },
Raw(String),
}
impl<T> JoinOn<T> {
pub fn cast_to<K>(self) -> JoinOn<K> {
match self {
JoinOn::Known { from, filter } => JoinOn::Known {
from: from.cast_to::<K>(),
filter,
},
JoinOn::Raw(sql) => JoinOn::Raw(sql),
}
}
}
pub trait JoinOnDsl<T> {
fn on(self, filter: Filter) -> JoinOn<T>;
}
impl<T, K> JoinOnDsl<K> for T
where
T: Into<FromClause<K>>,
{
fn on(self, filter: Filter) -> JoinOn<K> {
JoinOn::Known {
from: FromClause::from(self.into()),
filter,
}
}
}
#[ext(pub(crate), name = CastVecJoin)]
impl<T> Vec<Join<T>> {
fn cast_to<K>(self) -> Vec<Join<K>> {
self.into_iter().map(|join| join.cast_to::<K>()).collect()
}
}
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use fermium::{error::*, events::*, video::*, *};
use gl46::*;
fn main() {
unsafe {
SDL_Init(SDL_INIT_VIDEO);
// 0 for success, negative for error
assert_eq!(0, SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4));
assert_eq!(0, SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6));
assert_eq!(0, SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE.0 as _));
// make window
let win = SDL_CreateWindow(b"gl46 fermium demo\0".as_ptr().cast(), 50, 50, 800, 600, (SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL).0 as _);
if win.is_null() {
let mut v = Vec::with_capacity(4096);
let mut p = SDL_GetErrorMsg(v.as_mut_ptr(), v.capacity() as _);
while *p != 0 {
print!("{}", *p as u8 as char);
p = p.add(1);
}
println!();
panic!();
}
// make context the window will use
let ctx = SDL_GL_CreateContext(win);
if ctx.0.is_null() {
let mut v = Vec::with_capacity(4096);
let mut p = SDL_GetErrorMsg(v.as_mut_ptr(), v.capacity() as _);
while *p != 0 {
print!("{}", *p as u8 as char);
p = p.add(1);
}
println!();
panic!();
}
//
let gl = GlFns::load_from(&|c_char_ptr| SDL_GL_GetProcAddress(c_char_ptr.cast())).unwrap();
gl.ClearColor(0.2, 0.3, 0.3, 1.0);
let mut event: SDL_Event = core::mem::zeroed();
loop {
if SDL_PollEvent(&mut event) != 0 && event.common.type_ == SDL_QUIT as _ {
break;
} else {
gl.Clear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(win);
}
}
//
SDL_DestroyWindow(win);
SDL_Quit();
}
}
|
use scanlex::ScanError;
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub struct DateError {
details: String,
}
impl fmt::Display for DateError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}",self.details)
}
}
impl Error for DateError {}
pub type DateResult<T> = Result<T,DateError>;
pub fn date_error(msg: &str) -> DateError {
DateError{details: msg.into()}
}
pub fn date_result<T>(msg: &str) -> DateResult<T> {
Err(date_error(msg).into())
}
impl From<ScanError> for DateError {
fn from(err: ScanError) -> DateError {
date_error(&err.to_string())
}
}
/// This trait maps optional values onto `DateResult`
pub trait OrErr<T> {
/// use when the error message is always a simple string
fn or_err(self, msg: &str) -> DateResult<T>;
/// use when the message needs to be constructed
fn or_then_err<C: FnOnce()->String>(self,fun:C) -> DateResult<T>;
}
impl <T>OrErr<T> for Option<T> {
fn or_err(self, msg: &str) -> DateResult<T> {
self.ok_or(date_error(msg))
}
fn or_then_err<C: FnOnce()->String>(self,fun:C) -> DateResult<T> {
self.ok_or_else(|| date_error(&fun()))
}
}
|
//! Representation of the S-expression tree.
#![deny(missing_docs)]
#![deny(unsafe_code)]
use std::str::FromStr;
use std::fmt::{self, Display, Debug, Formatter};
use std::ops::Deref;
/**
* A single values with symbols represented using `String`.
*
* ```rust
* use atoms::StringValue;
*
* let int = StringValue::int(12);
* let float = StringValue::float(13.0);
* let string = StringValue::string("fourteen");
* // Symbols may not always be valid
* let symbol = StringValue::symbol("fifteen").unwrap();
*
* // A list
* let cons = StringValue::cons(
* int,
* StringValue::cons(
* float,
* StringValue::cons(
* string,
* StringValue::final_cons(
* symbol
* )
* )
* )
* );
* ```
*/
pub type StringValue = Value<String>;
/**
* A single value with a variable representation of symbols.
*
* ```rust
* use atoms::Value;
*
* // Represent symbols as `String`
* let int = Value::<String>::int(12);
* let float = Value::<String>::float(13.0);
* let string = Value::<String>::string("fourteen");
* // Symbols may not always be valid
* let symbol = Value::<String>::symbol("fifteen").unwrap();
*
* // A list
* let cons = Value::<String>::cons(
* int,
* Value::<String>::cons(
* float,
* Value::<String>::cons(
* string,
* Value::<String>::cons(
* symbol,
* Value::<String>::nil()
* )
* )
* )
* );
* ```
*/
#[derive(PartialEq, Clone, PartialOrd)]
pub enum Value<Sym> {
/// S-expression in data mode
Data(Box<Value<Sym>>),
/// S-expression in code mode
Code(Box<Value<Sym>>),
/// A quoted UTF-8 string value
Str(String),
/// An unquoted, case-sensitive symbol
Symbol(Sym),
/// An integer value
Int(i64),
/// A floating point value
Float(f64),
/// A Cons cell
Cons(Box<Value<Sym>>, Box<Value<Sym>>),
/// A Nil value
Nil,
}
impl<Sym: FromStr> Value<Sym> {
/**
* Automatically convert value
*
* This automatically creates the most sensible value for the types:
*
* * `i64`
* * `f64`
* * `String`
*
* ```rust
* use atoms::StringValue;
* assert_eq!(StringValue::auto(13), StringValue::int(13));
* assert_eq!(StringValue::auto(3.1415), StringValue::float(3.1415));
* assert_eq!(StringValue::auto("Text"), StringValue::string("Text"));
* ```
*/
pub fn auto<T>(value: T) -> Value<Sym> where T: AutoValue<Sym> {
value.auto()
}
/**
* Create a new symbol from a string.
*
* ```rust
* use atoms::StringValue;
* let symbol = StringValue::symbol("symbol").unwrap();
* assert_eq!(symbol.to_string(), "symbol");
* ```
*
* Depending on the type used to represent the symbol, this may fail to
* produce a symbol and return a `None`. This will be presented as an error
* by the parser.
*/
pub fn symbol(s: &str) -> Option<Value<Sym>> {
let sym = Sym::from_str(s);
match sym {
Ok(sym) => Some(Value::Symbol(sym)),
Err(_) => None,
}
}
/**
* Create a new string
*
* ```rust
* use atoms::StringValue;
* let string = StringValue::string("string");
* assert_eq!(string.to_string(), "\"string\"");
* ```
*/
pub fn string<S: Into<String>>(s: S) -> Value<Sym> {
Value::Str(s.into())
}
/**
* Create a new string
*
* ```rust
* use atoms::StringValue;
* let int = StringValue::int(42);
* assert_eq!(int.to_string(), "42");
* ```
*/
pub fn int<I: Into<i64>>(i: I) -> Value<Sym> {
Value::Int(i.into())
}
/**
* Create a new float
*
* ```rust
* use atoms::StringValue;
* let float = StringValue::float(13.0);
* assert_eq!(float.to_string(), "13.0");
* ```
*/
pub fn float<F: Into<f64>>(f: F) -> Value<Sym> {
Value::Float(f.into())
}
/**
* Shorthand from creating cons-cell lists out of `Vec`s.
*
* ```rust
* use atoms::StringValue;
* let ints = vec![
* StringValue::int(1),
* StringValue::int(2),
* StringValue::int(3),
* StringValue::int(4),
* StringValue::int(5),
* StringValue::int(6)
* ];
* let list = StringValue::list(ints);
* assert_eq!(list.to_string(), "(1 2 3 4 5 6)");
* ```
*/
pub fn list<V: Into<Value<Sym>>>(mut source_vec: Vec<V>) -> Value<Sym> {
// The end of the list is a nil
let mut result = Value::Nil;
while let Some(value) = source_vec.pop() {
result = Value::cons(value.into(), result)
}
result
}
/**
* Shorthand to convert a vec into a cons-cell list with a given map.
*
* ```rust
* use atoms::StringValue;
* let ints = vec![1, 2, 3, 4, 5, 6];
* let list = StringValue::into_list(ints, |c| StringValue::int(*c));
* assert_eq!(list.to_string(), "(1 2 3 4 5 6)");
* ```
*/
pub fn into_list<A, V: Into<Value<Sym>>, F>(source_vec: Vec<A>, map: F) -> Value<Sym>
where F: Fn(&A) -> V {
// Convert all members into values
let converted = source_vec.iter().map(map).collect();
Value::list(converted)
}
/**
* Create a cons cell.
*
* ```rust
* use atoms::StringValue;
* let cons = StringValue::cons(
* StringValue::int(12),
* StringValue::string("13")
* );
* assert_eq!(cons.to_string(), "(12 . \"13\")");
* ```
*/
pub fn cons<V: Into<Value<Sym>>>(left: V, right: V) -> Value<Sym> {
Value::Cons(Box::new(left.into()), Box::new(right.into()))
}
/**
* Create a cons cell with only a left element.
*
* This creates a cons cell with the right element being a nil. This is
* useful it you are manually constructing lists.
*
* ```rust
* use atoms::StringValue;
* let cons = StringValue::final_cons(
* StringValue::int(12),
* );
* assert_eq!(cons.to_string(), "(12)");
* ```
*/
pub fn final_cons<V: Into<Value<Sym>>>(left: V) -> Value<Sym> {
Value::cons(left.into(), Value::Nil)
}
/**
* Create a nil.
*
* ```rust
* use atoms::StringValue;
* assert_eq!(StringValue::nil().to_string(), "()");
* ```
*/
pub fn nil() -> Value<Sym> {
Value::Nil
}
/**
* Check if a value is a nil
*
* ```rust
* use atoms::StringValue;
* assert!(StringValue::nil().is_nil());
* assert!(!StringValue::final_cons(StringValue::nil()).is_nil());
* ```
*/
pub fn is_nil(&self) -> bool {
match *self {
Value::Nil => true,
_ => false,
}
}
/**
* Mark a value as code
*
* When using mixed-mode data, this marks an s-expression as code.
*
* ```rust
* use atoms::StringValue;
* StringValue::code(StringValue::symbol("map").unwrap()).to_string();
* ```
*/
pub fn code<V: Into<Value<Sym>>>(value: V) -> Value<Sym> {
Value::Code(Box::new(value.into()))
}
/**
* Mark a value as data
*
* When using mixed-mode data, this marks an s-expression as data.
*
* ```rust
* use atoms::StringValue;
* assert_eq!(
* StringValue::data(StringValue::symbol("apple").unwrap()).to_string(),
* "'apple"
* )
* ```
*/
pub fn data<V: Into<Value<Sym>>>(value: V) -> Value<Sym> {
Value::Data(Box::new(value.into()))
}
/**
* Check if a value is a cons
*
* ```rust
* use atoms::StringValue;
* assert!(StringValue::cons(
* StringValue::nil(),
* StringValue::nil()
* ).is_cons());
* assert!(!StringValue::nil().is_cons());
* ```
*/
pub fn is_cons(&self) -> bool {
match *self {
Value::Cons(_, _) => true,
_ => false,
}
}
/**
* Check if a value is a valid list.
*
* A value is a list if:
* * it is a `Value::Nil`, or
* * it is a `Value::Cons` with a rightmost element this is a list.
*
* ```rust
* use atoms::StringValue;
*
* // `Nil` is a valid list
* assert!(StringValue::nil().is_list());
*
* // `final_cons` ensures we get a valid list
* assert!(StringValue::cons(
* StringValue::int(12),
* StringValue::final_cons(
* StringValue::float(13.0)
* )
* ).is_list());
*
* // Manually terminated lists are valid
* assert!(StringValue::cons(
* StringValue::int(12),
* StringValue::cons(
* StringValue::float(13.0),
* StringValue::nil()
* )
* ).is_list());
*
* // These are not lists
* assert!(!StringValue::int(12).is_list());
* assert!(!StringValue::float(12.0).is_list());
* assert!(!StringValue::string("12").is_list());
* assert!(!StringValue::symbol("sym").unwrap().is_list());
* assert!(!StringValue::cons(
* StringValue::nil(),
* StringValue::symbol("sym").unwrap()
* ).is_list());
* ```
*/
pub fn is_list(&self) -> bool {
match *self {
Value::Nil => true,
Value::Cons(_, ref right) => right.is_list(),
_ => false,
}
}
/**
* Returns if is a wrapped data value
*
* ```rust
* use atoms::StringValue;
* assert!(
* StringValue::data(StringValue::symbol("apple").unwrap()).is_data()
* );
* assert!(
* !StringValue::code(StringValue::symbol("apple").unwrap()).is_data()
* );
* assert!(
* !StringValue::symbol("apple").unwrap().is_code()
* );
* ```
*/
pub fn is_data(&self) -> bool {
match *self {
Value::Data(_) => true,
_ => false,
}
}
/**
* Returns if is a wrapped code value
*
* ```rust
* use atoms::StringValue;
* assert!(
* StringValue::code(StringValue::symbol("map").unwrap()).is_code()
* );
* assert!(
* !StringValue::data(StringValue::symbol("map").unwrap()).is_code()
* );
* assert!(
* !StringValue::symbol("map").unwrap().is_code()
* );
* ```
*/
pub fn is_code(&self) -> bool {
match *self {
Value::Code(_) => true,
_ => false,
}
}
/**
* Unwrap code and data values.
*
* Code and data values are really only tagging their contents. To get the
* actual value of any `Value`, you can always `unwrap` it. Note that
* `unwrap` only unwraps a single layer, to completey unwrap an entire
* s-expression use `unwrap_all`.
*
* ```rust
* use atoms::StringValue;
* assert_eq!(
* StringValue::code(StringValue::symbol("inner").unwrap()).unwrap(),
* StringValue::symbol("inner").unwrap()
* );
* assert_eq!(
* StringValue::data(StringValue::symbol("inner").unwrap()).unwrap(),
* StringValue::symbol("inner").unwrap()
* );
* assert_eq!(
* StringValue::symbol("inner").unwrap().unwrap(),
* StringValue::symbol("inner").unwrap()
* );
* ```
*/
pub fn unwrap(self) -> Value<Sym> {
match self {
Value::Code(code) => code.unwrap(),
Value::Data(data) => data.unwrap(),
other => other,
}
}
/**
* Fully unwrap tree. Unwraps all data and code values.
*
* This will recursively unwrap an entire s-expression, removing any
* information about data or code. To only unwrap the outermost layer,
* use `unwrap`.
*
* ```rust
* use atoms::StringValue;
* assert_eq!(
* StringValue::code(StringValue::list(vec![
* StringValue::data(StringValue::auto(14)),
* StringValue::data(StringValue::auto(13.000)),
* StringValue::auto("twelve"),
* ])).unwrap_full(),
* StringValue::list(vec![
* StringValue::auto(14),
* StringValue::auto(13.000),
* StringValue::auto("twelve"),
* ])
* );
* ```
*/
pub fn unwrap_full(self) -> Value<Sym> {
match self {
Value::Code(code) => code.unwrap_full(),
Value::Data(data) => data.unwrap_full(),
Value::Cons(left, right) =>
Value::cons(
left.unwrap_full(),
right.unwrap_full()
),
_ => self,
}
}
/**
* Is a multimode data s-expression
*
* This will return true if the given value is explicitly tagged as data
* and contains children at any level that are code.
*
* ```rust
* use atoms::StringValue;
* assert!(
* StringValue::data(StringValue::list(vec![
* StringValue::code(StringValue::auto(14)),
* StringValue::code(StringValue::auto(13.000)),
* StringValue::auto("twelve"),
* ])).is_multimode()
* );
* assert!(
* !StringValue::data(StringValue::list(vec![
* StringValue::auto(14),
* StringValue::auto(13.000),
* StringValue::auto("twelve"),
* ])).is_multimode()
* );
* ```
*/
pub fn is_multimode(&self) -> bool {
match *self {
Value::Data(ref contents) => contents.code_children(),
_ => false
}
}
/**
* Finds any child in code mode
*/
fn code_children(&self) -> bool {
match *self {
Value::Code(_) => true,
Value::Data(ref child) =>
child.code_children(),
Value::Cons(ref left, ref right) =>
left.code_children() || right.code_children(),
_ => false
}
}
}
impl<Sym> AsRef<Value<Sym>> for Value<Sym> {
fn as_ref(&self) -> &Self {
match *self {
Value::Data(ref data) => data,
Value::Code(ref code) => code,
_ => self
}
}
}
impl<Sym> Display for Value<Sym> where Sym: ToString + FromStr {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match *self {
Value::Cons(ref left, ref right) => display_cons(left, right, true, f),
Value::Str(ref text) => write!(f, "\"{}\"", escape_string(&text)),
Value::Symbol(ref sym) => write!(f, "{}", escape_symbol(&sym.to_string())),
Value::Int(ref i) => write!(f, "{}", i),
Value::Float(ref fl) => format_float(f, *fl),
Value::Nil => write!(f, "()"),
// TODO: Apply quoting
Value::Data(ref data) =>
if self.is_multimode() {
write!(f, "{}", MultiMode::new(self))
} else {
write!(f, "'{}", data)
},
Value::Code(ref code) => write!(f, "{}", code),
}
}
}
impl<Sym> Debug for Value<Sym> where Sym: ToString + FromStr {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self)
}
}
fn display_cons<Sym>(left: &Value<Sym>, right: &Value<Sym>, root: bool, f: &mut Formatter)
-> Result<(), fmt::Error> where Sym: ToString + FromStr {
if root {
try!(write!(f, "("));
}
// Write the left value
try!(write!(f, "{}", left));
// Write the right value
match *right {
Value::Nil => write!(f, ")"),
Value::Cons(ref left, ref right) => {
try!(write!(f, " "));
display_cons(left, right, false, f)
}
_ => write!(f, " . {})", right),
}
}
fn escape_string(text: &AsRef<str>) -> String {
text.as_ref().chars().map(
|c| -> String {
match c {
'\t' => "\\t".to_string(),
'\n' => "\\n".to_string(),
'\r' => "\\r".to_string(),
'\'' => "\\\'".to_string(),
'\"' => "\\\"".to_string(),
'\\' => "\\\\".to_string(),
_ => c.to_string(),
}
}
).collect()
}
fn escape_symbol(text: &AsRef<str>) -> String {
escape_string(text).chars().map(
|c| -> String {
match c {
' ' => "\\ ".to_string(),
'(' => "\\(".to_string(),
')' => "\\)".to_string(),
'#' => "\\#".to_string(),
';' => "\\;".to_string(),
'`' => "\\`".to_string(),
',' => "\\,".to_string(),
_ => c.to_string(),
}
}
).collect()
}
fn format_float<F: Into<f64>>(f: &mut Formatter, fl: F) -> Result<(), fmt::Error> {
let float = fl.into();
if float.fract() == 0f64 {
write!(f, "{:.1}", float)
} else {
write!(f, "{}", float)
}
}
/**
* A helper struct that wraps a value to assist in multimode rendering, i.e.
* ensures that quasiqutoing is rendered properly
*/
#[derive(PartialEq, PartialOrd)]
struct MultiMode<'a, Sym: 'a + ToString + FromStr> {
value: &'a Value<Sym>,
is_data: bool,
declare_mode: bool,
}
impl<'a, Sym: 'a + FromStr + ToString> MultiMode<'a, Sym> {
/**
* Create a new nultimode-tagged value. We assume that this is
* only used to the root of a data expression that contains code
* expressions.
*/
fn new(data: &'a Value<Sym>) -> Self {
match *data {
Value::Data(_) => MultiMode {
value: data,
is_data: true,
declare_mode: true
},
_ => panic!("Multimode::new only to be used on Value::Data"),
}
}
/**
* Used to wrap a child value dependent on the mode of parent
*/
fn wrap_child<'b>(&self, child: &'b Value<Sym>) -> MultiMode<'b, Sym> {
let mode_flip = match *child {
Value::Data(_) => !self.is_data,
Value::Code(_) => self.is_data,
_ => false,
};
MultiMode {
value: child,
is_data: self.is_data ^ mode_flip,
declare_mode: mode_flip,
}
}
}
impl<'a, Sym: 'a + ToString + FromStr> Display for MultiMode<'a, Sym> {
/*
* This is implemented such that once we are displaying something tagged as
* multimode, we will never call the `Display` on a `Value::Data` or
* `Value::Code` directly but will always unwrap them. This ensures that we
* never end up with multiple layers of multi-mode.
*/
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
if self.declare_mode {
// Explicitly display the mode switch
match *self.value {
Value::Data(ref data) =>
write!(f, "`{}", self.wrap_child(data)),
Value::Code(ref code) =>
write!(f, ",{}", self.wrap_child(code)),
_ => unreachable!(),
}
} else if let Value::Cons(ref left, ref right) = *self.value {
// Render out a cons
display_cons_multimode(
self.wrap_child(left),
self.wrap_child(right),
true,
f
)
} else {
// Display all other simple values
match *self.value {
Value::Data(ref data) =>
write!(f, "{}", self.wrap_child(data)),
Value::Code(ref code) =>
write!(f, "{}", self.wrap_child(code)),
_ => write!(f, "{}", self.value),
}
}
}
}
impl<'a, Sym: 'a + ToString + FromStr> Debug for MultiMode<'a, Sym> {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self)
}
}
fn display_cons_multimode<Sym>(left: MultiMode<Sym>, right: MultiMode<Sym>, root: bool, f: &mut Formatter)
-> Result<(), fmt::Error> where Sym: ToString + FromStr {
if root {
try!(write!(f, "("));
}
// Write the left value
try!(write!(f, "{}", left));
// Write the right value
match *right {
Value::Nil => write!(f, ")"),
Value::Cons(ref i_left, ref i_right) => {
try!(write!(f, " "));
display_cons_multimode(
right.wrap_child(i_left),
right.wrap_child(i_right),
false,
f
)
}
_ => write!(f, " . {})", right),
}
}
impl<'a, Sym: FromStr + ToString + Sized> Deref for MultiMode<'a, Sym> {
type Target = Value<Sym>;
fn deref(&self) -> &Value<Sym> {
self.value
}
}
///Automatic Conversion
pub trait AutoValue<Sym> {
fn auto(self) -> Value<Sym>;
}
impl<Sym: FromStr> AutoValue<Sym> for Value<Sym> {
fn auto(self) -> Value<Sym> {
self
}
}
impl<Sym: FromStr> AutoValue<Sym> for i64 {
fn auto(self) -> Value<Sym> {
Value::int(self)
}
}
impl<Sym: FromStr> AutoValue<Sym> for f64 {
fn auto(self) -> Value<Sym> {
Value::float(self)
}
}
impl<'a, Sym: FromStr> AutoValue<Sym> for &'a str {
fn auto(self) -> Value<Sym> {
Value::string(self)
}
}
impl<Sym: FromStr> AutoValue<Sym> for String {
fn auto(self) -> Value<Sym> {
Value::string(self)
}
}
/**
* Inlining s-expressions
*
* This macro makes it trivial to inline s-expressions. For example, to inline
* the s-expression:
*
* ```lisp
* (the 'quick brown `(fox ,jumped over the 3 "lazy" dogs ,(aged 42.5)))
* ```
*
* The following macro could be used (in this case we are using `StringValue`
* as the value type):
*
* ```rust
* #[macro_use]
* extern crate atoms;
*
* use atoms::{StringValue, Parser};
*
* fn main() {
* let val = Parser::new(
* &"(the 'quick brown `(fox ,jumped over the 3 \"lazy\" dogs ,(aged 42.5)))"
* ).parse::<String>().unwrap();
* let inline = s_tree!(StringValue:
* ([the] [d:[quick]] [brown] [d:(
* [fox] [c:[jumped]] [over] [the] 3 "lazy" [dogs] [c:(
* [aged] 42.5
* )]
* )])
* );
* assert_eq!(val, inline);
* }
* ```
*
* # Structure
*
* The first part of the macro tells it what type to load the expression as and
* must be some kind of `Value`. This is followed by a literal `:` and then the
* expressions itself.
*
* ```rust
* #[macro_use]
* extern crate atoms;
*
* use atoms::StringValue;
*
* fn main() {
* s_tree!(StringValue: (1 2 3 4 5 6));
* }
* ```
*
* # Automatic Conversion
*
* The following types get automatically converted, whether they are literals or
* variables:
*
* * `String`
* * `i64`
* * `f64`
*
* This means you can just place them in your expression as-is.
*
* ```rust
* #[macro_use]
* extern crate atoms;
*
* use atoms::StringValue;
*
* fn main() {
* assert_eq!(
* s_tree!(StringValue: (13 "text" 3.1415)).to_string(),
* "(13 \"text\" 3.1415)"
* );
* }
* ```
*
* # Cons, List, and Nil
*
* These all work much the same way they do in Lisp. Cons are joined with a `.`,
* lists and cons are bound between `(` and `)`, and nil is simply `()`. One
* important thing to note is that constructs like `(1 2 3 . 4)` have to be
* constructed from explicit cons cells.
*
* ```rust
* #[macro_use]
* extern crate atoms;
*
* use atoms::StringValue;
*
* fn main() {
* s_tree!(StringValue: ());
* s_tree!(StringValue: (1 2 3 4 5));
* s_tree!(StringValue: ((1 . 2) . ((3 . 4) . 5)));
* assert_eq!(
* s_tree!(StringValue: (1 2 3 4 5)),
* s_tree!(StringValue: (1 . (2 . (3 . (4 . (5 . ()))))))
* );
* }
* ```
*
* # Symbols
*
* Symbols can be used in 2 ways. The first is the conversion method, which is
* for more complex symbols, is used with a `&str` and involves wrapping it in
* a `[s:]` construct. The second form is *quoting* and simply involves
* wrapping a series of tokens in `[]`.
*
* ```rust
* #[macro_use]
* extern crate atoms;
*
* use atoms::StringValue;
*
* fn main() {
* assert_eq!(
* s_tree!(StringValue: ([one] [s:"two"] [s:"compleχex"])).to_string(),
* "(one two compleχex)"
* )
* }
* ```
*
* # Data and Code
*
* Any value can be tagged as being data or code by wrapping it in the relevant
* construct, which are `[d:]` and `[c:]` respectively.
*
* ```rust
* #[macro_use]
* extern crate atoms;
*
* use atoms::{StringValue, Parser};
*
* fn main() {
* assert_eq!(
* Parser::new(&"'(this is ,quasiquoted ,(data `0 `12.3))")
* .parse::<String>().unwrap(),
* s_tree!(StringValue:
* [d:([this] [is] [c:[quasiquoted]] [c:(
* [data] [d:0] [d:12.3]
* )])]
* )
* );
* }
* ```
*
*/
#[macro_export]
macro_rules! s_tree {
($t:ident: ()) => {
$t::nil();
};
($t:ident: ($l:tt . $r:tt)) => {
$t::cons(s_tree!($t: $l), s_tree!($t: $r))
};
($t:ident: ($($i:tt)*)) => {
$t::list(vec![
$(s_tree!($t: $i)),*
])
};
($t:ident: [d:$v:tt]) => {
$t::data(s_tree!($t: $v))
};
($t:ident: [c:$v:tt]) => {
$t::code(s_tree!($t: $v))
};
($t:ident: [s:$v:tt]) => {
$t::symbol($v).unwrap()
};
($t:ident: [$v:tt]) => {
$t::symbol(stringify!($v)).unwrap()
};
($t:ident: [$k:ident:$v:expr]) => {
$t::$k($v)
};
($t:ident: $v:expr) => {
$t::auto($v)
};
}
#[test]
fn value_fmt_test() {
assert_eq!(format!("{:?}", Value::<String>::int(13)), "13");
assert_eq!(format!("{:?}", Value::<String>::int(-13)), "-13");
assert_eq!(format!("{:?}", Value::<String>::float(13.0)), "13.0");
assert_eq!(format!("{:?}", Value::<String>::float(13.125)), "13.125");
assert_eq!(format!("{:?}", Value::<String>::float(13.333)), "13.333");
assert_eq!(format!("{:?}", Value::<String>::float(-13.333)), "-13.333");
assert_eq!(format!("{:?}", Value::<String>::string("text")), "\"text\"");
assert_eq!(format!("{:?}", Value::<String>::string("hello\tthere\nfriend")), "\"hello\\tthere\\nfriend\"");
assert_eq!(format!("{:?}", Value::<String>::symbol("text").unwrap()), "text");
assert_eq!(format!("{:?}", Value::<String>::symbol("hello\tthere\nfriend").unwrap()), "hello\\tthere\\nfriend");
assert_eq!(
format!("{:?}", s_tree!(StringValue: (13 13.333 "text" [symbol]))),
"(13 13.333 \"text\" symbol)"
);
assert_eq!(
format!("{:?}", s_tree!(StringValue: (13 . (13.333 . ("text" . [symbol]))))),
"(13 13.333 \"text\" . symbol)"
);
assert_eq!(format!("{:?}", Value::<String>::cons(
Value::int(13),
Value::cons(
Value::float(13.333),
Value::cons(
Value::string("text"),
Value::symbol("symbol").unwrap()
)
)
)), "(13 13.333 \"text\" . symbol)");
}
#[test]
fn render_multimode() {
assert_eq!(format!(
"{:?}",
StringValue::code(StringValue::list(vec![
StringValue::data(StringValue::symbol("test").unwrap()),
StringValue::data(StringValue::list(vec![
StringValue::symbol("this").unwrap(),
StringValue::symbol("is").unwrap(),
StringValue::code(StringValue::symbol("not").unwrap()),
StringValue::symbol("data").unwrap(),
])),
StringValue::symbol("code?").unwrap(),
]))
), "('test `(this is ,not data) code?)");
assert_eq!(format!(
"{:?}",
s_tree!(StringValue: (
[d:[test]]
[d:([this] [is] [c:[not]] [data] [int:61])]
[s:"code"]
))
), "('test `(this is ,not data 61) code)");
}
|
//! Toast Box
//!
//! A widget represent a message box
use druid::{
lens::{self, LensExt},
BoxConstraints, Color, Data, Env, Event, EventCtx, LayoutCtx, PaintCtx, Point, Rect,
RenderContext, Size, UnitPoint, UpdateCtx, Widget, WidgetPod,
};
use druid::{
widget::{Align, Label, List, WidgetExt},
LifeCycle, LifeCycleCtx,
};
use super::painter::Painter;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
#[derive(Hash, Clone)]
struct TimerKey(Arc<String>);
impl PartialEq for TimerKey {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for TimerKey {}
pub struct NotificationContainer<T, L>
where
T: Data,
{
inner: WidgetPod<T, Box<dyn Widget<T>>>,
bars: Align<T>,
snackbar_lens: L,
lifes: HashMap<TimerKey, f64>,
}
#[derive(Data, Debug, Clone, Eq, PartialEq, Hash)]
pub struct Notification {
pub kind: NotificationKind,
pub msg: Arc<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Data)]
pub enum NotificationKind {
Info,
Error,
}
impl Notification {
pub fn info(s: impl Into<String>) -> Notification {
Notification { kind: NotificationKind::Info, msg: Arc::new(s.into()) }
}
pub fn error(s: impl Into<String>) -> Notification {
Notification { kind: NotificationKind::Error, msg: Arc::new(s.into()) }
}
}
type NotificationsData = Arc<Vec<Notification>>;
impl<T: Data, L: lens::Lens<T, NotificationsData> + 'static + Clone> NotificationContainer<T, L> {
pub fn new(inner: impl Widget<T> + 'static, snackbar_lens: L) -> Self {
let bars = List::new(|| {
Align::right(
Label::new(|item: &Notification, _env: &_| item.msg.as_ref().clone())
.padding(10.0)
.painter(|paint_ctx: &mut PaintCtx, data: &Notification, _env: &Env| {
let rt = Rect::from_origin_size(Point::ORIGIN, paint_ctx.size());
let color = match data.kind {
NotificationKind::Info => Color::grey(0.3),
NotificationKind::Error => Color::rgb(0.6, 0.0, 0.0),
};
paint_ctx.fill(rt, &color);
}),
)
.padding((10.0, 5.0))
})
.lens(snackbar_lens.clone());
Self {
inner: WidgetPod::new(inner).boxed(),
bars: Align::vertical(UnitPoint::BOTTOM_RIGHT, bars),
snackbar_lens,
lifes: HashMap::default(),
}
}
}
impl<T: Data, L: lens::Lens<T, NotificationsData>> NotificationContainer<T, L> {
fn remove_item(&self, data: &mut T, item: &Arc<String>) {
self.snackbar_lens.with_mut(data, |d: &mut _| {
if d.len() > 0 {
Arc::make_mut(d).retain(|it| !Arc::ptr_eq(&it.msg, item));
}
})
}
fn has_item(&self, data: &T) -> bool {
self.snackbar_lens.get(data).len() > 0
}
fn sync_lifes(&mut self, data: &NotificationsData) {
let mut avails = HashSet::new();
for item in data.iter() {
let key = TimerKey(item.msg.clone());
self.lifes.entry(key.clone()).or_insert_with(|| 0.0);
avails.insert(key);
}
self.lifes.retain(|key, _| avails.contains(key));
}
}
impl<T: Data, L: lens::Lens<T, NotificationsData> + Clone> Widget<T>
for NotificationContainer<T, L>
{
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
self.inner.lifecycle(ctx, event, data, env);
self.bars.lifecycle(ctx, event, data, env);
}
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
self.inner.event(ctx, event, data, env);
self.bars.event(ctx, event, data, env);
match event {
Event::AnimFrame(interval) => {
let dt = (*interval as f64) * 1e-9;
let mut remains = std::mem::take(&mut self.lifes);
remains.retain(|item, t| {
*t += dt;
if *t >= 3.0 {
self.remove_item(data, &item.0);
false
} else {
true
}
});
self.lifes = remains;
self.snackbar_lens.clone().with(data, |it| {
self.sync_lifes(it);
});
}
_ => (),
}
if self.has_item(data) {
ctx.request_anim_frame();
}
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) {
self.inner.update(ctx, data, env);
self.bars.update(ctx, old_data, data, env);
let lens = self.snackbar_lens.clone();
lens.with(old_data, |old| {
lens.with(data, |new| {
if !new.same(old) {
ctx.request_paint();
self.sync_lifes(new);
}
})
});
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
let size = self.bars.layout(ctx, &bc, data, env);
self.inner.set_layout_rect(ctx, data, env, Rect::from_origin_size(Point::ORIGIN, size));
let size = self.inner.layout(ctx, &bc, data, env);
self.inner.set_layout_rect(ctx, data, env, Rect::from_origin_size(Point::ORIGIN, size));
size
}
fn paint(&mut self, paint_ctx: &mut PaintCtx, data: &T, env: &Env) {
self.inner.paint(paint_ctx, data, env);
if self.snackbar_lens.get(data).len() > 0 {
self.bars.paint(paint_ctx, data, env);
}
}
}
|
extern crate regex;
extern crate gtk;
extern crate image;
extern crate imageproc;
extern crate rusttype;
extern crate conv;
extern crate webbrowser;
use regex::Regex;
use gtk::*;
mod decoder;
mod decoder_class;
mod decoder_usecase;
mod gui;
mod visuals;
mod visuals_class;
mod visuals_case;
mod decoding_to_visual;
fn main() {
let method_regex = Regex::new(r"^((public|private|protected|package)?:(static)?:(final)?:(\w+):(\w+):(.*)?(,?))*$").unwrap();
println!("{}",method_regex.is_match(":::voiddm:achWas:int=nummer"));
//visuals::use_case_hard();
gui::gui_main();
let abc = decoder_usecase::decode_use_cases("2:schlafen:EP".to_string());
} |
use crate::{
document::{PAGE_MAX, PAGE_MIN},
id::Id,
};
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use std::cmp::{max, min, Ordering};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Position(pub Vec<Id>);
impl Ord for Position {
fn cmp(&self, other: &Self) -> Ordering {
let (len1, len2) = (self.0.len(), other.0.len());
for i in 0..min(len1, len2) {
let ord = self.0[i].cmp(&other.0[i]);
if ord != Ordering::Equal {
return ord;
}
}
if len1 < len2 {
return Ordering::Less;
} else if len1 > len2 {
return Ordering::Greater;
} else {
return Ordering::Equal;
}
}
}
impl PartialOrd for Position {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<Idx> std::ops::Index<Idx> for Position
where
Idx: std::slice::SliceIndex<[Id]>,
{
type Output = Idx::Output;
fn index(&self, index: Idx) -> &Self::Output {
&self.0[index]
}
}
impl Position {
pub fn new(ids: &[Id]) -> Self {
Self(ids.to_vec())
}
/// Creates a new position identifier based on the following cases.
/// # Case 1: Digits differ by exactly 1
/// In this case, we can't find an integer that lies between the two digits.
/// Therefore, we must continue onto the next `Id`.
/// ```
/// prev (0.1311) : [1,1] -> *[3,1]* -> [1,1] -> [1,1] -> ..
/// next (0.1411) : [1,1] -> *[4,1]* -> [1,1] -> [1,1] -> ..
/// ```
/// # Case 2: Digits differ by more than 1
/// We can create a new identifier between the two digits
/// Note that the length of `between` will not be larger than `prev` or `next` in this case
/// ```
/// prev (0.1359) : [1,1] -> *[3,1]* -> [5,3] -> [9,2]
/// next (0.1610) : [1,1] -> *[6,1]* -> [10,1]
/// between (0.1500) : [1,1] -> [5,1]
/// ```
/// # Case 3: Same digits, different site
/// ```
/// prev (0.13590) : [1,1] -> *[3,1]* -> [5,3] -> [9,2]
/// next (0.13800) : [1,1] -> *[3,3]* -> [8,1]
/// between (0.13591) : [1,1] -> [3,1] -> [5,3] -> [9,2] -> [1,1]
pub fn create(site: i64, before: &[Id], after: &[Id]) -> Self {
let (virtual_min, virtual_max) = (Id::new(PAGE_MIN, site), Id::new(PAGE_MAX, site));
let max_len = max(before.len(), after.len());
let mut new_pos = Vec::new();
let mut is_same_site = true;
let mut did_change = false;
for i in 0..max_len {
let id1 = before.get(i).unwrap_or(&virtual_min);
let id2 = after
.get(i)
.filter(|_| is_same_site)
.unwrap_or(&virtual_max);
let diff = id2.digit - id1.digit;
if diff > 1 {
// Both digits differ by more than 1, so generate a random digit between the two ID digits, exclusively.
let new_digit = Self::generate_random_digit(id1.digit + 1, id2.digit);
did_change = true;
new_pos.push(Id::new(new_digit, site));
break;
} else {
// Both IDs differ by at most 1
new_pos.push(id1.to_owned());
is_same_site = id1.cmp(id2) == Ordering::Equal;
}
}
if !did_change {
// In this case, the digits at each i-th ID differed by at most one and each position had the same length.
// If this case wasn't here, then each ID will simply be appended each at step, so you'll get the same position as the n-th position, which isn't good.
let new_digit = Self::generate_random_digit(virtual_min.digit + 1, virtual_max.digit);
new_pos.push(Id::new(new_digit, site));
}
Position(new_pos)
}
fn generate_random_digit(lower_bound: u64, upper_bound: u64) -> u64 {
let mut rand = thread_rng();
rand.gen_range(lower_bound, upper_bound)
}
}
|
pub fn reply(message: &str) -> &str {
let trimmed = message.trim();
match trimmed {
trimmed if trimmed.is_empty() => "Fine. Be that way!",
trimmed if is_question(trimmed) && is_yell(trimmed) => "Calm down, I know what I'm doing!",
trimmed if is_question(trimmed) => "Sure.",
trimmed if is_yell(trimmed) => "Whoa, chill out!",
_ => "Whatever.",
}
}
fn is_question(msg: &str) -> bool {
msg.ends_with('?')
}
fn is_yell(msg: &str) -> bool {
let mut contains_letters = false;
for c in msg.chars() {
if c.is_alphabetic() {
contains_letters = true;
if !c.is_uppercase() {
return false;
}
}
}
contains_letters
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.