text stringlengths 8 4.13M |
|---|
#[doc = "Register `TTCTC` reader"]
pub type R = crate::R<TTCTC_SPEC>;
#[doc = "Field `CT` reader - Cycle Time"]
pub type CT_R = crate::FieldReader<u16>;
#[doc = "Field `CC` reader - Cycle Count"]
pub type CC_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:15 - Cycle Time"]
#[inline(always)]
pub fn ct(&self) -> CT_R {
CT_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:21 - Cycle Count"]
#[inline(always)]
pub fn cc(&self) -> CC_R {
CC_R::new(((self.bits >> 16) & 0x3f) as u8)
}
}
#[doc = "FDCAN TT Cycle Time and Count Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ttctc::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TTCTC_SPEC;
impl crate::RegisterSpec for TTCTC_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ttctc::R`](R) reader structure"]
impl crate::Readable for TTCTC_SPEC {}
#[doc = "`reset()` method sets TTCTC to value 0"]
impl crate::Resettable for TTCTC_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[derive(PartialEq)]
#[derive(Debug)]
pub enum PrizeType {
SPECIAL,
GRAND,
FIRST,
SECOND,
THIRD,
FOURTH,
FIFTH,
SIXTH,
ADDITIONAL,
NONE
}
#[derive(Debug)]
pub struct WinningNumbers {
pub special_prize: String,
pub grand_prize: String,
pub regular_prizes: [String; 3],
pub additional_prizes: [String; 3],
}
fn check_ticket(winning_number: &str, ticket_number: &str) -> usize {
let mut max_length = 0;
for length in (3..9).rev() {
let winning_reverse = winning_number.chars().rev().take(length);
let ticket_reverse = ticket_number.chars().rev().take(length);
if winning_reverse.eq(ticket_reverse){
max_length = length;
break;
}
}
max_length
}
fn convert_number_to_prize(number: usize) -> PrizeType {
match number {
8 => PrizeType::FIRST,
7 => PrizeType::SECOND,
6 => PrizeType::THIRD,
5 => PrizeType::FOURTH,
4 => PrizeType::FIFTH,
3 => PrizeType::SIXTH,
_ => PrizeType::NONE,
}
}
fn check_ticket_regular(regular_prizes: &[String; 3], ticket_number: &str) -> PrizeType {
let regular1 = check_ticket(®ular_prizes[0], ticket_number);
let regular2 = check_ticket(®ular_prizes[1], ticket_number);
let regular3 = check_ticket(®ular_prizes[2], ticket_number);
let results = [regular1, regular2, regular3];
let best_result = results.iter().max();
match best_result {
Some(number) => convert_number_to_prize(*number),
None => PrizeType::NONE,
}
}
pub fn check_ticket_all(winning_numbers: &WinningNumbers, ticket_number: &str) -> PrizeType
{
let special_rev = winning_numbers.special_prize.chars().rev();
let grand_rev = winning_numbers.grand_prize.chars().rev();
let ticket_rev : String = ticket_number.chars().rev().collect();
let regular_prize_result = check_ticket_regular(&winning_numbers.regular_prizes, ticket_number);
if ticket_rev.chars().take(8).eq(special_rev) {
PrizeType::SPECIAL
}
else if ticket_rev.chars().take(8).eq(grand_rev) {
PrizeType::GRAND
}
else if regular_prize_result != PrizeType::NONE {
regular_prize_result
}
else if ticket_rev.chars().take(3).eq(winning_numbers.additional_prizes[0].chars().rev()) {
PrizeType::ADDITIONAL
}
else if ticket_rev.chars().take(3).eq(winning_numbers.additional_prizes[1].chars().rev()) {
PrizeType::ADDITIONAL
}
else if ticket_rev.chars().take(3).eq(winning_numbers.additional_prizes[2].chars().rev()) {
PrizeType::ADDITIONAL
}
else
{
PrizeType::NONE
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_last_digit_off() {
assert_eq!(0, check_ticket("AB-87654320","AB-87654321"));
}
#[test]
fn test_full_match() {
assert_eq!(8, check_ticket("AB-87654321","AB-87654321"));
}
#[test]
fn test_last_three() {
assert_eq!(3, check_ticket("AB-87654321","AB-00000321"));
}
#[test]
fn test_last_two_no_match() {
assert_eq!(0, check_ticket("AB-87654321","AB-00000021"));
}
/////////////////////// Convert number to prize
#[test]
fn test_convert_number_to_prize() {
assert_eq!(PrizeType::FIRST, convert_number_to_prize(8));
assert_eq!(PrizeType::SECOND, convert_number_to_prize(7));
assert_eq!(PrizeType::THIRD, convert_number_to_prize(6));
assert_eq!(PrizeType::FOURTH, convert_number_to_prize(5));
assert_eq!(PrizeType::FIFTH, convert_number_to_prize(4));
assert_eq!(PrizeType::SIXTH, convert_number_to_prize(3));
assert_eq!(PrizeType::NONE, convert_number_to_prize(2));
assert_eq!(PrizeType::NONE, convert_number_to_prize(1));
assert_eq!(PrizeType::NONE, convert_number_to_prize(0));
assert_eq!(PrizeType::NONE, convert_number_to_prize(9));
}
/////////////////////// check_ticket_regular
#[test]
fn test_check_regular() {
let regular_numbers = [String::from("98765432"),
String::from("87654321"),
String::from("76543210")];
assert_eq!(PrizeType::FIRST, check_ticket_regular(®ular_numbers, "98765432"));
assert_eq!(PrizeType::FIRST, check_ticket_regular(®ular_numbers, "87654321"));
assert_eq!(PrizeType::FIRST, check_ticket_regular(®ular_numbers, "76543210"));
assert_eq!(PrizeType::SECOND, check_ticket_regular(®ular_numbers, "08765432"));
assert_eq!(PrizeType::THIRD, check_ticket_regular(®ular_numbers, "00765432"));
assert_eq!(PrizeType::FOURTH, check_ticket_regular(®ular_numbers, "00065432"));
assert_eq!(PrizeType::FIFTH, check_ticket_regular(®ular_numbers, "00005432"));
assert_eq!(PrizeType::SIXTH, check_ticket_regular(®ular_numbers, "00000432"));
assert_eq!(PrizeType::NONE, check_ticket_regular(®ular_numbers, "00000032"));
// Double check that smaller, non-first prizes are checked on the other winning numbers
assert_eq!(PrizeType::FIFTH, check_ticket_regular(®ular_numbers, "00004321"));
assert_eq!(PrizeType::SIXTH, check_ticket_regular(®ular_numbers, "00000210"));
}
///////////////////// check_ticket_all
#[test]
fn test_full_ticket() {
let winning_numbers = WinningNumbers {
special_prize: String::from("01234567"),
grand_prize: String::from("12345678"),
regular_prizes: [String::from("98765432"),
String::from("87654321"),
String::from("76543210")],
additional_prizes: [String::from("765"),
String::from("654"),
String::from("543")]
};
assert_eq!(PrizeType::NONE, check_ticket_all(&winning_numbers, "AZ-39842818"));
assert_eq!(PrizeType::SPECIAL, check_ticket_all(&winning_numbers, "AD-01234567"));
assert_eq!(PrizeType::GRAND, check_ticket_all(&winning_numbers, "AD-12345678"));
assert_eq!(PrizeType::FIRST, check_ticket_all(&winning_numbers, "AD-98765432"));
assert_eq!(PrizeType::SIXTH, check_ticket_all(&winning_numbers, "BB-00000210"));
assert_eq!(PrizeType::ADDITIONAL, check_ticket_all(&winning_numbers, "XX-00000543"));
assert_eq!(PrizeType::ADDITIONAL, check_ticket_all(&winning_numbers, "YY-00000654"));
assert_eq!(PrizeType::ADDITIONAL, check_ticket_all(&winning_numbers, "ZZ-00000765"));
}
#[test]
fn test_largest_prize_returned() {
let winning_numbers = WinningNumbers {
special_prize: String::from("98765432"),
grand_prize: String::from("87654321"),
regular_prizes: [String::from("08765432"), // Almost same as special
String::from("07654321"), // Almost same as grand
String::from("76543210")],
additional_prizes: [String::from("321"), //Same as last 3 of both grand and reguar
String::from("432"), //Same as last 3 of both special and reguar
String::from("314")]
};
assert_eq!(PrizeType::SPECIAL, check_ticket_all(&winning_numbers, "AZ-98765432"));
assert_eq!(PrizeType::GRAND, check_ticket_all(&winning_numbers, "AD-87654321"));
assert_eq!(PrizeType::FOURTH, check_ticket_all(&winning_numbers, "AF-00054321"));
}
#[test]
fn test_no_preceding_letters() {
let winning_numbers = WinningNumbers {
special_prize: String::from("01234567"),
grand_prize: String::from("12345678"),
regular_prizes: [String::from("98765432"),
String::from("87654321"),
String::from("76543210")],
additional_prizes: [String::from("765"),
String::from("654"),
String::from("543")]
};
assert_eq!(PrizeType::FIRST, check_ticket_all(&winning_numbers, "98765432"));
}
}
|
use chrono::{DateTime, Utc};
#[derive(Debug, Clone)]
pub struct StatusItem<S> {
date: DateTime<Utc>,
status: S,
}
impl<S> StatusItem<S> {
fn new(status: S) -> Self {
StatusItem {
date: Utc::now(),
status,
}
}
pub fn date(&self) -> &DateTime<Utc> {
&self.date
}
pub fn status(&self) -> &S {
&self.status
}
}
#[derive(Debug, Clone)]
pub struct StatusHistory<S> {
history: Vec<StatusItem<S>>,
}
impl<S> StatusHistory<S> {
pub fn new(status: S) -> Self {
StatusHistory {
history: vec![StatusItem::new(status)],
}
}
pub fn add_status(&mut self, status: S) {
self.history.push(StatusItem::new(status));
}
pub fn history(&self) -> &[StatusItem<S>] {
&self.history
}
pub fn current(&self) -> &StatusItem<S> {
// It's safe because history has at least one status. It's initialized with one status.
self.history.last().unwrap()
}
pub fn is_current<P>(&self, predicate: P) -> bool
where
P: Fn(&S) -> bool,
{
predicate(self.current().status())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, PartialEq)]
enum Status {
Init,
Open,
Closed,
}
#[test]
fn create() {
assert_eq!(StatusHistory::new(Status::Init).history().len(), 1);
assert_eq!(StatusHistory::new(Status::Init).history().len(), 1);
let mut sh = StatusHistory::new(Status::Init);
sh.add_status(Status::Open);
sh.add_status(Status::Closed);
sh.add_status(Status::Open);
assert_eq!(sh.history().len(), 4);
assert_eq!(sh.current().status(), &Status::Open);
let sh = StatusHistory::new(Status::Open);
assert_eq!(sh.history().len(), 1);
assert_eq!(sh.current().status(), &Status::Open);
}
#[test]
fn history() {
let mut sh = StatusHistory::new(Status::Init);
sh.add_status(Status::Open);
sh.add_status(Status::Closed);
sh.add_status(Status::Open);
sh.add_status(Status::Closed);
assert_eq!(sh.current().status(), &Status::Closed);
}
#[test]
fn compare() {
let mut sh = StatusHistory::new(Status::Init);
sh.add_status(Status::Open);
sh.add_status(Status::Closed);
sh.add_status(Status::Open);
assert!(sh.is_current(|s| match s {
Status::Open => true,
_ => false,
}));
assert!(!sh.is_current(|s| match s {
Status::Closed => true,
_ => false,
}));
}
}
|
use std::fmt;
use std::io;
use std::sync::Arc;
use std::time::Duration;
use crate::cancel::Cancel;
use crate::config::config;
use crate::join::{make_join_handle, Join, JoinHandle};
use crate::local::get_co_local_data;
use crate::local::CoroutineLocal;
use crate::park::Park;
use crate::scheduler::get_scheduler;
use crate::sync::AtomicOption;
use generator::{Generator, Gn};
/// /////////////////////////////////////////////////////////////////////////////
/// Coroutine framework types
/// /////////////////////////////////////////////////////////////////////////////
pub type EventResult = io::Error;
pub struct EventSubscriber {
resource: *mut dyn EventSource,
}
// the EventSource is usually a heap obj that resides within the
// generator, it should be safe to send between threads.
unsafe impl Send for EventSubscriber {}
impl EventSubscriber {
pub fn new(r: *mut dyn EventSource) -> Self {
EventSubscriber { resource: r }
}
pub fn subscribe(self, c: CoroutineImpl) {
let resource = unsafe { &mut *self.resource };
resource.subscribe(c);
}
}
pub trait EventSource {
/// kernel handler of the event
fn subscribe(&mut self, _c: CoroutineImpl);
/// after yield back process
fn yield_back(&self, cancel: &'static Cancel) {
// after return back we should re-check the panic and clear it
cancel.check_cancel();
}
}
/// /////////////////////////////////////////////////////////////////////////////
/// Coroutine destruction
/// /////////////////////////////////////////////////////////////////////////////
pub struct Done;
impl Done {
fn drop_coroutine(co: CoroutineImpl) {
// assert!(co.is_done(), "unfinished coroutine detected");
// just consume the coroutine
// destroy the local storage
let local = unsafe { Box::from_raw(get_co_local(&co)) };
let name = local.get_co().name();
// recycle the coroutine
let (size, used) = co.stack_usage();
if used == size {
eprintln!("stack overflow detected, size={size}");
::std::process::exit(1);
}
// show the actual used stack size in debug log
if local.get_co().stack_size() & 1 == 1 {
println!("coroutine name = {name:?}, stack size = {size}, used size = {used}");
}
if size == config().get_stack_size() {
get_scheduler().pool.put(co);
}
}
}
impl EventSource for Done {
fn subscribe(&mut self, co: CoroutineImpl) {
Self::drop_coroutine(co);
}
}
/// coroutines are static generator
/// the para type is EventResult, the result type is EventSubscriber
pub type CoroutineImpl = Generator<'static, EventResult, EventSubscriber>;
#[inline]
#[allow(clippy::cast_ptr_alignment)]
fn get_co_local(co: &CoroutineImpl) -> *mut CoroutineLocal {
co.get_local_data() as *mut CoroutineLocal
}
/// /////////////////////////////////////////////////////////////////////////////
/// Coroutine
/// /////////////////////////////////////////////////////////////////////////////
/// The internal representation of a `Coroutine` handle
struct Inner {
name: Option<String>,
stack_size: usize,
park: Park,
cancel: Cancel,
}
#[derive(Clone)]
/// A handle to a coroutine.
pub struct Coroutine {
inner: Arc<Inner>,
}
impl Coroutine {
// Used only internally to construct a coroutine object without spawning
fn new(name: Option<String>, stack_size: usize) -> Coroutine {
Coroutine {
inner: Arc::new(Inner {
name,
stack_size,
park: Park::new(),
cancel: Cancel::new(),
}),
}
}
/// Gets the coroutine stack size.
pub fn stack_size(&self) -> usize {
self.inner.stack_size
}
/// Atomically makes the handle's token available if it is not already.
pub fn unpark(&self) {
self.inner.park.unpark();
}
/// cancel a coroutine
/// # Safety
///
/// This function would force a coroutine exist when next scheduling
/// And would drop all the resource tha the coroutine currently holding
/// This may have unexpected side effects if you are not fully aware it
pub unsafe fn cancel(&self) {
self.inner.cancel.cancel();
}
/// Gets the coroutine name.
pub fn name(&self) -> Option<&str> {
self.inner.name.as_deref()
}
/// Get the internal cancel
#[cfg(unix)]
#[cfg(feature = "io_cancel")]
pub(crate) fn get_cancel(&self) -> &Cancel {
&self.inner.cancel
}
}
impl fmt::Debug for Coroutine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.name(), f)
}
}
////////////////////////////////////////////////////////////////////////////////
// Builder
////////////////////////////////////////////////////////////////////////////////
/// Coroutine factory, which can be used in order to configure the properties of
/// a new coroutine.
///
/// Methods can be chained on it in order to configure it.
///
/// The two configurations available are:
///
/// - [`name`]: specifies an [associated name for the coroutine][naming-coroutines]
/// - [`stack_size`]: specifies the [desired stack size for the coroutine][stack-size]
///
/// The [`spawn`] method will take ownership of the builder and create an
/// `io::Result` to the coroutine handle with the given configuration.
///
/// The [`coroutine::spawn`] free function uses a `Builder` with default
/// configuration and `unwrap`s its return value.
///
/// You may want to use [`spawn`] instead of [`coroutine::spawn`], when you want
/// to recover from a failure to launch a coroutine, indeed the free function will
/// panics where the `Builder` method will return a `io::Result`.
///
/// # Examples
///
/// ```
/// use may::coroutine;
///
/// let builder = coroutine::Builder::new();
/// let code = || {
/// // coroutine code
/// };
///
/// let handler = unsafe { builder.spawn(code).unwrap() };
///
/// handler.join().unwrap();
/// ```
///
/// [`coroutine::spawn`]: ./fn.spawn.html
/// [`stack_size`]: ./struct.Builder.html#method.stack_size
/// [`name`]: ./struct.Builder.html#method.name
/// [`spawn`]: ./struct.Builder.html#method.spawn
/// [naming-coroutines]: ./index.html#naming-coroutine
/// [stack-size]: ./index.html#stack-siz
#[derive(Default)]
pub struct Builder {
// A name for the coroutine-to-be, for identification in panic messages
name: Option<String>,
// The size of the stack for the spawned coroutine
stack_size: Option<usize>,
// The associated id of the coroutine, would select a specific thread to run
id: Option<usize>,
}
impl Builder {
/// Generates the base configuration for spawning a coroutine, from which
/// configuration methods can be chained.
pub fn new() -> Builder {
Builder {
name: None,
stack_size: None,
id: None,
}
}
/// Names the thread-to-be. Currently the name is used for identification
/// only in panic messages.
pub fn name(mut self, name: String) -> Builder {
self.name = Some(name);
self
}
/// Sets the size of the stack for the new coroutine.
pub fn stack_size(mut self, size: usize) -> Builder {
self.stack_size = Some(size);
self
}
/// Sets the id of the coroutine, would select a specific thread to run
pub fn id(mut self, id: usize) -> Builder {
self.id = Some(id);
self
}
/// Spawns a new coroutine, and returns a join handle for it.
/// The join handle can be used to block on
/// termination of the child coroutine, including recovering its panics.
fn spawn_impl<F, T>(self, f: F) -> io::Result<(CoroutineImpl, JoinHandle<T>)>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
static DONE: Done = Done {};
let sched = get_scheduler();
let name = self.name;
let stack_size = self.stack_size.unwrap_or_else(|| config().get_stack_size());
// create a join resource, shared by waited coroutine and *this* coroutine
let panic = Arc::new(AtomicOption::none());
let join = Arc::new(Join::new(panic.clone()));
let packet = Arc::new(AtomicOption::none());
let their_join = join.clone();
let their_packet = packet.clone();
let subscriber = EventSubscriber {
resource: &DONE as &dyn EventSource as *const _ as *mut dyn EventSource,
};
let closure = move || {
// trigger the JoinHandler
// we must declare the variable before calling f so that stack is prepared
// to unwind these local data. for the panic err we would set it in the
// coroutine local data so that can return from the packet variable
// set the return packet
their_packet.store(f());
their_join.trigger();
subscriber
};
let mut co = if stack_size == config().get_stack_size() {
let mut co = sched.pool.get();
co.init_code(closure);
co
} else {
Gn::new_opt(stack_size, closure)
};
let handle = Coroutine::new(name, stack_size);
// create the local storage
let local = CoroutineLocal::new(handle.clone(), join.clone());
// attache the local storage to the coroutine
co.set_local_data(Box::into_raw(local) as *mut u8);
Ok((co, make_join_handle(handle, join, packet, panic)))
}
/// Spawns a new coroutine by taking ownership of the `Builder`, and returns an
/// `io::Result` to its `JoinHandle`.
///
/// The spawned coroutine may outlive the caller. The join handle can be used
/// to block on termination of the child thread, including recovering its panics.
///
/// # Errors
///
/// Unlike the [`spawn`] free function, this method yields an
/// `io::Result` to capture any failure to create the thread at
/// the OS level.
///
/// # Safety
///
/// - Access [`TLS`] in coroutine may trigger undefined behavior.
/// - If the coroutine exceed the stack during execution, this would trigger
/// memory segment fault
///
/// If you find it annoying to wrap every thing in the unsafe block, you can
/// use the [`go!`] macro instead.
///
/// # Examples
///
/// ```
/// use may::coroutine;
///
/// let builder = coroutine::Builder::new();
///
/// let handler = unsafe {
/// builder.spawn(|| {
/// // thread code
/// }).unwrap()
/// };
///
/// handler.join().unwrap();
/// ```
///
/// [`TLS`]: ./index.html#TLS
/// [`go!`]: ../macro.go.html
/// [`spawn`]: ./fn.spawn.html
pub unsafe fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
// we will still get optimizations in spawn_impl
let id = self.id;
let (co, handle) = self.spawn_impl(f)?;
let s = get_scheduler();
match id {
None => s.schedule_global(co),
Some(id) => s.schedule_global_with_id(co, id),
}
Ok(handle)
}
/// first run the coroutine in current thread, you should always use
/// `spawn` instead of this API.
///
/// # Safety
///
/// Cancel would drop all the resource of the coroutine.
/// Normally this is safe but for some cases you should
/// take care of the side effect
pub unsafe fn spawn_local<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
// we will still get optimizations in spawn_impl
let (co, handle) = self.spawn_impl(f)?;
// first run the coroutine in current thread
run_coroutine(co);
Ok(handle)
}
}
////////////////////////////////////////////////////////////////////////////////
// Free functions
////////////////////////////////////////////////////////////////////////////////
/// Spawns a new coroutine, returning a [`JoinHandle`] for it.
///
/// The join handle will implicitly *detach* the child coroutine upon being
/// dropped. In this case, the child coroutine may outlive the parent.
/// Additionally, the join handle provides a [`join`] method that can be used
/// to join the child coroutine. If the child coroutine panics, [`join`] will
/// return an `Err` containing the argument given to `panic`.
///
/// This will create a coroutine using default parameters of [`Builder`], if you
/// want to specify the stack size or the name of the coroutine, use this API
/// instead.
///
/// This API has the same semantic as the `std::thread::spawn` API, except that
/// it is an unsafe method.
///
/// # Safety
///
/// - Access [`TLS`] in coroutine may trigger undefined behavior.
/// - If the coroutine exceed the stack during execution, this would trigger
/// memory segment fault
///
/// If you find it annoying to wrap every thing in the unsafe block, you can
/// use the [`go!`] macro instead.
///
/// # Examples
///
/// Creating a coroutine.
///
/// ```
/// use may::coroutine;
///
/// let handler = unsafe {
/// coroutine::spawn(|| {
/// // coroutine code
/// })
/// };
///
/// handler.join().unwrap();
/// ```
///
/// [`TLS`]: ./index.html#TLS
/// [`go!`]: ../macro.go.html
/// [`JoinHandle`]: struct.JoinHandle.html
/// [`join`]: struct.JoinHandle.html#method.join
/// [`Builder::spawn`]: struct.Builder.html#method.spawn
/// [`Builder`]: struct.Builder.html
pub unsafe fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
Builder::new().spawn(f).unwrap()
}
/// Gets a handle to the coroutine that invokes it.
/// it will panic if you call it in a thread context
#[inline]
pub fn current() -> Coroutine {
match get_co_local_data() {
Some(local) => unsafe { local.as_ref() }.get_co().clone(),
None => panic!("no current coroutine, did you call `current()` in thread context?"),
}
}
/// if current context is coroutine
#[inline]
pub fn is_coroutine() -> bool {
// we never call this function in a pure generator context
// so we can sure that this function is called
// either in a thread context or in a coroutine context
get_co_local_data().is_some()
}
/// get current coroutine cancel registration
/// panic in a thread context
#[inline]
pub(crate) fn current_cancel_data() -> &'static Cancel {
match get_co_local_data() {
Some(local) => &(unsafe { &*local.as_ptr() }.get_co().inner.cancel),
None => panic!("no cancel data, did you call `current_cancel_data()` in thread context?"),
}
}
#[inline]
pub(crate) fn co_cancel_data(co: &CoroutineImpl) -> &'static Cancel {
let local = unsafe { &*get_co_local(co) };
&local.get_co().inner.cancel
}
// windows use delay drop instead
#[cfg(unix)]
#[cfg(feature = "io_cancel")]
pub(crate) fn co_get_handle(co: &CoroutineImpl) -> Coroutine {
let local = unsafe { &*get_co_local(co) };
local.get_co().clone()
}
/// timeout block the current coroutine until it's get unparked
#[inline]
fn park_timeout_impl(dur: Option<Duration>) {
if crate::likely::unlikely(!is_coroutine()) {
// in thread context we do nothing
return;
}
let co_handle = current();
co_handle.inner.park.park_timeout(dur).ok();
}
/// block the current coroutine until it's get unparked
#[inline]
pub fn park() {
park_timeout_impl(None);
}
/// timeout block the current coroutine until it's get unparked
#[inline]
pub fn park_timeout(dur: Duration) {
park_timeout_impl(Some(dur));
}
/// run the coroutine
#[inline]
pub(crate) fn run_coroutine(mut co: CoroutineImpl) {
match co.resume() {
Some(ev) => ev.subscribe(co),
None => {
// panic happened here
let local = unsafe { &mut *get_co_local(&co) };
let join = local.get_join();
// set the panic data
if let Some(panic) = co.get_panic_data() {
join.set_panic_data(panic);
}
// trigger the join here
join.trigger();
Done::drop_coroutine(co);
}
}
}
|
//! The crate is basically just a permutation utility. With the goal of speed
//! and the smallest possible runtime memory impact possible. And so, the goal
//! of this crate is to be able to calculate and obtain a permutation of a value
//! as soon as possible.
//!
//! # Examples
//! Get all the permutations of a string of three characters:
//! ```rust
//! use heap_permute::PermuteIter;
//!
//! // Print all of the permutations of a string of three characters
//! fn main() {
//! const STRING: &'static str = "ABC";
//!
//! for p in PermuteIter::from(STRING) {
//! println!("{}", p);
//! }
//! }
//! // Prints:
//! // ABC
//! // BAC
//! // CAB
//! // ACB
//! // BCA
//! // CBA
//! ```
//!
//! Now time for something more interesting, let's permute the bits in a u8:
//! ```rust
//! use heap_permute::PermuteIter;
//!
//! fn main() {
//! for p in PermuteIter::from(0b1010_1001 as u8) {
//! println!("0b{:08b} ({})", p, p);
//! }
//! }
//! // Prints:
//! // 0b10101001 (169)
//! // 0b10101010 (170)
//! // 0b10101010 (170)
//! // 0b10101001 (169)
//! // 0b10101100 (172)
//! // 0b10101100 (172)
//! // 0b10100101 (165)
//! // 0b10100110 (166)
//! // 0b10100011 (163)
//! // 0b10100011 (163)
//! // ...
//! ```
//!
//! As it happens, the crate supports permutation for all of the primitive
//! numeric rust types.
//!
mod permutable;
mod heap;
mod iterator;
pub use crate::permutable::Permutable;
pub use crate::iterator::PermuteIter;
#[cfg(feature = "grapheme")]
pub use crate::permutable::GraphemeString;
/// A type that can permute a permutable, in this crate there is only one at the
/// moment.
trait Permutor {
fn permute(&mut self, source: &mut impl Permutable);
}
#[cfg(test)]
mod tests {
use super::*;
fn permute_general<T>(val: T, result: &mut Vec<T>, bound: usize)
where T: Permutable + Clone + std::fmt::Debug + std::cmp::PartialEq
{
for p in PermuteIter::from(val).take(bound) {
let cmp = result.pop().unwrap();
// Output
eprintln!("{:?}(Permutor), {:?}(Required)", p, cmp);
assert_eq!(p, cmp);
}
}
#[test]
fn permute_four() {
let string: String = "ABCD".into();
let mut result: Vec<String> = vec![
"ABCD",
"BACD",
"CABD",
"ACBD",
"BCAD",
"CBAD",
"DBCA",
"BDCA",
"CDBA",
"DCBA",
"BCDA",
"CBDA",
"DACB",
"ADCB",
"CDAB",
"DCAB",
"ACDB",
"CADB",
"DABC",
"ADBC",
"BDAC",
"DBAC",
"ABDC",
"BADC",
].iter().map(|s| String::from(*s)).rev().collect();
eprintln!("Permutations for test(length): {}", result.len());
// Check that at least the number of results is equal to 4!
assert!(result.len() == 24);
permute_general(string, &mut result, 24);
}
#[test]
fn permute_three() {
let string: String = "ABC".into();
let mut result: Vec<String> = vec![
"ABC",
"BAC",
"CAB",
"ACB",
"BCA",
"CBA",
].iter().map(|s| String::from(*s)).rev().collect();
eprintln!("Permutations for test(length): {}", result.len());
// Check that at least the number of results is equal to 3!
assert!(result.len() == 6);
permute_general(string, &mut result, 6);
}
#[test]
fn permute_bits() {
let mut result = vec![
0b10101001,
0b10101010,
0b10101010,
0b10101001,
0b10101100,
0b10101100,
0b10100101,
0b10100110,
0b10100011,
0b10100011,
].iter().rev().cloned().collect::<Vec<u8>>();
permute_general(0b1010_1001, &mut result, 10);
}
} |
#[doc = "Register `ICR` reader"]
pub type R = crate::R<ICR_SPEC>;
#[doc = "Register `ICR` writer"]
pub type W = crate::W<ICR_SPEC>;
#[doc = "Field `PECF` reader - Parity error clear flag"]
pub type PECF_R = crate::BitReader<PECF_A>;
#[doc = "Parity error clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PECF_A {
#[doc = "1: Clears the PE flag in the ISR register"]
Clear = 1,
}
impl From<PECF_A> for bool {
#[inline(always)]
fn from(variant: PECF_A) -> Self {
variant as u8 != 0
}
}
impl PECF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<PECF_A> {
match self.bits {
true => Some(PECF_A::Clear),
_ => None,
}
}
#[doc = "Clears the PE flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == PECF_A::Clear
}
}
#[doc = "Field `PECF` writer - Parity error clear flag"]
pub type PECF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PECF_A>;
impl<'a, REG, const O: u8> PECF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the PE flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(PECF_A::Clear)
}
}
#[doc = "Field `FECF` reader - Framing error clear flag"]
pub type FECF_R = crate::BitReader<FECF_A>;
#[doc = "Framing error clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FECF_A {
#[doc = "1: Clears the FE flag in the ISR register"]
Clear = 1,
}
impl From<FECF_A> for bool {
#[inline(always)]
fn from(variant: FECF_A) -> Self {
variant as u8 != 0
}
}
impl FECF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<FECF_A> {
match self.bits {
true => Some(FECF_A::Clear),
_ => None,
}
}
#[doc = "Clears the FE flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == FECF_A::Clear
}
}
#[doc = "Field `FECF` writer - Framing error clear flag"]
pub type FECF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FECF_A>;
impl<'a, REG, const O: u8> FECF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the FE flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(FECF_A::Clear)
}
}
#[doc = "Field `NCF` reader - Noise detected clear flag"]
pub type NCF_R = crate::BitReader<NCF_A>;
#[doc = "Noise detected clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NCF_A {
#[doc = "1: Clears the NF flag in the ISR register"]
Clear = 1,
}
impl From<NCF_A> for bool {
#[inline(always)]
fn from(variant: NCF_A) -> Self {
variant as u8 != 0
}
}
impl NCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<NCF_A> {
match self.bits {
true => Some(NCF_A::Clear),
_ => None,
}
}
#[doc = "Clears the NF flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == NCF_A::Clear
}
}
#[doc = "Field `NCF` writer - Noise detected clear flag"]
pub type NCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, NCF_A>;
impl<'a, REG, const O: u8> NCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the NF flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(NCF_A::Clear)
}
}
#[doc = "Field `ORECF` reader - Overrun error clear flag"]
pub type ORECF_R = crate::BitReader<ORECF_A>;
#[doc = "Overrun error clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ORECF_A {
#[doc = "1: Clears the ORE flag in the ISR register"]
Clear = 1,
}
impl From<ORECF_A> for bool {
#[inline(always)]
fn from(variant: ORECF_A) -> Self {
variant as u8 != 0
}
}
impl ORECF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<ORECF_A> {
match self.bits {
true => Some(ORECF_A::Clear),
_ => None,
}
}
#[doc = "Clears the ORE flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == ORECF_A::Clear
}
}
#[doc = "Field `ORECF` writer - Overrun error clear flag"]
pub type ORECF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ORECF_A>;
impl<'a, REG, const O: u8> ORECF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the ORE flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(ORECF_A::Clear)
}
}
#[doc = "Field `IDLECF` reader - Idle line detected clear flag"]
pub type IDLECF_R = crate::BitReader<IDLECF_A>;
#[doc = "Idle line detected clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IDLECF_A {
#[doc = "1: Clears the IDLE flag in the ISR register"]
Clear = 1,
}
impl From<IDLECF_A> for bool {
#[inline(always)]
fn from(variant: IDLECF_A) -> Self {
variant as u8 != 0
}
}
impl IDLECF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<IDLECF_A> {
match self.bits {
true => Some(IDLECF_A::Clear),
_ => None,
}
}
#[doc = "Clears the IDLE flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == IDLECF_A::Clear
}
}
#[doc = "Field `IDLECF` writer - Idle line detected clear flag"]
pub type IDLECF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, IDLECF_A>;
impl<'a, REG, const O: u8> IDLECF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the IDLE flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(IDLECF_A::Clear)
}
}
#[doc = "Field `TCCF` reader - Transmission complete clear flag"]
pub type TCCF_R = crate::BitReader<TCCF_A>;
#[doc = "Transmission complete clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TCCF_A {
#[doc = "1: Clears the TC flag in the ISR register"]
Clear = 1,
}
impl From<TCCF_A> for bool {
#[inline(always)]
fn from(variant: TCCF_A) -> Self {
variant as u8 != 0
}
}
impl TCCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<TCCF_A> {
match self.bits {
true => Some(TCCF_A::Clear),
_ => None,
}
}
#[doc = "Clears the TC flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == TCCF_A::Clear
}
}
#[doc = "Field `TCCF` writer - Transmission complete clear flag"]
pub type TCCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TCCF_A>;
impl<'a, REG, const O: u8> TCCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the TC flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(TCCF_A::Clear)
}
}
#[doc = "Field `LBDCF` reader - LIN break detection clear flag"]
pub type LBDCF_R = crate::BitReader<LBDCF_A>;
#[doc = "LIN break detection clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LBDCF_A {
#[doc = "1: Clears the LBDF flag in the ISR register"]
Clear = 1,
}
impl From<LBDCF_A> for bool {
#[inline(always)]
fn from(variant: LBDCF_A) -> Self {
variant as u8 != 0
}
}
impl LBDCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<LBDCF_A> {
match self.bits {
true => Some(LBDCF_A::Clear),
_ => None,
}
}
#[doc = "Clears the LBDF flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == LBDCF_A::Clear
}
}
#[doc = "Field `LBDCF` writer - LIN break detection clear flag"]
pub type LBDCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LBDCF_A>;
impl<'a, REG, const O: u8> LBDCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the LBDF flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(LBDCF_A::Clear)
}
}
#[doc = "Field `CTSCF` reader - CTS clear flag"]
pub type CTSCF_R = crate::BitReader<CTSCF_A>;
#[doc = "CTS clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CTSCF_A {
#[doc = "1: Clears the CTSIF flag in the ISR register"]
Clear = 1,
}
impl From<CTSCF_A> for bool {
#[inline(always)]
fn from(variant: CTSCF_A) -> Self {
variant as u8 != 0
}
}
impl CTSCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<CTSCF_A> {
match self.bits {
true => Some(CTSCF_A::Clear),
_ => None,
}
}
#[doc = "Clears the CTSIF flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == CTSCF_A::Clear
}
}
#[doc = "Field `CTSCF` writer - CTS clear flag"]
pub type CTSCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CTSCF_A>;
impl<'a, REG, const O: u8> CTSCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the CTSIF flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(CTSCF_A::Clear)
}
}
#[doc = "Field `RTOCF` reader - Receiver timeout clear flag"]
pub type RTOCF_R = crate::BitReader<RTOCF_A>;
#[doc = "Receiver timeout clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RTOCF_A {
#[doc = "1: Clears the RTOF flag in the ISR register"]
Clear = 1,
}
impl From<RTOCF_A> for bool {
#[inline(always)]
fn from(variant: RTOCF_A) -> Self {
variant as u8 != 0
}
}
impl RTOCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<RTOCF_A> {
match self.bits {
true => Some(RTOCF_A::Clear),
_ => None,
}
}
#[doc = "Clears the RTOF flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == RTOCF_A::Clear
}
}
#[doc = "Field `RTOCF` writer - Receiver timeout clear flag"]
pub type RTOCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RTOCF_A>;
impl<'a, REG, const O: u8> RTOCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the RTOF flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(RTOCF_A::Clear)
}
}
#[doc = "Field `EOBCF` reader - End of timeout clear flag"]
pub type EOBCF_R = crate::BitReader<EOBCF_A>;
#[doc = "End of timeout clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EOBCF_A {
#[doc = "1: Clears the EOBF flag in the ISR register"]
Clear = 1,
}
impl From<EOBCF_A> for bool {
#[inline(always)]
fn from(variant: EOBCF_A) -> Self {
variant as u8 != 0
}
}
impl EOBCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<EOBCF_A> {
match self.bits {
true => Some(EOBCF_A::Clear),
_ => None,
}
}
#[doc = "Clears the EOBF flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == EOBCF_A::Clear
}
}
#[doc = "Field `EOBCF` writer - End of timeout clear flag"]
pub type EOBCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EOBCF_A>;
impl<'a, REG, const O: u8> EOBCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the EOBF flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(EOBCF_A::Clear)
}
}
#[doc = "Field `CMCF` reader - Character match clear flag"]
pub type CMCF_R = crate::BitReader<CMCF_A>;
#[doc = "Character match clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CMCF_A {
#[doc = "1: Clears the CMF flag in the ISR register"]
Clear = 1,
}
impl From<CMCF_A> for bool {
#[inline(always)]
fn from(variant: CMCF_A) -> Self {
variant as u8 != 0
}
}
impl CMCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<CMCF_A> {
match self.bits {
true => Some(CMCF_A::Clear),
_ => None,
}
}
#[doc = "Clears the CMF flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == CMCF_A::Clear
}
}
#[doc = "Field `CMCF` writer - Character match clear flag"]
pub type CMCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CMCF_A>;
impl<'a, REG, const O: u8> CMCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the CMF flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(CMCF_A::Clear)
}
}
#[doc = "Field `WUCF` reader - Wakeup from Stop mode clear flag"]
pub type WUCF_R = crate::BitReader<WUCF_A>;
#[doc = "Wakeup from Stop mode clear flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WUCF_A {
#[doc = "1: Clears the WUF flag in the ISR register"]
Clear = 1,
}
impl From<WUCF_A> for bool {
#[inline(always)]
fn from(variant: WUCF_A) -> Self {
variant as u8 != 0
}
}
impl WUCF_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<WUCF_A> {
match self.bits {
true => Some(WUCF_A::Clear),
_ => None,
}
}
#[doc = "Clears the WUF flag in the ISR register"]
#[inline(always)]
pub fn is_clear(&self) -> bool {
*self == WUCF_A::Clear
}
}
#[doc = "Field `WUCF` writer - Wakeup from Stop mode clear flag"]
pub type WUCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, WUCF_A>;
impl<'a, REG, const O: u8> WUCF_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears the WUF flag in the ISR register"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(WUCF_A::Clear)
}
}
impl R {
#[doc = "Bit 0 - Parity error clear flag"]
#[inline(always)]
pub fn pecf(&self) -> PECF_R {
PECF_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Framing error clear flag"]
#[inline(always)]
pub fn fecf(&self) -> FECF_R {
FECF_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Noise detected clear flag"]
#[inline(always)]
pub fn ncf(&self) -> NCF_R {
NCF_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Overrun error clear flag"]
#[inline(always)]
pub fn orecf(&self) -> ORECF_R {
ORECF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Idle line detected clear flag"]
#[inline(always)]
pub fn idlecf(&self) -> IDLECF_R {
IDLECF_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 6 - Transmission complete clear flag"]
#[inline(always)]
pub fn tccf(&self) -> TCCF_R {
TCCF_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 8 - LIN break detection clear flag"]
#[inline(always)]
pub fn lbdcf(&self) -> LBDCF_R {
LBDCF_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - CTS clear flag"]
#[inline(always)]
pub fn ctscf(&self) -> CTSCF_R {
CTSCF_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 11 - Receiver timeout clear flag"]
#[inline(always)]
pub fn rtocf(&self) -> RTOCF_R {
RTOCF_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - End of timeout clear flag"]
#[inline(always)]
pub fn eobcf(&self) -> EOBCF_R {
EOBCF_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 17 - Character match clear flag"]
#[inline(always)]
pub fn cmcf(&self) -> CMCF_R {
CMCF_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 20 - Wakeup from Stop mode clear flag"]
#[inline(always)]
pub fn wucf(&self) -> WUCF_R {
WUCF_R::new(((self.bits >> 20) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Parity error clear flag"]
#[inline(always)]
#[must_use]
pub fn pecf(&mut self) -> PECF_W<ICR_SPEC, 0> {
PECF_W::new(self)
}
#[doc = "Bit 1 - Framing error clear flag"]
#[inline(always)]
#[must_use]
pub fn fecf(&mut self) -> FECF_W<ICR_SPEC, 1> {
FECF_W::new(self)
}
#[doc = "Bit 2 - Noise detected clear flag"]
#[inline(always)]
#[must_use]
pub fn ncf(&mut self) -> NCF_W<ICR_SPEC, 2> {
NCF_W::new(self)
}
#[doc = "Bit 3 - Overrun error clear flag"]
#[inline(always)]
#[must_use]
pub fn orecf(&mut self) -> ORECF_W<ICR_SPEC, 3> {
ORECF_W::new(self)
}
#[doc = "Bit 4 - Idle line detected clear flag"]
#[inline(always)]
#[must_use]
pub fn idlecf(&mut self) -> IDLECF_W<ICR_SPEC, 4> {
IDLECF_W::new(self)
}
#[doc = "Bit 6 - Transmission complete clear flag"]
#[inline(always)]
#[must_use]
pub fn tccf(&mut self) -> TCCF_W<ICR_SPEC, 6> {
TCCF_W::new(self)
}
#[doc = "Bit 8 - LIN break detection clear flag"]
#[inline(always)]
#[must_use]
pub fn lbdcf(&mut self) -> LBDCF_W<ICR_SPEC, 8> {
LBDCF_W::new(self)
}
#[doc = "Bit 9 - CTS clear flag"]
#[inline(always)]
#[must_use]
pub fn ctscf(&mut self) -> CTSCF_W<ICR_SPEC, 9> {
CTSCF_W::new(self)
}
#[doc = "Bit 11 - Receiver timeout clear flag"]
#[inline(always)]
#[must_use]
pub fn rtocf(&mut self) -> RTOCF_W<ICR_SPEC, 11> {
RTOCF_W::new(self)
}
#[doc = "Bit 12 - End of timeout clear flag"]
#[inline(always)]
#[must_use]
pub fn eobcf(&mut self) -> EOBCF_W<ICR_SPEC, 12> {
EOBCF_W::new(self)
}
#[doc = "Bit 17 - Character match clear flag"]
#[inline(always)]
#[must_use]
pub fn cmcf(&mut self) -> CMCF_W<ICR_SPEC, 17> {
CMCF_W::new(self)
}
#[doc = "Bit 20 - Wakeup from Stop mode clear flag"]
#[inline(always)]
#[must_use]
pub fn wucf(&mut self) -> WUCF_W<ICR_SPEC, 20> {
WUCF_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 = "Interrupt flag clear register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`icr::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 [`icr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ICR_SPEC;
impl crate::RegisterSpec for ICR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`icr::R`](R) reader structure"]
impl crate::Readable for ICR_SPEC {}
#[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;
}
|
/// Context:
/// * Rust does not have tail call optimization, so we cannot recurse wildly
/// * data lifetimes makes sure that the result of a function applied to a producer cannot live longer than the producer's data (unless there is cloning)
/// * previous implementation of Producer and Consumer spent its time copying buffers
/// * the old Consumer was handling everything and buffering data. The new design has the producer handle data, but the consumer makes seeking decision
use std::io::{self,Read,Seek,SeekFrom};
use std::fs::File;
use std::path::Path;
use std::ptr;
use std::iter::repeat;
use internal::Needed;
//pub type Computation<I,O,S,E> = Box<Fn(S, Input<I>) -> (I,Consumer<I,O,S,E>)>;
#[derive(Debug,Clone)]
pub enum Input<I> {
Element(I),
Empty,
Eof(Option<I>)
}
/// Stores a consumer's current computation state
#[derive(Debug,Clone)]
pub enum ConsumerState<O,E=(),M=()> {
/// A value pf type O has been produced
Done(M,O),
/// An error of type E has been encountered
Error(E),
/// Continue applying, and pass a message of type M to the data source
Continue(M)
}
impl<O:Clone,E:Copy,M:Copy> ConsumerState<O,E,M> {
pub fn map<P,F>(&self, f: F) -> ConsumerState<P,E,M> where F: FnOnce(O) -> P {
match *self {
ConsumerState::Error(e) => ConsumerState::Error(e),
ConsumerState::Continue(m) => ConsumerState::Continue(m),
ConsumerState::Done(m, ref o) => ConsumerState::Done(m, f(o.clone()))
}
}
pub fn flat_map<P,F>(&self, f: F) -> ConsumerState<P,E,M> where F: FnOnce(M, O) -> ConsumerState<P,E,M> {
match *self {
ConsumerState::Error(e) => ConsumerState::Error(e),
ConsumerState::Continue(m) => ConsumerState::Continue(m),
ConsumerState::Done(m, ref o) => f(m, o.clone())
}
}
}
/// The Consumer trait wraps a computation and its state
///
/// it depends on the input type I, the produced value's type O, the error type E, and the message type M
pub trait Consumer<I,O,E,M> {
/// implement hndle for the current computation, returning the new state of the consumer
fn handle(&mut self, input: Input<I>) -> &ConsumerState<O,E,M>;
/// returns the current state
fn state(&self) -> &ConsumerState<O,E,M>;
}
/// The producer wraps a data source, like file or network, and applies a consumer on it
///
/// it handles buffer copying and reallocation, to provide streaming patterns.
/// it depends on the input type I, and the message type M.
/// the consumer can change the way data is produced (for example, to seek in the source) by sending a message of type M.
pub trait Producer<'b,I,M: 'b> {
/// Applies a consumer once on the produced data, and return the consumer's state
///
/// a new producer has to implement this method
fn apply<'a, O,E>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> &'a ConsumerState<O,E,M>;
/// Applies a consumer once on the produced data, and returns the generated value if there is one
fn run<'a: 'b,O,E: 'b>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> Option<&O> {
if let &ConsumerState::Done(_,ref o) = self.apply(consumer) {
Some(o)
} else {
None
}
}
// fn fromFile, FromSocket, fromRead
}
/// ProducerRepeat takes a single value, and generates it at each step
pub struct ProducerRepeat<I:Copy> {
value: I
}
impl<'b,I:Copy,M: 'b> Producer<'b,I,M> for ProducerRepeat<I> {
fn apply<'a,O,E>(&'b mut self, consumer: &'a mut Consumer<I,O,E,M>) -> &'a ConsumerState<O,E,M> {
if {
if let &ConsumerState::Continue(_) = consumer.state() {
true
} else {
false
}
}
{
consumer.handle(Input::Element(self.value))
} else {
consumer.state()
}
}
}
/// A MemProducer generates values from an in memory byte buffer
///
/// it generates data by chunks, and keeps track of how much was consumed.
/// It can receive messages of type `Move` to handle consumption and seeking
pub struct MemProducer<'x> {
buffer: &'x [u8],
chunk_size: usize,
length: usize,
index: usize
}
impl<'x> MemProducer<'x> {
pub fn new(buffer: &'x[u8], chunk_size: usize) -> MemProducer {
MemProducer {
buffer: buffer,
chunk_size: chunk_size,
length: buffer.len(),
index: 0
}
}
}
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
pub enum Move {
/// indcates how much data was consumed
Consume(usize),
/// indicates where in the input the consumer must seek
Seek(SeekFrom),
/// indicates more data is needed
Await(Needed)
}
impl<'x,'b> Producer<'b,&'x[u8],Move> for MemProducer<'x> {
fn apply<'a,O,E>(&'b mut self, consumer: &'a mut Consumer<&'x[u8],O,E,Move>) -> &'a ConsumerState<O,E,Move> {
if {
if let &ConsumerState::Continue(ref m) = consumer.state() {
match *m {
Move::Consume(s) => {
if self.length - self.index >= s {
self.index += s
} else {
panic!("cannot consume past the end of the buffer");
}
},
Move::Await(a) => {
panic!("not handled for now: await({:?}", a);
}
Move::Seek(SeekFrom::Start(position)) => {
if position as usize > self.length {
self.index = self.length
} else {
self.index = position as usize
}
},
Move::Seek(SeekFrom::Current(offset)) => {
let next = if offset >= 0 {
(self.index as u64).checked_add(offset as u64)
} else {
(self.index as u64).checked_sub(-offset as u64)
};
match next {
None => None,
Some(u) => {
if u as usize > self.length {
self.index = self.length
} else {
self.index = u as usize
}
Some(self.index as u64)
}
};
},
Move::Seek(SeekFrom::End(i)) => {
let next = if i < 0 {
(self.length as u64).checked_sub(-i as u64)
} else {
// std::io::SeekFrom documentation explicitly allows
// seeking beyond the end of the stream, so we seek
// to the end of the content if the offset is 0 or
// greater.
Some(self.length as u64)
};
match next {
// std::io:SeekFrom documentation states that it `is an
// error to seek before byte 0.' So it's the sensible
// thing to refuse to seek on underflow.
None => None,
Some(u) => {
self.index = u as usize;
Some(u)
}
};
}
}
true
} else {
false
}
}
{
use std::cmp;
let end = cmp::min(self.index + self.chunk_size, self.length);
consumer.handle(Input::Element(&self.buffer[self.index..end]))
} else {
consumer.state()
}
}
}
#[derive(Debug,Copy,Clone,PartialEq,Eq)]
pub enum FileProducerState {
Normal,
Error,
Eof
}
#[derive(Debug)]
pub struct FileProducer {
size: usize,
file: File,
position: usize,
v: Vec<u8>,
start: usize,
end: usize,
state: FileProducerState,
}
impl FileProducer {
pub fn new(filename: &str, buffer_size: usize) -> io::Result<FileProducer> {
File::open(&Path::new(filename)).and_then(|mut f| {
f.seek(SeekFrom::Start(0)).map(|_| {
let mut v = Vec::with_capacity(buffer_size);
v.extend(repeat(0).take(buffer_size));
FileProducer {size: buffer_size, file: f, position: 0, v: v, start: 0, end: 0, state: FileProducerState::Normal }
})
})
}
pub fn state(&self) -> FileProducerState {
self.state
}
// FIXME: should handle refill until a certain size is obtained
pub fn refill(&mut self) -> Option<usize> {
shift(&mut self.v, self.start, self.end);
self.end = self.end - self.start;
self.start = 0;
match self.file.read(&mut self.v[self.end..]) {
Err(_) => {
self.state = FileProducerState::Error;
None
},
Ok(n) => {
//println!("read: {} bytes\ndata:\n{:?}", n, &self.v);
if n == 0 {
self.state = FileProducerState::Eof;
}
self.end += n;
Some(0)
}
}
}
/// Resize the internal buffer, copy the data to the new one and returned how much data was copied
///
/// If the new buffer is smaller, the prefix will be copied, and the rest of the data will be dropped
pub fn resize(&mut self, s: usize) -> usize {
let mut v = Vec::with_capacity(s);
let length = self.end - self.start;
v.extend(repeat(0).take(s));
let size = if length <= s { length } else { s };
unsafe {
let slice_ptr = (&self.v[self.start..self.end]).as_ptr();
ptr::copy(slice_ptr, v.as_mut_ptr(), size);
}
self.v = v;
self.start = 0;
self.end = size;
size
}
}
pub fn shift(s: &mut[u8], start: usize, end: usize) {
if start > 0 {
unsafe {
let length = end - start;
ptr::copy( (&s[start..end]).as_ptr(), (&mut s[..length]).as_mut_ptr(), length);
}
}
}
impl<'x> Producer<'x,&'x [u8],Move> for FileProducer {
fn apply<'a,O,E>(&'x mut self, consumer: &'a mut Consumer<&'x[u8],O,E,Move>) -> &'a ConsumerState<O,E,Move> {
//consumer.handle(Input::Element(&self.v[self.start..self.end]))
//self.my_apply(consumer)
if {
if let &ConsumerState::Continue(ref m) = consumer.state() {
match *m {
Move::Consume(s) => {
//println!("start: {}, end: {}, consumed: {}", self.start, self.end, s);
if self.end - self.start >= s {
self.start = self.start + s;
self.position = self.position + s;
} else {
panic!("cannot consume past the end of the buffer");
}
if self.start == self.end {
self.refill();
}
},
Move::Await(_) => {
self.refill();
},
// FIXME: naive seeking for now
Move::Seek(position) => {
let pos = match position {
// take into account data in the buffer
SeekFrom::Current(c) => SeekFrom::Current(c - (self.end - self.start) as i64),
default => default
};
match self.file.seek(pos) {
Ok(pos) => {
//println!("file got seek to position {:?}. New position is {:?}", position, next);
self.position = pos as usize;
self.start = 0;
self.end = 0;
self.refill();
},
Err(_) => {
self.state = FileProducerState::Error;
}
}
}
}
true
} else {
false
}
}
{
//println!("producer state: {:?}", self.state);
match self.state {
FileProducerState::Normal => consumer.handle(Input::Element(&self.v[self.start..self.end])),
FileProducerState::Eof => {
let slice = &self.v[self.start..self.end];
if slice.is_empty() {
consumer.handle(Input::Eof(None))
} else {
consumer.handle(Input::Eof(Some(slice)))
}
}
// is it right?
FileProducerState::Error => consumer.state()
}
} else {
consumer.state()
}
}
}
use std::marker::PhantomData;
/// MapConsumer takes a function S -> T and applies it on a consumer producing values of type S
pub struct MapConsumer<'a, C:'a,R,S,T,E,M,F> {
state: ConsumerState<T,E,M>,
consumer: &'a mut C,
f: F,
consumer_input_type: PhantomData<R>,
f_input_type: PhantomData<S>,
f_output_type: PhantomData<T>
}
impl<'a,R,S:Clone,T,E:Clone,M:Clone,F:Fn(S) -> T,C:Consumer<R,S,E,M>> MapConsumer<'a,C,R,S,T,E,M,F> {
pub fn new(c: &'a mut C, f: F) -> MapConsumer<'a,C,R,S,T,E,M,F> {
//let state = c.state();
let initial = match *c.state() {
ConsumerState::Done(ref m, ref o) => ConsumerState::Done(m.clone(), f(o.clone())),
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone())
};
MapConsumer {
state: initial,
consumer: c,
f: f,
consumer_input_type: PhantomData,
f_input_type: PhantomData,
f_output_type: PhantomData
}
}
}
impl<'a,R,S:Clone,T,E:Clone,M:Clone,F:Fn(S) -> T,C:Consumer<R,S,E,M>> Consumer<R,T,E,M> for MapConsumer<'a,C,R,S,T,E,M,F> {
fn handle(&mut self, input: Input<R>) -> &ConsumerState<T,E,M> {
let res:&ConsumerState<S,E,M> = self.consumer.handle(input);
self.state = match res {
&ConsumerState::Done(ref m, ref o) => ConsumerState::Done(m.clone(), (self.f)(o.clone())),
&ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
&ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone())
};
&self.state
}
fn state(&self) -> &ConsumerState<T,E,M> {
&self.state
}
}
/// ChainConsumer takes a consumer C1 R -> S, and a consumer C2 S -> T, and makes a consumer R -> T by applying C2 on C1's result
pub struct ChainConsumer<'a,'b, C1:'a,C2:'b,R,S,T,E,M> {
state: ConsumerState<T,E,M>,
consumer1: &'a mut C1,
consumer2: &'b mut C2,
input_type: PhantomData<R>,
temp_type: PhantomData<S>
}
impl<'a,'b,R,S:Clone,T:Clone,E:Clone,M:Clone,C1:Consumer<R,S,E,M>, C2:Consumer<S,T,E,M>> ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
pub fn new(c1: &'a mut C1, c2: &'b mut C2) -> ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
let initial = match *c1.state() {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(ref m, ref o) => match *c2.handle(Input::Element(o.clone())) {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m2) => ConsumerState::Continue(m2.clone()),
ConsumerState::Done(_,ref o2) => ConsumerState::Done(m.clone(), o2.clone())
}
};
ChainConsumer {
state: initial,
consumer1: c1,
consumer2: c2,
input_type: PhantomData,
temp_type: PhantomData
}
}
}
impl<'a,'b,R,S:Clone,T:Clone,E:Clone,M:Clone,C1:Consumer<R,S,E,M>, C2:Consumer<S,T,E,M>> Consumer<R,T,E,M> for ChainConsumer<'a,'b,C1,C2,R,S,T,E,M> {
fn handle(&mut self, input: Input<R>) -> &ConsumerState<T,E,M> {
let res:&ConsumerState<S,E,M> = self.consumer1.handle(input);
self.state = match *res {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(ref m, ref o) => match *self.consumer2.handle(Input::Element(o.clone())) {
ConsumerState::Error(ref e) => ConsumerState::Error(e.clone()),
ConsumerState::Continue(ref m) => ConsumerState::Continue(m.clone()),
ConsumerState::Done(_, ref o2) => ConsumerState::Done(m.clone(), o2.clone())
}
};
&self.state
}
fn state(&self) -> &ConsumerState<T,E,M> {
&self.state
}
}
#[macro_export]
macro_rules! consumer_from_parser (
//FIXME: should specify the error and move type
($name:ident<$input:ty, $output:ty>, $submac:ident!( $($args:tt)* )) => (
#[derive(Debug)]
struct $name {
state: $crate::ConsumerState<$output, (), $crate::Move>
}
impl $name {
fn new() -> $name {
$name { state: $crate::ConsumerState::Continue($crate::Move::Consume(0)) }
}
}
impl $crate::Consumer<$input, $output, (), $crate::Move> for $name {
fn handle(&mut self, input: $crate::Input<$input>) -> & $crate::ConsumerState<$output, (), $crate::Move> {
use $crate::HexDisplay;
match input {
$crate::Input::Empty | $crate::Input::Eof(None) => &self.state,
$crate::Input::Element(sl) | $crate::Input::Eof(Some(sl)) => {
self.state = match $submac!(sl, $($args)*) {
$crate::IResult::Incomplete(n) => {
$crate::ConsumerState::Continue($crate::Move::Await(n))
},
$crate::IResult::Error(_) => {
$crate::ConsumerState::Error(())
},
$crate::IResult::Done(i,o) => {
$crate::ConsumerState::Done($crate::Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &$crate::ConsumerState<$output, (), $crate::Move> {
&self.state
}
}
);
($name:ident<$output:ty>, $submac:ident!( $($args:tt)* )) => (
#[derive(Debug)]
struct $name {
state: $crate::ConsumerState<$output, (), $crate::Move>
}
impl $name {
fn new() -> $name {
$name { state: $crate::ConsumerState::Continue($crate::Move::Consume(0)) }
}
}
impl<'a> $crate::Consumer<&'a[u8], $output, (), $crate::Move> for $name {
fn handle(&mut self, input: $crate::Input<&'a[u8]>) -> & $crate::ConsumerState<$output, (), $crate::Move> {
use $crate::HexDisplay;
match input {
$crate::Input::Empty | $crate::Input::Eof(None) => &self.state,
$crate::Input::Element(sl) | $crate::Input::Eof(Some(sl)) => {
self.state = match $submac!(sl, $($args)*) {
$crate::IResult::Incomplete(n) => {
$crate::ConsumerState::Continue($crate::Move::Await(n))
},
$crate::IResult::Error(_) => {
$crate::ConsumerState::Error(())
},
$crate::IResult::Done(i,o) => {
$crate::ConsumerState::Done($crate::Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &$crate::ConsumerState<$output, (), $crate::Move> {
&self.state
}
}
);
($name:ident<$input:ty, $output:ty>, $f:expr) => (
consumer_from_parser!($name<$input, $output>, call!($f));
);
($name:ident<$output:ty>, $f:expr) => (
consumer_from_parser!($name<$output>, call!($f));
);
);
#[cfg(test)]
mod tests {
use super::*;
use internal::IResult;
use util::HexDisplay;
use std::str::from_utf8;
use std::io::SeekFrom;
#[derive(Debug)]
struct AbcdConsumer<'a> {
state: ConsumerState<&'a [u8], (), Move>
}
named!(abcd, tag!("abcd"));
impl<'a> Consumer<&'a [u8], &'a [u8], (), Move> for AbcdConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a [u8],(),Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) => {
match abcd(sl) {
IResult::Error(_) => {
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,o) => {
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)),o)
}
};
&self.state
}
Input::Eof(Some(sl)) => {
match abcd(sl) {
IResult::Error(_) => {
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
// we cannot return incomplete on Eof
self.state = ConsumerState::Error(())
},
IResult::Done(i,o) => {
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)), o)
}
};
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a [u8], (), Move> {
&self.state
}
}
#[test]
fn mem() {
let mut m = MemProducer::new(&b"abcdabcdabcdabcdabcd"[..], 8);
let mut a = AbcdConsumer { state: ConsumerState::Continue(Move::Consume(0)) };
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
}
named!(efgh, tag!("efgh"));
named!(ijkl, tag!("ijkl"));
#[derive(Debug)]
enum State {
Initial,
A,
B,
End,
Error
}
#[derive(Debug)]
struct StateConsumer<'a> {
state: ConsumerState<&'a [u8], (), Move>,
parsing_state: State
}
impl<'a> Consumer<&'a [u8], &'a [u8], (), Move> for StateConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a [u8], (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) => {
match self.parsing_state {
State::Initial => match abcd(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,_) => {
self.parsing_state = State::A;
self.state = ConsumerState::Continue(Move::Consume(sl.offset(i)))
}
},
State::A => match efgh(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,_) => {
self.parsing_state = State::B;
self.state = ConsumerState::Continue(Move::Consume(sl.offset(i)))
}
},
State::B => match ijkl(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.state = ConsumerState::Continue(Move::Consume(0))
},
IResult::Done(i,o) => {
self.parsing_state = State::End;
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)),o)
}
},
_ => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
}
}
&self.state
}
Input::Eof(Some(sl)) => {
match self.parsing_state {
State::Initial => match abcd(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(_,_) => {
self.parsing_state = State::A;
self.state = ConsumerState::Error(())
}
},
State::A => match efgh(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(_,_) => {
self.parsing_state = State::B;
self.state = ConsumerState::Error(())
}
},
State::B => match ijkl(sl) {
IResult::Error(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Incomplete(_) => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
},
IResult::Done(i,o) => {
self.parsing_state = State::End;
self.state = ConsumerState::Done(Move::Consume(sl.offset(i)), o)
}
},
_ => {
self.parsing_state = State::Error;
self.state = ConsumerState::Error(())
}
}
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a [u8], (), Move> {
&self.state
}
}
impl<'a> StateConsumer<'a> {
fn parsing(&self) -> &State {
&self.parsing_state
}
}
#[test]
fn mem2() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut a = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
println!("apply {:?}", m.apply(&mut a));
println!("state {:?}", a.parsing());
//assert!(false);
}
#[test]
fn map() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut s = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
let mut a = MapConsumer::new(&mut s, from_utf8);
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
}
#[derive(Debug)]
struct StrConsumer<'a> {
state: ConsumerState<&'a str, (), Move>
}
impl<'a> Consumer<&'a [u8], &'a str, (), Move> for StrConsumer<'a> {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<&'a str, (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) | Input::Eof(Some(sl)) => {
self.state = ConsumerState::Done(Move::Consume(sl.len()), from_utf8(sl).unwrap());
&self.state
}
}
}
fn state(&self) -> &ConsumerState<&'a str, (), Move> {
&self.state
}
}
#[test]
fn chain() {
let mut m = MemProducer::new(&b"abcdefghijklabcdabcd"[..], 8);
let mut s1 = StateConsumer { state: ConsumerState::Continue(Move::Consume(0)), parsing_state: State::Initial };
let mut s2 = StrConsumer { state: ConsumerState::Continue(Move::Consume(0)) };
let mut a = ChainConsumer::new(&mut s1, &mut s2);
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
println!("apply {:?}", m.apply(&mut a));
//assert!(false);
//
//let x = [0, 1, 2, 3, 4];
//let b = [1, 2, 3];
//assert_eq!(&x[1..3], &b[..]);
}
#[test]
fn shift_test() {
let mut v = vec![0,1,2,3,4,5];
shift(&mut v, 1, 3);
assert_eq!(&v[..2], &[1,2][..]);
let mut v2 = vec![0,1,2,3,4,5];
shift(&mut v2, 2, 6);
assert_eq!(&v2[..4], &[2,3,4,5][..]);
}
/*#[derive(Debug)]
struct LineConsumer {
state: ConsumerState<String, (), Move>
}
impl<'a> Consumer<&'a [u8], String, (), Move> for LineConsumer {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<String, (), Move> {
match input {
Input::Empty | Input::Eof(None) => &self.state,
Input::Element(sl) | Input::Eof(Some(sl)) => {
//println!("got slice: {:?}", sl);
self.state = match line(sl) {
IResult::Incomplete(n) => {
println!("line not complete, continue (line was \"{}\")", from_utf8(sl).unwrap());
ConsumerState::Continue(Move::Await(n))
},
IResult::Error(e) => {
println!("LineConsumer parsing error: {:?}", e);
ConsumerState::Error(())
},
IResult::Done(i,o) => {
let res = String::from(from_utf8(o).unwrap());
println!("found: {}", res);
//println!("sl: {:?}\ni:{:?}\noffset:{}", sl, i, sl.offset(i));
ConsumerState::Done(Move::Consume(sl.offset(i)), res)
}
};
&self.state
}
}
}
fn state(&self) -> &ConsumerState<String, (), Move> {
&self.state
}
}*/
fn lf(i:& u8) -> bool {
*i == '\n' as u8
}
fn to_utf8_string(input:&[u8]) -> String {
String::from(from_utf8(input).unwrap())
}
//named!(line<&[u8]>, terminated!(take_till!(lf), tag!("\n")));
consumer_from_parser!(LineConsumer<String>, map!(terminated!(take_till!(lf), tag!("\n")), to_utf8_string));
fn get_line(producer: &mut FileProducer, mv: Move) -> Option<(Move,String)> {
let mut a = LineConsumer { state: ConsumerState::Continue(mv) };
while let &ConsumerState::Continue(_) = producer.apply(&mut a) {
println!("continue");
}
if let &ConsumerState::Done(ref m, ref s) = a.state() {
Some((m.clone(), s.clone()))
} else {
None
}
}
#[test]
fn file() {
let mut f = FileProducer::new("LICENSE", 200).unwrap();
f.refill();
let mut mv = Move::Consume(0);
for i in 1..10 {
if let Some((m,s)) = get_line(&mut f, mv.clone()) {
println!("got line[{}]: {}", i, s);
mv = m;
} else {
assert!(false, "LineConsumer should not have failed");
}
}
//assert!(false);
}
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
enum SeekState {
Begin,
SeekedToEnd,
ShouldEof,
IsEof
}
#[derive(Debug)]
struct SeekingConsumer {
state: ConsumerState<(), u8, Move>,
position: SeekState
}
impl SeekingConsumer {
fn position(&self) -> SeekState {
self.position
}
}
impl<'a> Consumer<&'a [u8], (), u8, Move> for SeekingConsumer {
fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<(), u8, Move> {
println!("input: {:?}", input);
match self.position {
SeekState::Begin => {
self.state = ConsumerState::Continue(Move::Seek(SeekFrom::End(-4)));
self.position = SeekState::SeekedToEnd;
},
SeekState::SeekedToEnd => match input {
Input::Element(sl) => {
if sl.len() == 4 {
self.state = ConsumerState::Continue(Move::Consume(4));
self.position = SeekState::ShouldEof;
} else {
self.state = ConsumerState::Error(0);
}
},
Input::Eof(Some(sl)) => {
if sl.len() == 4 {
self.state = ConsumerState::Done(Move::Consume(4), ());
self.position = SeekState::IsEof;
} else {
self.state = ConsumerState::Error(1);
}
},
_ => self.state = ConsumerState::Error(2)
},
SeekState::ShouldEof => match input {
Input::Eof(Some(sl)) => {
if sl.len() == 0 {
self.state = ConsumerState::Done(Move::Consume(0), ());
self.position = SeekState::IsEof;
} else {
self.state = ConsumerState::Error(3);
}
},
Input::Eof(None) => {
self.state = ConsumerState::Done(Move::Consume(0), ());
self.position = SeekState::IsEof;
},
_ => self.state = ConsumerState::Error(4)
},
_ => self.state = ConsumerState::Error(5)
};
&self.state
}
fn state(&self) -> &ConsumerState<(), u8, Move> {
&self.state
}
}
#[test]
fn seeking_consumer() {
let mut f = FileProducer::new("assets/testfile.txt", 200).unwrap();
f.refill();
let mut a = SeekingConsumer { state: ConsumerState::Continue(Move::Consume(0)), position: SeekState::Begin };
for _ in 1..4 {
println!("file apply {:?}", f.apply(&mut a));
}
println!("consumer is now: {:?}", a);
if let &ConsumerState::Done(Move::Consume(0), ()) = a.state() {
println!("end");
} else {
println!("invalid state is {:?}", a.state());
assert!(false, "consumer is not at EOF");
}
assert_eq!(a.position(), SeekState::IsEof);
}
}
|
use crate::types::*;
use nalgebra_glm as glm;
// based on #6 Intro to Modern OpenGL Tutorial: Camera and Perspective
// by thebennybox, https://www.youtube.com/watch?v=e3sc72ZDDpo
impl Camera {
pub fn new(pos: V3, fov: f32, aspect: f32, z_near: f32, z_far: f32) -> Camera {
Camera { pos,
fov,
aspect,
z_near,
z_far,
perspective: glm::perspective(aspect, fov, z_near, z_far),
forward: V3::new(0.0, 0.0, 1.0),
up: V3::new(0.0, 1.0, 0.0) }
}
pub fn default() -> Camera {
let fov = std::f32::consts::PI / 2.0;
let z_near = 1.0; // if this is zero, then mouse picking will not work.
Camera::new(V3::new(0f32, 0f32, -10f32), fov, 1.0, z_near, 1000.0)
}
pub fn update_aspect(&mut self, w: f64, h: f64) {
if h <= EPSILON64 {
return;
}
self.aspect = (w / h) as f32;
self.perspective = glm::perspective(self.aspect, self.fov, self.z_near, self.z_far);
}
pub fn zoom_out(&mut self) {
if self.pos.z < -160.0 {
return;
}
self.pos.z *= 1.125;
}
pub fn zoom_in(&mut self) {
if self.pos.z >= -self.z_near * 1.125 {
return;
}
self.pos.z /= 1.125;
}
#[inline(always)]
fn zoom_factor(&self) -> f32 {
-self.pos.z * 0.1357 // four odd numbers in a row. (this is arbitrary)
}
pub fn pan_right(&mut self) {
self.pos.x += self.zoom_factor();
}
pub fn pan_left(&mut self) {
self.pos.x -= self.zoom_factor();
}
pub fn pan_up(&mut self) {
self.pos.y += self.zoom_factor();
}
pub fn pan_down(&mut self) {
self.pos.y -= self.zoom_factor();
}
pub fn center(&mut self) {
self.pos.y = 0.0;
self.pos.x = 0.0;
}
pub fn view_matrix(&self) -> glm::Mat4 {
glm::look_at(&self.pos, &(self.pos + self.forward), &self.up)
}
pub fn projection_matrix(&self) -> glm::Mat4 {
self.perspective
}
pub fn get_view_projection(&self) -> glm::Mat4 {
(self.perspective * self.view_matrix())
}
}
|
#[doc = "Clock divisor register for state machine 0\\n Frequency = clock freq / (CLKDIV_INT + CLKDIV_FRAC / 256)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sm_clkdiv](sm_clkdiv) module"]
pub type SM_CLKDIV = crate::Reg<u32, _SM_CLKDIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SM_CLKDIV;
#[doc = "`read()` method returns [sm_clkdiv::R](sm_clkdiv::R) reader structure"]
impl crate::Readable for SM_CLKDIV {}
#[doc = "`write(|w| ..)` method takes [sm_clkdiv::W](sm_clkdiv::W) writer structure"]
impl crate::Writable for SM_CLKDIV {}
#[doc = "Clock divisor register for state machine 0\\n Frequency = clock freq / (CLKDIV_INT + CLKDIV_FRAC / 256)"]
pub mod sm_clkdiv;
#[doc = "Execution/behavioural settings for state machine 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sm_execctrl](sm_execctrl) module"]
pub type SM_EXECCTRL = crate::Reg<u32, _SM_EXECCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SM_EXECCTRL;
#[doc = "`read()` method returns [sm_execctrl::R](sm_execctrl::R) reader structure"]
impl crate::Readable for SM_EXECCTRL {}
#[doc = "`write(|w| ..)` method takes [sm_execctrl::W](sm_execctrl::W) writer structure"]
impl crate::Writable for SM_EXECCTRL {}
#[doc = "Execution/behavioural settings for state machine 0"]
pub mod sm_execctrl;
#[doc = "Control behaviour of the input/output shift registers for state machine 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sm_shiftctrl](sm_shiftctrl) module"]
pub type SM_SHIFTCTRL = crate::Reg<u32, _SM_SHIFTCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SM_SHIFTCTRL;
#[doc = "`read()` method returns [sm_shiftctrl::R](sm_shiftctrl::R) reader structure"]
impl crate::Readable for SM_SHIFTCTRL {}
#[doc = "`write(|w| ..)` method takes [sm_shiftctrl::W](sm_shiftctrl::W) writer structure"]
impl crate::Writable for SM_SHIFTCTRL {}
#[doc = "Control behaviour of the input/output shift registers for state machine 0"]
pub mod sm_shiftctrl;
#[doc = "Current instruction address of state machine 0\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sm_addr](sm_addr) module"]
pub type SM_ADDR = crate::Reg<u32, _SM_ADDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SM_ADDR;
#[doc = "`read()` method returns [sm_addr::R](sm_addr::R) reader structure"]
impl crate::Readable for SM_ADDR {}
#[doc = "Current instruction address of state machine 0"]
pub mod sm_addr;
#[doc = "Read to see the instruction currently addressed by state machine 0's program counter\\n Write to execute an instruction immediately (including jumps) and then resume execution.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sm_instr](sm_instr) module"]
pub type SM_INSTR = crate::Reg<u32, _SM_INSTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SM_INSTR;
#[doc = "`read()` method returns [sm_instr::R](sm_instr::R) reader structure"]
impl crate::Readable for SM_INSTR {}
#[doc = "`write(|w| ..)` method takes [sm_instr::W](sm_instr::W) writer structure"]
impl crate::Writable for SM_INSTR {}
#[doc = "Read to see the instruction currently addressed by state machine 0's program counter\\n Write to execute an instruction immediately (including jumps) and then resume execution."]
pub mod sm_instr;
#[doc = "State machine pin control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sm_pinctrl](sm_pinctrl) module"]
pub type SM_PINCTRL = crate::Reg<u32, _SM_PINCTRL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SM_PINCTRL;
#[doc = "`read()` method returns [sm_pinctrl::R](sm_pinctrl::R) reader structure"]
impl crate::Readable for SM_PINCTRL {}
#[doc = "`write(|w| ..)` method takes [sm_pinctrl::W](sm_pinctrl::W) writer structure"]
impl crate::Writable for SM_PINCTRL {}
#[doc = "State machine pin control"]
pub mod sm_pinctrl;
|
pub mod async_test;
fn main() {
async_test::async_test();
} |
use super::message::MessageEntity;
use crate::{
repository::{GetEntityFuture, Repository},
utils, Backend, Entity,
};
use twilight_model::{
channel::Attachment,
id::{AttachmentId, MessageId},
};
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttachmentEntity {
pub filename: String,
pub height: Option<u64>,
pub id: AttachmentId,
pub message_id: MessageId,
pub proxy_url: String,
pub size: u64,
pub url: String,
pub width: Option<u64>,
}
impl From<(MessageId, Attachment)> for AttachmentEntity {
fn from((message_id, attachment): (MessageId, Attachment)) -> Self {
Self {
filename: attachment.filename,
height: attachment.height,
id: attachment.id,
message_id,
proxy_url: attachment.proxy_url,
size: attachment.size,
url: attachment.url,
width: attachment.width,
}
}
}
impl Entity for AttachmentEntity {
type Id = AttachmentId;
/// Return the attachment's ID.
fn id(&self) -> Self::Id {
self.id
}
}
pub trait AttachmentRepository<B: Backend>: Repository<AttachmentEntity, B> + Send {
fn message(&self, attachment_id: AttachmentId) -> GetEntityFuture<'_, MessageEntity, B::Error> {
utils::relation_map(
self.backend().attachments(),
self.backend().messages(),
attachment_id,
|attachment| attachment.message_id,
)
}
}
|
pub fn make_hey(name: &str) -> String {
format!("Hey {} !!!", name)
}
pub fn make_bye(name: &str) -> String {
format!("Bye {} !!!", name)
} |
use crate::{
db::HirDatabase,
expressions::{
AscriptionExprData, AssignmentData, BlockExprData, CallExprData, ExpressionData,
FieldExprData, IfExprData, LiteralData, LiteralKind, MatchExprData, RecordExprData,
StatementData,
},
ids::{
AscriptionExpr, Assignment, BlockExpr, CallExpr, Expression, FieldExpr, Identifier, IfExpr,
Literal, MatchExpr, Pattern, RecordExpr, Statement, Type,
},
lower::{
error::{LoweringError, Missing},
Lower, LoweringCtx,
},
};
use christmas_tree::RootOwnership;
use either::Either;
use valis_ds::Intern;
use valis_syntax::{
ast::{self, AstToken, NameRefOwner, PatternOwner},
syntax::SyntaxTree,
};
impl<R: RootOwnership<SyntaxTree>> Lower<ast::ExprRaw<R>> for Expression {
fn lower<'a, DB: HirDatabase>(
syntax: ast::ExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
use ast::ExprRawKind;
use ExpressionData as ExprData;
let expr_data = match syntax.kind() {
ExprRawKind::TupleExpr(inner) => ExprData::Record(RecordExpr::lower(inner, ctx)?),
ExprRawKind::StructExpr(inner) => ExprData::Record(RecordExpr::lower(inner, ctx)?),
ExprRawKind::VarExpr(inner) => ExprData::Variable(Identifier::lower(inner, ctx)?),
ExprRawKind::IfExpr(inner) => ExprData::If(IfExpr::lower(inner, ctx)?),
ExprRawKind::MatchExpr(inner) => ExprData::Match(MatchExpr::lower(inner, ctx)?),
ExprRawKind::CallExpr(inner) => ExprData::Call(CallExpr::lower(inner, ctx)?),
ExprRawKind::FieldExpr(inner) => ExprData::Field(FieldExpr::lower(inner, ctx)?),
ExprRawKind::AscriptionExpr(inner) => {
ExprData::Ascription(AscriptionExpr::lower(inner, ctx)?)
},
ExprRawKind::BlockExpr(inner) => ExprData::Block(BlockExpr::lower(inner, ctx)?),
ExprRawKind::Literal(inner) => ExprData::Literal(Literal::lower(inner, ctx)?),
};
Ok(expr_data.intern(ctx.tables()))
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::IfExprRaw<R>> for IfExpr {
fn lower<'a, DB: HirDatabase>(
syntax: ast::IfExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
use Either::*;
let condition_syn = syntax.condition().ok_or(LoweringError {
kind: Missing::IfConditionExpr.into(),
})?;
let condition = Expression::lower(condition_syn, ctx)?;
let then_block_syn = syntax.then_block().ok_or(LoweringError {
kind: Missing::IfThenBlockExpr.into(),
})?;
let then_block = BlockExpr::lower(then_block_syn, ctx)?;
let else_block = if let Some(else_block_syn) = syntax.else_block() {
let else_block = BlockExpr::lower(else_block_syn, ctx)?;
Some(Left(else_block))
} else if let Some(else_if_syn) = syntax.else_if() {
let else_if = IfExpr::lower(else_if_syn, ctx)?;
Some(Right(else_if))
} else {
None
};
let if_expr = IfExprData {
condition,
then_block,
else_block,
}
.intern(ctx.tables());
Ok(if_expr)
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::CallExprRaw<R>> for CallExpr {
fn lower<'a, DB: HirDatabase>(
syntax: ast::CallExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let callable_syn = syntax.inner_expr().ok_or(LoweringError {
kind: Missing::CallTarget.into(),
})?;
let callable = Expression::lower(callable_syn, ctx)?;
let arg_list_syn = syntax.arg_list().ok_or(LoweringError {
kind: Missing::ArgList.into(),
})?;
let arguments = arg_list_syn
.args()
.map(|arg_syn| Expression::lower(arg_syn, ctx))
.collect::<Result<Vec<_>, _>>()?;
let call_expr = CallExprData {
callable,
arguments,
}
.intern(ctx.tables());
Ok(call_expr)
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::FieldExprRaw<R>> for FieldExpr {
fn lower<'a, DB: HirDatabase>(
syntax: ast::FieldExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let record_expr_syn = syntax.inner_expr().ok_or(LoweringError {
kind: Missing::FieldExpr.into(),
})?;
let record = Expression::lower(record_expr_syn, ctx)?;
let field_syn = syntax.name_ref().ok_or(LoweringError {
kind: Missing::NameRef.into(),
})?;
let field = Identifier::lower(field_syn, ctx)?;
let field_expr = FieldExprData { record, field }.intern(ctx.tables());
Ok(field_expr)
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::TupleExprRaw<R>> for RecordExpr {
fn lower<'a, DB: HirDatabase>(
syntax: ast::TupleExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let values = syntax
.fields()
.map(|value_syn| Expression::lower(value_syn, ctx))
.collect::<Result<Vec<_>, _>>()?;
let labels = (0..values.len())
.map(|int_label| Identifier::lower(format!("{}", int_label), ctx))
.collect::<Result<_, _>>()?;
let record_expr = RecordExprData { labels, values }.intern(ctx.tables());
Ok(record_expr)
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::StructExprRaw<R>> for RecordExpr {
fn lower<'a, DB: HirDatabase>(
syntax: ast::StructExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let (labels, values) = {
let mut labels = Vec::new();
let mut values = Vec::new();
let _ = syntax.fields().try_fold(
(&mut labels, &mut values),
|(labels, values), field| {
let label_syn = field.name_ref().ok_or(LoweringError {
kind: Missing::NameRef.into(),
})?;
let label = Identifier::lower(label_syn, ctx)?;
let value_syn = field.inner_expr().ok_or(LoweringError {
kind: Missing::StructFieldExpr.into(),
})?;
let value = Expression::lower(value_syn, ctx)?;
labels.push(label);
values.push(value);
Ok((labels, values))
},
)?;
(labels, values)
};
let record_expr = RecordExprData { labels, values }.intern(ctx.tables());
Ok(record_expr)
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::BlockExprRaw<R>> for BlockExpr {
fn lower<'a, DB: HirDatabase>(
syntax: ast::BlockExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let statements: Vec<Statement> = syntax
.statements()
.map(|stmnt| Statement::lower(stmnt, ctx))
.collect::<Result<_, _>>()?;
let return_expr = if let Some(last_expr_syn) = syntax.last_expr() {
let last_expr = Expression::lower(last_expr_syn, ctx)?;
Some(last_expr)
} else {
None
};
let block_expr = BlockExprData {
statements,
return_expr,
}
.intern(ctx.tables());
Ok(block_expr)
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::MatchExprRaw<R>> for MatchExpr {
fn lower<'a, DB: HirDatabase>(
syntax: ast::MatchExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let condition_syn = syntax.condition().ok_or(LoweringError {
kind: Missing::MatchCondition.into(),
})?;
let condition = Expression::lower(condition_syn, ctx)?;
let match_arm_list_syn = syntax.arm_list().ok_or(LoweringError {
kind: Missing::MatchArmList.into(),
})?;
let arms = match_arm_list_syn
.arms()
.map(|arm_syn| {
let arm_pattern_syn = arm_syn.pattern().ok_or(LoweringError {
kind: Missing::MatchArmPattern.into(),
})?;
let arm_pattern = Pattern::lower(arm_pattern_syn, ctx)?;
let arm_expr_syn = arm_syn.body().ok_or(LoweringError {
kind: Missing::MatchArmExpression.into(),
})?;
let arm_expr = Expression::lower(arm_expr_syn, ctx)?;
Ok((arm_pattern, arm_expr))
})
.collect::<Result<Vec<_>, _>>()?;
let match_expr = MatchExprData { condition, arms }.intern(ctx.tables());
Ok(match_expr)
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::AscriptionExprRaw<R>> for AscriptionExpr {
fn lower<'a, DB: HirDatabase>(
syntax: ast::AscriptionExprRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let typed_expr_syn = syntax.inner_expr().ok_or(LoweringError {
kind: Missing::AscriptionExpr.into(),
})?;
let typed_expr = Expression::lower(typed_expr_syn, ctx)?;
let ascribed_type_syn = syntax.ascribed_type().ok_or(LoweringError {
kind: Missing::AscriptionType.into(),
})?;
let ascribed_type = Type::lower(ascribed_type_syn, ctx)?;
let ascription_expr = AscriptionExprData {
typed_expr,
ascribed_type,
}
.intern(ctx.tables());
Ok(ascription_expr)
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::LiteralRaw<R>> for Literal {
fn lower<'a, DB: HirDatabase>(
syntax: ast::LiteralRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let literal_expr = syntax.literal_expr().ok_or(LoweringError {
kind: Missing::Literal.into(),
})?;
let (kind, text) = match literal_expr.kind() {
ast::LiteralExprRawKind::IntNum(inner) => (LiteralKind::Integer, inner.text()),
ast::LiteralExprRawKind::FloatNum(inner) => (LiteralKind::Float, inner.text()),
ast::LiteralExprRawKind::Symbol(inner) => (LiteralKind::Symbol, inner.text()),
ast::LiteralExprRawKind::TrueKw(inner) => (LiteralKind::True, inner.text()),
ast::LiteralExprRawKind::FalseKw(inner) => (LiteralKind::False, inner.text()),
};
Ok(LiteralData { kind, text }.intern(ctx.tables()))
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::StatementRaw<R>> for Statement {
fn lower<'a, DB: HirDatabase>(
syntax: ast::StatementRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let stmnt_data = match syntax.kind() {
ast::StatementRawKind::LetStmnt(let_stmnt_syn) => {
let assignment = Assignment::lower(let_stmnt_syn, ctx)?;
StatementData::Assignment(assignment)
},
ast::StatementRawKind::ExprStmnt(expr_stmnt_syn) => {
let expr_syn = expr_stmnt_syn.inner_expr().ok_or(LoweringError {
kind: Missing::ExprStatmentExpression.into(),
})?;
let expr = Expression::lower(expr_syn, ctx)?;
StatementData::Expression(expr)
},
};
Ok(stmnt_data.intern(ctx.tables()))
}
}
impl<R: RootOwnership<SyntaxTree>> Lower<ast::LetStmntRaw<R>> for Assignment {
fn lower<'a, DB: HirDatabase>(
syntax: ast::LetStmntRaw<R>,
ctx: &mut LoweringCtx<'a, DB>,
) -> Result<Self, LoweringError> {
let destination_syn = syntax.pattern().ok_or(LoweringError {
kind: Missing::LetStmntPattern.into(),
})?;
let destination = Pattern::lower(destination_syn, ctx)?;
let value_syn = syntax.value().ok_or(LoweringError {
kind: Missing::LetStmntExpression.into(),
})?;
let value = Expression::lower(value_syn, ctx)?;
let assignment = AssignmentData { destination, value }.intern(ctx.tables());
Ok(assignment)
}
}
|
//! An `EngineDriver` drives multiple `SymbolicEngine`s, taking care of control flow from an
//! `il::Program` and handling `Platform`-specific actions.
//!
//! An `EngineDriver` performs the following actions:
//! * Keeps track of our current location in an `il::Program`.
//! * Handles `SymbolicSuccessor` results from a `SymbolicEngine`.
//! * Translates/lifts code using a `translator::Arch` with `SymbolicMemory` as the
//! `TranslationMemory` backing when we encounter branch targets we have not yet translated.
//!
//! An `EngineDriver` is the core component of symbolic execution with Falcon, whereas a
//! `SymbolicEngine` is the core component of an `EngineDriver`. `EngineDriver`, "Drives," a
//! `SymbolicEngine`.
use error::*;
use engine::*;
use il;
use platform::Platform;
use translator;
use std::collections::VecDeque;
use std::sync::Arc;
/// Takes a program and an address, and returns function, block, and instruction
/// index for the first IL instruction at that address.
pub fn instruction_address(program: &il::Program, address: u64)
-> Option<(u64, u64, u64)> {
for function in program.functions() {
for block in function.control_flow_graph().blocks() {
for instruction in block.instructions() {
if let Some(ins_address) = instruction.address() {
if ins_address == address {
return Some(
(function.index().unwrap(),
block.index(),
instruction.index()));
}
}
}
}
}
None
}
/// A unique location in a function
#[derive(Clone, Debug)]
pub enum FunctionLocation {
/// A function-unique identifier for an instruction.
Instruction {
block_index: u64,
instruction_index: u64,
},
/// A function-unique identifier for an edge.
Edge {
head: u64,
tail: u64
}
}
/// A unique location in a program
#[derive(Clone, Debug)]
pub struct ProgramLocation {
function_index: u64,
function_location: FunctionLocation
}
impl ProgramLocation {
/// Create a new `ProgramLocation`
pub fn new(
function_index: u64,
function_location: FunctionLocation
) -> ProgramLocation {
ProgramLocation {
function_index: function_index,
function_location: function_location
}
}
/// Convert an address to a `ProgramLocation`
///
/// If the address cannot be found, we return `None`.
pub fn from_address(address: u64, program: &il::Program)
-> Option<ProgramLocation> {
for function in program.functions() {
for block in function.control_flow_graph().blocks() {
for instruction in block.instructions() {
if let Some(ins_address) = instruction.address() {
if ins_address == address {
return Some(ProgramLocation::new(
function.index().unwrap(),
FunctionLocation::Instruction {
block_index: block.index(),
instruction_index: instruction.index()
}
));
}
}
}
}
}
None
}
/// Returns the index of this location's function
pub fn function_index(&self) -> u64 {
self.function_index
}
/// Return the `Function` for this location
pub fn function<'f>(&self, program: &'f il::Program) -> Option<&'f il::Function> {
program.function(self.function_index)
}
/// Return the `Block` for this location
pub fn block<'f>(&self, program: &'f il::Program) -> Option<&'f il::Block> {
if let FunctionLocation::Instruction { ref block_index, .. } = self.function_location {
if let Some(function) = self.function(program) {
return function.block(*block_index);
}
}
None
}
/// Return the `Instruction` for this location
pub fn instruction<'f>(&self, program: &'f il::Program) -> Option<&'f il::Instruction> {
if let FunctionLocation::Instruction { ref instruction_index, .. } =
self.function_location {
if let Some(block) = self.block(program) {
return block.instruction(*instruction_index);
}
}
None
}
/// Return the FunctionLocation for this location
pub fn function_location(&self) -> &FunctionLocation {
&self.function_location
}
/// Advances the `DriverLocation` to the next valid `il::Instruction` or
/// `il::Edge`
///
/// Advancing a location through the program may be tricky due to edge
/// cases. For example, we may have an unconditional edge leading to an
/// empty block, leading to another unconditional edge. In this case, we
/// want to advance past all of these to the next valid `ProgramLocation`.
pub fn advance(&self, program: &il::Program) -> Vec<ProgramLocation> {
// This is the list of locations which no longer need to be advanced
let mut final_locations = Vec::new();
// This is the queue of locations pending advancement
let mut queue = VecDeque::new();
queue.push_back(self.clone());
while queue.len() > 0 {
let location = queue.pop_front().unwrap();
// If we are at an instruction
match location.function_location {
FunctionLocation::Instruction { block_index, instruction_index } => {
// Iterate through the block to find this instruction
let instructions = location.function(program).unwrap()
.block(block_index).unwrap()
.instructions();
for i in 0..instructions.len() {
// We found this instruction
if instructions[i].index() == instruction_index {
// If there is a successor in the block, advance to the
// successor
if i + 1 < instructions.len() {
final_locations.push(ProgramLocation::new(
location.function_index,
FunctionLocation::Instruction {
block_index: block_index,
instruction_index: instructions[i + 1].index()
}
));
break;
}
// There is no successor, let's take a look at outgoing
// edges
for edge in location.function(program)
.unwrap()
.control_flow_graph()
.graph()
.edges_out(block_index)
.unwrap() {
// If this is a conditional edge, advance to the
// edge
if edge.condition().is_some() {
final_locations.push(ProgramLocation::new(
location.function_index,
FunctionLocation::Edge {
head: edge.head(),
tail: edge.tail()
}
));
}
// If this is an unconditional edge, push the
// unconditional edge onto the queue
else {
queue.push_back(ProgramLocation::new(
location.function_index,
FunctionLocation::Edge {
head: edge.head(),
tail: edge.tail()
}
));
}
} // for edge
} // if instructions[i].index()
} // for i in 0..instructions.len()
},
FunctionLocation::Edge { head: _, tail } => {
// Get the successor block
let block = location.function(program).unwrap()
.block(tail).unwrap();
// If this block is empty, we move straight to outgoing
// edges
if block.instructions().is_empty() {
for edge in location.function(program)
.unwrap()
.control_flow_graph()
.graph()
.edges_out(tail)
.unwrap() {
// We advance conditional edges, and push
// unconditional edges back on the queue
// TODO programs with infinite loops, I.E. `while (1) {}`,
// will cause us to hang here. We would prefer to hang somewhere else
// so we can eventually stop.
if edge.condition().is_some() {
final_locations.push(ProgramLocation::new(
location.function_index,
FunctionLocation::Edge {
head: edge.head(),
tail: edge.tail()
}
));
}
else {
queue.push_back(ProgramLocation::new(
location.function_index,
FunctionLocation::Edge {
head: edge.head(),
tail: edge.tail()
}
));
}
} // for edge in location
} // if block.instructions().is_empty()
// If this block isn't empty, we advance to the first instruction
else {
final_locations.push(ProgramLocation::new(
location.function_index,
FunctionLocation::Instruction {
block_index: block.index(),
instruction_index: block.instructions()[0].index()
}
));
}
}
} // match location
} // while queue.len() > 0
final_locations
}
}
/// An `EngineDriver` drive's a `SymbolicEngine` through an `il::Program` and `Platform`.
#[derive(Clone)]
pub struct EngineDriver<'e, P> {
program: Arc<il::Program>,
location: ProgramLocation,
engine: SymbolicEngine,
arch: &'e Box<translator::Arch>,
platform: Arc<P>
}
impl<'e, P> EngineDriver<'e, P> {
/// Create a new `EngineDriver`.
///
/// # Arguments
/// * `program`: An `il::Program`. Must not be complete, but must have the location pointed to by
/// _location_ validly translated.
/// * `location`: A valid location in _program_, which is the next instruction to execute.
/// * `engine`: The `SymbolicEngine` holding the state of the program at this point in time.
/// * `arch`: A `translator::Arch` for this program's architecture. This will be used to
/// translate unexplored program blocks on the fly.
/// * `platform`: The platform we will use to handle `Raise` instructions. `Platform` models the
/// external environment and may be stateful.
pub fn new(
program: Arc<il::Program>,
location: ProgramLocation,
engine: SymbolicEngine,
arch: &'e Box<translator::Arch>,
platform: Arc<P>
) -> EngineDriver<P> where P: Platform<P> {
EngineDriver {
program: program,
location: location,
engine: engine,
arch: arch,
platform: platform
}
}
/// Steps this engine forward, consuming the engine and returning some
/// variable number of `EngineDriver` back depending on how many possible
/// states are possible.
pub fn step(mut self) -> Result<Vec<EngineDriver<'e, P>>> where P: Platform<P> {
let mut new_engine_drivers = Vec::new();
match self.location.function_location {
FunctionLocation::Instruction { block_index, instruction_index } => {
let successors = {
let instruction = self.program
.function(self.location.function_index())
.unwrap()
.block(block_index)
.unwrap()
.instruction(instruction_index)
.unwrap();
// println!("Executing instruction {}", instruction);
match *instruction.operation() {
il::Operation::Load { ref index, .. } => {
let expr = self.engine.symbolize_expression(index)?;
if !engine::all_constants(&expr) {
println!("Loading from non-constant address");
if let Some(address) = self.address() {
println!("address: 0x{:x}", address);
}
}
},
_ => {}
}
self.engine.execute(instruction.operation())?
};
for successor in successors {
match successor.type_().clone() {
SuccessorType::FallThrough => {
// Get the possible successor locations for the current
// location
let engine = successor.into_engine();
let locations = self.location.advance(&self.program);
if locations.len() == 1 {
new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
locations[0].clone(),
engine,
self.arch,
self.platform.clone(),
));
}
else {
for location in locations {
new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
location,
engine.clone(),
self.arch,
self.platform.clone()
));
}
}
},
SuccessorType::Branch(address) => {
match ProgramLocation::from_address(address, &self.program) {
// We have already disassembled the branch target. Go straight to it.
Some(location) => new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
location,
successor.into_engine(),
self.arch,
self.platform.clone()
)),
// There's no instruction at this address. We will attempt
// disassembling a function here.
None => {
let engine = successor.into_engine();
let function = self.arch.translate_function(&engine, address);
match function {
Ok(function) => {
Arc::make_mut(&mut self.program).add_function(function);
let location = ProgramLocation::from_address(address, &self.program);
if let Some(location) = location {
new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
location,
engine,
self.arch,
self.platform.clone()
));
}
else {
bail!("No instruction at address 0x{:x}", address)
}
},
Err(_) => bail!("Failed to lift function at address 0x{:x}", address)
}
}
};
},
SuccessorType::Raise(expression) => {
let platform = Arc::make_mut(&mut self.platform).to_owned();
let locations = self.location.advance(&self.program);
let engine = successor.clone().into_engine();
let results = match platform.raise(&expression, engine) {
Ok(results) => results,
Err(e) => {
println!("Killing state because {}", e.description());
continue;
}
};
for location in locations {
for result in &results {
new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
location.clone(),
result.1.clone(),
self.arch,
Arc::new(result.0.clone())
));
}
}
}
}
}
},
FunctionLocation::Edge { head, tail } => {
let edge = self.location
.function(&self.program)
.unwrap()
.edge(head, tail)
.unwrap();
match *edge.condition() {
None => {
if edge.condition().is_none() {
let locations = self.location.advance(&self.program);
if locations.len() == 1 {
new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
locations[0].clone(),
self.engine,
self.arch,
self.platform.clone()
));
}
else {
for location in self.location.advance(&self.program) {
new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
location,
self.engine.clone(),
self.arch,
self.platform.clone()
));
}
}
}
},
Some(ref condition) => {
if self.engine.sat(Some(vec![condition.clone()]))? {
let mut engine = self.engine.clone();
engine.add_constraint(condition.clone())?;
let locations = self.location.advance(&self.program);
if locations.len() == 1 {
new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
locations[0].clone(),
engine,
self.arch,
self.platform.clone()
));
}
else {
for location in self.location.advance(&self.program) {
new_engine_drivers.push(EngineDriver::new(
self.program.clone(),
location,
engine.clone(),
self.arch,
self.platform.clone()
));
}
}
}
}
}
}
} // match self.location.function_location
Ok(new_engine_drivers)
}
/// If the current location of this EngineDriver is an instruction with an
/// address, return that address
pub fn address(&self) -> Option<u64> {
if let Some(instruction) = self.location.instruction(&self.program) {
instruction.address()
}
else {
None
}
}
/// Get the platform for this `EngineDriver`
pub fn platform(&self) -> Arc<P> {
self.platform.clone()
}
/// Return the program for this `EngineDriver`
pub fn program(&self) -> &il::Program {
&self.program
}
/// Return the location of this `EngineDriver`
pub fn location(&self) -> &ProgramLocation {
&self.location
}
/// Set the location for this `EngineDriver`.
pub fn set_location(&mut self, location: ProgramLocation) {
self.location = location;
}
/// Return the underlying symbolic engine for this `EngineDriver`
pub fn engine(&self) -> &SymbolicEngine {
&self.engine
}
}
|
use nom::branch::alt;
use nom::bytes::complete::{escaped, tag, take_until, take_while1};
use nom::character::complete::{
anychar, digit1, line_ending, none_of, not_line_ending, one_of, satisfy,
};
use nom::character::{is_alphabetic, is_alphanumeric};
use nom::combinator::{complete, map, not, opt, peek, recognize, rest, value};
use nom::error::{FromExternalError, VerboseError};
use nom::multi::{fold_many1, many0};
use nom::number::complete::double;
use nom::sequence::{delimited, pair, preceded, terminated};
use nom::{FindToken, Finish, IResult, InputTakeAtPosition};
use std::str::FromStr;
#[cfg(all(feature = "im", feature = "im-rc"))]
compile_error!("features `im` and `im-rc` are mutually exclusive");
#[cfg(feature = "im")]
use im::{HashMap as Map, HashSet as Set};
#[cfg(feature = "im-rc")]
use im_rc::{HashMap as Map, HashSet as Set};
#[cfg(all(not(feature = "im"), not(feature = "im-rc")))]
use std::collections::{BTreeMap as Map, BTreeSet as Set};
#[derive(Clone, Debug, PartialEq, PartialOrd, Ord, Eq, Hash)]
pub enum Edn<'edn> {
Nil,
Bool(bool),
String(&'edn str),
Character(char),
Symbol {
namespace: Option<&'edn str>,
name: &'edn str,
},
Keyword {
namespace: Option<&'edn str>,
name: &'edn str,
},
Integer(isize),
Float(ordered_float::OrderedFloat<f64>),
Decimal(rust_decimal::Decimal),
List(Vec<Edn<'edn>>),
Vector(Vec<Edn<'edn>>),
Map(Map<Edn<'edn>, Edn<'edn>>),
Set(Set<Edn<'edn>>),
// Right now `Comment` is a marker value that follows the edn spec
// by ignoring any subsequent data, but in the future we could
// make a variant of it that captures the comment data itself.
// There could be circumstances where one would want to
// capture comment data.
Comment,
Tag(Tag<'edn>),
}
#[derive(Clone, Debug, PartialEq, PartialOrd, Ord, Eq, Hash)]
pub enum Tag<'edn> {
Inst(chrono::DateTime<chrono::offset::FixedOffset>),
UUID(uuid::Uuid),
UserDefined {
prefix: &'edn str,
name: &'edn str,
element: Box<Edn<'edn>>,
},
}
pub struct InvalidTagElementError;
#[macro_export]
macro_rules! edn {
($b:expr) => {
parse_edn_one($b).unwrap()
};
}
#[macro_export]
macro_rules! edn_many {
($b:expr) => {
parse_edn_many($b).unwrap()
};
}
pub fn parse_edn_one(input: &str) -> Result<Edn, nom::error::VerboseError<&str>> {
if input.is_empty() {
return Ok(Edn::Nil);
}
let (_s, o) = edn_any(input).finish()?;
match o {
Some(edn) => Ok(edn),
None => Ok(Edn::Nil),
}
}
pub fn parse_edn_many(input: &str) -> Result<Vec<Edn>, nom::error::VerboseError<&str>> {
let (s, _) = opt(space_or_comma)(input).finish()?;
let (_s, edn) = many0(delimited(
opt(many0(line_ending)),
complete(edn_any),
opt(many0(line_ending)),
))(s)
.finish()?;
Ok(edn.into_iter().flatten().collect())
}
fn space_or_comma(s: &str) -> IResult<&str, &str, nom::error::VerboseError<&str>> {
s.split_at_position(|c| !" \t\r\n,".find_token(c))
}
fn edn_discard_sequence(s: &str) -> IResult<&str, Option<Edn>, nom::error::VerboseError<&str>> {
let (s, _) = preceded(tag("#_"), edn_any)(s)?;
Ok((s, None))
}
fn edn_nil(s: &str) -> IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, _) = tag("nil")(s)?;
Ok((s, Edn::Nil))
}
fn edn_bool(s: &str) -> IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, v) = alt((
map(tag("true"), |_| Edn::Bool(true)),
map(tag("false"), |_| Edn::Bool(false)),
))(s)?;
Ok((s, v))
}
fn edn_int(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, i) = map(
alt((
digit1,
recognize(pair(tag("-"), digit1)),
preceded(tag("+"), digit1),
)),
|digits: &str| digits.parse::<isize>().unwrap(),
)(s)?;
let (s, _) = not(tag("."))(s)?;
Ok((s, Edn::Integer(i)))
}
fn edn_float(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, f) = alt((
map(terminated(recognize(double), tag("M")), |d: &str| {
Edn::Decimal(rust_decimal::Decimal::from_str(d).unwrap())
}),
map(nom::number::complete::double, |d| Edn::Float(d.into())),
))(s)?;
Ok((s, f))
}
fn edn_string(s: &str) -> IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, _) = tag("\"")(s)?;
let (s, string) = map(
escaped(none_of("\"\\"), '\\', one_of("\"ntr\\")),
|s: &str| Edn::String(s),
)(s)?;
let (s, _) = tag("\"")(s)?;
Ok((s, string))
}
fn edn_char(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, c) = preceded(
tag("\\"),
alt((
map(preceded(tag("u"), hex_u32), |c| {
Edn::Character(unsafe { std::char::from_u32_unchecked(c) })
}),
map(tag("newline"), |_| Edn::Character('\n')),
map(tag("return"), |_| Edn::Character('\r')),
map(tag("space"), |_| Edn::Character(' ')),
map(tag("tab"), |_| Edn::Character('\t')),
map(anychar, Edn::Character),
)),
)(s)?;
Ok((s, c))
}
fn edn_keyword(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, _) = tag(":")(s)?;
let mut optional_namespace = opt(terminated(identifier, tag("/")));
let (s, namespace) = optional_namespace(s)?;
let (s, sym) = identifier(s)?;
Ok((
s,
Edn::Keyword {
namespace,
name: sym,
},
))
}
fn edn_symbol(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
peek(not(tag(":")))(s)?;
let mut optional_namespace = opt(terminated(identifier, tag("/")));
let (s, namespace) = optional_namespace(s)?;
let (s, sym) = identifier(s)?;
Ok((
s,
Edn::Symbol {
namespace,
name: sym,
},
))
}
fn edn_list(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, _) = tag("(")(s)?;
let (s, elements) = many0(delimited(opt(space_or_comma), edn_any, opt(space_or_comma)))(s)?;
let (s, _) = tag(")")(s)?;
Ok((s, Edn::List(elements.into_iter().flatten().collect())))
}
fn edn_vector(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, _) = tag("[")(s)?;
let (s, elements) = many0(delimited(opt(space_or_comma), edn_any, opt(space_or_comma)))(s)?;
let (s, _) = tag("]")(s)?;
Ok((s, Edn::Vector(elements.into_iter().flatten().collect())))
}
fn edn_map(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, _) = tag("{")(s)?;
let (s, map) = opt(fold_many1(
pair(
delimited(
opt(space_or_comma),
nom::combinator::complete(edn_any),
opt(space_or_comma),
),
delimited(
opt(space_or_comma),
nom::combinator::complete(edn_any),
opt(space_or_comma),
),
),
Map::new,
|mut acc: Map<_, _>, (k, v)| match (k, v) {
(Some(kk), Some(vv)) => {
acc.insert(kk, vv);
acc
}
_ => acc,
},
))(s)?;
let (s, _) = tag("}")(s)?;
Ok((s, Edn::Map(map.unwrap_or_else(Map::new))))
}
fn edn_set(s: &str) -> nom::IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, _) = tag("#{")(s)?;
let (s, set) = opt(fold_many1(
delimited(opt(space_or_comma), edn_any, opt(space_or_comma)),
Set::new,
|mut acc: Set<_>, v| {
if let Some(actual_v) = v {
acc.insert(actual_v);
}
acc
},
))(s)?;
let (s, _) = tag("}")(s)?;
Ok((s, Edn::Set(set.unwrap_or_else(Set::new))))
}
fn edn_comment(s: &str) -> IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, c) = preceded(
tag(";"),
value(
Edn::Comment,
alt((terminated(not_line_ending, line_ending), rest)),
),
)(s)?;
Ok((s, c))
}
fn edn_tag(s: &str) -> IResult<&str, crate::Edn, nom::error::VerboseError<&str>> {
let (s, _) = preceded(tag("#"), peek(satisfy(|c: char| is_alphabetic(c as u8))))(s)?;
let (s, tag) = alt((edn_tag_inst, edn_tag_uuid, edn_tag_user_defined))(s)?;
Ok((s, Edn::Tag(tag)))
}
fn edn_tag_inst(s: &str) -> IResult<&str, crate::Tag, nom::error::VerboseError<&str>> {
let (s, _) = tag("inst")(s)?;
let (s, _) = space_or_comma(s)?;
let (s, _) = tag("\"")(s)?;
let (s, as_str) = take_until("\"")(s)?;
let (s, _) = tag("\"")(s)?;
let datetime = chrono::DateTime::parse_from_rfc3339(as_str).map_err(|e| {
nom::Err::Error(nom::error::VerboseError::from_external_error(
s,
nom::error::ErrorKind::Tag,
e,
))
})?;
let tag = Tag::Inst(datetime);
Ok((s, tag))
}
fn edn_tag_uuid(s: &str) -> IResult<&str, crate::Tag, nom::error::VerboseError<&str>> {
let (s, _) = tag("uuid")(s)?;
let (s, _) = space_or_comma(s)?;
let (s, _) = tag("\"")(s)?;
let (s, as_str) = take_until("\"")(s)?;
let (s, _) = tag("\"")(s)?;
let uuid = uuid::Uuid::from_str(as_str).map_err(|e| {
nom::Err::Error(nom::error::VerboseError::from_external_error(
s,
nom::error::ErrorKind::Tag,
e,
))
})?;
let tag = Tag::UUID(uuid);
Ok((s, tag))
}
fn edn_tag_user_defined(s: &str) -> IResult<&str, crate::Tag, nom::error::VerboseError<&str>> {
let (s, prefix) = identifier(s)?;
let (s, _) = tag("/")(s)?;
let (s, name) = identifier(s)?;
let (s, _) = space_or_comma(s)?;
match edn_any(s)? {
(s, Some(Edn::Tag(_))) | (s, Some(Edn::Comment)) | (s, None) => {
Err(nom::Err::Error(VerboseError::from_external_error(
s,
nom::error::ErrorKind::Tag,
InvalidTagElementError,
)))
}
(s, Some(element)) => {
let tag = Tag::UserDefined {
prefix,
name,
element: Box::new(element),
};
Ok((s, tag))
}
}
}
fn edn_any(s: &str) -> IResult<&str, Option<crate::Edn>, nom::error::VerboseError<&str>> {
let (s, edn) = alt((
map(edn_string, Some),
map(edn_bool, Some),
map(edn_int, Some),
map(edn_float, Some),
map(edn_symbol, Some),
map(edn_keyword, Some),
map(edn_nil, Some),
map(edn_char, Some),
map(edn_list, Some),
map(edn_map, Some),
map(edn_vector, Some),
map(edn_set, Some),
map(edn_tag, Some),
map(edn_comment, |_| None),
edn_discard_sequence,
))(s)?;
Ok((s, edn))
}
fn identifier(s: &str) -> nom::IResult<&str, &str, nom::error::VerboseError<&str>> {
take_while1(matches_identifier_char)(s)
}
fn matches_identifier_char(c: char) -> bool {
is_alphanumeric(c as u8) || c == '-' || c == '_' || c == '.' || c == '+' || c == '&'
}
// fork of https://docs.rs/nom/6.0.1/src/nom/number/complete.rs.html#1341-1361
fn hex_u32<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, u32, E> {
let (i, o) = take_while1(|chr| {
let chr = chr as u8;
// 0-9, A-F, a-f
(0x30..=0x39).contains(&chr) || (0x41..=0x46).contains(&chr) || (0x61..=0x66).contains(&chr)
})(input)?;
// Do not parse more than 8 characters for a u32
let (parsed, remaining) = if o.len() <= 8 {
(o, i)
} else {
(&input[..8], &input[8..])
};
let res = parsed
.chars()
.rev()
.enumerate()
.map(|(k, v)| {
let digit = v as char;
digit.to_digit(16).unwrap_or(0) << (k * 4)
})
.sum();
Ok((remaining, res))
}
#[cfg(test)]
mod tests {
use super::Edn::*;
use super::*;
use rust_decimal;
use std::io::Read;
use std::str::FromStr;
const DEPS_DOT_EDN: &str = include_str!("../fixtures/deps.edn");
const ASCII_STL: &str = include_str!("../fixtures/ascii_stl.clj");
macro_rules! map {
() => {
crate::Map::new()
};
( $($x:expr, $y:expr),* ) => {
{
let mut hm = crate::Map::new();
$(
hm.insert($x, $y);
)*
hm
}
};
}
macro_rules! set {
() => {
crate::Set::new()
};
( $($x:expr),* ) => {
{
let mut hs = crate::Set::new();
$(
hs.insert($x);
)*
hs
}
};
}
#[test]
fn nil() {
let nil = "nil";
let res = edn_nil(nil);
assert_eq!(res, Ok(("", Edn::Nil)));
}
#[test]
fn bool() {
let truestr = "true";
let falsestr = "false";
let trueres = edn_bool(truestr);
let falseres = edn_bool(falsestr);
assert_eq!(trueres, Ok(("", Bool(true))));
assert_eq!(falseres, Ok(("", Bool(false))));
}
#[test]
fn keyword() {
let keystr = ":a-kw";
let res = nom::combinator::complete(edn_keyword)(keystr);
assert_eq!(
res,
Ok((
"",
Keyword {
namespace: None,
name: "a-kw"
}
))
);
}
#[test]
fn keyword_namespaced() {
let keystr = ":org.clojure/clojure";
let res = nom::combinator::complete(edn_keyword)(keystr);
assert_eq!(
res,
Ok((
"",
Keyword {
namespace: Some("org.clojure"),
name: "clojure"
}
))
);
}
#[test]
fn int() {
let intstr = "1";
let res = edn_int(intstr);
assert_eq!(res, Ok(("", Integer(1))));
let intstr = "-1";
let res = edn_int(intstr);
assert_eq!(res, Ok(("", Integer(-1))));
let intstr = isize::MAX.to_string();
let res = edn_int(&intstr);
assert_eq!(res, Ok(("", Integer(isize::MAX))));
let intstr = isize::MIN.to_string();
let res = edn_int(&intstr);
assert_eq!(res, Ok(("", Integer(isize::MIN))));
}
#[test]
fn float() {
let negative_0 = -0.0f64;
let negative_1 = -1.0f64;
let negative_120_000 = -120_000.0;
assert_eq!(edn_float("0.0"), Ok(("", Float(0.0.into()))));
assert_eq!(edn_float("-0.0"), Ok(("", Float(negative_0.into()))));
assert_eq!(edn_float("1.0"), Ok(("", Float(1.0.into()))));
assert_eq!(edn_float("-1.0"), Ok(("", Float(negative_1.into()))));
assert_eq!(
edn_float("-1.2E5"),
Ok(("", Float(negative_120_000.into())))
);
assert_eq!(
edn_float("-120000"),
Ok(("", Float(negative_120_000.into())))
);
}
#[test]
fn decimal() {
assert_eq!(
edn_float("0.0M"),
Ok(("", Decimal(rust_decimal::Decimal::from_str("0.0").unwrap())))
);
assert_eq!(
edn_float("1140141.1041040014014141M"),
Ok((
"",
Decimal(rust_decimal::Decimal::from_str("1140141.1041040014014141").unwrap())
))
);
}
#[test]
fn symbol() {
let symstr = "a-sym";
let res = edn_symbol(symstr);
assert_eq!(
res,
Ok((
"",
Symbol {
namespace: None,
name: "a-sym"
}
))
);
}
#[test]
fn symbol_namedspaced() {
let symstr = "org.clojure/clojure";
let res = edn_symbol(symstr);
assert_eq!(
res,
Ok((
"",
Symbol {
namespace: Some("org.clojure"),
name: "clojure"
}
))
);
}
#[test]
fn string() {
let strstr = "\"hello\"";
let res = edn_string(strstr);
assert_eq!(res, Ok(("", String("hello"))));
}
#[test]
fn string_escapes() {
let mut embedded_str = std::fs::File::open("./fixtures/embedded_str").unwrap();
// let embedded_str = "\"hel\"lo\"";
let mut buf = std::string::String::new();
embedded_str.read_to_string(&mut buf).unwrap();
let embedded_res = edn_string(&mut buf);
assert_eq!(embedded_res, Ok(("", String("hel\\\"lo"))));
}
#[test]
fn char_unicode_literals() {
let charstr1 = "\\u0065";
let charstr2 = "\\u0177";
let res1 = edn_char(charstr1);
let res2 = edn_char(charstr2);
assert_eq!(res1, Ok(("", Character('e'))));
assert_eq!(res2, Ok(("", Character('ŷ'))));
}
#[test]
fn char_ascii() {
let charstr1 = "\\a";
let charstr2 = "\\8";
let res1 = edn_char(charstr1);
let res2 = edn_char(charstr2);
assert_eq!(res1, Ok(("", Character('a'))));
assert_eq!(res2, Ok(("", Character('8'))));
}
#[test]
fn char_special_sequence_literals() {
let charstr_newline = "\\newline";
let res1 = edn_char(charstr_newline);
assert_eq!(res1, Ok(("", Character('\n'))));
let charstr_return = "\\return";
let res1 = edn_char(charstr_return);
assert_eq!(res1, Ok(("", Character('\r'))));
let charstr_space = "\\space";
let res1 = edn_char(charstr_space);
assert_eq!(res1, Ok(("", Character(' '))));
let charstr_tab = "\\tab";
let res1 = edn_char(charstr_tab);
assert_eq!(res1, Ok(("", Character('\t'))));
}
#[test]
fn list_homogenous() {
let list_str = "(:a :b :c)";
let list_res = edn_list(list_str);
assert_eq!(
list_res,
Ok((
"",
List(vec!(
Keyword {
namespace: None,
name: "a"
},
Keyword {
namespace: None,
name: "b"
},
Keyword {
namespace: None,
name: "c"
}
))
))
);
}
#[test]
fn list_heterogenous() {
let list_str = "(:a b true false some-sym :c)";
let list_res = edn_list(list_str);
assert_eq!(
list_res,
Ok((
"",
List(vec!(
Keyword {
namespace: None,
name: "a"
},
Symbol {
namespace: None,
name: "b"
},
Bool(true),
Bool(false),
Symbol {
namespace: None,
name: "some-sym"
},
Keyword {
namespace: None,
name: "c"
}
))
))
);
}
#[test]
fn list_heterogenous_nested() {
let list_str = "(:a b (1 2 5 :e) true false [[] 232 ()] some-sym :c)";
let list_res = edn_list(list_str);
assert_eq!(
list_res,
Ok((
"",
List(vec!(
Keyword {
namespace: None,
name: "a"
},
Symbol {
namespace: None,
name: "b"
},
List(vec!(
Integer(1),
Integer(2),
Integer(5),
Keyword {
namespace: None,
name: "e"
}
)),
Bool(true),
Bool(false),
Vector(vec!(Vector(vec!()), Integer(232), List(vec!()))),
Symbol {
namespace: None,
name: "some-sym"
},
Keyword {
namespace: None,
name: "c"
}
))
))
);
}
#[test]
fn list_whitespace() {
let list_str = "(\"hello\"abc)";
let list_res = edn_vector(list_str);
assert!(list_res.is_err());
}
#[test]
fn vector_homogenous() {
let vector_str = "[:a :b :c]";
let vector_res = edn_vector(vector_str);
assert_eq!(
vector_res,
Ok((
"",
Vector(vec![
Keyword {
namespace: None,
name: "a"
},
Keyword {
namespace: None,
name: "b"
},
Keyword {
namespace: None,
name: "c"
}
])
))
);
}
#[test]
fn vector_heterogenous() {
let vector_str = "[:a b 1 true false some-sym 44444 :c]";
let vector_res = edn_vector(vector_str);
assert_eq!(
vector_res,
Ok((
"",
Vector(vec!(
Keyword {
namespace: None,
name: "a"
},
Symbol {
namespace: None,
name: "b"
},
Integer(1),
Bool(true),
Bool(false),
Symbol {
namespace: None,
name: "some-sym"
},
Integer(44444),
Keyword {
namespace: None,
name: "c"
}
))
))
);
}
#[test]
fn vector_empty() {
let vector_str = "[]";
let vector_res = edn_vector(vector_str);
assert_eq!(vector_res, Ok(("", Vector(vec!()))));
}
#[test]
fn vector_varargs() {
let vector_str = "[& args]";
let vector_res = edn_vector(vector_str);
assert_eq!(
vector_res,
Ok((
"",
Vector(vec![
Symbol {
namespace: None,
name: "&"
},
Symbol {
namespace: None,
name: "args"
}
])
))
);
}
#[test]
fn vector_heterogenous_nested() {
let vector_str = "[:a b true false [[] 232 ()] some-sym :c]";
let vector_res = edn_vector(vector_str);
assert_eq!(
vector_res,
Ok((
"",
Vector(vec!(
Keyword {
namespace: None,
name: "a"
},
Symbol {
namespace: None,
name: "b"
},
Bool(true),
Bool(false),
Vector(vec!(Vector(vec!()), Integer(232), List(vec!()))),
Symbol {
namespace: None,
name: "some-sym"
},
Keyword {
namespace: None,
name: "c"
}
))
))
);
}
#[test]
fn map() {
let map_str = "{:a 1}";
let map_res = edn_map(map_str);
assert_eq!(
map_res,
Ok((
"",
Map(map!(
Keyword {
namespace: None,
name: "a"
},
Integer(1)
))
))
);
}
#[test]
fn map_empty() {
let map_str = "{}";
let map_res = edn_map(map_str);
assert_eq!(map_res, Ok(("", Map(map!()))));
}
#[test]
fn map_nested_values() {
let map_str = "{:a [1 2 4.01]}";
let map_res = edn_map(map_str);
assert_eq!(
map_res,
Ok((
"",
Map(map!(
Keyword {
namespace: None,
name: "a"
},
Vector(vec!(Integer(1), Integer(2), Float(4.01.into())))
))
))
);
}
#[test]
fn map_nested_keys() {
let map_str = "{[1 2 3] :a\n {} :bcd {} :zzzzzzzz}";
let (map_remaining, map_res) = edn_map(map_str).unwrap();
// :bcd should be gone, as :zzzzzzzz overwrites
assert!(match &map_res {
Map(m) => !m.values().collect::<crate::Set<&Edn>>().contains(&Symbol {
namespace: None,
name: "bcd"
}),
_ => panic!(),
});
assert_eq!(
(map_remaining, map_res),
(
"",
Map(map!(
Vector(vec!(Integer(1), Integer(2), Integer(3))),
Keyword {
namespace: None,
name: "a"
},
Map(map!()),
Keyword {
namespace: None,
name: "zzzzzzzz"
}
))
)
);
}
#[test]
fn set() {
let set_str = "#{:a 1}";
let set_res = edn_set(set_str);
assert_eq!(
set_res,
Ok((
"",
Set(set!(
Keyword {
namespace: None,
name: "a"
},
Integer(1)
))
))
);
}
#[test]
fn set_empty() {
let set_str = "#{}";
let set_res = edn_set(set_str);
assert_eq!(set_res, Ok(("", Set(set!()))));
}
#[test]
fn set_nested_values() {
let set_str = "#{:a [1 2 3]}";
let set_res = edn_set(set_str);
assert_eq!(
set_res,
Ok((
"",
Set(set!(
Keyword {
namespace: None,
name: "a"
},
Vector(vec!(Integer(1), Integer(2), Integer(3)))
))
))
);
}
#[test]
fn set_nested_keys() {
let set_str = "#{[1 2 3] :a\n {} :bcd {} #{} [] (1 2 #{}) :zzzzzzzz}"; // only one nested empty map
let set_res = edn_set(set_str);
assert_eq!(
set_res,
Ok((
"",
Set(set!(
Vector(vec!(Integer(1), Integer(2), Integer(3))),
Keyword {
namespace: None,
name: "a"
},
Map(map!()),
Keyword {
namespace: None,
name: "bcd"
},
Set(set!()),
Vector(vec!()),
List(vec!(Integer(1), Integer(2), Set(set!()))),
Keyword {
namespace: None,
name: "zzzzzzzz"
}
))
))
);
}
#[test]
fn set_leading_whitespace() {
let set_str = "#{,,,1 2 5}";
let set_res = edn_set(set_str);
assert_eq!(
set_res,
Ok(("", Set(set!(Integer(1), Integer(2), Integer(5)))))
);
}
#[test]
fn set_trailing_whitespace() {
let set_str = "#{1 2 5,, ,}";
let set_res = edn_set(set_str);
assert_eq!(
set_res,
Ok(("", Set(set!(Integer(1), Integer(2), Integer(5)))))
);
}
#[test]
fn set_leading_and_trailing_whitespace() {
let set_str = "#{ ,, ,, 1 2 5,, ,}";
let set_res = edn_set(set_str);
assert_eq!(
set_res,
Ok(("", Set(set!(Integer(1), Integer(2), Integer(5)))))
);
}
#[test]
fn discard_sequence() {
// only term is discarded results in
// an empty, but valid result
assert_eq!(edn_any("#_{:a :b :c :d}"), Ok(("", None)));
assert_eq!(
edn_any("[1 2 #_3 4]"),
Ok(("", Some(Vector(vec!(Integer(1), Integer(2), Integer(4))))))
);
// with weird nesting
assert_eq!(
edn_any("[1 2 #_[1 2 #_3] 4]"),
Ok(("", Some(Vector(vec!(Integer(1), Integer(2), Integer(4))))))
);
// with varied types
assert_eq!(
edn_map("{:a 1.01 #_:b #_38000 :c :d}"),
Ok((
"",
Map(map!(
Keyword {
namespace: None,
name: "a"
},
Float(1.01.into()),
Keyword {
namespace: None,
name: "c"
},
Keyword {
namespace: None,
name: "d"
}
))
))
)
}
#[test]
fn tags_inst() {
let inst = chrono::DateTime::parse_from_rfc3339("1985-04-12T23:20:50.52Z").unwrap();
assert_eq!(
edn_tag(r###"#inst "1985-04-12T23:20:50.52Z""###),
Ok(("", Edn::Tag(crate::Tag::Inst(inst))))
);
assert_eq!(
edn_tag("#inst \t \n\n \r\n \t\t \"1985-04-12T23:20:50.52Z\""),
Ok(("", Edn::Tag(crate::Tag::Inst(inst))))
);
}
#[test]
fn tags_uuid() {
let uuid = uuid::Uuid::from_str("f81d4fae-7dec-11d0-a765-00a0c91e6bf6").unwrap();
assert_eq!(
edn_tag("#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\""),
Ok(("", Edn::Tag(crate::Tag::UUID(uuid))))
);
}
#[test]
fn tags_user_defined() {
// custom simple tag
assert_eq!(
edn_tag("#myapp/Foo \"string as tag element\""),
Ok((
"",
Edn::Tag(crate::Tag::UserDefined {
prefix: "myapp",
name: "Foo",
element: Box::new(Edn::String("string as tag element"))
})
))
);
// custom complex tag
assert_eq!(
edn_tag("#myapp/Foo [1, \"2\", :a_keyword]"),
Ok((
"",
Edn::Tag(crate::Tag::UserDefined {
prefix: "myapp",
name: "Foo",
element: Box::new(Edn::Vector(vec![
Edn::Integer(1),
Edn::String("2"),
Edn::Keyword {
namespace: None,
name: "a_keyword"
}
]))
})
))
);
// tags require a name
assert_eq!(
edn_tag("#myapp [1, \"2\", :a_keyword]"),
Err(nom::Err::Error(VerboseError {
errors: vec![
(
" [1, \"2\", :a_keyword]",
nom::error::VerboseErrorKind::Nom(nom::error::ErrorKind::Tag)
),
(
"myapp [1, \"2\", :a_keyword]",
nom::error::VerboseErrorKind::Nom(nom::error::ErrorKind::Alt)
)
]
}))
);
// tags require a prefix
assert_eq!(
edn_tag("#Foo [1, \"2\", :a_keyword]"),
Err(nom::Err::Error(VerboseError {
errors: vec![
(
" [1, \"2\", :a_keyword]",
nom::error::VerboseErrorKind::Nom(nom::error::ErrorKind::Tag)
),
(
"Foo [1, \"2\", :a_keyword]",
nom::error::VerboseErrorKind::Nom(nom::error::ErrorKind::Alt)
)
]
}))
);
// tags can't be tag elements
assert_eq!(
edn_tag("#myapp/Foo #myapp/ASecondTag []"),
Err(nom::Err::Error(VerboseError {
errors: vec![
(
"",
nom::error::VerboseErrorKind::Nom(nom::error::ErrorKind::Tag)
),
(
"myapp/Foo #myapp/ASecondTag []",
nom::error::VerboseErrorKind::Nom(nom::error::ErrorKind::Alt)
)
]
}))
);
// comments can't be tag elements
assert_eq!(
edn_tag("#myapp/Foo ;; some comment"),
Err(nom::Err::Error(VerboseError {
errors: vec![
(
"",
nom::error::VerboseErrorKind::Nom(nom::error::ErrorKind::Tag)
),
(
"myapp/Foo ;; some comment",
nom::error::VerboseErrorKind::Nom(nom::error::ErrorKind::Alt)
)
]
}))
);
}
#[test]
fn comments() {
// with trailing newline
assert_eq!(
edn_comment(";; this is a comment and should not appear\n"),
Ok(("", Comment))
);
// with trailing \r\n
assert_eq!(
edn_comment(";; this is a comment and should not appear\r\n"),
Ok(("", Comment))
);
// preceding
assert_eq!(
edn_many!(";; this is a comment and should not appear\n[,,, 1,, 2 3 ,,]"),
vec![Vector(vec!(Integer(1), Integer(2), Integer(3)))]
);
// following
assert_eq!(
edn_many!("[ 1, 2, 3, ,,,];; this is a comment and should not appear"),
vec![Vector(vec!(Integer(1), Integer(2), Integer(3)))]
);
// middle
assert_eq!(
edn_many!("[1 2 3];; this is a comment and should not appear\n[4 5 6]"),
vec![
Vector(vec!(Integer(1), Integer(2), Integer(3))),
Vector(vec!(Integer(4), Integer(5), Integer(6)))
]
);
// at EOF
assert_eq!(
edn_many!(";; this is a comment and should not appear"),
vec![]
);
}
#[test]
fn whitespace_commas() {
// lists
assert_eq!(
edn_many!("(,,1,, 2 ,, 3,,,,)"),
vec![List(vec![Integer(1), Integer(2), Integer(3)])]
);
// vectors
assert_eq!(
edn_many!("[,,1,2,3 ,]"),
vec![Vector(vec![Integer(1), Integer(2), Integer(3)])]
);
// maps
assert_eq!(
edn_many!(",{,:a,1,,,,:b,2,}"),
vec![Map(map![
Keyword {
namespace: None,
name: "a"
},
Integer(1),
Keyword {
namespace: None,
name: "b"
},
Integer(2)
])]
);
// set
assert_eq!(
edn_many!("#{,,,, 1 , 2, 3 , }"),
vec![Set(set![Integer(1), Integer(2), Integer(3)])]
);
}
#[test]
fn real_edn() {
let start = std::time::Instant::now();
let embedded_res = edn!(DEPS_DOT_EDN);
let end = std::time::Instant::now();
println!("{:?}", end - start);
assert_eq!(
embedded_res,
Map(map!(
Keyword {
namespace: None,
name: "paths"
},
Vector(vec!(String("resources"), String("src"))),
Keyword {
namespace: None,
name: "deps"
},
Map(map!(
Symbol {
namespace: Some("org.clojure"),
name: "clojure"
},
Map(map!(
Keyword {
namespace: Some("mvn"),
name: "version"
},
String("1.10.0")
)),
Symbol {
namespace: None,
name: "instaparse".into()
},
Map(map!(
Keyword {
namespace: Some("mvn"),
name: "version"
},
String("1.4.9")
)),
Symbol {
namespace: None,
name: "quil"
},
Map(map!(
Keyword {
namespace: Some("mvn"),
name: "version"
},
String("2.8.0"),
Keyword {
namespace: None,
name: "exclusions"
},
Vector(vec!(Symbol {
namespace: Some("com.lowagie"),
name: "itext"
}))
),),
Symbol {
namespace: Some("com.hypirion"),
name: "clj-xchart"
},
Map(map!(
Keyword {
namespace: Some("mvn"),
name: "version"
},
String("0.2.0")
)),
Symbol {
namespace: Some("net.mikera"),
name: "core.matrix"
},
Map(map!(
Keyword {
namespace: Some("mvn"),
name: "version"
},
String("0.62.0")
)),
Symbol {
namespace: Some("net.mikera"),
name: "vectorz-clj"
},
Map(map!(
Keyword {
namespace: Some("mvn"),
name: "version"
},
String("0.48.0")
))
)),
Keyword {
namespace: None,
name: "aliases"
},
Map(map!(
Keyword {
namespace: None,
name: "more-mem"
},
Map(map!(
Keyword {
namespace: None,
name: "jvm-opts"
},
Vector(vec!(String("-Xmx12G -Xms12G")))
),),
Keyword {
namespace: None,
name: "test"
},
Map(map!(
Keyword {
namespace: None,
name: "extra-paths"
},
Vector(vec!(String("test"))),
Keyword {
namespace: None,
name: "extra-deps"
},
Map(map!(
Symbol {
namespace: Some("org.clojure"),
name: "test.check"
},
Map(map!(
Keyword {
namespace: Some("mvn"),
name: "version"
},
String("RELEASE")
))
))
)),
Keyword {
namespace: None,
name: "runner"
},
Map(map!(
Keyword {
namespace: None,
name: "extra-deps"
},
Map(map!(
Symbol {
namespace: Some("com.cognitect"),
name: "test-runner"
},
Map(map!(
Keyword {
namespace: Some("git"),
name: "url"
},
String("https://github.com/cognitect-labs/test-runner"),
Keyword {
namespace: None,
name: "sha"
},
String("76568540e7f40268ad2b646110f237a60295fa3c")
),)
)),
Keyword {
namespace: None,
name: "main-opts"
},
Vector(vec!(
String("-m"),
String("cognitect.test-runner"),
String("-d"),
String("test")
),)
))
),)
))
)
}
#[test]
fn equality() {
// Nil,
assert_eq!(Nil, Nil);
assert_ne!(
Nil,
Keyword {
namespace: None,
name: "Nil"
}
);
// Bool(bool),
assert_eq!(Bool(true), Bool(true));
assert_ne!(Bool(true), Bool(false));
// String(&'a str),
assert_eq!(String("a"), String("a"));
assert_ne!(String("a"), String("z"));
// Character(char),
assert_eq!(Character('a'), Character('a'));
assert_ne!(Character('a'), Character('b'));
// Symbol(String),
assert_eq!(
Symbol {
namespace: None,
name: "a"
},
Symbol {
namespace: None,
name: "a"
}
);
assert_ne!(
Symbol {
namespace: None,
name: "a"
},
Symbol {
namespace: None,
name: "z"
}
);
// Keyword(String),
assert_eq!(
Keyword {
namespace: None,
name: "a"
},
Keyword {
namespace: None,
name: "a"
}
);
assert_ne!(
Keyword {
namespace: None,
name: "a"
},
Keyword {
namespace: None,
name: "z"
}
);
// Integer(isize),
assert_eq!(Integer(1), Integer(1));
assert_ne!(Integer(1), Integer(2));
// Float(f64),
assert_eq!(Float(32.0.into()), Float(32.0.into()));
assert_ne!(Float(32.0.into()), Float(84.0.into()));
// Decimal(rust_decimal::Decimal),
assert_eq!(
Decimal(rust_decimal::Decimal::from_str("32.0").unwrap()),
Decimal(rust_decimal::Decimal::from_str("32.0").unwrap())
);
assert_ne!(
Decimal(rust_decimal::Decimal::from_str("32.0").unwrap()),
Decimal(rust_decimal::Decimal::from_str("19.9999999999").unwrap())
);
assert_ne!(
Decimal(rust_decimal::Decimal::from_str("32.0").unwrap()),
Float(32.0.into())
);
// List(Vec<Edn<'a>>),
assert_eq!(List(vec![]), List(vec![]));
assert_eq!(List(vec![Integer(1)]), List(vec![Integer(1)]));
assert_ne!(List(vec![Integer(1)]), List(vec![Float(1.0444444.into())]));
// Vector(Vec<Edn<'a>>),
assert_eq!(Vector(vec![]), Vector(vec![]));
assert_eq!(Vector(vec![Integer(1)]), Vector(vec![Integer(1)]));
assert_ne!(Vector(vec![Integer(1)]), List(vec![Integer(1)]));
// Map(HashMap<Edn<'a>, Edn<'a>>),
assert_eq!(Map(map!()), Map(map!()));
assert_eq!(
Map(map!(
Keyword {
namespace: None,
name: "a"
},
Integer(1)
)),
Map(map!(
Keyword {
namespace: None,
name: "a"
},
Integer(1)
))
);
assert_eq!(
Map(map!(
Keyword {
namespace: None,
name: "a"
},
Integer(1),
Keyword {
namespace: None,
name: "b"
},
Integer(2)
)),
Map(map!(
Keyword {
namespace: None,
name: "b"
},
Integer(2),
Keyword {
namespace: None,
name: "a"
},
Integer(1)
))
);
assert_ne!(
Map(map!(
Keyword {
namespace: None,
name: "a"
},
Float(2.1.into())
)),
Map(map!(
Keyword {
namespace: None,
name: "a"
},
Float(1.2.into())
))
);
// Set(HashSet<Edn<'a>>),
assert_eq!(Set(set![Integer(1)]), Set(set![Integer(1)]));
assert_ne!(Set(set![Integer(1)]), Set(set![Integer(91391)]));
assert_ne!(Set(set![Integer(1)]), List(vec![]));
}
#[test]
fn parses_ascii_stl_src() {
let start = std::time::Instant::now();
let result = edn_many!(ASCII_STL);
let end = std::time::Instant::now();
println!("ascii_stl_src time: {:?}", end - start);
assert_eq!(result.len(), 6);
}
#[test]
fn empty_input() {
assert_eq!(Edn::Nil, edn!(""))
}
}
|
use std::io::Cursor;
use glium::texture::{MipmapsOption, Texture2d};
use glium::{texture::RawImage2d, Display};
pub fn load_png_texture(display: &Display, bytes: &[u8]) -> Texture2d {
let image = image::load(Cursor::new(bytes), image::ImageFormat::Png)
.unwrap()
.to_rgba8();
let image_dimensions = image.dimensions();
let image = RawImage2d::from_raw_rgba_reversed(&image.into_raw(), image_dimensions);
let texture = glium::texture::Texture2d::with_mipmaps(
display,
image,
MipmapsOption::AutoGeneratedMipmaps,
)
.unwrap();
texture
}
|
mod cmds;
mod procs;
use std::process::{abort, exit};
use self::cmds::Commands;
use self::procs::{setup, run};
macro_rules! run_or_exit {
( $cmd:expr, $own_args:expr ) => {
match run($cmd.exe().unwrap(), $cmd.args(), $own_args) {
Ok(code) => if code != 0 { exit(code) },
Err(e) => { eprintln!("{}", e); abort(); },
}
};
}
fn main() {
let mut cmds = Commands::from_current_exe().unwrap_or_else(|e| {
eprintln!("{}", e);
abort();
});
setup().unwrap_or_else(|e| { eprintln!("{}", e); abort(); });
match cmds.next() {
Some(cmd) => run_or_exit!(cmd, true),
None => { abort(); },
};
for cmd in cmds {
run_or_exit!(cmd, false);
}
}
|
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
mod utils;
#[cfg(test)]
mod basic_directed_graph_tests {
use crate::utils::assert_sorted_vec_eq;
use graphific::{AnyGraph, BasicDirectedGraph, Edge, Kinship, Vertex};
#[test]
fn new_basic_directed_graph() {
let graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let vertices: Vec<Vertex<i32, i32>> = vec![];
let edges: Vec<Edge<i32>> = vec![];
assert_sorted_vec_eq(&vertices, &graph.vertices());
assert_sorted_vec_eq(&edges, &graph.edges());
}
#[test]
fn add_vertex() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let mut vertices: Vec<Vertex<i32, i32>> = vec![];
assert_sorted_vec_eq(&vertices, &graph.vertices());
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
graph = graph.add_vertex(v1.clone()).unwrap();
vertices.push(v1);
assert_sorted_vec_eq(&vertices, &graph.vertices());
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
graph = graph.add_vertex(v2.clone()).unwrap();
vertices.push(v2);
assert_sorted_vec_eq(&vertices, &graph.vertices());
let v3: Vertex<i32, i32> = Vertex::with_value(2, 9);
let should_be_none = graph.add_vertex(v3.clone());
assert_eq!(true, should_be_none.is_none());
}
#[test]
fn remove_vertex() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let mut vertices: Vec<Vertex<i32, i32>> = vec![];
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
vertices.push(v1.clone());
vertices.push(v2.clone());
// initial check
assert_sorted_vec_eq(&vertices, &graph.vertices());
// remove v1
let (graph, removed_v1, removed_edges) = graph.remove_vertex(&v1).unwrap();
let excepted_removed_edges: Vec<Edge<i32>> = vec![e1];
let excepted_remaining_edges: Vec<Edge<i32>> = vec![];
vertices = vec![v2.clone()];
assert_sorted_vec_eq(&vertices, &graph.vertices());
assert_sorted_vec_eq(&excepted_remaining_edges, &graph.edges());
assert_eq!(v1, removed_v1);
assert_sorted_vec_eq(&excepted_removed_edges, &removed_edges);
// try to remove v1 but fail
let should_be_none = graph.remove_vertex(&v1);
assert_eq!(true, should_be_none.is_none());
// remove v2
let (graph, removed_v2, removed_edges) = graph.remove_vertex(&v2).unwrap();
let excepted_removed_edges: Vec<Edge<i32>> = vec![];
let excepted_remaining_edges: Vec<Edge<i32>> = vec![];
vertices = vec![];
assert_sorted_vec_eq(&vertices, &graph.vertices());
assert_sorted_vec_eq(&excepted_remaining_edges, &graph.edges());
assert_eq!(v2, removed_v2);
assert_sorted_vec_eq(&excepted_removed_edges, &removed_edges);
}
#[test]
fn remove_all_vertices() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e4: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
graph = graph
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_vertex(v3.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap()
.add_edge(e3.clone())
.unwrap()
.add_edge(e4.clone())
.unwrap();
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove all vertices
let (result_graph, removed_vertices, removed_edges) = graph.remove_all_vertices().unwrap();
let expected_removed_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
let expected_removed_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
let expected_remaining_vertices: Vec<Vertex<i32, i32>> = vec![];
let expected_remaining_edges: Vec<Edge<i32>> = vec![];
assert_sorted_vec_eq(&expected_removed_vertices, &removed_vertices);
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_vertices, &result_graph.vertices());
assert_sorted_vec_eq(&expected_remaining_edges, &result_graph.edges());
}
#[test]
fn add_edge() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
// cannot add if their is no vertices
let should_be_none = graph.add_edge(e1.clone());
assert_eq!(true, should_be_none.is_none());
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
// add an edge
graph = graph.add_edge(e1.clone()).unwrap();
let expected_edges: Vec<Edge<i32>> = vec![e1.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// add more edges
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
let expected_edges: Vec<Edge<i32>> = vec![e1.clone(), e2.clone(), e3.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
}
#[test]
fn remove_edge() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone()];
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove e1
let (graph, removed_edge) = graph.remove_edge(&e1).unwrap();
assert_eq!(e1, removed_edge);
let expected_edges = vec![e2.clone(), e3.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// try to remove e1 but fail because this edge doesn't exists
let should_be_none = graph.remove_edge(&e1);
assert_eq!(true, should_be_none.is_none());
assert_sorted_vec_eq(&expected_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove v2 and v3
let (graph, removed_e2) = graph.remove_edge(&e2).unwrap();
let (graph, removed_e3) = graph.remove_edge(&e3).unwrap();
let expected_edges = vec![];
assert_eq!(e2, removed_e2);
assert_eq!(e3, removed_e3);
assert_sorted_vec_eq(&expected_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
}
#[test]
fn remove_all_edges() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e4: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
graph = graph
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_vertex(v3.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap()
.add_edge(e3.clone())
.unwrap()
.add_edge(e4.clone())
.unwrap();
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove all vertices
let (result_graph, removed_edges) = graph.remove_all_edges().unwrap();
let expected_removed_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
let expected_remaining_vertices: Vec<Vertex<i32, i32>> =
vec![v1.clone(), v2.clone(), v3.clone()];
let expected_remaining_edges: Vec<Edge<i32>> = vec![];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_vertices, &result_graph.vertices());
assert_sorted_vec_eq(&expected_remaining_edges, &result_graph.edges());
}
#[test]
fn remove_all_edges_where_vertex() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let v4: Vertex<i32, i32> = Vertex::with_value(-1, -1);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e4: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_vertex(v3.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
graph = graph.add_edge(e4.clone()).unwrap();
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove all from v1
let (graph, removed_edges) = graph.remove_all_edges_where_vertex(&v1).unwrap();
let expected_removed_edges = vec![e1.clone(), e2.clone(), e4.clone()];
let expected_remaining_edges = vec![e3.clone()];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// try to remove v4 but fail because v4 doesn't exists in graph
let should_be_none = graph.remove_all_edges_where_vertex(&v4);
assert_eq!(true, should_be_none.is_none());
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove all from v3
let (graph, removed_edges) = graph.remove_all_edges_where_vertex(&v3).unwrap();
let expected_removed_edges = vec![];
let expected_remaining_edges = vec![e3.clone()];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove all from v2
let (graph, removed_edges) = graph.remove_all_edges_where_vertex(&v2).unwrap();
let expected_removed_edges = vec![e3.clone()];
let expected_remaining_edges = vec![];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
}
#[test]
fn remove_all_edges_from() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let v4: Vertex<i32, i32> = Vertex::with_value(-1, -1);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e4: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_vertex(v3.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
graph = graph.add_edge(e4.clone()).unwrap();
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove all from v1
let (graph, removed_edges) = graph.remove_all_edges_from_vertex(&v1).unwrap();
let expected_removed_edges = vec![e1.clone(), e4.clone()];
let expected_remaining_edges = vec![e2.clone(), e3.clone()];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// try to remove v4 but fail because v4 doesn't exists in graph
let should_be_none = graph.remove_all_edges_from_vertex(&v4);
assert_eq!(true, should_be_none.is_none());
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove all from v3
let (graph, removed_edges) = graph.remove_all_edges_from_vertex(&v3).unwrap();
let expected_removed_edges = vec![];
let expected_remaining_edges = vec![e2.clone(), e3.clone()];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove all from v2
let (graph, removed_edges) = graph.remove_all_edges_from_vertex(&v2).unwrap();
let expected_removed_edges = vec![e2.clone(), e3.clone()];
let expected_remaining_edges = vec![];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
}
#[test]
fn successors() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e4: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
// init
graph = graph
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_vertex(v3.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap()
.add_edge(e3.clone())
.unwrap()
.add_edge(e4.clone())
.unwrap();
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// tests all vertices and its corresponding edges
let successors = graph.successors();
let expected_edges_v1 = vec![e1.clone(), e4.clone()];
let expected_edges_v2 = vec![e2.clone(), e3.clone()];
let expected_edges_v3 = vec![];
assert_sorted_vec_eq(&expected_edges_v1, &successors.get(&v1).unwrap());
assert_sorted_vec_eq(&expected_edges_v2, &successors.get(&v2).unwrap());
assert_sorted_vec_eq(&expected_edges_v3, &successors.get(&v3).unwrap());
// tests all keys and its corresponding edges
let successors = graph.successors_as_key_and_edges();
assert_sorted_vec_eq(&expected_edges_v1, &successors.get(v1.key()).unwrap());
assert_sorted_vec_eq(&expected_edges_v2, &successors.get(v2.key()).unwrap());
assert_sorted_vec_eq(&expected_edges_v3, &successors.get(v3.key()).unwrap());
}
#[test]
fn predecessors() {
let mut graph: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, -1);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e4: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
// init
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_vertex(v3.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
graph = graph.add_edge(e4.clone()).unwrap();
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
let predecessors = graph.predecessors();
// tests all vertices and its corresponding edges
let expected_edges_v1 = vec![e2.clone()];
let expected_edges_v2 = vec![e1.clone(), e3.clone()];
let expected_edges_v3 = vec![e4.clone()];
assert_sorted_vec_eq(&expected_edges_v1, &predecessors.get(&v1).unwrap());
assert_sorted_vec_eq(&expected_edges_v2, &predecessors.get(&v2).unwrap());
assert_sorted_vec_eq(&expected_edges_v3, &predecessors.get(&v3).unwrap());
// tests all keys and its corresponding edges
let predecessors = graph.predecessors_as_key_and_edges();
assert_sorted_vec_eq(&expected_edges_v1, &predecessors.get(v1.key()).unwrap());
assert_sorted_vec_eq(&expected_edges_v2, &predecessors.get(v2.key()).unwrap());
assert_sorted_vec_eq(&expected_edges_v3, &predecessors.get(v3.key()).unwrap());
}
#[test]
fn eq() {
let mut graph1: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let mut graph2: BasicDirectedGraph<i32, i32> = BasicDirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e4: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
// init
graph1 = graph1
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_vertex(v3.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap()
.add_edge(e3.clone())
.unwrap()
.add_edge(e4.clone())
.unwrap();
graph2 = graph2
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap()
.add_edge(e3.clone())
.unwrap();
assert_eq!(false, graph1.eq(&graph2));
assert_eq!(true, graph1.ne(&graph2));
graph2 = graph2.add_vertex(v3.clone()).unwrap();
assert_eq!(false, graph1.eq(&graph2));
assert_eq!(true, graph1.ne(&graph2));
graph2 = graph2.add_edge(e4.clone()).unwrap();
assert_eq!(true, graph1.eq(&graph2));
assert_eq!(false, graph1.ne(&graph2));
}
}
#[cfg(test)]
mod basic_undirected_graph_tests {
use crate::utils::assert_sorted_vec_eq;
use graphific::{AnyGraph, BasicUndirectedGraph, Edge, Kinship, Vertex};
#[test]
fn new_basic_directed_graph() {
let graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let vertices: Vec<Vertex<i32, i32>> = vec![];
let edges: Vec<Edge<i32>> = vec![];
assert_sorted_vec_eq(&vertices, &graph.vertices());
assert_sorted_vec_eq(&edges, &graph.edges());
}
#[test]
fn add_vertex() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let mut vertices: Vec<Vertex<i32, i32>> = vec![];
assert_sorted_vec_eq(&vertices, &graph.vertices());
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
graph = graph.add_vertex(v1.clone()).unwrap();
vertices.push(v1);
assert_sorted_vec_eq(&vertices, &graph.vertices());
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
graph = graph.add_vertex(v2.clone()).unwrap();
vertices.push(v2);
assert_sorted_vec_eq(&vertices, &graph.vertices());
let v3: Vertex<i32, i32> = Vertex::with_value(2, -1);
let should_be_none = graph.add_vertex(v3.clone());
assert_eq!(true, should_be_none.is_none());
}
#[test]
fn remove_vertex() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let mut vertices: Vec<Vertex<i32, i32>> = vec![];
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
vertices.push(v1.clone());
vertices.push(v2.clone());
// initial check
assert_sorted_vec_eq(&vertices, &graph.vertices());
// remove v1
let (graph, removed_v1, removed_edges) = graph.remove_vertex(&v1).unwrap();
let excepted_removed_edges: Vec<Edge<i32>> = vec![e1];
let excepted_remaining_edges: Vec<Edge<i32>> = vec![];
vertices = vec![v2.clone()];
assert_sorted_vec_eq(&vertices, &graph.vertices());
assert_sorted_vec_eq(&excepted_remaining_edges, &graph.edges());
assert_eq!(v1, removed_v1);
assert_sorted_vec_eq(&excepted_removed_edges, &removed_edges);
// try to remove v1 but fail
let should_be_none = graph.remove_vertex(&v1);
assert_eq!(true, should_be_none.is_none());
// remove v2
let (graph, removed_v2, removed_edges) = graph.remove_vertex(&v2).unwrap();
let excepted_removed_edges: Vec<Edge<i32>> = vec![];
let excepted_remaining_edges: Vec<Edge<i32>> = vec![];
vertices = vec![];
assert_sorted_vec_eq(&vertices, &graph.vertices());
assert_sorted_vec_eq(&excepted_remaining_edges, &graph.edges());
assert_eq!(v2, removed_v2);
assert_sorted_vec_eq(&excepted_removed_edges, &removed_edges);
}
#[test]
fn remove_all_vertices() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e3: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
let e4: Edge<i32> = Edge::new(v2.key().clone(), v3.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
graph = graph
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_vertex(v3.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap()
.add_edge(e3.clone())
.unwrap()
.add_edge(e4.clone())
.unwrap();
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove all vertices
let (result_graph, removed_vertices, removed_edges) = graph.remove_all_vertices().unwrap();
let expected_removed_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
let expected_removed_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
let expected_remaining_vertices: Vec<Vertex<i32, i32>> = vec![];
let expected_remaining_edges: Vec<Edge<i32>> = vec![];
assert_sorted_vec_eq(&expected_removed_vertices, &removed_vertices);
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_vertices, &result_graph.vertices());
assert_sorted_vec_eq(&expected_remaining_edges, &result_graph.edges());
}
#[test]
fn add_edge() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v1.key().clone());
let e3: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
// cannot add if their is no vertices
let should_be_none = graph.add_edge(e1.clone());
assert_eq!(true, should_be_none.is_none());
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
// add an edge
graph = graph.add_edge(e1.clone()).unwrap();
let expected_edges: Vec<Edge<i32>> = vec![e1.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// cannot add the same edge in reverse order
let should_be_none = graph.add_edge(e2.clone());
assert_eq!(true, should_be_none.is_none());
// add more edges
graph = graph.add_edge(e3.clone()).unwrap();
let expected_edges: Vec<Edge<i32>> = vec![e1.clone(), e3.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
}
#[test]
fn remove_edge() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone()];
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
let expected_edges = vec![e1.clone(), e2.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove e1
let (graph, removed_edge) = graph.remove_edge(&e1).unwrap();
assert_eq!(e1, removed_edge);
let expected_edges = vec![e2.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// try to remove e1 but fail because this edge doesn't exists
let should_be_none = graph.remove_edge(&e1);
assert_eq!(true, should_be_none.is_none());
assert_sorted_vec_eq(&expected_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove v2
let (graph, removed_e2) = graph.remove_edge(&e2).unwrap();
let expected_edges = vec![];
assert_eq!(e2, removed_e2);
assert_sorted_vec_eq(&expected_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
}
#[test]
fn remove_all_edges() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e3: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone()];
graph = graph
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_vertex(v3.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap()
.add_edge(e3.clone())
.unwrap();
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove all vertices
let (result_graph, removed_edges) = graph.remove_all_edges().unwrap();
let expected_removed_edges = vec![e1.clone(), e2.clone(), e3.clone()];
let expected_remaining_vertices: Vec<Vertex<i32, i32>> =
vec![v1.clone(), v2.clone(), v3.clone()];
let expected_remaining_edges: Vec<Edge<i32>> = vec![];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_vertices, &result_graph.vertices());
assert_sorted_vec_eq(&expected_remaining_edges, &result_graph.edges());
}
#[test]
fn remove_all_edges_where_vertex() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let v4: Vertex<i32, i32> = Vertex::with_value(-1, -1);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e3: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
let e4: Edge<i32> = Edge::new(v2.key().clone(), v3.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_vertex(v3.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
graph = graph.add_edge(e4.clone()).unwrap();
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove all from v1
let (graph, removed_edges) = graph.remove_all_edges_where_vertex(&v1).unwrap();
let expected_removed_edges = vec![e1.clone(), e3.clone()];
let expected_remaining_edges = vec![e2.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// try to remove v4 but fail because v4 doesn't exists in graph
let should_be_none = graph.remove_all_edges_where_vertex(&v4);
assert_eq!(true, should_be_none.is_none());
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove all from v3
let (graph, removed_edges) = graph.remove_all_edges_where_vertex(&v3).unwrap();
let expected_removed_edges = vec![e4.clone()];
let expected_remaining_edges = vec![e2.clone()];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove all from v2
let (graph, removed_edges) = graph.remove_all_edges_where_vertex(&v2).unwrap();
let expected_removed_edges = vec![e2.clone()];
let expected_remaining_edges = vec![];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
}
#[test]
fn remove_all_edges_from() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let v4: Vertex<i32, i32> = Vertex::with_value(-1, -1);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e3: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
let e4: Edge<i32> = Edge::new(v2.key().clone(), v3.key().clone());
// init
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_vertex(v3.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
graph = graph.add_edge(e4.clone()).unwrap();
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
// remove all from v1
let (graph, removed_edges) = graph.remove_all_edges_from_vertex(&v1).unwrap();
let expected_removed_edges = vec![e1.clone(), e3.clone()];
let expected_remaining_edges = vec![e2.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// try to remove v4 but fail because v4 doesn't exists in graph
let should_be_none = graph.remove_all_edges_from_vertex(&v4);
assert_eq!(true, should_be_none.is_none());
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove all from v3
let (graph, removed_edges) = graph.remove_all_edges_from_vertex(&v3).unwrap();
let expected_removed_edges = vec![e4.clone()];
let expected_remaining_edges = vec![e2.clone()];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
// remove all from v2
let (graph, removed_edges) = graph.remove_all_edges_from_vertex(&v2).unwrap();
let expected_removed_edges = vec![e2.clone()];
let expected_remaining_edges = vec![];
assert_sorted_vec_eq(&expected_removed_edges, &removed_edges);
assert_sorted_vec_eq(&expected_remaining_edges, &graph.edges());
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
}
#[test]
fn successors() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e3: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
let e4: Edge<i32> = Edge::new(v2.key().clone(), v3.key().clone());
// init
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_vertex(v3.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
graph = graph.add_edge(e4.clone()).unwrap();
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
let successors = graph.successors();
// tests all vertices and its corresponding edges
let expected_edges_v1 = vec![e1.clone(), e3.clone()];
let expected_edges_v2 = vec![e1.clone(), e2.clone(), e4.clone()];
let expected_edges_v3 = vec![e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges_v1, &successors.get(&v1).unwrap());
assert_sorted_vec_eq(&expected_edges_v2, &successors.get(&v2).unwrap());
assert_sorted_vec_eq(&expected_edges_v3, &successors.get(&v3).unwrap());
// tests all keys and its corresponding edges
let successors = graph.successors_as_key_and_edges();
assert_sorted_vec_eq(&expected_edges_v1, &successors.get(v1.key()).unwrap());
assert_sorted_vec_eq(&expected_edges_v2, &successors.get(v2.key()).unwrap());
assert_sorted_vec_eq(&expected_edges_v3, &successors.get(v3.key()).unwrap());
}
#[test]
fn predecessors() {
let mut graph: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e3: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
let e4: Edge<i32> = Edge::new(v2.key().clone(), v3.key().clone());
// init
graph = graph.add_vertex(v1.clone()).unwrap();
graph = graph.add_vertex(v2.clone()).unwrap();
graph = graph.add_vertex(v3.clone()).unwrap();
graph = graph.add_edge(e1.clone()).unwrap();
graph = graph.add_edge(e2.clone()).unwrap();
graph = graph.add_edge(e3.clone()).unwrap();
graph = graph.add_edge(e4.clone()).unwrap();
let expected_vertices = vec![v1.clone(), v2.clone(), v3.clone()];
assert_sorted_vec_eq(&expected_vertices, &graph.vertices());
let expected_edges = vec![e1.clone(), e2.clone(), e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges, &graph.edges());
let predecessors = graph.predecessors();
// tests all vertices and its corresponding edges
let expected_edges_v1 = vec![e1.clone(), e3.clone()];
let expected_edges_v2 = vec![e1.clone(), e2.clone(), e4.clone()];
let expected_edges_v3 = vec![e3.clone(), e4.clone()];
assert_sorted_vec_eq(&expected_edges_v1, &predecessors.get(&v1).unwrap());
assert_sorted_vec_eq(&expected_edges_v2, &predecessors.get(&v2).unwrap());
assert_sorted_vec_eq(&expected_edges_v3, &predecessors.get(&v3).unwrap());
// tests all keys and its corresponding edges
let predecessors = graph.predecessors_as_key_and_edges();
assert_sorted_vec_eq(&expected_edges_v1, &predecessors.get(v1.key()).unwrap());
assert_sorted_vec_eq(&expected_edges_v2, &predecessors.get(v2.key()).unwrap());
assert_sorted_vec_eq(&expected_edges_v3, &predecessors.get(v3.key()).unwrap());
}
#[test]
fn eq() {
let mut graph1: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let mut graph2: BasicUndirectedGraph<i32, i32> = BasicUndirectedGraph::new();
let v1: Vertex<i32, i32> = Vertex::with_value(1, 1);
let v2: Vertex<i32, i32> = Vertex::with_value(2, 4);
let v3: Vertex<i32, i32> = Vertex::with_value(3, 9);
let e1: Edge<i32> = Edge::new(v1.key().clone(), v2.key().clone());
let e2: Edge<i32> = Edge::new(v2.key().clone(), v2.key().clone());
let e3: Edge<i32> = Edge::new(v1.key().clone(), v3.key().clone());
let e4: Edge<i32> = Edge::new(v2.key().clone(), v3.key().clone());
// init
graph1 = graph1
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_vertex(v3.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap()
.add_edge(e3.clone())
.unwrap()
.add_edge(e4.clone())
.unwrap();
graph2 = graph2
.add_vertex(v1.clone())
.unwrap()
.add_vertex(v2.clone())
.unwrap()
.add_edge(e1.clone())
.unwrap()
.add_edge(e2.clone())
.unwrap();
assert_eq!(false, graph1.eq(&graph2));
assert_eq!(true, graph1.ne(&graph2));
graph2 = graph2.add_vertex(v3.clone()).unwrap();
assert_eq!(false, graph1.eq(&graph2));
assert_eq!(true, graph1.ne(&graph2));
graph2 = graph2
.add_edge(e3.clone())
.unwrap()
.add_edge(e4.clone())
.unwrap();
assert_eq!(true, graph1.eq(&graph2));
assert_eq!(false, graph1.ne(&graph2));
}
}
|
/*!
```rudra-poc
[target]
crate = "flumedb"
version = "0.1.4"
indexed_version = "0.1.3"
[report]
issue_url = "https://github.com/sunrise-choir/flumedb-rs/issues/10"
issue_date = 2021-01-07
rustsec_url = "https://github.com/RustSec/advisory-db/pull/661"
rustsec_id = "RUSTSEC-2021-0086"
[[bugs]]
analyzer = "UnsafeDataflow"
bug_class = "UninitExposure"
bug_count = 2
rudra_report_locations = ["src/go_offset_log.rs:212:1: 263:2", "src/offset_log.rs:330:1: 358:2"]
```
!*/
#![forbid(unsafe_code)]
fn main() {
panic!("This issue was reported without PoC");
}
|
use util::*;
const LEN: usize = 25;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let timer = Timer::new();
let input = input::lines::<usize>(&std::env::args().nth(1).unwrap());
let mut lookup = vec![[0; LEN - 1]; input.len()];
for (i, n) in input.iter().enumerate() {
let start = if i < LEN { 0 } else { i + 1 - LEN };
for (j, m) in input[start..i].iter().enumerate() {
lookup[i][j] = n + m;
}
}
timer.print();
let timer = Timer::new();
for (i, n) in input.into_iter().enumerate().skip(LEN) {
let start = if i < LEN { 0 } else { i - LEN };
let mut found = false;
for m in (&lookup[start..i]).iter().flatten() {
if n == *m {
found = true;
break;
}
}
if !found {
timer.print();
println!("{}", n);
break;
}
}
Ok(())
}
|
use exitfailure::ExitFailure;
use std::path::PathBuf;
use structopt::StructOpt;
use structopt_flags::{ForceFlag, LogLevel, Verbose};
#[derive(Debug, StructOpt)]
struct Opt {
#[structopt(flatten)]
verbose: Verbose,
#[structopt(flatten)]
force_flag: ForceFlag,
/// Specify the database file you want to use
#[structopt(short = "d", long = "db", parse(from_os_str), raw(global = "true"))]
dbfile: Option<PathBuf>,
}
struct Config {
dbfile: PathBuf,
force: bool,
}
impl From<Opt> for Config {
fn from(opt: Opt) -> Self {
Config {
dbfile: opt.dbfile.unwrap_or_else(myrello::db::dbfile_default),
force: opt.force_flag.force,
}
}
}
fn main() -> Result<(), ExitFailure> {
let opt = Opt::from_args();
opt.verbose.set_log_level();
let config: Config = opt.into();
if config.force {
myrello::db::dbdir_create(&config.dbfile)?;
}
Ok(())
}
|
//! # The XML `<database>` format
//!
//! Before the FDB file format was created, older versions of the client used an XML
//! file to store the client database. This was also used for LUPs to add their data
//! independently of the rest of the game.
use displaydoc::Display;
use quick_xml::{events::Event, Reader};
use std::{collections::HashMap, error::Error, io::BufRead, str::FromStr};
use super::common::{expect_elem, expect_named_elem, XmlError};
#[cfg(feature = "serialize")]
use serde::{
de::{self, Unexpected, Visitor},
Deserialize, Deserializer,
};
#[cfg(feature = "serialize")]
use std::fmt;
/// The value types for the database
///
/// This is a rustic representation of the data types in Transact-SQL that
/// were/are used in the database.
///
/// See: <https://docs.microsoft.com/en-us/sql/t-sql/data-types>
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ValueType {
/// `bit`
Bit,
/// `float`
Float,
/// `real`
Real,
/// `int`
Int,
/// `bigint`
BigInt,
/// `smallint`
SmallInt,
/// `tinyint`
TinyInt,
/// `binary`
Binary,
/// `varbinary`
VarBinary,
/// `char`
Char,
/// `varchar`
VarChar,
/// `nchar`
NChar,
/// `nvarchar`
NVarChar,
/// `ntext`
NText,
/// `text`
Text,
/// `image`
Image,
/// `datetime`
DateTime,
/// `xml`
Xml,
/// `null`
Null,
}
#[cfg(feature = "serialize")]
impl<'de> Deserialize<'de> for ValueType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(ValueTypeVisitor)
}
}
#[derive(Debug, Display)]
/// Unknown value type '{0}'
pub struct UnknownValueType(String);
impl Error for UnknownValueType {}
impl FromStr for ValueType {
type Err = UnknownValueType;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"bit" => Ok(Self::Bit),
"float" => Ok(Self::Float),
"real" => Ok(Self::Real),
"int" => Ok(Self::Int),
"bigint" => Ok(Self::BigInt),
"smallint" => Ok(Self::SmallInt),
"tinyint" => Ok(Self::TinyInt),
"binary" => Ok(Self::Binary),
"varbinary" => Ok(Self::VarBinary),
"char" => Ok(Self::Char),
"varchar" => Ok(Self::VarChar),
"nchar" => Ok(Self::NChar),
"nvarchar" => Ok(Self::NVarChar),
"text" => Ok(Self::Text),
"ntext" => Ok(Self::NText),
"image" => Ok(Self::Image),
"datetime" => Ok(Self::DateTime),
"xml" => Ok(Self::Xml),
"null" => Ok(Self::Null),
_ => Err(UnknownValueType(s.to_owned())),
}
}
}
#[cfg(feature = "serialize")]
struct ValueTypeVisitor;
#[cfg(feature = "serialize")]
impl<'de> Visitor<'de> for ValueTypeVisitor {
type Value = ValueType;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("T-SQL value type")
}
fn visit_str<E>(self, value: &str) -> Result<ValueType, E>
where
E: de::Error,
{
FromStr::from_str(value)
.map_err(|_| E::invalid_value(Unexpected::Other(value), &"T-SQL value type"))
}
}
/// A row of the database
#[cfg_attr(feature = "serialize", derive(Deserialize))]
#[derive(Debug, Eq, PartialEq)]
pub struct Row(HashMap<String, String>);
/// Expects an opening `<database>`
pub fn expect_database<B: BufRead>(
xml: &mut Reader<B>,
buf: &mut Vec<u8>,
) -> Result<Option<String>, XmlError> {
expect_named_elem(xml, buf, "database", None)
}
/// Expects an opening `<table>` tag or a closing `</database>` tag
pub fn expect_table<B: BufRead>(
xml: &mut Reader<B>,
buf: &mut Vec<u8>,
) -> Result<Option<String>, XmlError> {
expect_named_elem(xml, buf, "table", Some("database"))
}
/// Expects an opening `<columns>` tag
pub fn expect_columns<B: BufRead>(xml: &mut Reader<B>, buf: &mut Vec<u8>) -> Result<(), XmlError> {
expect_elem(xml, buf, "columns")
}
/// Expects an opening `<rows>` tag
pub fn expect_rows<B: BufRead>(xml: &mut Reader<B>, buf: &mut Vec<u8>) -> Result<(), XmlError> {
expect_elem(xml, buf, "rows")
}
/// The information on a column
#[cfg_attr(feature = "serialize", derive(Deserialize))]
pub struct Column {
/// The name of the column
pub name: String,
/// The data type of the column
pub r#type: ValueType,
}
/*#[derive(Deserialize)]
/// The Columns struct
pub struct Columns {
/// The columns
columns: Vec<Column>
}*/
/// Expects an empty `<column …/>` tag or a closing `</columns>` tag
pub fn expect_column_or_end_columns<B: BufRead>(
xml: &mut Reader<B>,
buf: &mut Vec<u8>,
) -> Result<Option<Column>, XmlError> {
match xml.read_event(buf)? {
Event::Empty(start) => {
if start.name() == b"column" {
let mut name = None;
let mut data_type = None;
for attr in start.attributes() {
let attr = attr?;
if attr.key == b"name" {
name = Some(xml.decode(&attr.value).into_owned());
}
if attr.key == b"type" {
data_type = Some(
xml.decode(&attr.value)
.parse()
.expect("Expected well-known value type"),
);
}
}
buf.clear();
Ok(Some(Column {
name: name.unwrap(),
r#type: data_type.unwrap(),
}))
} else {
todo!();
}
}
Event::End(v) => {
assert_eq!(v.name(), b"columns");
Ok(None)
}
Event::Eof => Err(XmlError::EofWhileExpecting("column")),
x => panic!("What? {:?}", x),
}
}
/// Expects an empty `<row …/>` tag or a closing `</rows>` tag
pub fn expect_row_or_end_rows<B: BufRead>(
xml: &mut Reader<B>,
buf: &mut Vec<u8>,
load_attrs: bool,
) -> Result<Option<HashMap<String, String>>, XmlError> {
match xml.read_event(buf)? {
Event::Empty(start) => {
if start.name() == b"row" {
let map = if load_attrs {
let mut m = HashMap::new();
for attr in start.attributes() {
let attr = attr?;
let key = xml.decode(attr.key).into_owned();
let value = attr.unescape_and_decode_value(xml)?;
m.insert(key, value);
}
m
} else {
HashMap::new()
};
buf.clear();
Ok(Some(map))
} else {
todo!();
}
}
Event::End(v) => {
assert_eq!(v.name(), b"rows");
Ok(None)
}
_ => todo!(),
}
}
#[cfg(test)]
#[cfg(feature = "serialize")]
mod tests {
use quick_xml::{de::Deserializer, DeError};
use super::*;
use quick_xml::Error as XmlError;
use std::io::BufReader;
use std::io::Cursor;
#[test]
fn test_simple_deserialize() {
use serde::Deserialize;
let st = br#"<row foo="bar"/></rows>"#;
let c = BufReader::new(Cursor::new(st));
let mut d = Deserializer::from_reader(c);
let row = Row::deserialize(&mut d).unwrap();
let mut cmp = HashMap::new();
let key = String::from("foo");
let val = String::from("bar");
cmp.insert(key, val);
assert_eq!(row.0, cmp);
if let Err(DeError::Xml(XmlError::EndEventMismatch { expected, found })) =
Row::deserialize(&mut d)
{
assert_eq!(&expected, "");
assert_eq!(&found, "rows");
}
}
}
|
#![allow(non_camel_case_types)]
use libusb_sys as ffi;
use libc::{c_int,c_uchar};
use std::{mem::{MaybeUninit}, slice, ptr};
use log::{debug, info, error};
use snafu::{GenerateBacktrace};
use crate::ftdi::core::{FtdiError, Result};
use crate::ftdi::ftdi_context::ftdi_context;
/// brief list of usb devices created by ftdi_usb_find_all()
pub struct ftdi_device_list {
/// Vector keeps all devices and all are freed later
/// pub ftdi_device_list: Vec<*mut ffi::libusb_device>,
/// found ans stored number of devices.
/// It equals to number of devices in vector
pub number_found_devices: usize,
/// pointer to libusb's usb_device
pub system_device_list: Option<*const *mut ffi::libusb_device>,
}
impl ftdi_device_list {
/// Creates usb device list for all available devices in system
pub fn new(ftdi: &ftdi_context) -> Result<Self> {
debug!("start new ftdi_device_list...");
// check ftdi context
if ftdi.usb_ctx == None {
let error = FtdiError::UsbInit {code: -100, message: "ftdi context is not initialized previously".to_string(),
backtrace: GenerateBacktrace::generate()
};
error!("{}", error);
return Err(error);
}
// fetch usb device list
// let (device_list, devices_len) = ftdi_device_list::get_usb_device_list_internal(ftdi)?;
let mut device_list_uninit: MaybeUninit::<*const *mut ffi::libusb_device> = MaybeUninit::uninit();
let get_device_list_result = unsafe { ffi::libusb_get_device_list(ftdi.usb_ctx.unwrap(), device_list_uninit.as_mut_ptr()) };
if get_device_list_result < 0 {
let result = FtdiError::UsbCommandError { code: -5, message: "libusb_get_device_list() failed".to_string(),
backtrace: GenerateBacktrace::generate()
};
error!("{}", result);
return Err(result);
}
let device_list: *const *mut ffi::libusb_device = unsafe { device_list_uninit.assume_init() };
debug!("found total usb device(s) quantity = [{}]", get_device_list_result);
// common fields are filled
let list = ftdi_device_list{
number_found_devices: get_device_list_result as usize,
system_device_list: Some(device_list)};
debug!("found usb device quantity = {}", get_device_list_result);
Ok(list)
}
/// Finds all ftdi devices with given VID:PID on the usb bus. Creates a new
/// ftdi_device_list which is deallocated automatically after use and going out of scope.
/// With VID:PID 0:0, it searches for the default devices
/// (0x403:0x6001, 0x403:0x6010, 0x403:0x6011, 0x403:0x6014, 0x403:0x6015)
///
/// param ftdi is ftdi_context to create
/// devlist is stored in devices field 'system_device_list' field
/// \param vendor Vendor ID to search for
/// \param product Product ID to search for
/// ```rust, no_run
/// use ::ftdi_library::ftdi::ftdi_context::ftdi_context;
/// use ::ftdi_library::ftdi::ftdi_device_list::ftdi_device_list;
/// use libc::{c_int};
///
/// let mut ftdi = ftdi_context::new_with_log_level(Some(4)).unwrap(); // ffi::LIBUSB_LOG_LEVEL_DEBUG
/// let mut ftdi_list = ftdi_device_list::new(&ftdi).unwrap();
/// match ftdi_list.ftdi_usb_find_all(&mut ftdi, 0, 0) {
/// Ok(ftdi_usb_list) => {
/// println!("ftdi_usb_list is OK, found FTDI system_device_list = {:?}", ftdi_usb_list.system_device_list);
/// println!("ftdi_list is OK, found FTDI number = {}", ftdi_usb_list.number_found_devices);
/// }
/// Err(internal_error) => {
/// println!("{:?}", internal_error);
/// }
/// }
/// ```
pub fn ftdi_usb_find_all(&mut self, ftdi: &mut ftdi_context, vendor: u16, product: u16) -> Result<Self> {
debug!("start new ftdi_device_list by vendor = {}, product={} ...", vendor, product);
// check ftdi context
if ftdi.usb_ctx == None {
let error = FtdiError::UsbInit {code: -100, message: "ftdi context is not initialized previously".to_string(),
backtrace: GenerateBacktrace::generate()
};
error!("{}", error);
return Err(error);
}
if self.system_device_list.is_none() && self.number_found_devices == 0 {
let error = FtdiError::UsbInit {code: -101, message: "fftdi_device_list is not created previously".to_string(),
backtrace: GenerateBacktrace::generate()
};
error!("{}", error);
return Err(error);
}
// make slice using device list and iterate over it
let sys_device_list = unsafe { slice::from_raw_parts(
self.system_device_list.unwrap(), self.number_found_devices) };
let mut usb_dev_index = 0;
let mut found_usb_count = 0;
// loop over devices
for dev in sys_device_list {
let speed = unsafe { ffi::libusb_get_device_speed(*dev) };
let mut descriptor_uninit: MaybeUninit::<ffi::libusb_device_descriptor> = MaybeUninit::uninit();
// get description from usb device
let has_descriptor = match unsafe { ffi::libusb_get_device_descriptor(*dev, descriptor_uninit.as_mut_ptr()) } {
0 => {
true
},
_err => {
error!("{}", FtdiError::UsbCommandError{code: -6, message: "libusb_get_device_descriptor() failed".to_string(),
backtrace: GenerateBacktrace::generate()
});
false
},
};
let handle: *mut ffi::libusb_device_handle = ptr::null_mut();
if has_descriptor {
let descriptor: ffi::libusb_device_descriptor = unsafe { descriptor_uninit.assume_init() };
info!("USB ID [{:?}] : {:04x}:{:04x}", usb_dev_index, descriptor.idVendor, descriptor.idProduct);
// extract usb devices only specified by vendor and product ids
if (vendor > 0 || product > 0 &&
descriptor.idVendor == vendor && descriptor.idProduct == product) ||
!(vendor > 0 || product > 0) &&
(descriptor.idVendor == 0x403) && (descriptor.idProduct == 0x6001 || descriptor.idProduct == 0x6010
|| descriptor.idProduct == 0x6011 || descriptor.idProduct == 0x6014
|| descriptor.idProduct == 0x6015) {
debug!("Process matched device [{}]", usb_dev_index);
print_debug_device_descriptor(handle, &descriptor, speed);
unsafe { ffi::libusb_ref_device(*dev) };
ftdi.usb_dev = Some(handle);
found_usb_count += 1; // count found
} else {
debug!("SKIPPED unmatched USB ID [{:?}] : {:04x}:{:04x}", usb_dev_index, descriptor.idVendor, descriptor.idProduct);
}
}
usb_dev_index += 1;
}
let list = ftdi_device_list{
number_found_devices: found_usb_count,
// system_device_list: Some(sys_device_list.as_ptr())
system_device_list: None
};
if self.system_device_list != None {
unsafe { ffi::libusb_free_device_list(self.system_device_list.unwrap(),1); };
self.system_device_list = None;
}
debug!("usb device quantity: ftdi found = [{}], total usb found = [{}]", found_usb_count, usb_dev_index);
Ok(list)
}
// Helper internal method to fetch usb device list.
// Return tuple with found list and found device quantity
/* fn get_usb_device_list_internal(ftdi: &ftdi_context) -> Result< (*const *mut ffi::libusb_device, isize) > {
let mut device_list_uninit: MaybeUninit::<*const *mut ffi::libusb_device> = MaybeUninit::uninit();
let get_device_list_result = unsafe { ffi::libusb_get_device_list(ftdi.usb_ctx.unwrap(), device_list_uninit.as_mut_ptr()) };
if get_device_list_result < 0 {
let result = FtdiError::UsbCommandError { code: -5, message: "libusb_get_device_list() failed".to_string(),
backtrace: GenerateBacktrace::generate()
};
error!("{}", result);
return Err(result);
}
let device_list: *const *mut ffi::libusb_device = unsafe { device_list_uninit.assume_init() };
debug!("found total usb device(s) quantity = [{}]", get_device_list_result);
Ok( (device_list, get_device_list_result) )
}
*/
}
impl Drop for ftdi_device_list {
fn drop(&mut self) {
if self.system_device_list.is_some() {
debug!("cleaning up ftdi_device_list...");
unsafe { ffi::libusb_free_device_list(self.system_device_list.unwrap(), self.number_found_devices as c_int) };
self.system_device_list = None;
self.number_found_devices = 0;
}
debug!("cleaned up ftdi_device_list - OK");
}
}
pub fn print_debug_device_descriptor(handle: *mut ffi::libusb_device_handle,
descriptor: &ffi::libusb_device_descriptor,
speed: c_int) {
debug!("======= Device Descriptor: =======");
debug!(" bLength: {:16}", descriptor.bLength);
debug!(" bDescriptorType: {:8} {}", descriptor.bDescriptorType, get_descriptor_type(descriptor.bDescriptorType));
debug!(" bcdUSB: {:#06x} {}", descriptor.bcdUSB, get_bcd_version(descriptor.bcdUSB));
debug!(" bDeviceClass: {:#04x} {}", descriptor.bDeviceClass, get_class_type(descriptor.bDeviceClass));
debug!(" bDeviceSubClass: {:8}", descriptor.bDeviceSubClass);
debug!(" bDeviceProtocol: {:8}", descriptor.bDeviceProtocol);
debug!(" bMaxPacketSize0: {:8}", descriptor.bMaxPacketSize0);
debug!(" idVendor: {:#06x}", descriptor.idVendor);
debug!(" idProduct: {:#06x}", descriptor.idProduct);
debug!(" bcdDevice: {:#06x}", descriptor.bcdDevice);
debug!(" iManufacturer: {:10} {}", descriptor.iManufacturer, get_string_descriptor(handle, descriptor.iManufacturer).unwrap_or_default());
debug!(" iProduct: {:15} {}", descriptor.iProduct, get_string_descriptor(handle, descriptor.iProduct).unwrap_or_default());
debug!(" iSerialNumber: {:10} {}", descriptor.iSerialNumber, get_string_descriptor(handle, descriptor.iSerialNumber).unwrap_or_default());
debug!(" bNumConfigurations: {:5}", descriptor.bNumConfigurations);
debug!(" Speed: {:>25}\n", get_device_speed(speed));
}
pub(crate) fn get_descriptor_type(desc_type: u8) -> &'static str {
match desc_type {
ffi::LIBUSB_DT_DEVICE => "Device",
ffi::LIBUSB_DT_CONFIG => "Configuration",
ffi::LIBUSB_DT_STRING => "String",
ffi::LIBUSB_DT_INTERFACE => "Interface",
ffi::LIBUSB_DT_ENDPOINT => "Endpoint",
ffi::LIBUSB_DT_BOS => "BOS",
ffi::LIBUSB_DT_DEVICE_CAPABILITY => "Device Capability",
ffi::LIBUSB_DT_HID => "HID",
ffi::LIBUSB_DT_REPORT => "Report",
ffi::LIBUSB_DT_PHYSICAL => "Physical",
ffi::LIBUSB_DT_HUB => "HUB",
ffi::LIBUSB_DT_SUPERSPEED_HUB => "Superspeed Hub",
ffi::LIBUSB_DT_SS_ENDPOINT_COMPANION => "Superspeed Endpoint Companion",
_ => "unknown type"
}
}
pub(crate) fn get_bcd_version(bcd_version: u16) -> String {
let digit1 = (bcd_version & 0xF000) >> 12;
let digit2 = (bcd_version & 0x0F00) >> 8;
let digit3 = (bcd_version & 0x00F0) >> 4;
let digit4 = (bcd_version & 0x000F) >> 0;
if digit1 > 0 {
format!("{}{}.{}{}", digit1, digit2, digit3, digit4)
}
else {
format!("{}.{}{}", digit2, digit3, digit4)
}
}
pub(crate) fn get_class_type(class: u8) -> &'static str {
match class {
ffi::LIBUSB_CLASS_PER_INTERFACE => "(Defined at Interface level)",
ffi::LIBUSB_CLASS_AUDIO => "Audio",
ffi::LIBUSB_CLASS_COMM => "Comm",
ffi::LIBUSB_CLASS_HID => "HID",
ffi::LIBUSB_CLASS_PHYSICAL => "Physical",
ffi::LIBUSB_CLASS_PRINTER => "Printer",
ffi::LIBUSB_CLASS_IMAGE => "Image",
ffi::LIBUSB_CLASS_MASS_STORAGE => "Mass Storage",
ffi::LIBUSB_CLASS_HUB => "Hub",
ffi::LIBUSB_CLASS_DATA => "Data",
ffi::LIBUSB_CLASS_SMART_CARD => "Smart Card",
ffi::LIBUSB_CLASS_CONTENT_SECURITY => "Content Security",
ffi::LIBUSB_CLASS_VIDEO => "Video",
ffi::LIBUSB_CLASS_PERSONAL_HEALTHCARE => "Personal Healthcare",
ffi::LIBUSB_CLASS_DIAGNOSTIC_DEVICE => "Diagnostic Device",
ffi::LIBUSB_CLASS_WIRELESS => "Wireless",
ffi::LIBUSB_CLASS_APPLICATION => "Application",
ffi::LIBUSB_CLASS_VENDOR_SPEC => "Vendor Specific",
_ => ""
}
}
pub(crate) fn get_string_descriptor(handle: *mut ffi::libusb_device_handle, desc_index: u8) -> Option<String> {
if handle.is_null() || desc_index == 0 {
return None
}
let mut vec = Vec::<u8>::with_capacity(256);
let ptr = (&mut vec[..]).as_mut_ptr();
let len = unsafe { ffi::libusb_get_string_descriptor_ascii(handle, desc_index, ptr as *mut c_uchar, vec.capacity() as c_int) };
if len > 0 {
unsafe { vec.set_len(len as usize) };
match String::from_utf8(vec) {
Ok(s) => Some(s),
Err(_) => None
}
} else {
None
}
}
pub(crate) fn get_device_speed(speed: c_int) -> &'static str {
match speed {
ffi::LIBUSB_SPEED_SUPER => "5000 Mbps",
ffi::LIBUSB_SPEED_HIGH => " 480 Mbps",
ffi::LIBUSB_SPEED_FULL => " 12 Mbps",
ffi::LIBUSB_SPEED_LOW => " 1.5 Mbps",
ffi::LIBUSB_SPEED_UNKNOWN => "(unknown)",
_ => "what's an odd usb speed value?",
}
}
|
#[doc = "Register `CFG1` reader"]
pub type R = crate::R<CFG1_SPEC>;
#[doc = "Register `CFG1` writer"]
pub type W = crate::W<CFG1_SPEC>;
#[doc = "Field `DSIZE` reader - Number of bits in at single SPI data frame"]
pub type DSIZE_R = crate::FieldReader;
#[doc = "Field `DSIZE` writer - Number of bits in at single SPI data frame"]
pub type DSIZE_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 5, O>;
#[doc = "Field `FTHLV` reader - threshold level"]
pub type FTHLV_R = crate::FieldReader<FTHLV_A>;
#[doc = "threshold level\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum FTHLV_A {
#[doc = "0: 1 frame"]
OneFrame = 0,
#[doc = "1: 2 frames"]
TwoFrames = 1,
#[doc = "2: 3 frames"]
ThreeFrames = 2,
#[doc = "3: 4 frames"]
FourFrames = 3,
#[doc = "4: 5 frames"]
FiveFrames = 4,
#[doc = "5: 6 frames"]
SixFrames = 5,
#[doc = "6: 7 frames"]
SevenFrames = 6,
#[doc = "7: 8 frames"]
EightFrames = 7,
#[doc = "8: 9 frames"]
NineFrames = 8,
#[doc = "9: 10 frames"]
TenFrames = 9,
#[doc = "10: 11 frames"]
ElevenFrames = 10,
#[doc = "11: 12 frames"]
TwelveFrames = 11,
#[doc = "12: 13 frames"]
ThirteenFrames = 12,
#[doc = "13: 14 frames"]
FourteenFrames = 13,
#[doc = "14: 15 frames"]
FifteenFrames = 14,
#[doc = "15: 16 frames"]
SixteenFrames = 15,
}
impl From<FTHLV_A> for u8 {
#[inline(always)]
fn from(variant: FTHLV_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for FTHLV_A {
type Ux = u8;
}
impl FTHLV_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FTHLV_A {
match self.bits {
0 => FTHLV_A::OneFrame,
1 => FTHLV_A::TwoFrames,
2 => FTHLV_A::ThreeFrames,
3 => FTHLV_A::FourFrames,
4 => FTHLV_A::FiveFrames,
5 => FTHLV_A::SixFrames,
6 => FTHLV_A::SevenFrames,
7 => FTHLV_A::EightFrames,
8 => FTHLV_A::NineFrames,
9 => FTHLV_A::TenFrames,
10 => FTHLV_A::ElevenFrames,
11 => FTHLV_A::TwelveFrames,
12 => FTHLV_A::ThirteenFrames,
13 => FTHLV_A::FourteenFrames,
14 => FTHLV_A::FifteenFrames,
15 => FTHLV_A::SixteenFrames,
_ => unreachable!(),
}
}
#[doc = "1 frame"]
#[inline(always)]
pub fn is_one_frame(&self) -> bool {
*self == FTHLV_A::OneFrame
}
#[doc = "2 frames"]
#[inline(always)]
pub fn is_two_frames(&self) -> bool {
*self == FTHLV_A::TwoFrames
}
#[doc = "3 frames"]
#[inline(always)]
pub fn is_three_frames(&self) -> bool {
*self == FTHLV_A::ThreeFrames
}
#[doc = "4 frames"]
#[inline(always)]
pub fn is_four_frames(&self) -> bool {
*self == FTHLV_A::FourFrames
}
#[doc = "5 frames"]
#[inline(always)]
pub fn is_five_frames(&self) -> bool {
*self == FTHLV_A::FiveFrames
}
#[doc = "6 frames"]
#[inline(always)]
pub fn is_six_frames(&self) -> bool {
*self == FTHLV_A::SixFrames
}
#[doc = "7 frames"]
#[inline(always)]
pub fn is_seven_frames(&self) -> bool {
*self == FTHLV_A::SevenFrames
}
#[doc = "8 frames"]
#[inline(always)]
pub fn is_eight_frames(&self) -> bool {
*self == FTHLV_A::EightFrames
}
#[doc = "9 frames"]
#[inline(always)]
pub fn is_nine_frames(&self) -> bool {
*self == FTHLV_A::NineFrames
}
#[doc = "10 frames"]
#[inline(always)]
pub fn is_ten_frames(&self) -> bool {
*self == FTHLV_A::TenFrames
}
#[doc = "11 frames"]
#[inline(always)]
pub fn is_eleven_frames(&self) -> bool {
*self == FTHLV_A::ElevenFrames
}
#[doc = "12 frames"]
#[inline(always)]
pub fn is_twelve_frames(&self) -> bool {
*self == FTHLV_A::TwelveFrames
}
#[doc = "13 frames"]
#[inline(always)]
pub fn is_thirteen_frames(&self) -> bool {
*self == FTHLV_A::ThirteenFrames
}
#[doc = "14 frames"]
#[inline(always)]
pub fn is_fourteen_frames(&self) -> bool {
*self == FTHLV_A::FourteenFrames
}
#[doc = "15 frames"]
#[inline(always)]
pub fn is_fifteen_frames(&self) -> bool {
*self == FTHLV_A::FifteenFrames
}
#[doc = "16 frames"]
#[inline(always)]
pub fn is_sixteen_frames(&self) -> bool {
*self == FTHLV_A::SixteenFrames
}
}
#[doc = "Field `FTHLV` writer - threshold level"]
pub type FTHLV_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O, FTHLV_A>;
impl<'a, REG, const O: u8> FTHLV_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "1 frame"]
#[inline(always)]
pub fn one_frame(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::OneFrame)
}
#[doc = "2 frames"]
#[inline(always)]
pub fn two_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::TwoFrames)
}
#[doc = "3 frames"]
#[inline(always)]
pub fn three_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::ThreeFrames)
}
#[doc = "4 frames"]
#[inline(always)]
pub fn four_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::FourFrames)
}
#[doc = "5 frames"]
#[inline(always)]
pub fn five_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::FiveFrames)
}
#[doc = "6 frames"]
#[inline(always)]
pub fn six_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::SixFrames)
}
#[doc = "7 frames"]
#[inline(always)]
pub fn seven_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::SevenFrames)
}
#[doc = "8 frames"]
#[inline(always)]
pub fn eight_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::EightFrames)
}
#[doc = "9 frames"]
#[inline(always)]
pub fn nine_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::NineFrames)
}
#[doc = "10 frames"]
#[inline(always)]
pub fn ten_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::TenFrames)
}
#[doc = "11 frames"]
#[inline(always)]
pub fn eleven_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::ElevenFrames)
}
#[doc = "12 frames"]
#[inline(always)]
pub fn twelve_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::TwelveFrames)
}
#[doc = "13 frames"]
#[inline(always)]
pub fn thirteen_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::ThirteenFrames)
}
#[doc = "14 frames"]
#[inline(always)]
pub fn fourteen_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::FourteenFrames)
}
#[doc = "15 frames"]
#[inline(always)]
pub fn fifteen_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::FifteenFrames)
}
#[doc = "16 frames"]
#[inline(always)]
pub fn sixteen_frames(self) -> &'a mut crate::W<REG> {
self.variant(FTHLV_A::SixteenFrames)
}
}
#[doc = "Field `UDRCFG` reader - Behavior of slave transmitter at underrun condition"]
pub type UDRCFG_R = crate::FieldReader<UDRCFG_A>;
#[doc = "Behavior of slave transmitter at underrun condition\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum UDRCFG_A {
#[doc = "0: Slave sends a constant underrun pattern"]
Constant = 0,
#[doc = "1: Slave repeats last received data frame from master"]
RepeatReceived = 1,
#[doc = "2: Slave repeats last transmitted data frame"]
RepeatTransmitted = 2,
}
impl From<UDRCFG_A> for u8 {
#[inline(always)]
fn from(variant: UDRCFG_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for UDRCFG_A {
type Ux = u8;
}
impl UDRCFG_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<UDRCFG_A> {
match self.bits {
0 => Some(UDRCFG_A::Constant),
1 => Some(UDRCFG_A::RepeatReceived),
2 => Some(UDRCFG_A::RepeatTransmitted),
_ => None,
}
}
#[doc = "Slave sends a constant underrun pattern"]
#[inline(always)]
pub fn is_constant(&self) -> bool {
*self == UDRCFG_A::Constant
}
#[doc = "Slave repeats last received data frame from master"]
#[inline(always)]
pub fn is_repeat_received(&self) -> bool {
*self == UDRCFG_A::RepeatReceived
}
#[doc = "Slave repeats last transmitted data frame"]
#[inline(always)]
pub fn is_repeat_transmitted(&self) -> bool {
*self == UDRCFG_A::RepeatTransmitted
}
}
#[doc = "Field `UDRCFG` writer - Behavior of slave transmitter at underrun condition"]
pub type UDRCFG_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, UDRCFG_A>;
impl<'a, REG, const O: u8> UDRCFG_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Slave sends a constant underrun pattern"]
#[inline(always)]
pub fn constant(self) -> &'a mut crate::W<REG> {
self.variant(UDRCFG_A::Constant)
}
#[doc = "Slave repeats last received data frame from master"]
#[inline(always)]
pub fn repeat_received(self) -> &'a mut crate::W<REG> {
self.variant(UDRCFG_A::RepeatReceived)
}
#[doc = "Slave repeats last transmitted data frame"]
#[inline(always)]
pub fn repeat_transmitted(self) -> &'a mut crate::W<REG> {
self.variant(UDRCFG_A::RepeatTransmitted)
}
}
#[doc = "Field `UDRDET` reader - Detection of underrun condition at slave transmitter"]
pub type UDRDET_R = crate::FieldReader<UDRDET_A>;
#[doc = "Detection of underrun condition at slave transmitter\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum UDRDET_A {
#[doc = "0: Underrun is detected at begin of data frame"]
StartOfFrame = 0,
#[doc = "1: Underrun is detected at end of last data frame"]
EndOfFrame = 1,
#[doc = "2: Underrun is detected at begin of active SS signal"]
StartOfSlaveSelect = 2,
}
impl From<UDRDET_A> for u8 {
#[inline(always)]
fn from(variant: UDRDET_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for UDRDET_A {
type Ux = u8;
}
impl UDRDET_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<UDRDET_A> {
match self.bits {
0 => Some(UDRDET_A::StartOfFrame),
1 => Some(UDRDET_A::EndOfFrame),
2 => Some(UDRDET_A::StartOfSlaveSelect),
_ => None,
}
}
#[doc = "Underrun is detected at begin of data frame"]
#[inline(always)]
pub fn is_start_of_frame(&self) -> bool {
*self == UDRDET_A::StartOfFrame
}
#[doc = "Underrun is detected at end of last data frame"]
#[inline(always)]
pub fn is_end_of_frame(&self) -> bool {
*self == UDRDET_A::EndOfFrame
}
#[doc = "Underrun is detected at begin of active SS signal"]
#[inline(always)]
pub fn is_start_of_slave_select(&self) -> bool {
*self == UDRDET_A::StartOfSlaveSelect
}
}
#[doc = "Field `UDRDET` writer - Detection of underrun condition at slave transmitter"]
pub type UDRDET_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, UDRDET_A>;
impl<'a, REG, const O: u8> UDRDET_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Underrun is detected at begin of data frame"]
#[inline(always)]
pub fn start_of_frame(self) -> &'a mut crate::W<REG> {
self.variant(UDRDET_A::StartOfFrame)
}
#[doc = "Underrun is detected at end of last data frame"]
#[inline(always)]
pub fn end_of_frame(self) -> &'a mut crate::W<REG> {
self.variant(UDRDET_A::EndOfFrame)
}
#[doc = "Underrun is detected at begin of active SS signal"]
#[inline(always)]
pub fn start_of_slave_select(self) -> &'a mut crate::W<REG> {
self.variant(UDRDET_A::StartOfSlaveSelect)
}
}
#[doc = "Field `RXDMAEN` reader - Rx DMA stream enable"]
pub type RXDMAEN_R = crate::BitReader<RXDMAEN_A>;
#[doc = "Rx DMA stream enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RXDMAEN_A {
#[doc = "0: Rx buffer DMA disabled"]
Disabled = 0,
#[doc = "1: Rx buffer DMA enabled"]
Enabled = 1,
}
impl From<RXDMAEN_A> for bool {
#[inline(always)]
fn from(variant: RXDMAEN_A) -> Self {
variant as u8 != 0
}
}
impl RXDMAEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RXDMAEN_A {
match self.bits {
false => RXDMAEN_A::Disabled,
true => RXDMAEN_A::Enabled,
}
}
#[doc = "Rx buffer DMA disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == RXDMAEN_A::Disabled
}
#[doc = "Rx buffer DMA enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == RXDMAEN_A::Enabled
}
}
#[doc = "Field `RXDMAEN` writer - Rx DMA stream enable"]
pub type RXDMAEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RXDMAEN_A>;
impl<'a, REG, const O: u8> RXDMAEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Rx buffer DMA disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(RXDMAEN_A::Disabled)
}
#[doc = "Rx buffer DMA enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(RXDMAEN_A::Enabled)
}
}
#[doc = "Field `TXDMAEN` reader - Tx DMA stream enable"]
pub type TXDMAEN_R = crate::BitReader<TXDMAEN_A>;
#[doc = "Tx DMA stream enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TXDMAEN_A {
#[doc = "0: Tx buffer DMA disabled"]
Disabled = 0,
#[doc = "1: Tx buffer DMA enabled"]
Enabled = 1,
}
impl From<TXDMAEN_A> for bool {
#[inline(always)]
fn from(variant: TXDMAEN_A) -> Self {
variant as u8 != 0
}
}
impl TXDMAEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TXDMAEN_A {
match self.bits {
false => TXDMAEN_A::Disabled,
true => TXDMAEN_A::Enabled,
}
}
#[doc = "Tx buffer DMA disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == TXDMAEN_A::Disabled
}
#[doc = "Tx buffer DMA enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == TXDMAEN_A::Enabled
}
}
#[doc = "Field `TXDMAEN` writer - Tx DMA stream enable"]
pub type TXDMAEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TXDMAEN_A>;
impl<'a, REG, const O: u8> TXDMAEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Tx buffer DMA disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(TXDMAEN_A::Disabled)
}
#[doc = "Tx buffer DMA enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(TXDMAEN_A::Enabled)
}
}
#[doc = "Field `CRCSIZE` reader - Length of CRC frame to be transacted and compared"]
pub type CRCSIZE_R = crate::FieldReader;
#[doc = "Field `CRCSIZE` writer - Length of CRC frame to be transacted and compared"]
pub type CRCSIZE_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 5, O>;
#[doc = "Field `CRCEN` reader - Hardware CRC computation enable"]
pub type CRCEN_R = crate::BitReader<CRCEN_A>;
#[doc = "Hardware CRC computation enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CRCEN_A {
#[doc = "0: CRC calculation disabled"]
Disabled = 0,
#[doc = "1: CRC calculation enabled"]
Enabled = 1,
}
impl From<CRCEN_A> for bool {
#[inline(always)]
fn from(variant: CRCEN_A) -> Self {
variant as u8 != 0
}
}
impl CRCEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CRCEN_A {
match self.bits {
false => CRCEN_A::Disabled,
true => CRCEN_A::Enabled,
}
}
#[doc = "CRC calculation disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == CRCEN_A::Disabled
}
#[doc = "CRC calculation enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == CRCEN_A::Enabled
}
}
#[doc = "Field `CRCEN` writer - Hardware CRC computation enable"]
pub type CRCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CRCEN_A>;
impl<'a, REG, const O: u8> CRCEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "CRC calculation disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(CRCEN_A::Disabled)
}
#[doc = "CRC calculation enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(CRCEN_A::Enabled)
}
}
#[doc = "Field `MBR` reader - Master baud rate"]
pub type MBR_R = crate::FieldReader<MBR_A>;
#[doc = "Master baud rate\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum MBR_A {
#[doc = "0: f_spi_ker_ck / 2"]
Div2 = 0,
#[doc = "1: f_spi_ker_ck / 4"]
Div4 = 1,
#[doc = "2: f_spi_ker_ck / 8"]
Div8 = 2,
#[doc = "3: f_spi_ker_ck / 16"]
Div16 = 3,
#[doc = "4: f_spi_ker_ck / 32"]
Div32 = 4,
#[doc = "5: f_spi_ker_ck / 64"]
Div64 = 5,
#[doc = "6: f_spi_ker_ck / 128"]
Div128 = 6,
#[doc = "7: f_spi_ker_ck / 256"]
Div256 = 7,
}
impl From<MBR_A> for u8 {
#[inline(always)]
fn from(variant: MBR_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for MBR_A {
type Ux = u8;
}
impl MBR_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MBR_A {
match self.bits {
0 => MBR_A::Div2,
1 => MBR_A::Div4,
2 => MBR_A::Div8,
3 => MBR_A::Div16,
4 => MBR_A::Div32,
5 => MBR_A::Div64,
6 => MBR_A::Div128,
7 => MBR_A::Div256,
_ => unreachable!(),
}
}
#[doc = "f_spi_ker_ck / 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == MBR_A::Div2
}
#[doc = "f_spi_ker_ck / 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == MBR_A::Div4
}
#[doc = "f_spi_ker_ck / 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == MBR_A::Div8
}
#[doc = "f_spi_ker_ck / 16"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == MBR_A::Div16
}
#[doc = "f_spi_ker_ck / 32"]
#[inline(always)]
pub fn is_div32(&self) -> bool {
*self == MBR_A::Div32
}
#[doc = "f_spi_ker_ck / 64"]
#[inline(always)]
pub fn is_div64(&self) -> bool {
*self == MBR_A::Div64
}
#[doc = "f_spi_ker_ck / 128"]
#[inline(always)]
pub fn is_div128(&self) -> bool {
*self == MBR_A::Div128
}
#[doc = "f_spi_ker_ck / 256"]
#[inline(always)]
pub fn is_div256(&self) -> bool {
*self == MBR_A::Div256
}
}
#[doc = "Field `MBR` writer - Master baud rate"]
pub type MBR_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 3, O, MBR_A>;
impl<'a, REG, const O: u8> MBR_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "f_spi_ker_ck / 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(MBR_A::Div2)
}
#[doc = "f_spi_ker_ck / 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(MBR_A::Div4)
}
#[doc = "f_spi_ker_ck / 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(MBR_A::Div8)
}
#[doc = "f_spi_ker_ck / 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut crate::W<REG> {
self.variant(MBR_A::Div16)
}
#[doc = "f_spi_ker_ck / 32"]
#[inline(always)]
pub fn div32(self) -> &'a mut crate::W<REG> {
self.variant(MBR_A::Div32)
}
#[doc = "f_spi_ker_ck / 64"]
#[inline(always)]
pub fn div64(self) -> &'a mut crate::W<REG> {
self.variant(MBR_A::Div64)
}
#[doc = "f_spi_ker_ck / 128"]
#[inline(always)]
pub fn div128(self) -> &'a mut crate::W<REG> {
self.variant(MBR_A::Div128)
}
#[doc = "f_spi_ker_ck / 256"]
#[inline(always)]
pub fn div256(self) -> &'a mut crate::W<REG> {
self.variant(MBR_A::Div256)
}
}
impl R {
#[doc = "Bits 0:4 - Number of bits in at single SPI data frame"]
#[inline(always)]
pub fn dsize(&self) -> DSIZE_R {
DSIZE_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bits 5:8 - threshold level"]
#[inline(always)]
pub fn fthlv(&self) -> FTHLV_R {
FTHLV_R::new(((self.bits >> 5) & 0x0f) as u8)
}
#[doc = "Bits 9:10 - Behavior of slave transmitter at underrun condition"]
#[inline(always)]
pub fn udrcfg(&self) -> UDRCFG_R {
UDRCFG_R::new(((self.bits >> 9) & 3) as u8)
}
#[doc = "Bits 11:12 - Detection of underrun condition at slave transmitter"]
#[inline(always)]
pub fn udrdet(&self) -> UDRDET_R {
UDRDET_R::new(((self.bits >> 11) & 3) as u8)
}
#[doc = "Bit 14 - Rx DMA stream enable"]
#[inline(always)]
pub fn rxdmaen(&self) -> RXDMAEN_R {
RXDMAEN_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - Tx DMA stream enable"]
#[inline(always)]
pub fn txdmaen(&self) -> TXDMAEN_R {
TXDMAEN_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bits 16:20 - Length of CRC frame to be transacted and compared"]
#[inline(always)]
pub fn crcsize(&self) -> CRCSIZE_R {
CRCSIZE_R::new(((self.bits >> 16) & 0x1f) as u8)
}
#[doc = "Bit 22 - Hardware CRC computation enable"]
#[inline(always)]
pub fn crcen(&self) -> CRCEN_R {
CRCEN_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bits 28:30 - Master baud rate"]
#[inline(always)]
pub fn mbr(&self) -> MBR_R {
MBR_R::new(((self.bits >> 28) & 7) as u8)
}
}
impl W {
#[doc = "Bits 0:4 - Number of bits in at single SPI data frame"]
#[inline(always)]
#[must_use]
pub fn dsize(&mut self) -> DSIZE_W<CFG1_SPEC, 0> {
DSIZE_W::new(self)
}
#[doc = "Bits 5:8 - threshold level"]
#[inline(always)]
#[must_use]
pub fn fthlv(&mut self) -> FTHLV_W<CFG1_SPEC, 5> {
FTHLV_W::new(self)
}
#[doc = "Bits 9:10 - Behavior of slave transmitter at underrun condition"]
#[inline(always)]
#[must_use]
pub fn udrcfg(&mut self) -> UDRCFG_W<CFG1_SPEC, 9> {
UDRCFG_W::new(self)
}
#[doc = "Bits 11:12 - Detection of underrun condition at slave transmitter"]
#[inline(always)]
#[must_use]
pub fn udrdet(&mut self) -> UDRDET_W<CFG1_SPEC, 11> {
UDRDET_W::new(self)
}
#[doc = "Bit 14 - Rx DMA stream enable"]
#[inline(always)]
#[must_use]
pub fn rxdmaen(&mut self) -> RXDMAEN_W<CFG1_SPEC, 14> {
RXDMAEN_W::new(self)
}
#[doc = "Bit 15 - Tx DMA stream enable"]
#[inline(always)]
#[must_use]
pub fn txdmaen(&mut self) -> TXDMAEN_W<CFG1_SPEC, 15> {
TXDMAEN_W::new(self)
}
#[doc = "Bits 16:20 - Length of CRC frame to be transacted and compared"]
#[inline(always)]
#[must_use]
pub fn crcsize(&mut self) -> CRCSIZE_W<CFG1_SPEC, 16> {
CRCSIZE_W::new(self)
}
#[doc = "Bit 22 - Hardware CRC computation enable"]
#[inline(always)]
#[must_use]
pub fn crcen(&mut self) -> CRCEN_W<CFG1_SPEC, 22> {
CRCEN_W::new(self)
}
#[doc = "Bits 28:30 - Master baud rate"]
#[inline(always)]
#[must_use]
pub fn mbr(&mut self) -> MBR_W<CFG1_SPEC, 28> {
MBR_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 = "configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfg1::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 [`cfg1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CFG1_SPEC;
impl crate::RegisterSpec for CFG1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cfg1::R`](R) reader structure"]
impl crate::Readable for CFG1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cfg1::W`](W) writer structure"]
impl crate::Writable for CFG1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CFG1 to value 0x0007_0007"]
impl crate::Resettable for CFG1_SPEC {
const RESET_VALUE: Self::Ux = 0x0007_0007;
}
|
const LOWER: i32 = 1;
const UPPER: i32 = 1000;
// Because the rule for our series is simply adding one, the number of terms are the number of
// digits between LOWER and UPPER
const NUMBER_OF_TERMS: i32 = (UPPER + 1) - LOWER;
fn main() {
// Formulaic method
println!("{}", (NUMBER_OF_TERMS * (LOWER + UPPER)) / 2);
// Naive method
println!("{}", (LOWER..UPPER + 1).fold(0, |sum, x| sum + x));
}
|
pub mod material;
pub mod mesh;
pub mod obj;
pub mod shader;
pub mod texture;
|
mod cfg;
mod log_merge;
mod server;
mod tentacle;
use crate::cfg::read_config;
use crate::server::start_server;
use std::error::Error;
use std::sync::Arc;
pub fn run<S: AsRef<str>>(maybe_settings: &Option<S>) -> Result<(), Box<dyn Error>> {
let settings = Arc::new(read_config(maybe_settings)?);
let sys = actix::System::new("logtopus");
start_server(settings.clone());
sys.run();
Ok(())
}
|
use std::cmp::max;
use std::io::{self, Cursor, Seek, SeekFrom, Write};
use std::ops::{Deref, DerefMut};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use bytes::Bytes;
use snafu::{ResultExt, Snafu};
use crate::encoding_type::{EncodingError, EncodingType};
use crate::node_types::StandardType;
#[derive(Debug, Snafu)]
pub enum ByteBufferError {
#[snafu(display(
"Out-of-bounds read attempted at offset: {} with size: {}",
offset,
size
))]
OutOfBounds { offset: usize, size: usize },
#[snafu(display("Failed to read {} byte(s) from data buffer", size))]
DataRead { size: usize, source: io::Error },
#[snafu(display("Failed to read aligned {} byte(s) from data buffer", size))]
ReadAligned {
size: usize,
source: Box<ByteBufferError>,
},
#[snafu(display("Failed to read data size from data buffer"))]
ReadSize { source: io::Error },
#[snafu(display(
"Failed to seek forward {} byte(s) in data buffer after size read",
size
))]
ReadSizeSeek { size: usize, source: io::Error },
#[snafu(display("Failed to write length to data buffer (len: {})", len))]
WriteLength { len: usize, source: io::Error },
#[snafu(display("Failed to write data byte {} to data buffer", offset))]
WriteDataByte { offset: usize, source: io::Error },
#[snafu(display("Failed to write data block to data buffer"))]
WriteDataBlock { source: io::Error },
#[snafu(display("Failed to encode string"))]
StringEncode { source: EncodingError },
#[snafu(display("Failed to write padding {} byte(s) to data buffer", size))]
WritePadding { size: usize, source: io::Error },
#[snafu(display(
"Mismatched size for {} node data (expected: {}, actual: {})",
node_type,
expected,
actual
))]
WriteSizeMismatch {
node_type: StandardType,
expected: usize,
actual: usize,
},
#[snafu(display("Failed to seek to {} in data buffer", offset))]
SeekOffset { offset: usize, source: io::Error },
#[snafu(display("Failed to seek forward {} byte(s) in data buffer", size))]
SeekForward { size: usize, source: io::Error },
}
/// Remove trailing null bytes, used for the `String` type
pub(crate) fn strip_trailing_null_bytes(data: &[u8]) -> &[u8] {
let len = data.len();
if len == 0 {
return data;
}
let mut index = len - 1;
while index > 0 && index < len && data[index] == 0x00 {
index -= 1;
}
// Handle case where the buffer is only a null byte
if index == 0 && data.len() == 1 && data[index] == 0x00 {
&[]
} else {
&data[..=index]
}
}
pub struct ByteBufferRead {
cursor: Cursor<Bytes>,
buffer: Bytes,
offset_1: usize,
offset_2: usize,
}
pub struct ByteBufferWrite {
buffer: Cursor<Vec<u8>>,
offset_1: u64,
offset_2: u64,
}
impl ByteBufferRead {
pub fn new(buffer: Bytes) -> Self {
Self {
cursor: Cursor::new(buffer.clone()),
buffer,
offset_1: 0,
offset_2: 0,
}
}
#[inline]
fn data_buf_offset(&self) -> usize {
// Position is not the index of the previously read byte, it is the current
// index (offset).
//
// This is so much fun to debug.
//data_buf.position() - 1
self.cursor.position() as usize
}
fn check_read_size(&self, start: usize, size: usize) -> Result<usize, ByteBufferError> {
let end = start + size;
if end > self.buffer.len() {
Err(ByteBufferError::OutOfBounds {
offset: start,
size,
})
} else {
Ok(end)
}
}
fn buf_read_size(&mut self, size: usize) -> Result<Bytes, ByteBufferError> {
// To avoid an allocation of a `Vec` here, the raw input byte array is used
let start = self.data_buf_offset();
let end = self.check_read_size(start, size)?;
let data = self.buffer.slice(start..end);
trace!(
"buf_read_size => index: {}, size: {}, data: 0x{:02x?}",
self.cursor.position(),
data.len(),
&*data
);
self.cursor
.seek(SeekFrom::Current(size as i64))
.context(ReadSizeSeekSnafu { size })?;
Ok(data)
}
pub fn buf_read(&mut self) -> Result<Bytes, ByteBufferError> {
let size = self.cursor.read_u32::<BigEndian>().context(ReadSizeSnafu)?;
debug!(
"buf_read => index: {}, size: {}",
self.cursor.position(),
size
);
let data = self.buf_read_size(size as usize)?;
self.realign_reads(None)?;
Ok(data)
}
pub fn get(&mut self, size: u32) -> Result<Bytes, ByteBufferError> {
let data = self.buf_read_size(size as usize)?;
trace!("get => size: {}, data: 0x{:02x?}", size, &*data);
Ok(data)
}
pub fn get_aligned(&mut self, node_type: StandardType) -> Result<Bytes, ByteBufferError> {
if self.offset_1 % 4 == 0 {
self.offset_1 = self.data_buf_offset();
}
if self.offset_2 % 4 == 0 {
self.offset_2 = self.data_buf_offset();
}
let old_pos = self.data_buf_offset();
let size = node_type.size * node_type.count;
trace!("get_aligned => old_pos: {}, size: {}", old_pos, size);
let (check_old, data) = match size {
1 => {
let end = self.check_read_size(self.offset_1, 1)?;
let data = self.buffer.slice(self.offset_1..end);
self.offset_1 += 1;
(true, data)
},
2 => {
let end = self.check_read_size(self.offset_2, 2)?;
let data = self.buffer.slice(self.offset_2..end);
self.offset_2 += 2;
(true, data)
},
size => {
let data = self
.buf_read_size(size as usize)
.map_err(Box::new)
.context(ReadAlignedSnafu { size })?;
self.realign_reads(None)?;
(false, data)
},
};
if check_old {
let trailing = max(self.offset_1, self.offset_2);
trace!(
"get_aligned => old_pos: {}, trailing: {}",
old_pos,
trailing
);
if old_pos < trailing {
self.cursor
.seek(SeekFrom::Start(trailing as u64))
.context(SeekOffsetSnafu { offset: trailing })?;
self.realign_reads(None)?;
}
}
Ok(data)
}
pub fn realign_reads(&mut self, size: Option<u64>) -> Result<(), ByteBufferError> {
let size = size.unwrap_or(4);
trace!(
"realign_reads => position: {}, size: {}",
self.cursor.position(),
size
);
while self.cursor.position() % size > 0 {
self.cursor
.seek(SeekFrom::Current(1))
.context(SeekForwardSnafu { size: 1usize })?;
}
trace!("realign_reads => realigned to: {}", self.cursor.position());
Ok(())
}
}
impl ByteBufferWrite {
pub fn new(buffer: Vec<u8>) -> Self {
Self {
buffer: Cursor::new(buffer),
offset_1: 0,
offset_2: 0,
}
}
pub fn into_inner(self) -> Vec<u8> {
self.buffer.into_inner()
}
#[inline]
fn data_buf_offset(&self) -> u64 {
// Position is not the index of the previously read byte, it is the current
// index (offset).
//
// This is so much fun to debug.
//data_buf.position() - 1
self.buffer.position()
}
pub fn buf_write(&mut self, data: &[u8]) -> Result<(), ByteBufferError> {
self.buffer
.write_u32::<BigEndian>(data.len() as u32)
.context(WriteLengthSnafu { len: data.len() })?;
debug!(
"buf_write => index: {}, size: {}",
self.buffer.position(),
data.len()
);
self.buffer.write_all(data).context(WriteDataBlockSnafu)?;
trace!(
"buf_write => index: {}, size: {}, data: 0x{:02x?}",
self.buffer.position(),
data.len(),
data
);
self.realign_writes(None)?;
Ok(())
}
pub fn write_str(&mut self, encoding: EncodingType, data: &str) -> Result<(), ByteBufferError> {
trace!(
"write_str => input: {}, data: 0x{:02x?}",
data,
data.as_bytes()
);
let bytes = encoding.encode_bytes(data).context(StringEncodeSnafu)?;
self.buf_write(&bytes)?;
Ok(())
}
pub fn write_aligned(
&mut self,
node_type: StandardType,
data: &[u8],
) -> Result<(), ByteBufferError> {
if self.offset_1 % 4 == 0 {
self.offset_1 = self.data_buf_offset();
}
if self.offset_2 % 4 == 0 {
self.offset_2 = self.data_buf_offset();
}
let old_pos = self.data_buf_offset();
let size = node_type.size * node_type.count;
trace!(
"write_aligned => old_pos: {}, size: {}, data: 0x{:02x?}",
old_pos,
size,
data
);
if size != data.len() {
return Err(ByteBufferError::WriteSizeMismatch {
node_type,
expected: size,
actual: data.len(),
});
}
let check_old = match size {
1 => {
// Make room for new DWORD
if self.offset_1 % 4 == 0 {
self.buffer
.write_u32::<BigEndian>(0)
.context(WritePaddingSnafu { size: 4usize })?;
}
self.buffer
.seek(SeekFrom::Start(self.offset_1))
.context(SeekOffsetSnafu {
offset: self.offset_1 as usize,
})?;
self.buffer
.write_u8(data[0])
.context(WriteDataByteSnafu { offset: 1usize })?;
self.offset_1 += 1;
true
},
2 => {
// Make room for new DWORD
if self.offset_2 % 4 == 0 {
self.buffer
.write_u32::<BigEndian>(0)
.context(WritePaddingSnafu { size: 4usize })?;
}
self.buffer
.seek(SeekFrom::Start(self.offset_2))
.context(SeekOffsetSnafu {
offset: self.offset_2 as usize,
})?;
self.buffer
.write_u8(data[0])
.context(WriteDataByteSnafu { offset: 1usize })?;
self.buffer
.write_u8(data[1])
.context(WriteDataByteSnafu { offset: 2usize })?;
self.offset_2 += 2;
true
},
_ => {
self.buffer.write_all(data).context(WriteDataBlockSnafu)?;
self.realign_writes(None)?;
false
},
};
if check_old {
self.buffer
.seek(SeekFrom::Start(old_pos))
.context(SeekOffsetSnafu {
offset: old_pos as usize,
})?;
let trailing = max(self.offset_1, self.offset_2);
trace!(
"write_aligned => old_pos: {}, trailing: {}",
old_pos,
trailing
);
if old_pos < trailing {
self.buffer
.seek(SeekFrom::Start(trailing))
.context(SeekOffsetSnafu {
offset: trailing as usize,
})?;
self.realign_writes(None)?;
}
}
Ok(())
}
pub fn realign_writes(&mut self, size: Option<u64>) -> Result<(), ByteBufferError> {
let size = size.unwrap_or(4);
trace!(
"realign_writes => position: {}, size: {}",
self.buffer.position(),
size
);
while self.buffer.position() % size > 0 {
self.buffer
.write_u8(0)
.context(WritePaddingSnafu { size: 1usize })?;
}
trace!("realign_writes => realigned to: {}", self.buffer.position());
Ok(())
}
}
impl Deref for ByteBufferRead {
type Target = Cursor<Bytes>;
fn deref(&self) -> &Self::Target {
&self.cursor
}
}
impl DerefMut for ByteBufferRead {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.cursor
}
}
impl Deref for ByteBufferWrite {
type Target = Cursor<Vec<u8>>;
fn deref(&self) -> &Self::Target {
&self.buffer
}
}
impl DerefMut for ByteBufferWrite {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.buffer
}
}
|
use crate::cfg::CFG;
use crate::gen::fs;
use std::error::Error as StdError;
use std::ffi::OsString;
use std::fmt::{self, Display};
use std::path::Path;
pub(super) type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug)]
pub(super) enum Error {
NoEnv(OsString),
Fs(fs::Error),
ExportedDirNotAbsolute(&'static Path),
ExportedEmptyPrefix,
ExportedDirsWithoutLinks,
ExportedPrefixesWithoutLinks,
ExportedLinksWithoutLinks,
UnusedExportedPrefix(&'static str),
UnusedExportedLinks(&'static str),
}
macro_rules! expr {
($expr:expr) => {{
let _ = $expr; // ensure it doesn't fall out of sync with CFG definition
stringify!($expr)
}};
}
const LINKS_DOCUMENTATION: &str =
"https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key";
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::NoEnv(var) => {
write!(f, "missing {} environment variable", var.to_string_lossy())
}
Error::Fs(err) => err.fmt(f),
Error::ExportedDirNotAbsolute(path) => write!(
f,
"element of {} must be absolute path, but was: {:?}",
expr!(CFG.exported_header_dirs),
path,
),
Error::ExportedEmptyPrefix => write!(
f,
"element of {} must not be empty string",
expr!(CFG.exported_header_prefixes),
),
Error::ExportedDirsWithoutLinks => write!(
f,
"if {} is nonempty then `links` needs to be set in Cargo.toml; see {}",
expr!(CFG.exported_header_dirs),
LINKS_DOCUMENTATION,
),
Error::ExportedPrefixesWithoutLinks => write!(
f,
"if {} is nonempty then `links` needs to be set in Cargo.toml; see {}",
expr!(CFG.exported_header_prefixes),
LINKS_DOCUMENTATION,
),
Error::ExportedLinksWithoutLinks => write!(
f,
"if {} is nonempty then `links` needs to be set in Cargo.toml; see {}",
expr!(CFG.exported_header_links),
LINKS_DOCUMENTATION,
),
Error::UnusedExportedPrefix(unused) => write!(
f,
"unused element in {}: {:?} does not match the include prefix of any direct dependency",
expr!(CFG.exported_header_prefixes),
unused,
),
Error::UnusedExportedLinks(unused) => write!(
f,
"unused element in {}: {:?} does not match the `links` attribute any direct dependency",
expr!(CFG.exported_header_links),
unused,
),
}
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Error::Fs(err) => err.source(),
_ => None,
}
}
}
impl From<fs::Error> for Error {
fn from(err: fs::Error) -> Self {
Error::Fs(err)
}
}
|
use crate::bytes_response::BytesResponse;
use crate::BytesStream;
use crate::StreamError;
use bytes::Bytes;
use futures::Stream;
use futures::StreamExt;
use http::{header::HeaderName, HeaderMap, HeaderValue, StatusCode};
use std::pin::Pin;
type PinnedStream = Pin<Box<dyn Stream<Item = Result<Bytes, StreamError>> + Send + Sync>>;
#[allow(dead_code)]
pub(crate) struct ResponseBuilder {
status: StatusCode,
headers: HeaderMap,
}
impl ResponseBuilder {
#[allow(dead_code)]
pub fn new(status: StatusCode) -> Self {
Self {
status,
headers: HeaderMap::new(),
}
}
#[allow(dead_code)]
pub fn with_header(&mut self, key: &HeaderName, value: HeaderValue) -> &mut Self {
self.headers.append(key, value);
self
}
#[allow(dead_code)]
pub fn with_pinned_stream(self, response: PinnedStream) -> Response {
Response::new(self.status, self.headers, response)
}
}
// An HTTP Response
pub struct Response {
status: StatusCode,
headers: HeaderMap,
body: PinnedStream,
}
impl Response {
pub(crate) fn new(status: StatusCode, headers: HeaderMap, body: PinnedStream) -> Self {
Self {
status,
headers,
body,
}
}
pub fn status(&self) -> StatusCode {
self.status
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn deconstruct(self) -> (StatusCode, HeaderMap, PinnedStream) {
(self.status, self.headers, self.body)
}
pub async fn into_body_string(self) -> String {
pinned_stream_into_utf8_string(self.body).await
}
}
impl std::fmt::Debug for Response {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Response")
.field("status", &self.status)
.field("headers", &self.headers)
.field("body", &"<BODY>")
.finish()
}
}
/// Convenience function that transforms a `PinnedStream` in a `bytes::Bytes` struct by collecting all the chunks. It consumes the response stream.
pub async fn collect_pinned_stream(mut pinned_stream: PinnedStream) -> Result<Bytes, StreamError> {
let mut final_result = Vec::new();
while let Some(res) = pinned_stream.next().await {
let res = res?;
final_result.extend(&res);
}
Ok(final_result.into())
}
/// Collects a `PinnedStream` into a utf8 String
///
/// If the stream cannot be collected or is not utf8, a placeholder string
/// will be returned.
pub async fn pinned_stream_into_utf8_string(stream: PinnedStream) -> String {
let body = collect_pinned_stream(stream)
.await
.unwrap_or_else(|_| Bytes::from_static("<INVALID BODY>".as_bytes()));
let body = std::str::from_utf8(&body)
.unwrap_or("<NON-UTF8 BODY>")
.to_owned();
body
}
impl From<BytesResponse> for Response {
fn from(bytes_response: BytesResponse) -> Self {
let (status, headers, body) = bytes_response.deconstruct();
let bytes_stream: BytesStream = body.into();
Self {
status,
headers,
body: Box::pin(bytes_stream),
}
}
}
|
#[doc = "Register `AHB3SMENR` reader"]
pub type R = crate::R<AHB3SMENR_SPEC>;
#[doc = "Register `AHB3SMENR` writer"]
pub type W = crate::W<AHB3SMENR_SPEC>;
#[doc = "Field `PKASMEN` reader - PKA accelerator clock enable during CPU1 CSleep mode."]
pub type PKASMEN_R = crate::BitReader;
#[doc = "Field `PKASMEN` writer - PKA accelerator clock enable during CPU1 CSleep mode."]
pub type PKASMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AESSMEN` reader - AES accelerator clock enable during CPU1 CSleep mode."]
pub type AESSMEN_R = crate::BitReader;
#[doc = "Field `AESSMEN` writer - AES accelerator clock enable during CPU1 CSleep mode."]
pub type AESSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RNGSMEN` reader - True RNG clocks enable during CPU1 Csleep and CStop modes"]
pub type RNGSMEN_R = crate::BitReader;
#[doc = "Field `RNGSMEN` writer - True RNG clocks enable during CPU1 Csleep and CStop modes"]
pub type RNGSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM1SMEN` reader - SRAM1 interface clock enable during CPU1 CSleep mode."]
pub type SRAM1SMEN_R = crate::BitReader;
#[doc = "Field `SRAM1SMEN` writer - SRAM1 interface clock enable during CPU1 CSleep mode."]
pub type SRAM1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM2SMEN` reader - SRAM2 memory interface clock enable during CPU1 CSleep mode"]
pub type SRAM2SMEN_R = crate::BitReader;
#[doc = "Field `SRAM2SMEN` writer - SRAM2 memory interface clock enable during CPU1 CSleep mode"]
pub type SRAM2SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FLASHSMEN` reader - Flash interface clock enable during CPU1 CSleep mode."]
pub type FLASHSMEN_R = crate::BitReader;
#[doc = "Field `FLASHSMEN` writer - Flash interface clock enable during CPU1 CSleep mode."]
pub type FLASHSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 16 - PKA accelerator clock enable during CPU1 CSleep mode."]
#[inline(always)]
pub fn pkasmen(&self) -> PKASMEN_R {
PKASMEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - AES accelerator clock enable during CPU1 CSleep mode."]
#[inline(always)]
pub fn aessmen(&self) -> AESSMEN_R {
AESSMEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - True RNG clocks enable during CPU1 Csleep and CStop modes"]
#[inline(always)]
pub fn rngsmen(&self) -> RNGSMEN_R {
RNGSMEN_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 23 - SRAM1 interface clock enable during CPU1 CSleep mode."]
#[inline(always)]
pub fn sram1smen(&self) -> SRAM1SMEN_R {
SRAM1SMEN_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - SRAM2 memory interface clock enable during CPU1 CSleep mode"]
#[inline(always)]
pub fn sram2smen(&self) -> SRAM2SMEN_R {
SRAM2SMEN_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Flash interface clock enable during CPU1 CSleep mode."]
#[inline(always)]
pub fn flashsmen(&self) -> FLASHSMEN_R {
FLASHSMEN_R::new(((self.bits >> 25) & 1) != 0)
}
}
impl W {
#[doc = "Bit 16 - PKA accelerator clock enable during CPU1 CSleep mode."]
#[inline(always)]
#[must_use]
pub fn pkasmen(&mut self) -> PKASMEN_W<AHB3SMENR_SPEC, 16> {
PKASMEN_W::new(self)
}
#[doc = "Bit 17 - AES accelerator clock enable during CPU1 CSleep mode."]
#[inline(always)]
#[must_use]
pub fn aessmen(&mut self) -> AESSMEN_W<AHB3SMENR_SPEC, 17> {
AESSMEN_W::new(self)
}
#[doc = "Bit 18 - True RNG clocks enable during CPU1 Csleep and CStop modes"]
#[inline(always)]
#[must_use]
pub fn rngsmen(&mut self) -> RNGSMEN_W<AHB3SMENR_SPEC, 18> {
RNGSMEN_W::new(self)
}
#[doc = "Bit 23 - SRAM1 interface clock enable during CPU1 CSleep mode."]
#[inline(always)]
#[must_use]
pub fn sram1smen(&mut self) -> SRAM1SMEN_W<AHB3SMENR_SPEC, 23> {
SRAM1SMEN_W::new(self)
}
#[doc = "Bit 24 - SRAM2 memory interface clock enable during CPU1 CSleep mode"]
#[inline(always)]
#[must_use]
pub fn sram2smen(&mut self) -> SRAM2SMEN_W<AHB3SMENR_SPEC, 24> {
SRAM2SMEN_W::new(self)
}
#[doc = "Bit 25 - Flash interface clock enable during CPU1 CSleep mode."]
#[inline(always)]
#[must_use]
pub fn flashsmen(&mut self) -> FLASHSMEN_W<AHB3SMENR_SPEC, 25> {
FLASHSMEN_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 = "AHB3 peripheral clocks enable in Sleep and Stop modes register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb3smenr::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 [`ahb3smenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB3SMENR_SPEC;
impl crate::RegisterSpec for AHB3SMENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb3smenr::R`](R) reader structure"]
impl crate::Readable for AHB3SMENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb3smenr::W`](W) writer structure"]
impl crate::Writable for AHB3SMENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB3SMENR to value 0x0387_0000"]
impl crate::Resettable for AHB3SMENR_SPEC {
const RESET_VALUE: Self::Ux = 0x0387_0000;
}
|
mod helpers;
use helpers as h;
use helpers::{Playground, Stub::*};
#[test]
fn first_gets_first_rows_by_amount() {
Playground::setup("first_test_1", |dirs, sandbox| {
sandbox.with_files(vec![
EmptyFile("los.1.txt"),
EmptyFile("tres.1.txt"),
EmptyFile("amigos.1.txt"),
EmptyFile("arepas.1.clu"),
]);
let actual = nu!(
cwd: dirs.test(), h::pipeline(
r#"
ls
| get name
| first 2
| split-column "."
| get Column2
| str --to-int
| sum
| echo $it
"#
));
assert_eq!(actual, "2");
})
}
#[test]
fn first_requires_an_amount() {
Playground::setup("first_test_2", |dirs, _| {
let actual = nu_error!(
cwd: dirs.test(), "ls | first"
);
assert!(actual.contains("requires amount parameter"));
})
}
#[test]
fn get() {
Playground::setup("get_test_1", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContent(
"sample.toml",
r#"
nu_party_venue = "zion"
"#,
)]);
let actual = nu!(
cwd: dirs.test(), h::pipeline(
r#"
open sample.toml
| get nu_party_venue
| echo $it
"#
));
assert_eq!(actual, "zion");
})
}
#[test]
fn get_more_than_one_member() {
Playground::setup("get_test_2", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContent(
"sample.toml",
r#"
[[fortune_tellers]]
name = "Andrés N. Robalino"
arepas = 1
broken_builds = 0
[[fortune_tellers]]
name = "Jonathan Turner"
arepas = 1
broken_builds = 1
[[fortune_tellers]]
name = "Yehuda Katz"
arepas = 1
broken_builds = 1
"#,
)]);
let actual = nu!(
cwd: dirs.test(), h::pipeline(
r#"
open sample.toml
| get fortune_tellers
| get arepas broken_builds
| sum
| echo $it
"#
));
assert_eq!(actual, "5");
})
}
#[test]
fn get_requires_at_least_one_member() {
Playground::setup("first_test_3", |dirs, sandbox| {
sandbox.with_files(vec![EmptyFile("andres.txt")]);
let actual = nu_error!(
cwd: dirs.test(), "ls | get"
);
assert!(actual.contains("requires member parameter"));
})
}
#[test]
fn lines() {
let actual = nu!(
cwd: "tests/fixtures/formats", h::pipeline(
r#"
open cargo_sample.toml --raw
| lines
| skip-while $it != "[dependencies]"
| skip 1
| first 1
| split-column "="
| get Column1
| trim
| echo $it
"#
));
assert_eq!(actual, "rustyline");
}
#[test]
fn save_figures_out_intelligently_where_to_write_out_with_metadata() {
Playground::setup("save_test_1", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContent(
"cargo_sample.toml",
r#"
[package]
name = "nu"
version = "0.1.1"
authors = ["Yehuda Katz <wycats@gmail.com>"]
description = "A shell for the GitHub era"
license = "ISC"
edition = "2018"
"#,
)]);
let subject_file = dirs.test().join("cargo_sample.toml");
nu!(
cwd: dirs.root(),
"open save_test_1/cargo_sample.toml | inc package.version --minor | save"
);
let actual = h::file_contents(&subject_file);
assert!(actual.contains("0.2.0"));
})
}
#[test]
fn save_can_write_out_csv() {
Playground::setup("save_test_2", |dirs, _| {
let expected_file = dirs.test().join("cargo_sample.csv");
nu!(
cwd: dirs.root(),
"open {}/cargo_sample.toml | inc package.version --minor | get package | save save_test_2/cargo_sample.csv",
dirs.formats()
);
let actual = h::file_contents(expected_file);
assert!(actual.contains("[Table],A shell for the GitHub era,2018,ISC,nu,0.2.0"));
})
}
// This test is more tricky since we are checking for binary output. The output rendered in ASCII is (roughly):
// �authors+0Yehuda Katz <wycats@gmail.com>descriptionA shell for the GitHub eraedition2018licenseISCnamenuversion0.2.0
// It is not valid utf-8, so this is just an approximation.
#[test]
fn save_can_write_out_bson() {
Playground::setup("save_test_3", |dirs, _| {
let expected_file = dirs.test().join("cargo_sample.bson");
nu!(
cwd: dirs.root(),
"open {}/cargo_sample.toml | inc package.version --minor | get package | save save_test_3/cargo_sample.bson",
dirs.formats()
);
let actual = h::file_contents_binary(expected_file);
assert!(
actual
== vec![
168, 0, 0, 0, 4, 97, 117, 116, 104, 111, 114, 115, 0, 43, 0, 0, 0, 2, 48, 0,
31, 0, 0, 0, 89, 101, 104, 117, 100, 97, 32, 75, 97, 116, 122, 32, 60, 119,
121, 99, 97, 116, 115, 64, 103, 109, 97, 105, 108, 46, 99, 111, 109, 62, 0, 0,
2, 100, 101, 115, 99, 114, 105, 112, 116, 105, 111, 110, 0, 27, 0, 0, 0, 65,
32, 115, 104, 101, 108, 108, 32, 102, 111, 114, 32, 116, 104, 101, 32, 71, 105,
116, 72, 117, 98, 32, 101, 114, 97, 0, 2, 101, 100, 105, 116, 105, 111, 110, 0,
5, 0, 0, 0, 50, 48, 49, 56, 0, 2, 108, 105, 99, 101, 110, 115, 101, 0, 4, 0, 0,
0, 73, 83, 67, 0, 2, 110, 97, 109, 101, 0, 3, 0, 0, 0, 110, 117, 0, 2, 118,
101, 114, 115, 105, 111, 110, 0, 6, 0, 0, 0, 48, 46, 50, 46, 48, 0, 0
]
);
})
}
|
#[macro_use(accepts, to_sql_checked)]
extern crate postgres;
extern crate chrono;
extern crate byteorder;
extern crate num;
#[macro_use(value_t)]
extern crate clap;
mod account;
mod balance;
mod currency;
mod deposit;
use clap::{App, ArgMatches};
fn prepare_interface<'a, 'b>() -> ArgMatches<'a, 'b> {
// Top level command.
let mut app = App::new("investments")
.about("Keeps track of investments");
// Register top-level subcommands.
app = app.subcommand(account::get_subcommands());
app = app.subcommand(balance::get_subcommands());
app = app.subcommand(deposit::get_subcommands());
return app.get_matches();
}
fn main() {
let matches = prepare_interface();
match matches.subcommand() {
("account", Some(matches)) => {account::handle(matches)},
("balance", Some(matches)) => {balance::handle(matches)},
("deposit", Some(matches)) => {deposit::handle(matches)},
_ => {},
}
}
|
$NetBSD: patch-third__party_rust_authenticator_src_lib.rs,v 1.1 2023/02/05 08:32:24 he Exp $
--- third_party/rust/authenticator/src/lib.rs.orig 2020-08-28 21:33:54.000000000 +0000
+++ third_party/rust/authenticator/src/lib.rs
@@ -5,7 +5,7 @@
#[macro_use]
mod util;
-#[cfg(any(target_os = "linux", target_os = "freebsd"))]
+#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "netbsd"))]
pub mod hidproto;
#[cfg(any(target_os = "linux"))]
@@ -22,6 +22,10 @@ extern crate devd_rs;
#[path = "freebsd/mod.rs"]
pub mod platform;
+#[cfg(any(target_os = "netbsd"))]
+#[path = "netbsd/mod.rs"]
+pub mod platform;
+
#[cfg(any(target_os = "openbsd"))]
#[path = "openbsd/mod.rs"]
pub mod platform;
@@ -41,6 +45,7 @@ pub mod platform;
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd",
+ target_os = "netbsd",
target_os = "macos",
target_os = "windows"
)))]
|
use letters::LETTERS_POS;
use colors::CPAIRS;
use ncurses::*;
use std::process::Command;
pub type Color = i16;
pub enum Source {
StaticText(String),
Subcommand(String),
}
impl Source {
pub fn emit_string(&self) -> String {
match *self {
Source::StaticText(ref text) => text.clone(),
Source::Subcommand(ref text) => {
let split = text.split(" ").collect::<Vec<&str>>();
let args = &split[1..];
let cmd = split[0];
let output = Command::new(cmd).args(args).output();
match output {
Ok(r) => String::from_utf8(r.stdout).unwrap(),
Err(r) => "-".to_string(),
}
}
}
}
}
pub enum Content {
Empty,
Text(Source),
BigText(Source),
}
// ======================================================================
// Window
pub struct Window {
pub x: i32,
pub y: i32,
pub border_v: u64,
pub border_h: u64,
pub width: i32,
pub height: i32,
pub children: Vec<Window>,
pub content: Content,
pub _win: WINDOW,
}
impl Window {
pub fn new(x: i32, y: i32, width: i32, height: i32, content: Content) -> Window {
Window {
x: x,
y: y,
width: width,
height: height,
border_h: 0,
border_v: 0,
children: vec![],
content: content,
_win: Window::_create_win(x, y, width, height),
}
}
pub fn draw(&self) {
let content = match self.content {
Content::Empty => "".to_string(),
Content::Text(ref source) => source.emit_string(),
Content::BigText(ref source) => source.emit_string(),
};
werase(self._win);
match self.content {
Content::Empty => (),
Content::Text(_) => self.print(&content, 1, 1, *CPAIRS.get("BLUE_ON_BLACK").unwrap()),
Content::BigText(_) => {
self.print_big(&content, 2, 1, *CPAIRS.get("BLUE_ON_BLACK").unwrap())
}
};
box_(self._win, self.border_h, self.border_v);
wrefresh(self._win);
}
fn _create_win(x: i32, y: i32, width: i32, height: i32) -> WINDOW {
let win = newwin(height, width, y, x);
wrefresh(win);
win
}
pub fn print(&self, text: &String, x: i32, y: i32, color: Color) {
wmove(self._win, y, x);
wattron(self._win, COLOR_PAIR(color) as i32);
for c in text.chars() {
wprintw(self._win, &*c.to_string());
if c == '\n' {
wprintw(self._win, &*" ".to_string());
}
}
wattroff(self._win, COLOR_PAIR(color) as i32);
}
pub fn print_big(&self, text: &String, mut x: i32, y: i32, color: Color) {
for c in text.chars() {
let pos = LETTERS_POS.get(&c);
match pos {
Some(ps) => {
for p in ps.iter() {
self.print(&" ".to_string(), x + p.0, y + p.1, color);
}
}
_ => (),
}
x += 8;
}
}
}
// ======================================================================
// Canvas
pub struct Canvas {
pub width: i32,
pub height: i32,
pub root: Window,
pub delay: i32,
}
impl Canvas {
pub fn new() -> Canvas {
Canvas {
width: 0,
height: 0,
delay: 1000,
root: Window::new(0, 0, 0, 0, Content::Empty),
}
}
pub fn refresh(&mut self) {
for win in &self.root.children {
win.draw();
}
mv(0, 0);
}
pub fn initialize(&mut self) {
// Start ncurses.
initscr();
raw();
keypad(stdscr, true);
noecho();
// Invisible cursor.
curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE);
// start colors.
start_color();
// Get the screen bounds.
getmaxyx(stdscr, &mut self.height, &mut self.width);
refresh();
let (w, h) = (self.width, self.height);
self.root = Window::new(0, 0, w, h, Content::Empty);
}
pub fn cleanup(&mut self) {
endwin();
}
}
impl Drop for Canvas {
fn drop(&mut self) {
self.cleanup();
}
}
pub fn destroy_win(win: WINDOW) {
println!("Destroying {:?}", win);
let ch = ' ' as chtype;
wborder(win, ch, ch, ch, ch, ch, ch, ch, ch);
wrefresh(win);
delwin(win);
}
|
use super::*;
/// A venue.
#[derive(Debug,Deserialize)]
pub struct Venue {
/// The venue's location.
pub location: Box<Location>,
/// The name of the venue.
pub title: String,
/// The address of the venue.
pub address: String,
/// The venue's Foursquare identifier.
pub foursquare_id: Option<String>,
}
|
use rand::prelude::SliceRandom;
use std::convert::TryInto;
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
#[repr(u8)]
enum Facelet {
White,
Orange,
Green,
Red,
Yellow,
Blue,
}
impl fmt::Display for Facelet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::White => write!(f, "W"),
Self::Orange => write!(f, "O"),
Self::Green => write!(f, "G"),
Self::Red => write!(f, "R"),
Self::Yellow => write!(f, "Y"),
Self::Blue => write!(f, "B"),
}
}
}
impl FromStr for Facelet {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"W" => Ok(Self::White),
"O" => Ok(Self::Orange),
"G" => Ok(Self::Green),
"R" => Ok(Self::Red),
"Y" => Ok(Self::Yellow),
"B" => Ok(Self::Blue),
_ => Err("Unknown facelet colour"),
}
}
}
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
#[repr(u8)]
pub enum Move {
Forward,
ForwardPrime,
ForwardHalf,
Up,
UpPrime,
UpHalf,
Right,
RightPrime,
RightHalf,
}
impl fmt::Display for Move {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::Forward => write!(f, "F"),
Self::ForwardPrime => write!(f, "F'"),
Self::ForwardHalf => write!(f, "F2"),
Self::Up => write!(f, "U"),
Self::UpPrime => write!(f, "U'"),
Self::UpHalf => write!(f, "U2"),
Self::Right => write!(f, "R"),
Self::RightPrime => write!(f, "R'"),
Self::RightHalf => write!(f, "R2"),
}
}
}
impl FromStr for Move {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"F" => Ok(Self::Forward),
"F'" => Ok(Self::ForwardPrime),
"F2" => Ok(Self::ForwardHalf),
"U" => Ok(Self::Up),
"U'" => Ok(Self::UpPrime),
"U2" => Ok(Self::UpHalf),
"R" => Ok(Self::Right),
"R'" => Ok(Self::RightPrime),
"R2" => Ok(Self::RightHalf),
_ => Err("Unknown move"),
}
}
}
impl Move {
fn available() -> [Self; 9] {
[
Self::Forward,
Self::ForwardPrime,
Self::ForwardHalf,
Self::Up,
Self::UpPrime,
Self::UpHalf,
Self::Right,
Self::RightPrime,
Self::RightHalf,
]
}
pub fn inverse(self) -> Self {
match self {
Self::Forward => Self::ForwardPrime,
Self::ForwardPrime => Self::Forward,
Self::Up => Self::UpPrime,
Self::UpPrime => Self::Up,
Self::Right => Self::RightPrime,
Self::RightPrime => Self::Right,
_ => self,
}
}
}
type CubeState = [Facelet; 24];
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub struct Cube {
state: CubeState,
}
impl fmt::Display for Cube {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
self.state
.iter()
.map(|face| format!("{}", face))
.collect::<String>()
)
}
}
impl FromStr for Cube {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let facelets: Vec<Facelet> = s
.chars()
.map(|facelet| facelet.to_string().parse())
.collect::<Result<Vec<_>, _>>()?;
let state: CubeState = match facelets.try_into() {
Ok(cube_state) => Ok(cube_state),
Err(_) => Err("Invalid facelet colour sequence"),
}?;
if (state[7], state[19], state[22]) != (Facelet::Orange, Facelet::Yellow, Facelet::Blue) {
return Err("Orange/Yellow/Blue cubie must be positioned at DLB");
}
Ok(Cube { state })
}
}
impl Cube {
pub fn random(total_moves: u8) -> Self {
let mut rng = rand::thread_rng();
(0..total_moves).fold(Self::solved(), |cube, _| {
cube.apply_move(&Move::available().choose(&mut rng).unwrap())
})
}
#[rustfmt::skip]
pub fn solved() -> Self {
Self {
state: [
Facelet::White, Facelet::White, Facelet::White, Facelet::White,
Facelet::Orange, Facelet::Orange, Facelet::Orange, Facelet::Orange,
Facelet::Green, Facelet::Green, Facelet::Green, Facelet::Green,
Facelet::Red, Facelet::Red, Facelet::Red, Facelet::Red,
Facelet::Yellow, Facelet::Yellow, Facelet::Yellow, Facelet::Yellow,
Facelet::Blue, Facelet::Blue, Facelet::Blue, Facelet::Blue,
],
}
}
fn rotate(self, rotations: [usize; 24]) -> CubeState {
let mut rotated = self.state;
for idx in 0..rotated.len() {
rotated[idx] = self.state[rotations[idx]];
}
rotated
}
#[rustfmt::skip]
pub fn apply_move(self, action: &Move) -> Self {
match action {
Move::Forward => Self {
state: self.rotate([
0, 1, 5, 6, 4, 16, 17, 7, 11, 8, 9, 10, 3,
13, 14, 2, 15, 12, 18, 19, 20, 21, 22, 23,
]),
},
Move::ForwardPrime => Self {
state: self.rotate([
0, 1, 15, 12, 4, 2, 3, 7, 9, 10, 11, 8, 17,
13, 14, 16, 5, 6, 18, 19, 20, 21, 22, 23,
]),
},
Move::ForwardHalf => self.apply_moves(vec![Move::Forward, Move::Forward]),
Move::Up => Self {
state: self.rotate([
3, 0, 1, 2, 8, 9, 6, 7, 12, 13, 10, 11, 20,
21, 14, 15, 16, 17, 18, 19, 4, 5, 22, 23,
]),
},
Move::UpPrime => Self {
state: self.rotate([
1, 2, 3, 0, 20, 21, 6, 7, 4, 5, 10, 11, 8,
9, 14, 15, 16, 17, 18, 19, 12, 13, 22, 23,
]),
},
Move::UpHalf => self.apply_moves(vec![Move::Up, Move::Up]),
Move::Right => Self {
state: self.rotate([
0, 9, 10, 3, 4, 5, 6, 7, 8, 17, 18, 11, 15,
12, 13, 14, 16, 23, 20, 19, 2, 21, 22, 1,
]),
},
Move::RightPrime => Self {
state: self.rotate([
0, 23, 20, 3, 4, 5, 6, 7, 8, 1, 2, 11, 13,
14, 15, 12, 16, 9, 10, 19, 18, 21, 22, 17,
]),
},
Move::RightHalf => self.apply_moves(vec![Move::Right, Move::Right]),
}
}
pub fn apply_moves(self, actions: Vec<Move>) -> Self {
actions
.iter()
.fold(self, |cube, action| cube.apply_move(action))
}
pub fn next_states(self) -> [(Move, Self); 9] {
return [
(Move::Forward, self.apply_move(&Move::Forward)),
(Move::ForwardPrime, self.apply_move(&Move::ForwardPrime)),
(Move::ForwardHalf, self.apply_move(&Move::ForwardHalf)),
(Move::Up, self.apply_move(&Move::Up)),
(Move::UpPrime, self.apply_move(&Move::UpPrime)),
(Move::UpHalf, self.apply_move(&Move::UpHalf)),
(Move::Right, self.apply_move(&Move::Right)),
(Move::RightPrime, self.apply_move(&Move::RightPrime)),
(Move::RightHalf, self.apply_move(&Move::RightHalf)),
];
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! cube_move_tests {
($($name:ident: $value:expr,)*) => {
$(
#[test]
fn $name() {
let (input, expected) = $value;
assert_eq!(expected, Cube::solved().apply_move(&input).to_string());
}
)*
}
}
cube_move_tests! {
forward: (Move::Forward, "WWOOOYYOGGGGWRRWRRYYBBBB"),
forward_prime: (Move::ForwardPrime, "WWRROWWOGGGGYRRYOOYYBBBB"),
forward_half: (Move::ForwardHalf, "WWYYORROGGGGORROWWYYBBBB"),
up: (Move::Up, "WWWWGGOORRGGBBRRYYYYOOBB"),
up_prime: (Move::UpPrime, "WWWWBBOOOOGGGGRRYYYYRRBB"),
up_half: (Move::UpHalf, "WWWWRROOBBGGOORRYYYYGGBB"),
right: (Move::Right, "WGGWOOOOGYYGRRRRYBBYWBBW"),
right_prime: (Move::RightPrime, "WBBWOOOOGWWGRRRRYGGYYBBY"),
right_half: (Move::RightHalf, "WYYWOOOOGBBGRRRRYWWYGBBG"),
}
#[test]
fn applying_half_move_twice_returns_to_initial_state() {
assert_eq!(
Cube::solved(),
Cube::solved().apply_moves(vec![Move::ForwardHalf, Move::ForwardHalf])
);
}
#[test]
fn applying_double_quarter_turn_is_the_same_as_single_half_turn() {
assert_eq!(
Cube::solved().apply_move(&Move::ForwardHalf),
Cube::solved().apply_moves(vec![Move::Forward, Move::Forward])
);
assert_eq!(
Cube::solved().apply_move(&Move::ForwardHalf),
Cube::solved().apply_moves(vec![Move::ForwardPrime, Move::ForwardPrime])
);
}
}
|
fn main() -> std::io::Result<()> {
let input = std::fs::read_to_string("examples/13/input.txt")?;
let mut lines = input.lines();
let timestamp = lines.next().unwrap().parse::<u64>().unwrap();
let buses = lines
.next()
.unwrap()
.split(',')
.filter(|x| x != &"x")
.map(|x| x.parse::<u64>().unwrap());
let minutes = buses.map(|x| (x - (timestamp % x), x)).min().unwrap();
println!("{}", minutes.1 * minutes.0);
// Part 2
let mut lines = input.lines();
let timestamp = lines.next().unwrap().parse::<u64>().unwrap();
let buses: Vec<(usize, u64)> = lines
.next()
.unwrap()
.split(',')
.enumerate()
.filter(|(_, x)| x != &"x")
.map(|(i, x)| (i, x.parse::<u64>().unwrap()))
.collect();
// All ids are primes so they are pairwise coprimes, so we can use the chinese remainder theorem
// to solve the set of linear congruences
let product: u64 = buses.iter().map(|(_, x)| x).product();
let solution: u64 = buses
.iter()
.map(|(i, x)| {
let rem = x - (*i as u64 % x);
let m = product / x;
// the second factor could be found using the extended Euclidean algorithm
rem * ((1..).find(|y| (y * m) % x == 1)).unwrap() * m
})
.sum();
println!("{}", solution % product);
Ok(())
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// SyntheticsTestProcessStatus : Status of a Synthetic test.
/// Status of a Synthetic test.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum SyntheticsTestProcessStatus {
#[serde(rename = "not_scheduled")]
NOT_SCHEDULED,
#[serde(rename = "scheduled")]
SCHEDULED,
#[serde(rename = "started")]
STARTED,
#[serde(rename = "finished")]
FINISHED,
#[serde(rename = "finished_with_error")]
FINISHED_WITH_ERROR,
}
impl ToString for SyntheticsTestProcessStatus {
fn to_string(&self) -> String {
match self {
Self::NOT_SCHEDULED => String::from("not_scheduled"),
Self::SCHEDULED => String::from("scheduled"),
Self::STARTED => String::from("started"),
Self::FINISHED => String::from("finished"),
Self::FINISHED_WITH_ERROR => String::from("finished_with_error"),
}
}
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//! Provides the main OPAQUE API
use crate::{
errors::{utils::check_slice_size, InternalPakeError, PakeError, ProtocolError},
group::Group,
key_exchange::{
finish_ke, generate_ke1, generate_ke2, generate_ke3, KE1Message, KE1State, KE2Message,
KE2State, KE3Message, KE1_STATE_LEN, KE2_MESSAGE_LEN,
},
keypair::{Key, KeyPair, SizedBytes},
oprf,
oprf::OprfClientBytes,
rkr_encryption::{RKRCipher, RKRCiphertext},
};
use generic_array::{
typenum::{Unsigned, U32, U64},
GenericArray,
};
use hkdf::Hkdf;
use rand_core::{CryptoRng, RngCore};
use sha2::{Digest, Sha256};
use std::{convert::TryFrom, marker::PhantomData};
use zeroize::Zeroize;
// Constant string used as salt for HKDF computation
const STR_ENVU: &[u8] = b"EnvU";
/// The length of the "key-derivation key" output by the client registration
/// and login finish steps
pub const DERIVED_KEY_LEN: usize = 32;
// Messages
// =========
/// The message sent by the client to the server, to initiate registration
pub struct RegisterFirstMessage<Grp> {
/// blinded password information
alpha: Grp,
}
impl<Grp: Group> TryFrom<&[u8]> for RegisterFirstMessage<Grp> {
type Error = ProtocolError;
fn try_from(first_message_bytes: &[u8]) -> Result<Self, Self::Error> {
// Check that the message is actually containing an element of the
// correct subgroup
let arr = GenericArray::from_slice(first_message_bytes);
let alpha = Grp::from_element_slice(arr)?;
Ok(Self { alpha })
}
}
impl<Grp: Group> RegisterFirstMessage<Grp> {
pub fn to_bytes(&self) -> GenericArray<u8, Grp::ElemLen> {
self.alpha.to_bytes()
}
}
/// The answer sent by the server to the user, upon reception of the
/// registration attempt
pub struct RegisterSecondMessage<Grp> {
/// The server's oprf output
beta: Grp,
}
impl<Grp> TryFrom<&[u8]> for RegisterSecondMessage<Grp>
where
Grp: Group,
{
type Error = ProtocolError;
fn try_from(second_message_bytes: &[u8]) -> Result<Self, Self::Error> {
let checked_slice = check_slice_size(
second_message_bytes,
Grp::ElemLen::to_usize(),
"second_message_bytes",
)?;
// Check that the message is actually containing an element of the
// correct subgroup
let arr = GenericArray::from_slice(&checked_slice);
let beta = Grp::from_element_slice(arr)?;
Ok(Self { beta })
}
}
impl<Grp> RegisterSecondMessage<Grp>
where
Grp: Group,
{
pub fn to_bytes(&self) -> Vec<u8> {
self.beta.to_bytes().to_vec()
}
}
/// The final message from the client, containing encrypted cryptographic
/// identifiers
pub struct RegisterThirdMessage<Aead, KeyFormat: KeyPair> {
/// The "envelope" generated by the user, containing encrypted
/// cryptographic identifiers
envelope: RKRCiphertext<Aead>,
/// The user's public key
client_s_pk: KeyFormat::Repr,
}
impl<Aead, KeyFormat> RegisterThirdMessage<Aead, KeyFormat>
where
Aead: aead::Aead + aead::NewAead<KeySize = U32>,
KeyFormat: KeyPair,
{
pub fn to_bytes(&self) -> Vec<u8> {
let mut res = Vec::new();
res.extend(self.envelope.to_bytes());
res.extend(self.client_s_pk.to_arr());
res
}
}
impl<Aead, KeyFormat> TryFrom<&[u8]> for RegisterThirdMessage<Aead, KeyFormat>
where
Aead: aead::Aead + aead::NewAead<KeySize = U32>,
KeyFormat: KeyPair,
{
type Error = ProtocolError;
fn try_from(third_message_bytes: &[u8]) -> Result<Self, Self::Error> {
let rkr_size = RKRCiphertext::<Aead>::rkr_with_nonce_size();
let key_len = <KeyFormat::Repr as SizedBytes>::Len::to_usize();
let checked_bytes =
check_slice_size(third_message_bytes, rkr_size + key_len, "third_message")?;
let unchecked_client_s_pk = KeyFormat::Repr::from_bytes(&checked_bytes[rkr_size..])?;
let client_s_pk = KeyFormat::check_public_key(unchecked_client_s_pk)?;
Ok(Self {
envelope: RKRCiphertext::from_bytes(&checked_bytes[..rkr_size])?,
client_s_pk,
})
}
}
/// The message sent by the user to the server, to initiate registration
pub struct LoginFirstMessage<Grp> {
/// blinded password information
alpha: Grp,
ke1_message: KE1Message,
}
impl<Grp: Group> TryFrom<&[u8]> for LoginFirstMessage<Grp> {
type Error = ProtocolError;
fn try_from(first_message_bytes: &[u8]) -> Result<Self, Self::Error> {
// Check that the message is actually containing an element of the
// correct subgroup
let elem_len = Grp::ElemLen::to_usize();
let arr = GenericArray::from_slice(&first_message_bytes[..elem_len]);
let alpha = Grp::from_element_slice(arr)?;
let ke1_message = KE1Message::try_from(&first_message_bytes[elem_len..])?;
Ok(Self { alpha, ke1_message })
}
}
impl<Grp: Group> LoginFirstMessage<Grp> {
pub fn to_bytes(&self) -> Vec<u8> {
let output: Vec<u8> = [
self.alpha.to_bytes().as_slice(),
&self.ke1_message.to_bytes(),
]
.concat();
output
}
}
/// The answer sent by the server to the user, upon reception of the
/// login attempt.
pub struct LoginSecondMessage<Aead, Grp> {
/// the server's oprf output
beta: Grp,
/// the user's encrypted information,
envelope: RKRCiphertext<Aead>,
ke2_message: KE2Message,
}
impl<Aead, Grp> LoginSecondMessage<Aead, Grp>
where
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group,
{
pub fn to_bytes(&self) -> Vec<u8> {
[
&self.beta.to_bytes()[..],
&self.envelope.to_bytes()[..],
&self.ke2_message.to_bytes()[..],
]
.concat()
}
}
impl<Aead, Grp> TryFrom<&[u8]> for LoginSecondMessage<Aead, Grp>
where
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group,
{
type Error = ProtocolError;
fn try_from(second_message_bytes: &[u8]) -> Result<Self, Self::Error> {
let cipher_len = RKRCiphertext::<Aead>::rkr_with_nonce_size();
let elem_len = Grp::ElemLen::to_usize();
let checked_slice = check_slice_size(
second_message_bytes,
elem_len + cipher_len + KE2_MESSAGE_LEN,
"login_second_message_bytes",
)?;
// Check that the message is actually containing an element of the
// correct subgroup
let beta_bytes = &checked_slice[..elem_len];
let arr = GenericArray::from_slice(beta_bytes);
let beta = Grp::from_element_slice(arr)?;
let envelope =
RKRCiphertext::<Aead>::from_bytes(&checked_slice[elem_len..elem_len + cipher_len])?;
let ke2_message = KE2Message::try_from(&checked_slice[elem_len + cipher_len..])?;
Ok(Self {
beta,
envelope,
ke2_message,
})
}
}
/// The answer sent by the client to the server, upon reception of the
/// encrypted envelope
pub struct LoginThirdMessage {
ke3_message: KE3Message,
}
impl TryFrom<&[u8]> for LoginThirdMessage {
type Error = ProtocolError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
let ke3_message = KE3Message::try_from(&bytes[..])?;
Ok(Self { ke3_message })
}
}
impl LoginThirdMessage {
pub fn to_bytes(&self) -> Vec<u8> {
self.ke3_message.to_bytes()
}
}
// Registration
// ============
/// The state elements the client holds to register itself
pub struct ClientRegistration<Aead, Grp: Group> {
/// A choice of symmetric encryption for the envelope
_aead: PhantomData<Aead>,
/// a blinding factor
pub(crate) blinding_factor: Grp::Scalar,
/// the client's password
password: Vec<u8>,
}
impl<Aead: aead::NewAead<KeySize = U32> + aead::Aead, Grp: Group> TryFrom<&[u8]>
for ClientRegistration<Aead, Grp>
{
type Error = ProtocolError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
// Check that the message is actually containing an element of the
// correct subgroup
let scalar_len = Grp::ScalarLen::to_usize();
let blinding_factor_bytes = GenericArray::from_slice(&bytes[..scalar_len]);
let blinding_factor = Grp::from_scalar_slice(blinding_factor_bytes)?;
let password = bytes[scalar_len..].to_vec();
Ok(Self {
_aead: PhantomData,
blinding_factor,
password,
})
}
}
impl<Aead, Grp> ClientRegistration<Aead, Grp>
where
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group,
{
pub fn to_bytes(&self) -> Vec<u8> {
let output: Vec<u8> = [
Grp::scalar_as_bytes(&self.blinding_factor).as_slice(),
&self.password,
]
.concat();
output
}
}
impl<Aead, Grp> ClientRegistration<Aead, Grp>
where
Grp: Group<ScalarLen = U32, UniformBytesLen = U64>,
{
/// Returns an initial "blinded" request to send to the server, as well as a ClientRegistration
///
/// # Arguments
/// * `password` - A user password
///
/// # Example
///
/// ```
/// use opaque_ke::opaque::ClientRegistration;
/// # use opaque_ke::errors::ProtocolError;
/// use chacha20poly1305::ChaCha20Poly1305;
/// use curve25519_dalek::ristretto::RistrettoPoint;
/// use rand_core::{OsRng, RngCore};
/// let mut rng = OsRng;
/// let (register_m1, registration_state) = ClientRegistration::<ChaCha20Poly1305, RistrettoPoint>::start(b"hunter2", None, &mut rng)?;
/// # Ok::<(), ProtocolError>(())
/// ```
pub fn start<R: RngCore + CryptoRng>(
password: &[u8],
pepper: Option<&[u8]>,
blinding_factor_rng: &mut R,
) -> Result<(RegisterFirstMessage<Grp>, Self), ProtocolError> {
let OprfClientBytes {
alpha,
blinding_factor,
} = oprf::generate_oprf1::<R, Grp>(&password, pepper, blinding_factor_rng)?;
Ok((
RegisterFirstMessage::<Grp> { alpha },
Self {
_aead: PhantomData,
blinding_factor,
password: password.to_vec(),
},
))
}
}
type ClientRegistrationFinishResult<Aead, KeyFormat> = (
RegisterThirdMessage<Aead, KeyFormat>,
GenericArray<u8, <Sha256 as Digest>::OutputSize>,
);
impl<Aead, Grp> ClientRegistration<Aead, Grp>
where
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group,
{
/// "Unblinds" the server's answer and returns a final message containing
/// cryptographic identifiers, to be sent to the server on setup finalization
///
/// # Arguments
/// * `message` - the server's answer to the initial registration attempt
///
/// # Example
///
/// ```
/// use opaque_ke::{opaque::{ClientRegistration, ServerRegistration}, keypair::{X25519KeyPair, SizedBytes}};
/// # use opaque_ke::errors::ProtocolError;
/// # use opaque_ke::keypair::KeyPair;
/// use rand_core::{OsRng, RngCore};
/// use chacha20poly1305::ChaCha20Poly1305;
/// use curve25519_dalek::ristretto::RistrettoPoint;
/// let mut client_rng = OsRng;
/// let mut server_rng = OsRng;
/// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
/// let (register_m1, client_state) = ClientRegistration::<ChaCha20Poly1305, RistrettoPoint>::start(b"hunter2", None, &mut client_rng)?;
/// let (register_m2, server_state) =
/// ServerRegistration::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(register_m1, &mut server_rng)?;
/// let mut client_rng = OsRng;
/// let register_m3 = client_state.finish::<_, X25519KeyPair>(register_m2, server_kp.public(), &mut client_rng)?;
/// # Ok::<(), ProtocolError>(())
/// ```
pub fn finish<R: CryptoRng + RngCore, KeyFormat: KeyPair>(
self,
r2: RegisterSecondMessage<Grp>,
server_s_pk: &KeyFormat::Repr,
rng: &mut R,
) -> Result<ClientRegistrationFinishResult<Aead, KeyFormat>, ProtocolError> {
let client_static_keypair = KeyFormat::generate_random(rng)?;
let password_derived_key =
get_password_derived_key::<Grp>(self.password.clone(), r2.beta, &self.blinding_factor)?;
let h = Hkdf::<Sha256>::new(None, &password_derived_key);
let mut okm = [0u8; 3 * DERIVED_KEY_LEN];
h.expand(STR_ENVU, &mut okm)
.map_err(|_| InternalPakeError::HkdfError)?;
let encryption_key = &okm[..DERIVED_KEY_LEN];
let hmac_key = &okm[DERIVED_KEY_LEN..2 * DERIVED_KEY_LEN];
let kd_key = &okm[2 * DERIVED_KEY_LEN..];
let envelope = RKRCiphertext::<Aead>::encrypt(
&encryption_key,
&hmac_key,
&client_static_keypair.private().to_arr(),
&server_s_pk.to_arr(),
rng,
)?;
Ok((
RegisterThirdMessage {
envelope,
client_s_pk: client_static_keypair.public().clone(),
},
*GenericArray::from_slice(&kd_key),
))
}
}
// This can't be derived because of the use of a phantom parameter
impl<Aead, Grp: Group> Zeroize for ClientRegistration<Aead, Grp> {
fn zeroize(&mut self) {
self.password.zeroize();
self.blinding_factor.zeroize();
}
}
impl<Aead, Grp: Group> Drop for ClientRegistration<Aead, Grp> {
fn drop(&mut self) {
self.zeroize();
}
}
// This can't be derived because of the use of a phantom parameter
impl<Aead, Grp: Group, KeyFormat> Zeroize for ClientLogin<Aead, Grp, KeyFormat> {
fn zeroize(&mut self) {
self.password.zeroize();
self.blinding_factor.zeroize();
}
}
impl<Aead, Grp: Group, KeyFormat> Drop for ClientLogin<Aead, Grp, KeyFormat> {
fn drop(&mut self) {
self.zeroize();
}
}
/// The state elements the server holds to record a registration
pub struct ServerRegistration<Aead, Grp: Group, KeyFormat: KeyPair> {
envelope: Option<RKRCiphertext<Aead>>,
client_s_pk: Option<KeyFormat::Repr>,
pub(crate) oprf_key: Grp::Scalar,
}
impl<Aead, Grp, KeyFormat> TryFrom<&[u8]> for ServerRegistration<Aead, Grp, KeyFormat>
where
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group,
KeyFormat: KeyPair + PartialEq,
<KeyFormat::Repr as SizedBytes>::Len: std::ops::Add<<KeyFormat::Repr as SizedBytes>::Len>,
generic_array::typenum::Sum<
<KeyFormat::Repr as SizedBytes>::Len,
<KeyFormat::Repr as SizedBytes>::Len,
>: generic_array::ArrayLength<u8>,
{
type Error = ProtocolError;
fn try_from(server_registration_bytes: &[u8]) -> Result<Self, Self::Error> {
let key_len = <KeyFormat::Repr as SizedBytes>::Len::to_usize();
let scalar_len = Grp::ScalarLen::to_usize();
let rkr_size = RKRCiphertext::<Aead>::rkr_with_nonce_size();
if server_registration_bytes.len() == scalar_len {
return Ok(Self {
oprf_key: Grp::from_scalar_slice(GenericArray::from_slice(
server_registration_bytes,
))?,
client_s_pk: None,
envelope: None,
});
}
let checked_bytes = check_slice_size(
server_registration_bytes,
rkr_size + key_len + scalar_len,
"server_registration_bytes",
)?;
let oprf_key_bytes = GenericArray::from_slice(&checked_bytes[..scalar_len]);
let oprf_key = Grp::from_scalar_slice(oprf_key_bytes)?;
let unchecked_client_s_pk =
KeyFormat::Repr::from_bytes(&checked_bytes[scalar_len..scalar_len + key_len])?;
let client_s_pk = KeyFormat::check_public_key(unchecked_client_s_pk)?;
Ok(Self {
envelope: Some(RKRCiphertext::from_bytes(
&checked_bytes[checked_bytes.len() - rkr_size..],
)?),
client_s_pk: Some(client_s_pk),
oprf_key,
})
}
}
impl<Aead, Grp, KeyFormat> ServerRegistration<Aead, Grp, KeyFormat>
where
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group,
KeyFormat: KeyPair + PartialEq,
<KeyFormat::Repr as SizedBytes>::Len: std::ops::Add<<KeyFormat::Repr as SizedBytes>::Len>,
generic_array::typenum::Sum<
<KeyFormat::Repr as SizedBytes>::Len,
<KeyFormat::Repr as SizedBytes>::Len,
>: generic_array::ArrayLength<u8>,
{
pub fn to_bytes(&self) -> Vec<u8> {
let mut output: Vec<u8> = Grp::scalar_as_bytes(&self.oprf_key).to_vec();
match &self.client_s_pk {
Some(v) => output.extend_from_slice(&v.to_arr()),
None => {}
};
match &self.envelope {
Some(v) => output.extend_from_slice(&v.to_bytes()),
None => {}
};
output
}
/// From the client's "blinded" password, returns a response to be
/// sent back to the client, as well as a ServerRegistration
///
/// # Arguments
/// * `message` - the initial registration message
///
/// # Example
///
/// ```
/// use opaque_ke::{opaque::*, keypair::{X25519KeyPair, SizedBytes}};
/// # use opaque_ke::errors::ProtocolError;
/// # use opaque_ke::keypair::KeyPair;
/// use rand_core::{OsRng, RngCore};
/// use chacha20poly1305::ChaCha20Poly1305;
/// use curve25519_dalek::ristretto::RistrettoPoint;
/// let mut client_rng = OsRng;
/// let mut server_rng = OsRng;
/// let (register_m1, client_state) = ClientRegistration::<ChaCha20Poly1305, RistrettoPoint>::start(b"hunter2", None, &mut client_rng)?;
/// let (register_m2, server_state) =
/// ServerRegistration::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(register_m1, &mut server_rng)?;
/// # Ok::<(), ProtocolError>(())
/// ```
pub fn start<R: RngCore + CryptoRng>(
message: RegisterFirstMessage<Grp>,
rng: &mut R,
) -> Result<(RegisterSecondMessage<Grp>, Self), ProtocolError> {
// RFC: generate oprf_key (salt) and v_u = g^oprf_key
let oprf_key = Grp::random_scalar(rng);
// Compute beta = alpha^oprf_key
let beta = oprf::generate_oprf2::<Grp>(message.alpha, &oprf_key)?;
Ok((
RegisterSecondMessage { beta },
Self {
envelope: None,
client_s_pk: None,
oprf_key,
},
))
}
/// From the client's cryptographic identifiers, fully populates and
/// returns a ServerRegistration
///
/// # Arguments
/// * `message` - the final client message
///
/// # Example
///
/// ```
/// use opaque_ke::{opaque::*, keypair::{X25519KeyPair, SizedBytes}};
/// # use opaque_ke::errors::ProtocolError;
/// # use opaque_ke::keypair::KeyPair;
/// use rand_core::{OsRng, RngCore};
/// use chacha20poly1305::ChaCha20Poly1305;
/// use curve25519_dalek::ristretto::RistrettoPoint;
/// let mut client_rng = OsRng;
/// let mut server_rng = OsRng;
/// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
/// let (register_m1, client_state) = ClientRegistration::<ChaCha20Poly1305, RistrettoPoint>::start(b"hunter2", None, &mut client_rng)?;
/// let (register_m2, server_state) =
/// ServerRegistration::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(register_m1, &mut server_rng)?;
/// let mut client_rng = OsRng;
/// let (register_m3, _opaque_key) = client_state.finish(register_m2, server_kp.public(), &mut client_rng)?;
/// let client_record = server_state.finish(register_m3)?;
/// # Ok::<(), ProtocolError>(())
/// ```
pub fn finish(
self,
message: RegisterThirdMessage<Aead, KeyFormat>,
) -> Result<Self, ProtocolError> {
Ok(Self {
envelope: Some(message.envelope),
client_s_pk: Some(message.client_s_pk),
oprf_key: self.oprf_key,
})
}
}
// Login
// =====
/// The state elements the client holds to perform a login
pub struct ClientLogin<Aead, Grp: Group, KeyFormat> {
/// A choice of symmetric encryption for the envelope
_aead: PhantomData<Aead>,
/// A choice of the keypair type
_key_format: PhantomData<KeyFormat>,
/// A blinding factor, which is used to mask (and unmask) secret
/// information before transmission
blinding_factor: Grp::Scalar,
/// The user's password
password: Vec<u8>,
ke1_state: KE1State,
}
impl<Aead: aead::NewAead<KeySize = U32> + aead::Aead, Grp: Group, KeyFormat: KeyPair> TryFrom<&[u8]>
for ClientLogin<Aead, Grp, KeyFormat>
{
type Error = ProtocolError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
let scalar_len = Grp::ScalarLen::to_usize();
let blinding_factor_bytes = GenericArray::from_slice(&bytes[..scalar_len]);
let blinding_factor = Grp::from_scalar_slice(blinding_factor_bytes)?;
let ke1_state = KE1State::try_from(&bytes[scalar_len..scalar_len + KE1_STATE_LEN])?;
let password = bytes[scalar_len + KE1_STATE_LEN..].to_vec();
Ok(Self {
_aead: PhantomData,
_key_format: PhantomData,
blinding_factor,
password,
ke1_state,
})
}
}
impl<Aead, Grp, KeyFormat> ClientLogin<Aead, Grp, KeyFormat>
where
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group,
KeyFormat: KeyPair,
{
pub fn to_bytes(&self) -> Vec<u8> {
let output: Vec<u8> = [
Grp::scalar_as_bytes(&self.blinding_factor).as_slice(),
&self.ke1_state.to_bytes(),
&self.password,
]
.concat();
output
}
}
type ClientLoginFinishResult = (
LoginThirdMessage,
Vec<u8>,
GenericArray<u8, <Sha256 as Digest>::OutputSize>,
);
impl<Aead, Grp, KeyFormat> ClientLogin<Aead, Grp, KeyFormat>
where
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group<UniformBytesLen = U64>,
KeyFormat: KeyPair<Repr = Key>,
{
/// Returns an initial "blinded" password request to send to the server, as well as a ClientLogin
///
/// # Arguments
/// * `password` - A user password
///
/// # Example
///
/// ```
/// use opaque_ke::opaque::ClientLogin;
/// # use opaque_ke::errors::ProtocolError;
/// use chacha20poly1305::ChaCha20Poly1305;
/// use curve25519_dalek::ristretto::RistrettoPoint;
/// use opaque_ke::keypair::X25519KeyPair;
/// use rand_core::{OsRng, RngCore};
/// let mut client_rng = OsRng;
/// let (login_m1, client_login_state) = ClientLogin::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(b"hunter2", None, &mut client_rng)?;
/// # Ok::<(), ProtocolError>(())
/// ```
pub fn start<R: RngCore + CryptoRng>(
password: &[u8],
pepper: Option<&[u8]>,
rng: &mut R,
) -> Result<(LoginFirstMessage<Grp>, Self), ProtocolError> {
let OprfClientBytes {
alpha,
blinding_factor,
} = oprf::generate_oprf1::<R, Grp>(&password, pepper, rng)?;
let (ke1_state, ke1_message) =
generate_ke1::<_, KeyFormat>(alpha.to_bytes().to_vec(), rng)?;
let l1 = LoginFirstMessage { alpha, ke1_message };
Ok((
l1,
Self {
_aead: PhantomData,
_key_format: PhantomData,
blinding_factor,
password: password.to_vec(),
ke1_state,
},
))
}
/// "Unblinds" the server's answer and returns the decrypted assets from
/// the server
///
/// # Arguments
/// * `message` - the server's answer to the initial login attempt
///
/// # Example
///
/// ```
/// use opaque_ke::opaque::{ClientLogin, ServerLogin};
/// # use opaque_ke::opaque::{ClientRegistration, ServerRegistration};
/// # use opaque_ke::errors::ProtocolError;
/// # use opaque_ke::keypair::{X25519KeyPair, KeyPair};
/// use rand_core::{OsRng, RngCore};
/// use chacha20poly1305::ChaCha20Poly1305;
/// use curve25519_dalek::ristretto::RistrettoPoint;
/// let mut client_rng = OsRng;
/// # let mut server_rng = OsRng;
/// # let (register_m1, client_state) = ClientRegistration::<ChaCha20Poly1305, RistrettoPoint>::start(b"hunter2", None, &mut client_rng)?;
/// # let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
/// # let (register_m2, server_state) = ServerRegistration::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(register_m1, &mut server_rng)?;
/// # let (register_m3, _opaque_key) = client_state.finish(register_m2, server_kp.public(), &mut client_rng)?;
/// # let p_file = server_state.finish(register_m3)?;
/// let (login_m1, client_login_state) = ClientLogin::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(b"hunter2", None, &mut client_rng)?;
/// let (login_m2, server_login_state) = ServerLogin::start(p_file, &server_kp.private(), login_m1, &mut server_rng)?;
/// let (login_m3, client_transport, _opaque_key) = client_login_state.finish(login_m2, &server_kp.public(), &mut client_rng)?;
/// # Ok::<(), ProtocolError>(())
/// ```
pub fn finish<R: RngCore + CryptoRng>(
self,
l2: LoginSecondMessage<Aead, Grp>,
server_s_pk: &KeyFormat::Repr,
_client_e_sk_rng: &mut R,
) -> Result<ClientLoginFinishResult, ProtocolError> {
let l2_bytes: Vec<u8> = [l2.beta.to_bytes().as_slice(), &l2.envelope.to_bytes()].concat();
let password_derived_key =
get_password_derived_key::<Grp>(self.password.clone(), l2.beta, &self.blinding_factor)?;
let h = Hkdf::<Sha256>::new(None, &password_derived_key);
let mut okm = [0u8; 3 * DERIVED_KEY_LEN];
h.expand(STR_ENVU, &mut okm)
.map_err(|_| InternalPakeError::HkdfError)?;
let encryption_key = &okm[..DERIVED_KEY_LEN];
let hmac_key = &okm[DERIVED_KEY_LEN..2 * DERIVED_KEY_LEN];
let kd_key = &okm[2 * DERIVED_KEY_LEN..];
let client_s_sk = Key::from_bytes(
&l2.envelope
.decrypt(&encryption_key, &hmac_key, &server_s_pk.to_arr())
.map_err(|e| match e {
PakeError::DecryptionHmacError => PakeError::InvalidLoginError,
err => err,
})?,
)?;
let (ke3_state, ke3_message) = generate_ke3::<KeyFormat>(
l2_bytes,
l2.ke2_message,
&self.ke1_state,
server_s_pk.clone(),
client_s_sk,
)?;
Ok((
LoginThirdMessage { ke3_message },
ke3_state.shared_secret,
*GenericArray::from_slice(&kd_key),
))
}
}
/// The state elements the server holds to record a login
pub struct ServerLogin {
ke2_state: KE2State,
}
impl TryFrom<&[u8]> for ServerLogin {
type Error = ProtocolError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
Ok(Self {
ke2_state: KE2State::try_from(&bytes[..])?,
})
}
}
impl ServerLogin {
pub fn to_bytes(&self) -> Vec<u8> {
self.ke2_state.to_bytes()
}
/// From the client's "blinded"" password, returns a challenge to be
/// sent back to the client, as well as a ServerLogin
///
/// # Arguments
/// * `message` - the initial registration message
///
/// # Example
///
/// ```
/// use opaque_ke::opaque::{ClientLogin, ServerLogin};
/// # use opaque_ke::opaque::{ClientRegistration, ServerRegistration};
/// # use opaque_ke::errors::ProtocolError;
/// # use opaque_ke::keypair::{KeyPair, X25519KeyPair};
/// use rand_core::{OsRng, RngCore};
/// use chacha20poly1305::ChaCha20Poly1305;
/// use curve25519_dalek::ristretto::RistrettoPoint;
/// let mut client_rng = OsRng;
/// let mut server_rng = OsRng;
/// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
/// # let (register_m1, client_state) = ClientRegistration::<ChaCha20Poly1305, RistrettoPoint>::start(b"hunter2", None, &mut client_rng)?;
/// # let (register_m2, server_state) =
/// ServerRegistration::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(register_m1, &mut server_rng)?;
/// # let (register_m3, _opaque_key) = client_state.finish(register_m2, server_kp.public(), &mut client_rng)?;
/// # let p_file = server_state.finish(register_m3)?;
/// let (login_m1, client_login_state) = ClientLogin::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(b"hunter2", None, &mut client_rng)?;
/// let (login_m2, server_login_state) = ServerLogin::start(p_file, &server_kp.private(), login_m1, &mut server_rng)?;
/// # Ok::<(), ProtocolError>(())
/// ```
pub fn start<
R: RngCore + CryptoRng,
Aead: aead::NewAead<KeySize = U32> + aead::Aead,
Grp: Group,
KeyFormat: KeyPair<Repr = Key>,
>(
password_file: ServerRegistration<Aead, Grp, KeyFormat>,
server_s_sk: &Key,
l1: LoginFirstMessage<Grp>,
rng: &mut R,
) -> Result<(LoginSecondMessage<Aead, Grp>, Self), ProtocolError> {
let l1_bytes = &l1.to_bytes();
let beta = oprf::generate_oprf2(l1.alpha, &password_file.oprf_key)?;
let client_s_pk = password_file
.client_s_pk
.ok_or(PakeError::EncryptionError)?;
let envelope = password_file.envelope.ok_or(PakeError::EncryptionError)?;
let l2_component: Vec<u8> = [beta.to_bytes().as_slice(), &envelope.to_bytes()].concat();
let (ke2_state, ke2_message) = generate_ke2::<_, KeyFormat>(
rng,
l1_bytes.to_vec(),
l2_component,
l1.ke1_message.client_e_pk,
client_s_pk,
server_s_sk.clone(),
l1.ke1_message.client_nonce.to_vec(),
)?;
let l2 = LoginSecondMessage {
beta,
envelope,
ke2_message,
};
Ok((l2, Self { ke2_state }))
}
/// From the client's second & final message, check the client's
/// authentication & produce a message transport
///
/// # Arguments
/// * `message` - the client's second login message
///
/// # Example
///
/// ```
/// use opaque_ke::opaque::{ClientLogin, ServerLogin};
/// # use opaque_ke::opaque::{ClientRegistration, ServerRegistration};
/// # use opaque_ke::errors::ProtocolError;
/// # use opaque_ke::keypair::{KeyPair, X25519KeyPair};
/// use rand_core::{OsRng, RngCore};
/// use chacha20poly1305::ChaCha20Poly1305;
/// use curve25519_dalek::ristretto::RistrettoPoint;
/// let mut client_rng = OsRng;
/// let mut server_rng = OsRng;
/// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
/// # let (register_m1, client_state) = ClientRegistration::<ChaCha20Poly1305, RistrettoPoint>::start(b"hunter2", None, &mut client_rng)?;
/// # let (register_m2, server_state) =
/// ServerRegistration::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(register_m1, &mut server_rng)?;
/// # let (register_m3, _opaque_key) = client_state.finish(register_m2, server_kp.public(), &mut client_rng)?;
/// # let p_file = server_state.finish(register_m3)?;
/// let (login_m1, client_login_state) = ClientLogin::<ChaCha20Poly1305, RistrettoPoint, X25519KeyPair>::start(b"hunter2", None, &mut client_rng)?;
/// let (login_m2, server_login_state) = ServerLogin::start(p_file, &server_kp.private(), login_m1, &mut server_rng)?;
/// let (login_m3, client_transport, _opaque_key) = client_login_state.finish(login_m2, &server_kp.public(), &mut client_rng)?;
/// let mut server_transport = server_login_state.finish(login_m3)?;
/// # Ok::<(), ProtocolError>(())
/// ```
pub fn finish(&self, message: LoginThirdMessage) -> Result<Vec<u8>, ProtocolError> {
finish_ke(message.ke3_message, &self.ke2_state).map_err(|e| match e {
ProtocolError::VerificationError(PakeError::KeyExchangeMacValidationError) => {
ProtocolError::VerificationError(PakeError::InvalidLoginError)
}
err => err,
})
}
}
// Helper functions
fn get_password_derived_key<G: Group>(
password: Vec<u8>,
beta: G,
blinding_factor: &G::Scalar,
) -> Result<GenericArray<u8, <Sha256 as Digest>::OutputSize>, PakeError> {
Ok(oprf::generate_oprf3::<G>(&password, beta, blinding_factor)?)
}
|
pub mod led_ctrl;
pub mod config; |
use std::collections::HashMap;
use std::collections::hash_map;
use std::hash::Hash;
use std::borrow::Borrow;
pub struct LazyHashMap<K, V> {
map: Option<HashMap<K, V>>,
}
impl<K, V> LazyHashMap<K, V>
where K: ::std::hash::Hash + Eq
{
pub fn new() -> LazyHashMap<K, V> {
LazyHashMap { map: None }
}
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where K: Borrow<Q>,
Q: Hash + Eq
{
self.map.as_ref().map_or(false, |m| m.contains_key(key))
}
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where K: Borrow<Q>,
Q: Hash + Eq
{
self.map.as_ref().and_then(|m| m.get(key))
}
pub fn insert(&mut self, key: K, val: V) -> Option<V> {
self.map = match self.map.take() {
Some(m) => Some(m),
None => Some(HashMap::new()),
};
self.map.as_mut().and_then(|m| {
m.insert(key, val)
})
}
pub fn iter(&self) -> Iter<K, V> {
Iter(self.map.as_ref().map(|m| m.iter()))
}
}
pub struct Iter<'a, K: 'a, V: 'a>(Option<hash_map::Iter<'a, K, V>>);
impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.0.as_mut().and_then(|i| i.next())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.as_ref().map_or((0, Some(0)), |i| i.size_hint())
}
}
|
use common::*;
use standard;
/// A Stream that produces a stream of random `u8`s with no delay
#[derive(Debug)]
pub struct Producer {
next: standard::instant::Producer,
}
impl Producer {
pub fn new() -> Producer {
Producer{next: standard::instant::Producer::new()}
}
}
impl Stream for Producer {
type Item = u8;
type Error = Void;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let next = try_ready!(self.next.poll());
self.next = standard::instant::Producer::new();
Ok(Async::Ready(Some(next)))
}
}
/// A Sink that consumes `u8`s with no delay
pub struct Consumer {
sending: Option<standard::instant::Consumer>,
}
impl Consumer {
pub fn new() -> Consumer {
Consumer{sending: None}
}
}
impl Sink for Consumer {
type SinkItem = u8;
type SinkError = Void;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
if self.sending.is_some() {
self.poll_complete()?;
}
if self.sending.is_some() {
Ok(AsyncSink::NotReady(item))
} else {
self.sending = Some(standard::instant::Consumer::new(item));
Ok(AsyncSink::Ready)
}
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
if self.sending.is_some() {
try_ready!(self.sending.as_mut().unwrap().poll());
self.sending = None;
}
Ok(Async::Ready(()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn producer_returns_all_values() {
let mut seen = HashSet::new();
let expected = 2usize.pow(8);
let mut producer = Producer::new().into_future();
while seen.len() < expected {
let (value, next) = producer.wait().unwrap();
seen.insert(value.unwrap());
producer = next.into_future();
}
}
#[test]
fn forward_to_consumer() {
let expected = 10000;
let mut produced = 0;
{
let producer = Producer::new()
.inspect(|_| produced += 1 )
.take(expected);
let consumer = Consumer::new();
producer.forward(consumer).wait().unwrap();
}
assert_eq!(produced, expected);
}
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::AUX7 {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `TMRB7EN23`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB7EN23R {
#[doc = "Disable enhanced functions. value."]
DIS,
#[doc = "Enable enhanced functions. value."]
EN,
}
impl TMRB7EN23R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB7EN23R::DIS => true,
TMRB7EN23R::EN => false,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB7EN23R {
match value {
true => TMRB7EN23R::DIS,
false => TMRB7EN23R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB7EN23R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRB7EN23R::EN
}
}
#[doc = "Possible values of the field `TMRB7POL23`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB7POL23R {
#[doc = "Upper output normal polarity value."]
NORM,
#[doc = "Upper output inverted polarity. value."]
INV,
}
impl TMRB7POL23R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB7POL23R::NORM => false,
TMRB7POL23R::INV => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB7POL23R {
match value {
false => TMRB7POL23R::NORM,
true => TMRB7POL23R::INV,
}
}
#[doc = "Checks if the value of the field is `NORM`"]
#[inline]
pub fn is_norm(&self) -> bool {
*self == TMRB7POL23R::NORM
}
#[doc = "Checks if the value of the field is `INV`"]
#[inline]
pub fn is_inv(&self) -> bool {
*self == TMRB7POL23R::INV
}
}
#[doc = "Possible values of the field `TMRB7TINV`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB7TINVR {
#[doc = "Disable invert on trigger value."]
DIS,
#[doc = "Enable invert on trigger value."]
EN,
}
impl TMRB7TINVR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB7TINVR::DIS => false,
TMRB7TINVR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB7TINVR {
match value {
false => TMRB7TINVR::DIS,
true => TMRB7TINVR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB7TINVR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRB7TINVR::EN
}
}
#[doc = "Possible values of the field `TMRB7NOSYNC`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB7NOSYNCR {
#[doc = "Synchronization on source clock value."]
DIS,
#[doc = "No synchronization on source clock value."]
NOSYNC,
}
impl TMRB7NOSYNCR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRB7NOSYNCR::DIS => false,
TMRB7NOSYNCR::NOSYNC => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRB7NOSYNCR {
match value {
false => TMRB7NOSYNCR::DIS,
true => TMRB7NOSYNCR::NOSYNC,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB7NOSYNCR::DIS
}
#[doc = "Checks if the value of the field is `NOSYNC`"]
#[inline]
pub fn is_nosync(&self) -> bool {
*self == TMRB7NOSYNCR::NOSYNC
}
}
#[doc = "Possible values of the field `TMRB7TRIG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRB7TRIGR {
#[doc = "Trigger source is disabled. value."]
DIS,
#[doc = "Trigger source is CTIMERA7 OUT. value."]
A7OUT,
#[doc = "Trigger source is CTIMERB3 OUT. value."]
B3OUT,
#[doc = "Trigger source is CTIMERA3 OUT. value."]
A3OUT,
#[doc = "Trigger source is CTIMERA5 OUT. value."]
A5OUT,
#[doc = "Trigger source is CTIMERB5 OUT. value."]
B5OUT,
#[doc = "Trigger source is CTIMERA2 OUT. value."]
A2OUT,
#[doc = "Trigger source is CTIMERB2 OUT. value."]
B2OUT,
#[doc = "Trigger source is CTIMERB3 OUT2. value."]
B3OUT2,
#[doc = "Trigger source is CTIMERA3 OUT2. value."]
A3OUT2,
#[doc = "Trigger source is CTIMERA2 OUT2. value."]
A2OUT2,
#[doc = "Trigger source is CTIMERB2 OUT2. value."]
B2OUT2,
#[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."]
A6OUT2DUAL,
#[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."]
A7OUT2DUAL,
#[doc = "Trigger source is CTIMERB1 OUT2, dual edge. value."]
B1OUT2DUAL,
#[doc = "Trigger source is CTIMERA1 OUT2, dual edge. value."]
A1OUT2DUAL,
}
impl TMRB7TRIGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRB7TRIGR::DIS => 0,
TMRB7TRIGR::A7OUT => 1,
TMRB7TRIGR::B3OUT => 2,
TMRB7TRIGR::A3OUT => 3,
TMRB7TRIGR::A5OUT => 4,
TMRB7TRIGR::B5OUT => 5,
TMRB7TRIGR::A2OUT => 6,
TMRB7TRIGR::B2OUT => 7,
TMRB7TRIGR::B3OUT2 => 8,
TMRB7TRIGR::A3OUT2 => 9,
TMRB7TRIGR::A2OUT2 => 10,
TMRB7TRIGR::B2OUT2 => 11,
TMRB7TRIGR::A6OUT2DUAL => 12,
TMRB7TRIGR::A7OUT2DUAL => 13,
TMRB7TRIGR::B1OUT2DUAL => 14,
TMRB7TRIGR::A1OUT2DUAL => 15,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRB7TRIGR {
match value {
0 => TMRB7TRIGR::DIS,
1 => TMRB7TRIGR::A7OUT,
2 => TMRB7TRIGR::B3OUT,
3 => TMRB7TRIGR::A3OUT,
4 => TMRB7TRIGR::A5OUT,
5 => TMRB7TRIGR::B5OUT,
6 => TMRB7TRIGR::A2OUT,
7 => TMRB7TRIGR::B2OUT,
8 => TMRB7TRIGR::B3OUT2,
9 => TMRB7TRIGR::A3OUT2,
10 => TMRB7TRIGR::A2OUT2,
11 => TMRB7TRIGR::B2OUT2,
12 => TMRB7TRIGR::A6OUT2DUAL,
13 => TMRB7TRIGR::A7OUT2DUAL,
14 => TMRB7TRIGR::B1OUT2DUAL,
15 => TMRB7TRIGR::A1OUT2DUAL,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRB7TRIGR::DIS
}
#[doc = "Checks if the value of the field is `A7OUT`"]
#[inline]
pub fn is_a7out(&self) -> bool {
*self == TMRB7TRIGR::A7OUT
}
#[doc = "Checks if the value of the field is `B3OUT`"]
#[inline]
pub fn is_b3out(&self) -> bool {
*self == TMRB7TRIGR::B3OUT
}
#[doc = "Checks if the value of the field is `A3OUT`"]
#[inline]
pub fn is_a3out(&self) -> bool {
*self == TMRB7TRIGR::A3OUT
}
#[doc = "Checks if the value of the field is `A5OUT`"]
#[inline]
pub fn is_a5out(&self) -> bool {
*self == TMRB7TRIGR::A5OUT
}
#[doc = "Checks if the value of the field is `B5OUT`"]
#[inline]
pub fn is_b5out(&self) -> bool {
*self == TMRB7TRIGR::B5OUT
}
#[doc = "Checks if the value of the field is `A2OUT`"]
#[inline]
pub fn is_a2out(&self) -> bool {
*self == TMRB7TRIGR::A2OUT
}
#[doc = "Checks if the value of the field is `B2OUT`"]
#[inline]
pub fn is_b2out(&self) -> bool {
*self == TMRB7TRIGR::B2OUT
}
#[doc = "Checks if the value of the field is `B3OUT2`"]
#[inline]
pub fn is_b3out2(&self) -> bool {
*self == TMRB7TRIGR::B3OUT2
}
#[doc = "Checks if the value of the field is `A3OUT2`"]
#[inline]
pub fn is_a3out2(&self) -> bool {
*self == TMRB7TRIGR::A3OUT2
}
#[doc = "Checks if the value of the field is `A2OUT2`"]
#[inline]
pub fn is_a2out2(&self) -> bool {
*self == TMRB7TRIGR::A2OUT2
}
#[doc = "Checks if the value of the field is `B2OUT2`"]
#[inline]
pub fn is_b2out2(&self) -> bool {
*self == TMRB7TRIGR::B2OUT2
}
#[doc = "Checks if the value of the field is `A6OUT2DUAL`"]
#[inline]
pub fn is_a6out2dual(&self) -> bool {
*self == TMRB7TRIGR::A6OUT2DUAL
}
#[doc = "Checks if the value of the field is `A7OUT2DUAL`"]
#[inline]
pub fn is_a7out2dual(&self) -> bool {
*self == TMRB7TRIGR::A7OUT2DUAL
}
#[doc = "Checks if the value of the field is `B1OUT2DUAL`"]
#[inline]
pub fn is_b1out2dual(&self) -> bool {
*self == TMRB7TRIGR::B1OUT2DUAL
}
#[doc = "Checks if the value of the field is `A1OUT2DUAL`"]
#[inline]
pub fn is_a1out2dual(&self) -> bool {
*self == TMRB7TRIGR::A1OUT2DUAL
}
}
#[doc = r" Value of the field"]
pub struct TMRB7LMTR {
bits: u8,
}
impl TMRB7LMTR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = "Possible values of the field `TMRA7EN23`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA7EN23R {
#[doc = "Disable enhanced functions. value."]
DIS,
#[doc = "Enable enhanced functions. value."]
EN,
}
impl TMRA7EN23R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA7EN23R::DIS => true,
TMRA7EN23R::EN => false,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA7EN23R {
match value {
true => TMRA7EN23R::DIS,
false => TMRA7EN23R::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA7EN23R::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRA7EN23R::EN
}
}
#[doc = "Possible values of the field `TMRA7POL23`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA7POL23R {
#[doc = "Upper output normal polarity value."]
NORM,
#[doc = "Upper output inverted polarity. value."]
INV,
}
impl TMRA7POL23R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA7POL23R::NORM => false,
TMRA7POL23R::INV => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA7POL23R {
match value {
false => TMRA7POL23R::NORM,
true => TMRA7POL23R::INV,
}
}
#[doc = "Checks if the value of the field is `NORM`"]
#[inline]
pub fn is_norm(&self) -> bool {
*self == TMRA7POL23R::NORM
}
#[doc = "Checks if the value of the field is `INV`"]
#[inline]
pub fn is_inv(&self) -> bool {
*self == TMRA7POL23R::INV
}
}
#[doc = "Possible values of the field `TMRA7TINV`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA7TINVR {
#[doc = "Disable invert on trigger value."]
DIS,
#[doc = "Enable invert on trigger value."]
EN,
}
impl TMRA7TINVR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA7TINVR::DIS => false,
TMRA7TINVR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA7TINVR {
match value {
false => TMRA7TINVR::DIS,
true => TMRA7TINVR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA7TINVR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TMRA7TINVR::EN
}
}
#[doc = "Possible values of the field `TMRA7NOSYNC`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA7NOSYNCR {
#[doc = "Synchronization on source clock value."]
DIS,
#[doc = "No synchronization on source clock value."]
NOSYNC,
}
impl TMRA7NOSYNCR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TMRA7NOSYNCR::DIS => false,
TMRA7NOSYNCR::NOSYNC => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TMRA7NOSYNCR {
match value {
false => TMRA7NOSYNCR::DIS,
true => TMRA7NOSYNCR::NOSYNC,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA7NOSYNCR::DIS
}
#[doc = "Checks if the value of the field is `NOSYNC`"]
#[inline]
pub fn is_nosync(&self) -> bool {
*self == TMRA7NOSYNCR::NOSYNC
}
}
#[doc = "Possible values of the field `TMRA7TRIG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TMRA7TRIGR {
#[doc = "Trigger source is disabled. value."]
DIS,
#[doc = "Trigger source is CTIMERB7 OUT. value."]
B7OUT,
#[doc = "Trigger source is CTIMERB3 OUT. value."]
B3OUT,
#[doc = "Trigger source is CTIMERA3 OUT. value."]
A3OUT,
#[doc = "Trigger source is CTIMERA1 OUT. value."]
A1OUT,
#[doc = "Trigger source is CTIMERB1 OUT. value."]
B1OUT,
#[doc = "Trigger source is CTIMERA4 OUT. value."]
A4OUT,
#[doc = "Trigger source is CTIMERB4 OUT. value."]
B4OUT,
#[doc = "Trigger source is CTIMERB3 OUT2. value."]
B3OUT2,
#[doc = "Trigger source is CTIMERA3 OUT2. value."]
A3OUT2,
#[doc = "Trigger source is CTIMERA2 OUT2. value."]
A2OUT2,
#[doc = "Trigger source is CTIMERB2 OUT2. value."]
B2OUT2,
#[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."]
A6OUT2DUAL,
#[doc = "Trigger source is CTIMERA5 OUT2, dual edge. value."]
A5OUT2DUAL,
#[doc = "Trigger source is CTIMERB4 OUT2, dual edge. value."]
B4OUT2DUAL,
#[doc = "Trigger source is CTIMERA4 OUT2, dual edge. value."]
A4OUT2DUAL,
}
impl TMRA7TRIGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TMRA7TRIGR::DIS => 0,
TMRA7TRIGR::B7OUT => 1,
TMRA7TRIGR::B3OUT => 2,
TMRA7TRIGR::A3OUT => 3,
TMRA7TRIGR::A1OUT => 4,
TMRA7TRIGR::B1OUT => 5,
TMRA7TRIGR::A4OUT => 6,
TMRA7TRIGR::B4OUT => 7,
TMRA7TRIGR::B3OUT2 => 8,
TMRA7TRIGR::A3OUT2 => 9,
TMRA7TRIGR::A2OUT2 => 10,
TMRA7TRIGR::B2OUT2 => 11,
TMRA7TRIGR::A6OUT2DUAL => 12,
TMRA7TRIGR::A5OUT2DUAL => 13,
TMRA7TRIGR::B4OUT2DUAL => 14,
TMRA7TRIGR::A4OUT2DUAL => 15,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TMRA7TRIGR {
match value {
0 => TMRA7TRIGR::DIS,
1 => TMRA7TRIGR::B7OUT,
2 => TMRA7TRIGR::B3OUT,
3 => TMRA7TRIGR::A3OUT,
4 => TMRA7TRIGR::A1OUT,
5 => TMRA7TRIGR::B1OUT,
6 => TMRA7TRIGR::A4OUT,
7 => TMRA7TRIGR::B4OUT,
8 => TMRA7TRIGR::B3OUT2,
9 => TMRA7TRIGR::A3OUT2,
10 => TMRA7TRIGR::A2OUT2,
11 => TMRA7TRIGR::B2OUT2,
12 => TMRA7TRIGR::A6OUT2DUAL,
13 => TMRA7TRIGR::A5OUT2DUAL,
14 => TMRA7TRIGR::B4OUT2DUAL,
15 => TMRA7TRIGR::A4OUT2DUAL,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TMRA7TRIGR::DIS
}
#[doc = "Checks if the value of the field is `B7OUT`"]
#[inline]
pub fn is_b7out(&self) -> bool {
*self == TMRA7TRIGR::B7OUT
}
#[doc = "Checks if the value of the field is `B3OUT`"]
#[inline]
pub fn is_b3out(&self) -> bool {
*self == TMRA7TRIGR::B3OUT
}
#[doc = "Checks if the value of the field is `A3OUT`"]
#[inline]
pub fn is_a3out(&self) -> bool {
*self == TMRA7TRIGR::A3OUT
}
#[doc = "Checks if the value of the field is `A1OUT`"]
#[inline]
pub fn is_a1out(&self) -> bool {
*self == TMRA7TRIGR::A1OUT
}
#[doc = "Checks if the value of the field is `B1OUT`"]
#[inline]
pub fn is_b1out(&self) -> bool {
*self == TMRA7TRIGR::B1OUT
}
#[doc = "Checks if the value of the field is `A4OUT`"]
#[inline]
pub fn is_a4out(&self) -> bool {
*self == TMRA7TRIGR::A4OUT
}
#[doc = "Checks if the value of the field is `B4OUT`"]
#[inline]
pub fn is_b4out(&self) -> bool {
*self == TMRA7TRIGR::B4OUT
}
#[doc = "Checks if the value of the field is `B3OUT2`"]
#[inline]
pub fn is_b3out2(&self) -> bool {
*self == TMRA7TRIGR::B3OUT2
}
#[doc = "Checks if the value of the field is `A3OUT2`"]
#[inline]
pub fn is_a3out2(&self) -> bool {
*self == TMRA7TRIGR::A3OUT2
}
#[doc = "Checks if the value of the field is `A2OUT2`"]
#[inline]
pub fn is_a2out2(&self) -> bool {
*self == TMRA7TRIGR::A2OUT2
}
#[doc = "Checks if the value of the field is `B2OUT2`"]
#[inline]
pub fn is_b2out2(&self) -> bool {
*self == TMRA7TRIGR::B2OUT2
}
#[doc = "Checks if the value of the field is `A6OUT2DUAL`"]
#[inline]
pub fn is_a6out2dual(&self) -> bool {
*self == TMRA7TRIGR::A6OUT2DUAL
}
#[doc = "Checks if the value of the field is `A5OUT2DUAL`"]
#[inline]
pub fn is_a5out2dual(&self) -> bool {
*self == TMRA7TRIGR::A5OUT2DUAL
}
#[doc = "Checks if the value of the field is `B4OUT2DUAL`"]
#[inline]
pub fn is_b4out2dual(&self) -> bool {
*self == TMRA7TRIGR::B4OUT2DUAL
}
#[doc = "Checks if the value of the field is `A4OUT2DUAL`"]
#[inline]
pub fn is_a4out2dual(&self) -> bool {
*self == TMRA7TRIGR::A4OUT2DUAL
}
}
#[doc = r" Value of the field"]
pub struct TMRA7LMTR {
bits: u8,
}
impl TMRA7LMTR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = "Values that can be written to the field `TMRB7EN23`"]
pub enum TMRB7EN23W {
#[doc = "Disable enhanced functions. value."]
DIS,
#[doc = "Enable enhanced functions. value."]
EN,
}
impl TMRB7EN23W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB7EN23W::DIS => true,
TMRB7EN23W::EN => false,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB7EN23W<'a> {
w: &'a mut W,
}
impl<'a> _TMRB7EN23W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB7EN23W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable enhanced functions. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB7EN23W::DIS)
}
#[doc = "Enable enhanced functions. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRB7EN23W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 30;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB7POL23`"]
pub enum TMRB7POL23W {
#[doc = "Upper output normal polarity value."]
NORM,
#[doc = "Upper output inverted polarity. value."]
INV,
}
impl TMRB7POL23W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB7POL23W::NORM => false,
TMRB7POL23W::INV => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB7POL23W<'a> {
w: &'a mut W,
}
impl<'a> _TMRB7POL23W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB7POL23W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Upper output normal polarity value."]
#[inline]
pub fn norm(self) -> &'a mut W {
self.variant(TMRB7POL23W::NORM)
}
#[doc = "Upper output inverted polarity. value."]
#[inline]
pub fn inv(self) -> &'a mut W {
self.variant(TMRB7POL23W::INV)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 29;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB7TINV`"]
pub enum TMRB7TINVW {
#[doc = "Disable invert on trigger value."]
DIS,
#[doc = "Enable invert on trigger value."]
EN,
}
impl TMRB7TINVW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB7TINVW::DIS => false,
TMRB7TINVW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB7TINVW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB7TINVW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB7TINVW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable invert on trigger value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB7TINVW::DIS)
}
#[doc = "Enable invert on trigger value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRB7TINVW::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 28;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB7NOSYNC`"]
pub enum TMRB7NOSYNCW {
#[doc = "Synchronization on source clock value."]
DIS,
#[doc = "No synchronization on source clock value."]
NOSYNC,
}
impl TMRB7NOSYNCW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRB7NOSYNCW::DIS => false,
TMRB7NOSYNCW::NOSYNC => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB7NOSYNCW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB7NOSYNCW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB7NOSYNCW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Synchronization on source clock value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB7NOSYNCW::DIS)
}
#[doc = "No synchronization on source clock value."]
#[inline]
pub fn nosync(self) -> &'a mut W {
self.variant(TMRB7NOSYNCW::NOSYNC)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 27;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRB7TRIG`"]
pub enum TMRB7TRIGW {
#[doc = "Trigger source is disabled. value."]
DIS,
#[doc = "Trigger source is CTIMERA7 OUT. value."]
A7OUT,
#[doc = "Trigger source is CTIMERB3 OUT. value."]
B3OUT,
#[doc = "Trigger source is CTIMERA3 OUT. value."]
A3OUT,
#[doc = "Trigger source is CTIMERA5 OUT. value."]
A5OUT,
#[doc = "Trigger source is CTIMERB5 OUT. value."]
B5OUT,
#[doc = "Trigger source is CTIMERA2 OUT. value."]
A2OUT,
#[doc = "Trigger source is CTIMERB2 OUT. value."]
B2OUT,
#[doc = "Trigger source is CTIMERB3 OUT2. value."]
B3OUT2,
#[doc = "Trigger source is CTIMERA3 OUT2. value."]
A3OUT2,
#[doc = "Trigger source is CTIMERA2 OUT2. value."]
A2OUT2,
#[doc = "Trigger source is CTIMERB2 OUT2. value."]
B2OUT2,
#[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."]
A6OUT2DUAL,
#[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."]
A7OUT2DUAL,
#[doc = "Trigger source is CTIMERB1 OUT2, dual edge. value."]
B1OUT2DUAL,
#[doc = "Trigger source is CTIMERA1 OUT2, dual edge. value."]
A1OUT2DUAL,
}
impl TMRB7TRIGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRB7TRIGW::DIS => 0,
TMRB7TRIGW::A7OUT => 1,
TMRB7TRIGW::B3OUT => 2,
TMRB7TRIGW::A3OUT => 3,
TMRB7TRIGW::A5OUT => 4,
TMRB7TRIGW::B5OUT => 5,
TMRB7TRIGW::A2OUT => 6,
TMRB7TRIGW::B2OUT => 7,
TMRB7TRIGW::B3OUT2 => 8,
TMRB7TRIGW::A3OUT2 => 9,
TMRB7TRIGW::A2OUT2 => 10,
TMRB7TRIGW::B2OUT2 => 11,
TMRB7TRIGW::A6OUT2DUAL => 12,
TMRB7TRIGW::A7OUT2DUAL => 13,
TMRB7TRIGW::B1OUT2DUAL => 14,
TMRB7TRIGW::A1OUT2DUAL => 15,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRB7TRIGW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB7TRIGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRB7TRIGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Trigger source is disabled. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRB7TRIGW::DIS)
}
#[doc = "Trigger source is CTIMERA7 OUT. value."]
#[inline]
pub fn a7out(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A7OUT)
}
#[doc = "Trigger source is CTIMERB3 OUT. value."]
#[inline]
pub fn b3out(self) -> &'a mut W {
self.variant(TMRB7TRIGW::B3OUT)
}
#[doc = "Trigger source is CTIMERA3 OUT. value."]
#[inline]
pub fn a3out(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A3OUT)
}
#[doc = "Trigger source is CTIMERA5 OUT. value."]
#[inline]
pub fn a5out(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A5OUT)
}
#[doc = "Trigger source is CTIMERB5 OUT. value."]
#[inline]
pub fn b5out(self) -> &'a mut W {
self.variant(TMRB7TRIGW::B5OUT)
}
#[doc = "Trigger source is CTIMERA2 OUT. value."]
#[inline]
pub fn a2out(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A2OUT)
}
#[doc = "Trigger source is CTIMERB2 OUT. value."]
#[inline]
pub fn b2out(self) -> &'a mut W {
self.variant(TMRB7TRIGW::B2OUT)
}
#[doc = "Trigger source is CTIMERB3 OUT2. value."]
#[inline]
pub fn b3out2(self) -> &'a mut W {
self.variant(TMRB7TRIGW::B3OUT2)
}
#[doc = "Trigger source is CTIMERA3 OUT2. value."]
#[inline]
pub fn a3out2(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A3OUT2)
}
#[doc = "Trigger source is CTIMERA2 OUT2. value."]
#[inline]
pub fn a2out2(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A2OUT2)
}
#[doc = "Trigger source is CTIMERB2 OUT2. value."]
#[inline]
pub fn b2out2(self) -> &'a mut W {
self.variant(TMRB7TRIGW::B2OUT2)
}
#[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."]
#[inline]
pub fn a6out2dual(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A6OUT2DUAL)
}
#[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."]
#[inline]
pub fn a7out2dual(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A7OUT2DUAL)
}
#[doc = "Trigger source is CTIMERB1 OUT2, dual edge. value."]
#[inline]
pub fn b1out2dual(self) -> &'a mut W {
self.variant(TMRB7TRIGW::B1OUT2DUAL)
}
#[doc = "Trigger source is CTIMERA1 OUT2, dual edge. value."]
#[inline]
pub fn a1out2dual(self) -> &'a mut W {
self.variant(TMRB7TRIGW::A1OUT2DUAL)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 23;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _TMRB7LMTW<'a> {
w: &'a mut W,
}
impl<'a> _TMRB7LMTW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 63;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA7EN23`"]
pub enum TMRA7EN23W {
#[doc = "Disable enhanced functions. value."]
DIS,
#[doc = "Enable enhanced functions. value."]
EN,
}
impl TMRA7EN23W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA7EN23W::DIS => true,
TMRA7EN23W::EN => false,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA7EN23W<'a> {
w: &'a mut W,
}
impl<'a> _TMRA7EN23W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA7EN23W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable enhanced functions. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA7EN23W::DIS)
}
#[doc = "Enable enhanced functions. value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRA7EN23W::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 14;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA7POL23`"]
pub enum TMRA7POL23W {
#[doc = "Upper output normal polarity value."]
NORM,
#[doc = "Upper output inverted polarity. value."]
INV,
}
impl TMRA7POL23W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA7POL23W::NORM => false,
TMRA7POL23W::INV => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA7POL23W<'a> {
w: &'a mut W,
}
impl<'a> _TMRA7POL23W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA7POL23W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Upper output normal polarity value."]
#[inline]
pub fn norm(self) -> &'a mut W {
self.variant(TMRA7POL23W::NORM)
}
#[doc = "Upper output inverted polarity. value."]
#[inline]
pub fn inv(self) -> &'a mut W {
self.variant(TMRA7POL23W::INV)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 13;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA7TINV`"]
pub enum TMRA7TINVW {
#[doc = "Disable invert on trigger value."]
DIS,
#[doc = "Enable invert on trigger value."]
EN,
}
impl TMRA7TINVW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA7TINVW::DIS => false,
TMRA7TINVW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA7TINVW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA7TINVW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA7TINVW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable invert on trigger value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA7TINVW::DIS)
}
#[doc = "Enable invert on trigger value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TMRA7TINVW::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA7NOSYNC`"]
pub enum TMRA7NOSYNCW {
#[doc = "Synchronization on source clock value."]
DIS,
#[doc = "No synchronization on source clock value."]
NOSYNC,
}
impl TMRA7NOSYNCW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TMRA7NOSYNCW::DIS => false,
TMRA7NOSYNCW::NOSYNC => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA7NOSYNCW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA7NOSYNCW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA7NOSYNCW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Synchronization on source clock value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA7NOSYNCW::DIS)
}
#[doc = "No synchronization on source clock value."]
#[inline]
pub fn nosync(self) -> &'a mut W {
self.variant(TMRA7NOSYNCW::NOSYNC)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TMRA7TRIG`"]
pub enum TMRA7TRIGW {
#[doc = "Trigger source is disabled. value."]
DIS,
#[doc = "Trigger source is CTIMERB7 OUT. value."]
B7OUT,
#[doc = "Trigger source is CTIMERB3 OUT. value."]
B3OUT,
#[doc = "Trigger source is CTIMERA3 OUT. value."]
A3OUT,
#[doc = "Trigger source is CTIMERA1 OUT. value."]
A1OUT,
#[doc = "Trigger source is CTIMERB1 OUT. value."]
B1OUT,
#[doc = "Trigger source is CTIMERA4 OUT. value."]
A4OUT,
#[doc = "Trigger source is CTIMERB4 OUT. value."]
B4OUT,
#[doc = "Trigger source is CTIMERB3 OUT2. value."]
B3OUT2,
#[doc = "Trigger source is CTIMERA3 OUT2. value."]
A3OUT2,
#[doc = "Trigger source is CTIMERA2 OUT2. value."]
A2OUT2,
#[doc = "Trigger source is CTIMERB2 OUT2. value."]
B2OUT2,
#[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."]
A6OUT2DUAL,
#[doc = "Trigger source is CTIMERA5 OUT2, dual edge. value."]
A5OUT2DUAL,
#[doc = "Trigger source is CTIMERB4 OUT2, dual edge. value."]
B4OUT2DUAL,
#[doc = "Trigger source is CTIMERA4 OUT2, dual edge. value."]
A4OUT2DUAL,
}
impl TMRA7TRIGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TMRA7TRIGW::DIS => 0,
TMRA7TRIGW::B7OUT => 1,
TMRA7TRIGW::B3OUT => 2,
TMRA7TRIGW::A3OUT => 3,
TMRA7TRIGW::A1OUT => 4,
TMRA7TRIGW::B1OUT => 5,
TMRA7TRIGW::A4OUT => 6,
TMRA7TRIGW::B4OUT => 7,
TMRA7TRIGW::B3OUT2 => 8,
TMRA7TRIGW::A3OUT2 => 9,
TMRA7TRIGW::A2OUT2 => 10,
TMRA7TRIGW::B2OUT2 => 11,
TMRA7TRIGW::A6OUT2DUAL => 12,
TMRA7TRIGW::A5OUT2DUAL => 13,
TMRA7TRIGW::B4OUT2DUAL => 14,
TMRA7TRIGW::A4OUT2DUAL => 15,
}
}
}
#[doc = r" Proxy"]
pub struct _TMRA7TRIGW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA7TRIGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TMRA7TRIGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Trigger source is disabled. value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TMRA7TRIGW::DIS)
}
#[doc = "Trigger source is CTIMERB7 OUT. value."]
#[inline]
pub fn b7out(self) -> &'a mut W {
self.variant(TMRA7TRIGW::B7OUT)
}
#[doc = "Trigger source is CTIMERB3 OUT. value."]
#[inline]
pub fn b3out(self) -> &'a mut W {
self.variant(TMRA7TRIGW::B3OUT)
}
#[doc = "Trigger source is CTIMERA3 OUT. value."]
#[inline]
pub fn a3out(self) -> &'a mut W {
self.variant(TMRA7TRIGW::A3OUT)
}
#[doc = "Trigger source is CTIMERA1 OUT. value."]
#[inline]
pub fn a1out(self) -> &'a mut W {
self.variant(TMRA7TRIGW::A1OUT)
}
#[doc = "Trigger source is CTIMERB1 OUT. value."]
#[inline]
pub fn b1out(self) -> &'a mut W {
self.variant(TMRA7TRIGW::B1OUT)
}
#[doc = "Trigger source is CTIMERA4 OUT. value."]
#[inline]
pub fn a4out(self) -> &'a mut W {
self.variant(TMRA7TRIGW::A4OUT)
}
#[doc = "Trigger source is CTIMERB4 OUT. value."]
#[inline]
pub fn b4out(self) -> &'a mut W {
self.variant(TMRA7TRIGW::B4OUT)
}
#[doc = "Trigger source is CTIMERB3 OUT2. value."]
#[inline]
pub fn b3out2(self) -> &'a mut W {
self.variant(TMRA7TRIGW::B3OUT2)
}
#[doc = "Trigger source is CTIMERA3 OUT2. value."]
#[inline]
pub fn a3out2(self) -> &'a mut W {
self.variant(TMRA7TRIGW::A3OUT2)
}
#[doc = "Trigger source is CTIMERA2 OUT2. value."]
#[inline]
pub fn a2out2(self) -> &'a mut W {
self.variant(TMRA7TRIGW::A2OUT2)
}
#[doc = "Trigger source is CTIMERB2 OUT2. value."]
#[inline]
pub fn b2out2(self) -> &'a mut W {
self.variant(TMRA7TRIGW::B2OUT2)
}
#[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."]
#[inline]
pub fn a6out2dual(self) -> &'a mut W {
self.variant(TMRA7TRIGW::A6OUT2DUAL)
}
#[doc = "Trigger source is CTIMERA5 OUT2, dual edge. value."]
#[inline]
pub fn a5out2dual(self) -> &'a mut W {
self.variant(TMRA7TRIGW::A5OUT2DUAL)
}
#[doc = "Trigger source is CTIMERB4 OUT2, dual edge. value."]
#[inline]
pub fn b4out2dual(self) -> &'a mut W {
self.variant(TMRA7TRIGW::B4OUT2DUAL)
}
#[doc = "Trigger source is CTIMERA4 OUT2, dual edge. value."]
#[inline]
pub fn a4out2dual(self) -> &'a mut W {
self.variant(TMRA7TRIGW::A4OUT2DUAL)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _TMRA7LMTW<'a> {
w: &'a mut W,
}
impl<'a> _TMRA7LMTW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 127;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 30 - Counter/Timer B7 Upper compare enable."]
#[inline]
pub fn tmrb7en23(&self) -> TMRB7EN23R {
TMRB7EN23R::_from({
const MASK: bool = true;
const OFFSET: u8 = 30;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 29 - Upper output polarity"]
#[inline]
pub fn tmrb7pol23(&self) -> TMRB7POL23R {
TMRB7POL23R::_from({
const MASK: bool = true;
const OFFSET: u8 = 29;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 28 - Counter/Timer B7 Invert on trigger."]
#[inline]
pub fn tmrb7tinv(&self) -> TMRB7TINVR {
TMRB7TINVR::_from({
const MASK: bool = true;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 27 - Source clock synchronization control."]
#[inline]
pub fn tmrb7nosync(&self) -> TMRB7NOSYNCR {
TMRB7NOSYNCR::_from({
const MASK: bool = true;
const OFFSET: u8 = 27;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 23:26 - Counter/Timer B7 Trigger Select."]
#[inline]
pub fn tmrb7trig(&self) -> TMRB7TRIGR {
TMRB7TRIGR::_from({
const MASK: u8 = 15;
const OFFSET: u8 = 23;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 16:21 - Counter/Timer B7 Pattern Limit Count."]
#[inline]
pub fn tmrb7lmt(&self) -> TMRB7LMTR {
let bits = {
const MASK: u8 = 63;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) as u8
};
TMRB7LMTR { bits }
}
#[doc = "Bit 14 - Counter/Timer A7 Upper compare enable."]
#[inline]
pub fn tmra7en23(&self) -> TMRA7EN23R {
TMRA7EN23R::_from({
const MASK: bool = true;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 13 - Counter/Timer A7 Upper output polarity"]
#[inline]
pub fn tmra7pol23(&self) -> TMRA7POL23R {
TMRA7POL23R::_from({
const MASK: bool = true;
const OFFSET: u8 = 13;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 12 - Counter/Timer A7 Invert on trigger."]
#[inline]
pub fn tmra7tinv(&self) -> TMRA7TINVR {
TMRA7TINVR::_from({
const MASK: bool = true;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 11 - Source clock synchronization control."]
#[inline]
pub fn tmra7nosync(&self) -> TMRA7NOSYNCR {
TMRA7NOSYNCR::_from({
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 7:10 - Counter/Timer A7 Trigger Select."]
#[inline]
pub fn tmra7trig(&self) -> TMRA7TRIGR {
TMRA7TRIGR::_from({
const MASK: u8 = 15;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 0:6 - Counter/Timer A7 Pattern Limit Count."]
#[inline]
pub fn tmra7lmt(&self) -> TMRA7LMTR {
let bits = {
const MASK: u8 = 127;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
TMRA7LMTR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 30 - Counter/Timer B7 Upper compare enable."]
#[inline]
pub fn tmrb7en23(&mut self) -> _TMRB7EN23W {
_TMRB7EN23W { w: self }
}
#[doc = "Bit 29 - Upper output polarity"]
#[inline]
pub fn tmrb7pol23(&mut self) -> _TMRB7POL23W {
_TMRB7POL23W { w: self }
}
#[doc = "Bit 28 - Counter/Timer B7 Invert on trigger."]
#[inline]
pub fn tmrb7tinv(&mut self) -> _TMRB7TINVW {
_TMRB7TINVW { w: self }
}
#[doc = "Bit 27 - Source clock synchronization control."]
#[inline]
pub fn tmrb7nosync(&mut self) -> _TMRB7NOSYNCW {
_TMRB7NOSYNCW { w: self }
}
#[doc = "Bits 23:26 - Counter/Timer B7 Trigger Select."]
#[inline]
pub fn tmrb7trig(&mut self) -> _TMRB7TRIGW {
_TMRB7TRIGW { w: self }
}
#[doc = "Bits 16:21 - Counter/Timer B7 Pattern Limit Count."]
#[inline]
pub fn tmrb7lmt(&mut self) -> _TMRB7LMTW {
_TMRB7LMTW { w: self }
}
#[doc = "Bit 14 - Counter/Timer A7 Upper compare enable."]
#[inline]
pub fn tmra7en23(&mut self) -> _TMRA7EN23W {
_TMRA7EN23W { w: self }
}
#[doc = "Bit 13 - Counter/Timer A7 Upper output polarity"]
#[inline]
pub fn tmra7pol23(&mut self) -> _TMRA7POL23W {
_TMRA7POL23W { w: self }
}
#[doc = "Bit 12 - Counter/Timer A7 Invert on trigger."]
#[inline]
pub fn tmra7tinv(&mut self) -> _TMRA7TINVW {
_TMRA7TINVW { w: self }
}
#[doc = "Bit 11 - Source clock synchronization control."]
#[inline]
pub fn tmra7nosync(&mut self) -> _TMRA7NOSYNCW {
_TMRA7NOSYNCW { w: self }
}
#[doc = "Bits 7:10 - Counter/Timer A7 Trigger Select."]
#[inline]
pub fn tmra7trig(&mut self) -> _TMRA7TRIGW {
_TMRA7TRIGW { w: self }
}
#[doc = "Bits 0:6 - Counter/Timer A7 Pattern Limit Count."]
#[inline]
pub fn tmra7lmt(&mut self) -> _TMRA7LMTW {
_TMRA7LMTW { w: self }
}
}
|
extern crate difference;
extern crate getopts;
use std::env;
use getopts::Options;
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("s", "split", "", "char|word|line");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
let split = match matches.opt_str("s") {
Some(ref x) if x == "char" => "",
Some(ref x) if x == "word" => " ",
Some(ref x) if x == "line" => "\n",
_ => " "
};
if matches.free.len() > 1 {
difference::print_diff(&matches.free[0], &matches.free[1], split);
} else {
print!("{}", opts.usage(&format!("Usage: {} [options]", program)));
return;
};
}
|
use lib::{Token, Node, Pprint};
pub fn parse(token_vec: Vec<Token::Token>, filename: &str) -> Vec<Node::Node> {
// println!("");
// println!("----------------");
// println!("[+] Parser:");
// Get the token vector
let mut token_vec = token_vec;
// Pprint::print_token(&token_vec);
// Build AST
let mut ast: Vec<Node::Node> = Vec::new();
// println!("\n[+] Start parsing.\n");
program(&mut token_vec,&mut ast, filename);
// println!("\n[+] Finish parsing.");
ast
}
fn program(mut token_vec: &mut Vec<Token::Token>, mut ast: &mut Vec<Node::Node>, filename: &str) {
// first node of AST
ast.push(Node::new());
ast[0]._level = String::from("Program");
ast[0]._type = String::from("FILE");
ast[0]._name = String::from(filename);
if ast.len() == 0 { panic!("Parser: Unable to create AST."); }
while token_vec.len() != 0 {
function(&mut token_vec, &mut ast, 0);
}
}
fn function(mut token_vec: &mut Vec<Token::Token>, mut ast: &mut Vec<Node::Node>, root: usize) {
loop {
let id = ast.len();
// push ast node
ast.push(Node::new());
// add previous node's "to"
ast[root].to.push(id);
// set Function node's level
ast[id]._level = String::from("Function");
// set Function node's type
if token_vec[0]._type == "INT_KEYWORD" {
ast[id]._type = String::from(token_vec[0]._type.clone());
token_vec.remove(0);
} else { panic!("Parser: Function type was invalid.\n Function type: {} {}", token_vec[0]._type, token_vec[0]._value); }
// set Function node's name, value
if token_vec[0]._type == "IDENTIFIER" {
ast[id]._name = String::from(token_vec[0]._value.clone());
token_vec.remove(0);
} else { panic!("Parser: Function name was unvalid.\n Function name: {} {}", token_vec[0]._type, token_vec[0]._value); }
// set Function node's (
if token_vec[0]._type == "OPEN_PAREN" {
token_vec.remove(0);
} else { panic!("Parser: Function ( not found.\n Function (: {} {}", token_vec[0]._type, token_vec[0]._value); }
// set Function node's )
if token_vec[0]._type == "CLOSE_PAREN" {
token_vec.remove(0);
} else { panic!("Parser: Function ) not found.\n Function ): {} {}", token_vec[0]._type, token_vec[0]._value); }
// set Function node's {
if token_vec[0]._type == "OPEN_BRACE" {
token_vec.remove(0);
} else { panic!("Parser: Function {{ not found.\n Function {{: {} {}", token_vec[0]._type, token_vec[0]._value); }
statement(&mut token_vec, &mut ast, id);
// set Function node's }
if token_vec[0]._type == "CLOSE_BRACE" {
token_vec.remove(0);
break;
} else { panic!("Parser: Function }} not found.\n Function }}: {} {}", token_vec[0]._type, token_vec[0]._value); }
}
}
fn statement(mut token_vec: &mut Vec<Token::Token>, mut ast: &mut Vec<Node::Node>, root: usize) {
// set Statement node's type
while token_vec[0]._type != "CLOSE_BRACE" {
let id = ast.len();
// push ast node
ast.push(Node::new());
// set previous node's "to"
ast[root].to.push(id);
// set Statement node's level
ast[id]._level = String::from("Statement");
match token_vec[0]._type.as_str() {
"RETURN_KEYWORD" => Return(&mut token_vec, &mut ast, id),
_ => panic!("Parser: Statement type was wrong. \n Statement type: {} {}", token_vec[0]._type, token_vec[0]._value),
}
if token_vec[0]._type == "SEMICOLON" {
token_vec.remove(0);
} else { panic!("Parser: Statement end was wrong. \n Statement end: {} {}", token_vec[0]._type, token_vec[0]._value); }
}
}
fn Return(mut token_vec: &mut Vec<Token::Token>, mut ast: &mut Vec<Node::Node>, root: usize) {
let id = ast.len()-1;
ast[id]._type = String::from(token_vec[0]._type.clone());
ast[id]._name = String::from(token_vec[0]._value.clone());
token_vec.remove(0);
expression(&mut token_vec, &mut ast, root)
}
//
fn expression(mut token_vec: &mut Vec<Token::Token>, mut ast: &mut Vec<Node::Node>, root: usize) {
let id = ast.len();
// push ast node
ast.push(Node::new());
// add previous node's "to"
ast[root].to.push(id);
// set Expression node's level
ast[id]._level = String::from("Expression");
ast[id]._type = String::from(token_vec[0]._type.clone());
ast[id]._value = String::from(token_vec[0]._value.clone());
token_vec.remove(0);
match ast[id]._type.as_str() {
"NEGATION" | "BIT_COMPLE" | "LOGIC_NEG" => expression(&mut token_vec, &mut ast, id),
"CONSTANT" => (),
_ => panic!("Parser: Expression type was wrong. \n Expression type: {} {}", token_vec[0]._type, token_vec[0]._value),
}
}
// fn expression_unary_op(token_vec: &mut Vec<Token::Token>, ast: &mut Vec<Node::Node>, root: usize) {
// let _type = token_vec[0]._type.clone();
// token_vec.remove(0);
// match _type.as_str() {
// "NEGATION" => Neg(&mut token_vec, &mut ast, root),
// "BIT_COMPLE" => BitComple(&mut token_vec, &mut ast, root),
// "LOGIC_NEG" => LogicNeg(&mut token_vec, &mut ast, root),
// }
// }
// fn Constant(token_vec: &mut Vec<Token::Token>, ast: &mut Vec<Node::Node>, root: usize) {
// let id = ast.len()-1;
// ast[id]._type = String::from(token_vec[0]._type.clone());
// ast[id]._value = String::from(token_vec[0]._value.clone());
// token_vec.remove(0);
// }
// fn Neg(token_vec: &mut Vec<Token::Token>, ast: &mut Vec<Node::Node>, root: usize) {
// let id = ast.len()-1;
// // remove "-" token
// token_vec.remove(0);
// // ensure next token is a constant
// if token_vec[0]._type != "CONSTANT" {
// panic!("Parser expression_neg: token not constant.\nToken: {} {}", token_vec[0]._type, token_vec[0]._value);
// }
// let val = -1 * token_vec[0]._value.parse()
// .expressionect("Parser expression_neg: Unable to parse the constant");
// ast[id]._type = String::from(token_vec[0]._type.clone());
// ast[id]._value = String::from(val);
// token_vec.remove(0);
// }
// fn BitComple(token_vec: &mut Vec<Token::Token>, ast: &mut Vec<Node::Node>, root: usize) {
// }
// fn LogicNeg(token_vec: &mut Vec<Token::Token>, ast: &mut Vec<Node::Node>, root: usize) {
// } |
use hydroflow::hydroflow_syntax;
fn main() {
let mut df = hydroflow_syntax! {
diff = difference();
source_iter([1]) -> [pos]diff;
diff -> [neg]diff;
};
df.run_available();
}
|
#[doc = "Register `C2SCR` writer"]
pub type W = crate::W<C2SCR_SPEC>;
#[doc = "Field `CH1C` writer - processor 2 Receive channel 1 status clear"]
pub type CH1C_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH2C` writer - processor 2 Receive channel 2 status clear"]
pub type CH2C_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH3C` writer - processor 2 Receive channel 3 status clear"]
pub type CH3C_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH4C` writer - processor 2 Receive channel 4 status clear"]
pub type CH4C_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH5C` writer - processor 2 Receive channel 5 status clear"]
pub type CH5C_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH6C` writer - processor 2 Receive channel 6 status clear"]
pub type CH6C_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH1S` writer - processor 2 Transmit channel 1 status set"]
pub type CH1S_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH2S` writer - processor 2 Transmit channel 2 status set"]
pub type CH2S_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH3S` writer - processor 2 Transmit channel 3 status set"]
pub type CH3S_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH4S` writer - processor 2 Transmit channel 4 status set"]
pub type CH4S_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH5S` writer - processor 2 Transmit channel 5 status set"]
pub type CH5S_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CH6S` writer - processor 2 Transmit channel 6 status set"]
pub type CH6S_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl W {
#[doc = "Bit 0 - processor 2 Receive channel 1 status clear"]
#[inline(always)]
#[must_use]
pub fn ch1c(&mut self) -> CH1C_W<C2SCR_SPEC, 0> {
CH1C_W::new(self)
}
#[doc = "Bit 1 - processor 2 Receive channel 2 status clear"]
#[inline(always)]
#[must_use]
pub fn ch2c(&mut self) -> CH2C_W<C2SCR_SPEC, 1> {
CH2C_W::new(self)
}
#[doc = "Bit 2 - processor 2 Receive channel 3 status clear"]
#[inline(always)]
#[must_use]
pub fn ch3c(&mut self) -> CH3C_W<C2SCR_SPEC, 2> {
CH3C_W::new(self)
}
#[doc = "Bit 3 - processor 2 Receive channel 4 status clear"]
#[inline(always)]
#[must_use]
pub fn ch4c(&mut self) -> CH4C_W<C2SCR_SPEC, 3> {
CH4C_W::new(self)
}
#[doc = "Bit 4 - processor 2 Receive channel 5 status clear"]
#[inline(always)]
#[must_use]
pub fn ch5c(&mut self) -> CH5C_W<C2SCR_SPEC, 4> {
CH5C_W::new(self)
}
#[doc = "Bit 5 - processor 2 Receive channel 6 status clear"]
#[inline(always)]
#[must_use]
pub fn ch6c(&mut self) -> CH6C_W<C2SCR_SPEC, 5> {
CH6C_W::new(self)
}
#[doc = "Bit 16 - processor 2 Transmit channel 1 status set"]
#[inline(always)]
#[must_use]
pub fn ch1s(&mut self) -> CH1S_W<C2SCR_SPEC, 16> {
CH1S_W::new(self)
}
#[doc = "Bit 17 - processor 2 Transmit channel 2 status set"]
#[inline(always)]
#[must_use]
pub fn ch2s(&mut self) -> CH2S_W<C2SCR_SPEC, 17> {
CH2S_W::new(self)
}
#[doc = "Bit 18 - processor 2 Transmit channel 3 status set"]
#[inline(always)]
#[must_use]
pub fn ch3s(&mut self) -> CH3S_W<C2SCR_SPEC, 18> {
CH3S_W::new(self)
}
#[doc = "Bit 19 - processor 2 Transmit channel 4 status set"]
#[inline(always)]
#[must_use]
pub fn ch4s(&mut self) -> CH4S_W<C2SCR_SPEC, 19> {
CH4S_W::new(self)
}
#[doc = "Bit 20 - processor 2 Transmit channel 5 status set"]
#[inline(always)]
#[must_use]
pub fn ch5s(&mut self) -> CH5S_W<C2SCR_SPEC, 20> {
CH5S_W::new(self)
}
#[doc = "Bit 21 - processor 2 Transmit channel 6 status set"]
#[inline(always)]
#[must_use]
pub fn ch6s(&mut self) -> CH6S_W<C2SCR_SPEC, 21> {
CH6S_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 = "Status Set or Clear register CPU2\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 [`c2scr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct C2SCR_SPEC;
impl crate::RegisterSpec for C2SCR_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`c2scr::W`](W) writer structure"]
impl crate::Writable for C2SCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets C2SCR to value 0"]
impl crate::Resettable for C2SCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = "Register `ILS` reader"]
pub type R = crate::R<ILS_SPEC>;
#[doc = "Register `ILS` writer"]
pub type W = crate::W<ILS_SPEC>;
#[doc = "Field `RF0NL` reader - Rx FIFO 0 New Message Interrupt Line"]
pub type RF0NL_R = crate::BitReader;
#[doc = "Field `RF0NL` writer - Rx FIFO 0 New Message Interrupt Line"]
pub type RF0NL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF0WL` reader - Rx FIFO 0 Watermark Reached Interrupt Line"]
pub type RF0WL_R = crate::BitReader;
#[doc = "Field `RF0WL` writer - Rx FIFO 0 Watermark Reached Interrupt Line"]
pub type RF0WL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF0FL` reader - Rx FIFO 0 Full Interrupt Line"]
pub type RF0FL_R = crate::BitReader;
#[doc = "Field `RF0FL` writer - Rx FIFO 0 Full Interrupt Line"]
pub type RF0FL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF0LL` reader - Rx FIFO 0 Message Lost Interrupt Line"]
pub type RF0LL_R = crate::BitReader;
#[doc = "Field `RF0LL` writer - Rx FIFO 0 Message Lost Interrupt Line"]
pub type RF0LL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF1NL` reader - Rx FIFO 1 New Message Interrupt Line"]
pub type RF1NL_R = crate::BitReader;
#[doc = "Field `RF1NL` writer - Rx FIFO 1 New Message Interrupt Line"]
pub type RF1NL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF1WL` reader - Rx FIFO 1 Watermark Reached Interrupt Line"]
pub type RF1WL_R = crate::BitReader;
#[doc = "Field `RF1WL` writer - Rx FIFO 1 Watermark Reached Interrupt Line"]
pub type RF1WL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF1FL` reader - Rx FIFO 1 Full Interrupt Line"]
pub type RF1FL_R = crate::BitReader;
#[doc = "Field `RF1FL` writer - Rx FIFO 1 Full Interrupt Line"]
pub type RF1FL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RF1LL` reader - Rx FIFO 1 Message Lost Interrupt Line"]
pub type RF1LL_R = crate::BitReader;
#[doc = "Field `RF1LL` writer - Rx FIFO 1 Message Lost Interrupt Line"]
pub type RF1LL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HPML` reader - High Priority Message Interrupt Line"]
pub type HPML_R = crate::BitReader;
#[doc = "Field `HPML` writer - High Priority Message Interrupt Line"]
pub type HPML_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TCL` reader - Transmission Completed Interrupt Line"]
pub type TCL_R = crate::BitReader;
#[doc = "Field `TCL` writer - Transmission Completed Interrupt Line"]
pub type TCL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TCFL` reader - Transmission Cancellation Finished Interrupt Line"]
pub type TCFL_R = crate::BitReader;
#[doc = "Field `TCFL` writer - Transmission Cancellation Finished Interrupt Line"]
pub type TCFL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFL` reader - Tx FIFO Empty Interrupt Line"]
pub type TEFL_R = crate::BitReader;
#[doc = "Field `TEFL` writer - Tx FIFO Empty Interrupt Line"]
pub type TEFL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFNL` reader - Tx Event FIFO New Entry Interrupt Line"]
pub type TEFNL_R = crate::BitReader;
#[doc = "Field `TEFNL` writer - Tx Event FIFO New Entry Interrupt Line"]
pub type TEFNL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFWL` reader - Tx Event FIFO Watermark Reached Interrupt Line"]
pub type TEFWL_R = crate::BitReader;
#[doc = "Field `TEFWL` writer - Tx Event FIFO Watermark Reached Interrupt Line"]
pub type TEFWL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFFL` reader - Tx Event FIFO Full Interrupt Line"]
pub type TEFFL_R = crate::BitReader;
#[doc = "Field `TEFFL` writer - Tx Event FIFO Full Interrupt Line"]
pub type TEFFL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TEFLL` reader - Tx Event FIFO Element Lost Interrupt Line"]
pub type TEFLL_R = crate::BitReader;
#[doc = "Field `TEFLL` writer - Tx Event FIFO Element Lost Interrupt Line"]
pub type TEFLL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TSWL` reader - Timestamp Wraparound Interrupt Line"]
pub type TSWL_R = crate::BitReader;
#[doc = "Field `TSWL` writer - Timestamp Wraparound Interrupt Line"]
pub type TSWL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MRAFL` reader - Message RAM Access Failure Interrupt Line"]
pub type MRAFL_R = crate::BitReader;
#[doc = "Field `MRAFL` writer - Message RAM Access Failure Interrupt Line"]
pub type MRAFL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TOOL` reader - Timeout Occurred Interrupt Line"]
pub type TOOL_R = crate::BitReader;
#[doc = "Field `TOOL` writer - Timeout Occurred Interrupt Line"]
pub type TOOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DRXL` reader - Message stored to Dedicated Rx Buffer Interrupt Line"]
pub type DRXL_R = crate::BitReader;
#[doc = "Field `DRXL` writer - Message stored to Dedicated Rx Buffer Interrupt Line"]
pub type DRXL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `BECL` reader - Bit Error Corrected Interrupt Line"]
pub type BECL_R = crate::BitReader;
#[doc = "Field `BECL` writer - Bit Error Corrected Interrupt Line"]
pub type BECL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `BEUL` reader - Bit Error Uncorrected Interrupt Line"]
pub type BEUL_R = crate::BitReader;
#[doc = "Field `BEUL` writer - Bit Error Uncorrected Interrupt Line"]
pub type BEUL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ELOL` reader - Error Logging Overflow Interrupt Line"]
pub type ELOL_R = crate::BitReader;
#[doc = "Field `ELOL` writer - Error Logging Overflow Interrupt Line"]
pub type ELOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EPL` reader - Error Passive Interrupt Line"]
pub type EPL_R = crate::BitReader;
#[doc = "Field `EPL` writer - Error Passive Interrupt Line"]
pub type EPL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EWL` reader - Warning Status Interrupt Line"]
pub type EWL_R = crate::BitReader;
#[doc = "Field `EWL` writer - Warning Status Interrupt Line"]
pub type EWL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `BOL` reader - Bus_Off Status"]
pub type BOL_R = crate::BitReader;
#[doc = "Field `BOL` writer - Bus_Off Status"]
pub type BOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WDIL` reader - Watchdog Interrupt Line"]
pub type WDIL_R = crate::BitReader;
#[doc = "Field `WDIL` writer - Watchdog Interrupt Line"]
pub type WDIL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PEAL` reader - Protocol Error in Arbitration Phase Line"]
pub type PEAL_R = crate::BitReader;
#[doc = "Field `PEAL` writer - Protocol Error in Arbitration Phase Line"]
pub type PEAL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PEDL` reader - Protocol Error in Data Phase Line"]
pub type PEDL_R = crate::BitReader;
#[doc = "Field `PEDL` writer - Protocol Error in Data Phase Line"]
pub type PEDL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ARAL` reader - Access to Reserved Address Line"]
pub type ARAL_R = crate::BitReader;
#[doc = "Field `ARAL` writer - Access to Reserved Address Line"]
pub type ARAL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Rx FIFO 0 New Message Interrupt Line"]
#[inline(always)]
pub fn rf0nl(&self) -> RF0NL_R {
RF0NL_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Rx FIFO 0 Watermark Reached Interrupt Line"]
#[inline(always)]
pub fn rf0wl(&self) -> RF0WL_R {
RF0WL_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Rx FIFO 0 Full Interrupt Line"]
#[inline(always)]
pub fn rf0fl(&self) -> RF0FL_R {
RF0FL_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Rx FIFO 0 Message Lost Interrupt Line"]
#[inline(always)]
pub fn rf0ll(&self) -> RF0LL_R {
RF0LL_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Rx FIFO 1 New Message Interrupt Line"]
#[inline(always)]
pub fn rf1nl(&self) -> RF1NL_R {
RF1NL_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Rx FIFO 1 Watermark Reached Interrupt Line"]
#[inline(always)]
pub fn rf1wl(&self) -> RF1WL_R {
RF1WL_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Rx FIFO 1 Full Interrupt Line"]
#[inline(always)]
pub fn rf1fl(&self) -> RF1FL_R {
RF1FL_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Rx FIFO 1 Message Lost Interrupt Line"]
#[inline(always)]
pub fn rf1ll(&self) -> RF1LL_R {
RF1LL_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - High Priority Message Interrupt Line"]
#[inline(always)]
pub fn hpml(&self) -> HPML_R {
HPML_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Transmission Completed Interrupt Line"]
#[inline(always)]
pub fn tcl(&self) -> TCL_R {
TCL_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Transmission Cancellation Finished Interrupt Line"]
#[inline(always)]
pub fn tcfl(&self) -> TCFL_R {
TCFL_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Tx FIFO Empty Interrupt Line"]
#[inline(always)]
pub fn tefl(&self) -> TEFL_R {
TEFL_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - Tx Event FIFO New Entry Interrupt Line"]
#[inline(always)]
pub fn tefnl(&self) -> TEFNL_R {
TEFNL_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - Tx Event FIFO Watermark Reached Interrupt Line"]
#[inline(always)]
pub fn tefwl(&self) -> TEFWL_R {
TEFWL_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - Tx Event FIFO Full Interrupt Line"]
#[inline(always)]
pub fn teffl(&self) -> TEFFL_R {
TEFFL_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - Tx Event FIFO Element Lost Interrupt Line"]
#[inline(always)]
pub fn tefll(&self) -> TEFLL_R {
TEFLL_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - Timestamp Wraparound Interrupt Line"]
#[inline(always)]
pub fn tswl(&self) -> TSWL_R {
TSWL_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - Message RAM Access Failure Interrupt Line"]
#[inline(always)]
pub fn mrafl(&self) -> MRAFL_R {
MRAFL_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - Timeout Occurred Interrupt Line"]
#[inline(always)]
pub fn tool(&self) -> TOOL_R {
TOOL_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - Message stored to Dedicated Rx Buffer Interrupt Line"]
#[inline(always)]
pub fn drxl(&self) -> DRXL_R {
DRXL_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - Bit Error Corrected Interrupt Line"]
#[inline(always)]
pub fn becl(&self) -> BECL_R {
BECL_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - Bit Error Uncorrected Interrupt Line"]
#[inline(always)]
pub fn beul(&self) -> BEUL_R {
BEUL_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - Error Logging Overflow Interrupt Line"]
#[inline(always)]
pub fn elol(&self) -> ELOL_R {
ELOL_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - Error Passive Interrupt Line"]
#[inline(always)]
pub fn epl(&self) -> EPL_R {
EPL_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - Warning Status Interrupt Line"]
#[inline(always)]
pub fn ewl(&self) -> EWL_R {
EWL_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - Bus_Off Status"]
#[inline(always)]
pub fn bol(&self) -> BOL_R {
BOL_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - Watchdog Interrupt Line"]
#[inline(always)]
pub fn wdil(&self) -> WDIL_R {
WDIL_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - Protocol Error in Arbitration Phase Line"]
#[inline(always)]
pub fn peal(&self) -> PEAL_R {
PEAL_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - Protocol Error in Data Phase Line"]
#[inline(always)]
pub fn pedl(&self) -> PEDL_R {
PEDL_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - Access to Reserved Address Line"]
#[inline(always)]
pub fn aral(&self) -> ARAL_R {
ARAL_R::new(((self.bits >> 29) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Rx FIFO 0 New Message Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn rf0nl(&mut self) -> RF0NL_W<ILS_SPEC, 0> {
RF0NL_W::new(self)
}
#[doc = "Bit 1 - Rx FIFO 0 Watermark Reached Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn rf0wl(&mut self) -> RF0WL_W<ILS_SPEC, 1> {
RF0WL_W::new(self)
}
#[doc = "Bit 2 - Rx FIFO 0 Full Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn rf0fl(&mut self) -> RF0FL_W<ILS_SPEC, 2> {
RF0FL_W::new(self)
}
#[doc = "Bit 3 - Rx FIFO 0 Message Lost Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn rf0ll(&mut self) -> RF0LL_W<ILS_SPEC, 3> {
RF0LL_W::new(self)
}
#[doc = "Bit 4 - Rx FIFO 1 New Message Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn rf1nl(&mut self) -> RF1NL_W<ILS_SPEC, 4> {
RF1NL_W::new(self)
}
#[doc = "Bit 5 - Rx FIFO 1 Watermark Reached Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn rf1wl(&mut self) -> RF1WL_W<ILS_SPEC, 5> {
RF1WL_W::new(self)
}
#[doc = "Bit 6 - Rx FIFO 1 Full Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn rf1fl(&mut self) -> RF1FL_W<ILS_SPEC, 6> {
RF1FL_W::new(self)
}
#[doc = "Bit 7 - Rx FIFO 1 Message Lost Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn rf1ll(&mut self) -> RF1LL_W<ILS_SPEC, 7> {
RF1LL_W::new(self)
}
#[doc = "Bit 8 - High Priority Message Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn hpml(&mut self) -> HPML_W<ILS_SPEC, 8> {
HPML_W::new(self)
}
#[doc = "Bit 9 - Transmission Completed Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn tcl(&mut self) -> TCL_W<ILS_SPEC, 9> {
TCL_W::new(self)
}
#[doc = "Bit 10 - Transmission Cancellation Finished Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn tcfl(&mut self) -> TCFL_W<ILS_SPEC, 10> {
TCFL_W::new(self)
}
#[doc = "Bit 11 - Tx FIFO Empty Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn tefl(&mut self) -> TEFL_W<ILS_SPEC, 11> {
TEFL_W::new(self)
}
#[doc = "Bit 12 - Tx Event FIFO New Entry Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn tefnl(&mut self) -> TEFNL_W<ILS_SPEC, 12> {
TEFNL_W::new(self)
}
#[doc = "Bit 13 - Tx Event FIFO Watermark Reached Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn tefwl(&mut self) -> TEFWL_W<ILS_SPEC, 13> {
TEFWL_W::new(self)
}
#[doc = "Bit 14 - Tx Event FIFO Full Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn teffl(&mut self) -> TEFFL_W<ILS_SPEC, 14> {
TEFFL_W::new(self)
}
#[doc = "Bit 15 - Tx Event FIFO Element Lost Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn tefll(&mut self) -> TEFLL_W<ILS_SPEC, 15> {
TEFLL_W::new(self)
}
#[doc = "Bit 16 - Timestamp Wraparound Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn tswl(&mut self) -> TSWL_W<ILS_SPEC, 16> {
TSWL_W::new(self)
}
#[doc = "Bit 17 - Message RAM Access Failure Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn mrafl(&mut self) -> MRAFL_W<ILS_SPEC, 17> {
MRAFL_W::new(self)
}
#[doc = "Bit 18 - Timeout Occurred Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn tool(&mut self) -> TOOL_W<ILS_SPEC, 18> {
TOOL_W::new(self)
}
#[doc = "Bit 19 - Message stored to Dedicated Rx Buffer Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn drxl(&mut self) -> DRXL_W<ILS_SPEC, 19> {
DRXL_W::new(self)
}
#[doc = "Bit 20 - Bit Error Corrected Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn becl(&mut self) -> BECL_W<ILS_SPEC, 20> {
BECL_W::new(self)
}
#[doc = "Bit 21 - Bit Error Uncorrected Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn beul(&mut self) -> BEUL_W<ILS_SPEC, 21> {
BEUL_W::new(self)
}
#[doc = "Bit 22 - Error Logging Overflow Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn elol(&mut self) -> ELOL_W<ILS_SPEC, 22> {
ELOL_W::new(self)
}
#[doc = "Bit 23 - Error Passive Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn epl(&mut self) -> EPL_W<ILS_SPEC, 23> {
EPL_W::new(self)
}
#[doc = "Bit 24 - Warning Status Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn ewl(&mut self) -> EWL_W<ILS_SPEC, 24> {
EWL_W::new(self)
}
#[doc = "Bit 25 - Bus_Off Status"]
#[inline(always)]
#[must_use]
pub fn bol(&mut self) -> BOL_W<ILS_SPEC, 25> {
BOL_W::new(self)
}
#[doc = "Bit 26 - Watchdog Interrupt Line"]
#[inline(always)]
#[must_use]
pub fn wdil(&mut self) -> WDIL_W<ILS_SPEC, 26> {
WDIL_W::new(self)
}
#[doc = "Bit 27 - Protocol Error in Arbitration Phase Line"]
#[inline(always)]
#[must_use]
pub fn peal(&mut self) -> PEAL_W<ILS_SPEC, 27> {
PEAL_W::new(self)
}
#[doc = "Bit 28 - Protocol Error in Data Phase Line"]
#[inline(always)]
#[must_use]
pub fn pedl(&mut self) -> PEDL_W<ILS_SPEC, 28> {
PEDL_W::new(self)
}
#[doc = "Bit 29 - Access to Reserved Address Line"]
#[inline(always)]
#[must_use]
pub fn aral(&mut self) -> ARAL_W<ILS_SPEC, 29> {
ARAL_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 = "FDCAN Interrupt Line Select Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ils::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 [`ils::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ILS_SPEC;
impl crate::RegisterSpec for ILS_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ils::R`](R) reader structure"]
impl crate::Readable for ILS_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ils::W`](W) writer structure"]
impl crate::Writable for ILS_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets ILS to value 0"]
impl crate::Resettable for ILS_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// Generated by `scripts/generate.js`
use std::os::raw::c_char;
use std::ops::Deref;
use std::ptr;
use std::cmp;
use std::mem;
use utils::c_bindings::*;
use utils::vk_convert::*;
use utils::vk_null::*;
use utils::vk_ptr::*;
use utils::vk_traits::*;
use vulkan::vk::*;
use vulkan::vk::{VkStructureType,RawVkStructureType};
/// Wrapper for [VkPhysicalDeviceDeviceGeneratedCommandsPropertiesNV](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkPhysicalDeviceDeviceGeneratedCommandsPropertiesNV.html).
#[derive(Debug, Clone)]
pub struct VkPhysicalDeviceDeviceGeneratedCommandsProperties {
pub max_graphics_shader_group_count: usize,
pub max_indirect_sequence_count: usize,
pub max_indirect_commands_token_count: usize,
pub max_indirect_commands_stream_count: usize,
pub max_indirect_commands_token_offset: usize,
pub max_indirect_commands_stream_stride: usize,
pub min_sequences_count_buffer_offset_alignment: usize,
pub min_sequences_index_buffer_offset_alignment: usize,
pub min_indirect_commands_buffer_offset_alignment: usize,
}
#[doc(hidden)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct RawVkPhysicalDeviceDeviceGeneratedCommandsProperties {
pub s_type: RawVkStructureType,
pub next: *mut c_void,
pub max_graphics_shader_group_count: u32,
pub max_indirect_sequence_count: u32,
pub max_indirect_commands_token_count: u32,
pub max_indirect_commands_stream_count: u32,
pub max_indirect_commands_token_offset: u32,
pub max_indirect_commands_stream_stride: u32,
pub min_sequences_count_buffer_offset_alignment: u32,
pub min_sequences_index_buffer_offset_alignment: u32,
pub min_indirect_commands_buffer_offset_alignment: u32,
}
impl VkWrappedType<RawVkPhysicalDeviceDeviceGeneratedCommandsProperties> for VkPhysicalDeviceDeviceGeneratedCommandsProperties {
fn vk_to_raw(src: &VkPhysicalDeviceDeviceGeneratedCommandsProperties, dst: &mut RawVkPhysicalDeviceDeviceGeneratedCommandsProperties) {
dst.s_type = vk_to_raw_value(&VkStructureType::PhysicalDeviceDeviceGeneratedCommandsPropertiesNv);
dst.next = ptr::null_mut();
dst.max_graphics_shader_group_count = vk_to_raw_value(&src.max_graphics_shader_group_count);
dst.max_indirect_sequence_count = vk_to_raw_value(&src.max_indirect_sequence_count);
dst.max_indirect_commands_token_count = vk_to_raw_value(&src.max_indirect_commands_token_count);
dst.max_indirect_commands_stream_count = vk_to_raw_value(&src.max_indirect_commands_stream_count);
dst.max_indirect_commands_token_offset = vk_to_raw_value(&src.max_indirect_commands_token_offset);
dst.max_indirect_commands_stream_stride = vk_to_raw_value(&src.max_indirect_commands_stream_stride);
dst.min_sequences_count_buffer_offset_alignment = vk_to_raw_value(&src.min_sequences_count_buffer_offset_alignment);
dst.min_sequences_index_buffer_offset_alignment = vk_to_raw_value(&src.min_sequences_index_buffer_offset_alignment);
dst.min_indirect_commands_buffer_offset_alignment = vk_to_raw_value(&src.min_indirect_commands_buffer_offset_alignment);
}
}
impl VkRawType<VkPhysicalDeviceDeviceGeneratedCommandsProperties> for RawVkPhysicalDeviceDeviceGeneratedCommandsProperties {
fn vk_to_wrapped(src: &RawVkPhysicalDeviceDeviceGeneratedCommandsProperties) -> VkPhysicalDeviceDeviceGeneratedCommandsProperties {
VkPhysicalDeviceDeviceGeneratedCommandsProperties {
max_graphics_shader_group_count: u32::vk_to_wrapped(&src.max_graphics_shader_group_count),
max_indirect_sequence_count: u32::vk_to_wrapped(&src.max_indirect_sequence_count),
max_indirect_commands_token_count: u32::vk_to_wrapped(&src.max_indirect_commands_token_count),
max_indirect_commands_stream_count: u32::vk_to_wrapped(&src.max_indirect_commands_stream_count),
max_indirect_commands_token_offset: u32::vk_to_wrapped(&src.max_indirect_commands_token_offset),
max_indirect_commands_stream_stride: u32::vk_to_wrapped(&src.max_indirect_commands_stream_stride),
min_sequences_count_buffer_offset_alignment: u32::vk_to_wrapped(&src.min_sequences_count_buffer_offset_alignment),
min_sequences_index_buffer_offset_alignment: u32::vk_to_wrapped(&src.min_sequences_index_buffer_offset_alignment),
min_indirect_commands_buffer_offset_alignment: u32::vk_to_wrapped(&src.min_indirect_commands_buffer_offset_alignment),
}
}
}
impl Default for VkPhysicalDeviceDeviceGeneratedCommandsProperties {
fn default() -> VkPhysicalDeviceDeviceGeneratedCommandsProperties {
VkPhysicalDeviceDeviceGeneratedCommandsProperties {
max_graphics_shader_group_count: 0,
max_indirect_sequence_count: 0,
max_indirect_commands_token_count: 0,
max_indirect_commands_stream_count: 0,
max_indirect_commands_token_offset: 0,
max_indirect_commands_stream_stride: 0,
min_sequences_count_buffer_offset_alignment: 0,
min_sequences_index_buffer_offset_alignment: 0,
min_indirect_commands_buffer_offset_alignment: 0,
}
}
}
impl VkSetup for VkPhysicalDeviceDeviceGeneratedCommandsProperties {
fn vk_setup(&mut self, fn_table: *mut VkFunctionTable) {
}
}
impl VkFree for RawVkPhysicalDeviceDeviceGeneratedCommandsProperties {
fn vk_free(&self) {
}
} |
#[doc = "Reader of register GPIO_OUT_CLR"]
pub type R = crate::R<u32, super::GPIO_OUT_CLR>;
#[doc = "Writer for register GPIO_OUT_CLR"]
pub type W = crate::W<u32, super::GPIO_OUT_CLR>;
#[doc = "Register GPIO_OUT_CLR `reset()`'s with value 0"]
impl crate::ResetValue for super::GPIO_OUT_CLR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `GPIO_OUT_CLR`"]
pub type GPIO_OUT_CLR_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `GPIO_OUT_CLR`"]
pub struct GPIO_OUT_CLR_W<'a> {
w: &'a mut W,
}
impl<'a> GPIO_OUT_CLR_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0x3fff_ffff) | ((value as u32) & 0x3fff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:29 - Perform an atomic bit-clear on GPIO_OUT, i.e. `GPIO_OUT &= ~wdata`"]
#[inline(always)]
pub fn gpio_out_clr(&self) -> GPIO_OUT_CLR_R {
GPIO_OUT_CLR_R::new((self.bits & 0x3fff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:29 - Perform an atomic bit-clear on GPIO_OUT, i.e. `GPIO_OUT &= ~wdata`"]
#[inline(always)]
pub fn gpio_out_clr(&mut self) -> GPIO_OUT_CLR_W {
GPIO_OUT_CLR_W { w: self }
}
}
|
use crate::options::{
Frequenzy, NWeekday, NWeekdayIdentifier, Options, ParsedOptions, RRuleParseError,
};
use crate::utils::is_some_and_not_empty;
use chrono::prelude::*;
use chrono_tz::{Tz, UTC};
// TODO: More validation here
pub fn parse_options(options: &Options) -> Result<ParsedOptions, RRuleParseError> {
let mut default_partial_options = Options::new();
default_partial_options.interval = Some(1);
default_partial_options.freq = Some(Frequenzy::Yearly);
default_partial_options.wkst = Some(0);
let tzid: Tz = if options.tzid.is_some() {
options.tzid.clone().unwrap()
} else {
UTC
};
let _bynweekday: Vec<Vec<isize>> = vec![];
let mut bynmonthday: Vec<isize> = vec![];
let mut partial_options = Options::concat(&default_partial_options, options);
if partial_options.byeaster.is_some() {
partial_options.freq = Some(Frequenzy::Yearly);
}
let freq = partial_options.freq.unwrap_or(Frequenzy::Daily);
if partial_options.dtstart.is_none() {
return Err(RRuleParseError(String::from("Dtstart can not be None")));
}
if partial_options.wkst.is_none() {
partial_options.wkst = Some(0);
}
if let Some(bysetpos) = &partial_options.bysetpos {
for pos in bysetpos {
if *pos == 0 || !(*pos >= -366 && *pos <= 366) {
return Err(RRuleParseError(String::from(
"Bysetpos must be between 1 and 366, or between -366 and -1",
)));
}
}
}
let dtstart = if partial_options.dtstart.is_some() {
partial_options.dtstart.unwrap()
} else {
return Err(RRuleParseError(String::from("Dtstart was not specified")));
};
if !(partial_options.byweekno.is_some()
|| is_some_and_not_empty(&partial_options.byweekno)
|| is_some_and_not_empty(&partial_options.byyearday)
|| partial_options.bymonthday.is_some()
|| is_some_and_not_empty(&partial_options.bymonthday)
|| partial_options.byweekday.is_some()
|| partial_options.byeaster.is_some())
{
match &freq {
Frequenzy::Yearly => {
if partial_options.bymonth.is_none() {
partial_options.bymonth = Some(vec![dtstart.month() as usize]);
}
partial_options.bymonthday = Some(vec![dtstart.day() as isize]);
}
Frequenzy::Monthly => {
partial_options.bymonthday = Some(vec![dtstart.day() as isize]);
}
Frequenzy::Weekly => {
partial_options.byweekday = Some(vec![NWeekday::new(
dtstart.weekday() as usize,
NWeekdayIdentifier::Every,
)]);
}
_ => (),
};
}
match &partial_options.bymonthday {
None => bynmonthday = vec![],
Some(opts_bymonthday) => {
let mut bymonthday = vec![];
for v in opts_bymonthday {
if *v > 0 {
bymonthday.push(*v);
} else if *v < 0 {
bynmonthday.push(*v);
}
}
partial_options.bymonthday = Some(bymonthday);
}
}
let mut byweekday = vec![];
let mut bynweekday: Vec<Vec<isize>> = vec![];
// byweekday / bynweekday // ! more to do here
if let Some(opts_byweekday) = partial_options.byweekday {
for wday in opts_byweekday {
match wday.n {
NWeekdayIdentifier::Every => byweekday.push(wday.weekday),
NWeekdayIdentifier::Identifier(n) => {
bynweekday.push(vec![wday.weekday as isize, n]);
}
}
// if wday.n == {
// byweekday.push(wday.weekday);
// } else {
// bynweekday.push(vec![wday.weekday as isize, wday.n]);
// }
}
}
// byhour
if partial_options.byhour.is_none() && freq < Frequenzy::Hourly {
partial_options.byhour = Some(vec![dtstart.hour() as usize]);
}
// byminute
if partial_options.byminute.is_none() && freq < Frequenzy::Minutely {
partial_options.byminute = Some(vec![dtstart.minute() as usize]);
}
// bysecond
if partial_options.bysecond.is_none() && freq < Frequenzy::Secondly {
partial_options.bysecond = Some(vec![dtstart.second() as usize]);
}
Ok(ParsedOptions {
freq,
interval: partial_options.interval.unwrap(),
count: partial_options.count,
until: partial_options.until,
tzid,
dtstart,
wkst: partial_options.wkst.unwrap(),
bysetpos: partial_options.bysetpos.unwrap_or(vec![]),
bymonth: partial_options.bymonth.unwrap_or(vec![]),
bymonthday: partial_options.bymonthday.unwrap_or(vec![]),
bynmonthday,
byyearday: partial_options.byyearday.unwrap_or(vec![]),
byweekno: partial_options.byweekno.unwrap_or(vec![]),
byweekday,
bynweekday,
byhour: partial_options.byhour.unwrap_or(vec![]),
byminute: partial_options.byminute.unwrap_or(vec![]),
bysecond: partial_options.bysecond.unwrap_or(vec![]),
byeaster: partial_options.byeaster,
})
}
|
use nu_engine::CallExt;
use nu_protocol::{
ast::{Call, CellPath},
engine::{Command, EngineState, Stack},
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Value,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"into bool"
}
fn signature(&self) -> Signature {
Signature::build("into bool")
.rest(
"rest",
SyntaxShape::CellPath,
"column paths to convert to boolean (for table input)",
)
.category(Category::Conversions)
}
fn usage(&self) -> &str {
"Convert value to boolean"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "boolean", "true", "false", "1", "0"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
into_bool(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
let span = Span::test_data();
vec![
Example {
description: "Convert value to boolean in table",
example: "echo [[value]; ['false'] ['1'] [0] [1.0] [true]] | into bool value",
result: Some(Value::List {
vals: vec![
Value::Record {
cols: vec!["value".to_string()],
vals: vec![Value::boolean(false, span)],
span,
},
Value::Record {
cols: vec!["value".to_string()],
vals: vec![Value::boolean(true, span)],
span,
},
Value::Record {
cols: vec!["value".to_string()],
vals: vec![Value::boolean(false, span)],
span,
},
Value::Record {
cols: vec!["value".to_string()],
vals: vec![Value::boolean(true, span)],
span,
},
Value::Record {
cols: vec!["value".to_string()],
vals: vec![Value::boolean(true, span)],
span,
},
],
span,
}),
},
Example {
description: "Convert bool to boolean",
example: "true | into bool",
result: Some(Value::boolean(true, span)),
},
Example {
description: "convert integer to boolean",
example: "1 | into bool",
result: Some(Value::boolean(true, span)),
},
Example {
description: "convert decimal string to boolean",
example: "'0.0' | into bool",
result: Some(Value::boolean(false, span)),
},
Example {
description: "convert string to boolean",
example: "'true' | into bool",
result: Some(Value::boolean(true, span)),
},
]
}
}
fn into_bool(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
input.map(
move |v| {
if column_paths.is_empty() {
action(&v, head)
} else {
let mut ret = v;
for path in &column_paths {
let r =
ret.update_cell_path(&path.members, Box::new(move |old| action(old, head)));
if let Err(error) = r {
return Value::Error { error };
}
}
ret
}
},
engine_state.ctrlc.clone(),
)
}
fn string_to_boolean(s: &str, span: Span) -> Result<bool, ShellError> {
match s.trim().to_lowercase().as_str() {
"true" => Ok(true),
"false" => Ok(false),
o => {
let val = o.parse::<f64>();
match val {
Ok(f) => Ok(f.abs() >= f64::EPSILON),
Err(_) => Err(ShellError::CantConvert(
"boolean".to_string(),
"string".to_string(),
span,
Some(
r#"the strings "true" and "false" can be converted into a bool"#
.to_string(),
),
)),
}
}
}
}
fn action(input: &Value, span: Span) -> Value {
match input {
Value::Bool { .. } => input.clone(),
Value::Int { val, .. } => Value::Bool {
val: *val != 0,
span,
},
Value::Float { val, .. } => Value::Bool {
val: val.abs() >= f64::EPSILON,
span,
},
Value::String { val, .. } => match string_to_boolean(val, span) {
Ok(val) => Value::Bool { val, span },
Err(error) => Value::Error { error },
},
_ => Value::Error {
error: ShellError::UnsupportedInput(
"'into bool' does not support this input".into(),
span,
),
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}
|
// Copyright 2020 IOTA Stiftung
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
use crate::{message::TransactionRequest, milestone::MilestoneIndex, protocol::Protocol, worker::SenderWorker};
use bee_bundle::Hash;
use bee_tangle::tangle;
use bee_ternary::T5B1Buf;
use std::cmp::Ordering;
use bytemuck::cast_slice;
use futures::{channel::oneshot, future::FutureExt, select};
use log::info;
use rand::{Rng, SeedableRng};
use rand_pcg::Pcg32;
#[derive(Eq, PartialEq)]
pub(crate) struct TransactionRequesterWorkerEntry(pub(crate) Hash, pub(crate) MilestoneIndex);
// TODO check that this is the right order
impl PartialOrd for TransactionRequesterWorkerEntry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.1.partial_cmp(&other.1)
}
}
impl Ord for TransactionRequesterWorkerEntry {
fn cmp(&self, other: &Self) -> Ordering {
self.1.cmp(&other.1)
}
}
pub(crate) struct TransactionRequesterWorker {
rng: Pcg32,
}
impl TransactionRequesterWorker {
pub(crate) fn new() -> Self {
Self {
rng: Pcg32::from_entropy(),
}
}
async fn process_request(&mut self, hash: Hash, index: MilestoneIndex) {
if Protocol::get().peer_manager.handshaked_peers.is_empty() {
return;
}
// TODO check that neighbor may have the tx (by the index)
Protocol::get().requested.insert(hash, index);
match Protocol::get().peer_manager.handshaked_peers.iter().nth(
self.rng
.gen_range(0, Protocol::get().peer_manager.handshaked_peers.len()),
) {
Some(entry) => {
SenderWorker::<TransactionRequest>::send(
entry.key(),
TransactionRequest::new(cast_slice(hash.as_trits().encode::<T5B1Buf>().as_i8_slice())),
)
.await;
}
None => {}
}
}
pub(crate) async fn run(mut self, shutdown: oneshot::Receiver<()>) {
info!("[TransactionRequesterWorker ] Running.");
let mut shutdown_fused = shutdown.fuse();
loop {
select! {
// TODO impl fused stream
entry = Protocol::get().transaction_requester_worker.0.pop().fuse() => {
if let TransactionRequesterWorkerEntry(hash, index) = entry {
if !tangle().is_solid_entry_point(&hash) && !tangle().contains_transaction(&hash) {
self.process_request(hash, index).await;
}
}
},
_ = shutdown_fused => {
break;
}
}
}
info!("[TransactionRequesterWorker ] Stopped.");
}
}
|
/// An enum to represent all characters in the Javanese block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Javanese {
/// \u{a980}: 'ꦀ'
SignPanyangga,
/// \u{a981}: 'ꦁ'
SignCecak,
/// \u{a982}: 'ꦂ'
SignLayar,
/// \u{a983}: 'ꦃ'
SignWignyan,
/// \u{a984}: 'ꦄ'
LetterA,
/// \u{a985}: 'ꦅ'
LetterIKawi,
/// \u{a986}: 'ꦆ'
LetterI,
/// \u{a987}: 'ꦇ'
LetterIi,
/// \u{a988}: 'ꦈ'
LetterU,
/// \u{a989}: 'ꦉ'
LetterPaCerek,
/// \u{a98a}: 'ꦊ'
LetterNgaLelet,
/// \u{a98b}: 'ꦋ'
LetterNgaLeletRaswadi,
/// \u{a98c}: 'ꦌ'
LetterE,
/// \u{a98d}: 'ꦍ'
LetterAi,
/// \u{a98e}: 'ꦎ'
LetterO,
/// \u{a98f}: 'ꦏ'
LetterKa,
/// \u{a990}: 'ꦐ'
LetterKaSasak,
/// \u{a991}: 'ꦑ'
LetterKaMurda,
/// \u{a992}: 'ꦒ'
LetterGa,
/// \u{a993}: 'ꦓ'
LetterGaMurda,
/// \u{a994}: 'ꦔ'
LetterNga,
/// \u{a995}: 'ꦕ'
LetterCa,
/// \u{a996}: 'ꦖ'
LetterCaMurda,
/// \u{a997}: 'ꦗ'
LetterJa,
/// \u{a998}: 'ꦘ'
LetterNyaMurda,
/// \u{a999}: 'ꦙ'
LetterJaMahaprana,
/// \u{a99a}: 'ꦚ'
LetterNya,
/// \u{a99b}: 'ꦛ'
LetterTta,
/// \u{a99c}: 'ꦜ'
LetterTtaMahaprana,
/// \u{a99d}: 'ꦝ'
LetterDda,
/// \u{a99e}: 'ꦞ'
LetterDdaMahaprana,
/// \u{a99f}: 'ꦟ'
LetterNaMurda,
/// \u{a9a0}: 'ꦠ'
LetterTa,
/// \u{a9a1}: 'ꦡ'
LetterTaMurda,
/// \u{a9a2}: 'ꦢ'
LetterDa,
/// \u{a9a3}: 'ꦣ'
LetterDaMahaprana,
/// \u{a9a4}: 'ꦤ'
LetterNa,
/// \u{a9a5}: 'ꦥ'
LetterPa,
/// \u{a9a6}: 'ꦦ'
LetterPaMurda,
/// \u{a9a7}: 'ꦧ'
LetterBa,
/// \u{a9a8}: 'ꦨ'
LetterBaMurda,
/// \u{a9a9}: 'ꦩ'
LetterMa,
/// \u{a9aa}: 'ꦪ'
LetterYa,
/// \u{a9ab}: 'ꦫ'
LetterRa,
/// \u{a9ac}: 'ꦬ'
LetterRaAgung,
/// \u{a9ad}: 'ꦭ'
LetterLa,
/// \u{a9ae}: 'ꦮ'
LetterWa,
/// \u{a9af}: 'ꦯ'
LetterSaMurda,
/// \u{a9b0}: 'ꦰ'
LetterSaMahaprana,
/// \u{a9b1}: 'ꦱ'
LetterSa,
/// \u{a9b2}: 'ꦲ'
LetterHa,
/// \u{a9b3}: '꦳'
SignCecakTelu,
/// \u{a9b4}: 'ꦴ'
VowelSignTarung,
/// \u{a9b5}: 'ꦵ'
VowelSignTolong,
/// \u{a9b6}: 'ꦶ'
VowelSignWulu,
/// \u{a9b7}: 'ꦷ'
VowelSignWuluMelik,
/// \u{a9b8}: 'ꦸ'
VowelSignSuku,
/// \u{a9b9}: 'ꦹ'
VowelSignSukuMendut,
/// \u{a9ba}: 'ꦺ'
VowelSignTaling,
/// \u{a9bb}: 'ꦻ'
VowelSignDirgaMure,
/// \u{a9bc}: 'ꦼ'
VowelSignPepet,
/// \u{a9bd}: 'ꦽ'
ConsonantSignKeret,
/// \u{a9be}: 'ꦾ'
ConsonantSignPengkal,
/// \u{a9bf}: 'ꦿ'
ConsonantSignCakra,
/// \u{a9c0}: '꧀'
Pangkon,
/// \u{a9c1}: '꧁'
LeftRerenggan,
/// \u{a9c2}: '꧂'
RightRerenggan,
/// \u{a9c3}: '꧃'
PadaAndap,
/// \u{a9c4}: '꧄'
PadaMadya,
/// \u{a9c5}: '꧅'
PadaLuhur,
/// \u{a9c6}: '꧆'
PadaWindu,
/// \u{a9c7}: '꧇'
PadaPangkat,
/// \u{a9c8}: '꧈'
PadaLingsa,
/// \u{a9c9}: '꧉'
PadaLungsi,
/// \u{a9ca}: '꧊'
PadaAdeg,
/// \u{a9cb}: '꧋'
PadaAdegAdeg,
/// \u{a9cc}: '꧌'
PadaPiseleh,
/// \u{a9cd}: '꧍'
TurnedPadaPiseleh,
/// \u{a9cf}: 'ꧏ'
Pangrangkep,
/// \u{a9d0}: '꧐'
DigitZero,
/// \u{a9d1}: '꧑'
DigitOne,
/// \u{a9d2}: '꧒'
DigitTwo,
/// \u{a9d3}: '꧓'
DigitThree,
/// \u{a9d4}: '꧔'
DigitFour,
/// \u{a9d5}: '꧕'
DigitFive,
/// \u{a9d6}: '꧖'
DigitSix,
/// \u{a9d7}: '꧗'
DigitSeven,
/// \u{a9d8}: '꧘'
DigitEight,
/// \u{a9d9}: '꧙'
DigitNine,
/// \u{a9de}: '꧞'
PadaTirtaTumetes,
}
impl Into<char> for Javanese {
fn into(self) -> char {
match self {
Javanese::SignPanyangga => 'ꦀ',
Javanese::SignCecak => 'ꦁ',
Javanese::SignLayar => 'ꦂ',
Javanese::SignWignyan => 'ꦃ',
Javanese::LetterA => 'ꦄ',
Javanese::LetterIKawi => 'ꦅ',
Javanese::LetterI => 'ꦆ',
Javanese::LetterIi => 'ꦇ',
Javanese::LetterU => 'ꦈ',
Javanese::LetterPaCerek => 'ꦉ',
Javanese::LetterNgaLelet => 'ꦊ',
Javanese::LetterNgaLeletRaswadi => 'ꦋ',
Javanese::LetterE => 'ꦌ',
Javanese::LetterAi => 'ꦍ',
Javanese::LetterO => 'ꦎ',
Javanese::LetterKa => 'ꦏ',
Javanese::LetterKaSasak => 'ꦐ',
Javanese::LetterKaMurda => 'ꦑ',
Javanese::LetterGa => 'ꦒ',
Javanese::LetterGaMurda => 'ꦓ',
Javanese::LetterNga => 'ꦔ',
Javanese::LetterCa => 'ꦕ',
Javanese::LetterCaMurda => 'ꦖ',
Javanese::LetterJa => 'ꦗ',
Javanese::LetterNyaMurda => 'ꦘ',
Javanese::LetterJaMahaprana => 'ꦙ',
Javanese::LetterNya => 'ꦚ',
Javanese::LetterTta => 'ꦛ',
Javanese::LetterTtaMahaprana => 'ꦜ',
Javanese::LetterDda => 'ꦝ',
Javanese::LetterDdaMahaprana => 'ꦞ',
Javanese::LetterNaMurda => 'ꦟ',
Javanese::LetterTa => 'ꦠ',
Javanese::LetterTaMurda => 'ꦡ',
Javanese::LetterDa => 'ꦢ',
Javanese::LetterDaMahaprana => 'ꦣ',
Javanese::LetterNa => 'ꦤ',
Javanese::LetterPa => 'ꦥ',
Javanese::LetterPaMurda => 'ꦦ',
Javanese::LetterBa => 'ꦧ',
Javanese::LetterBaMurda => 'ꦨ',
Javanese::LetterMa => 'ꦩ',
Javanese::LetterYa => 'ꦪ',
Javanese::LetterRa => 'ꦫ',
Javanese::LetterRaAgung => 'ꦬ',
Javanese::LetterLa => 'ꦭ',
Javanese::LetterWa => 'ꦮ',
Javanese::LetterSaMurda => 'ꦯ',
Javanese::LetterSaMahaprana => 'ꦰ',
Javanese::LetterSa => 'ꦱ',
Javanese::LetterHa => 'ꦲ',
Javanese::SignCecakTelu => '꦳',
Javanese::VowelSignTarung => 'ꦴ',
Javanese::VowelSignTolong => 'ꦵ',
Javanese::VowelSignWulu => 'ꦶ',
Javanese::VowelSignWuluMelik => 'ꦷ',
Javanese::VowelSignSuku => 'ꦸ',
Javanese::VowelSignSukuMendut => 'ꦹ',
Javanese::VowelSignTaling => 'ꦺ',
Javanese::VowelSignDirgaMure => 'ꦻ',
Javanese::VowelSignPepet => 'ꦼ',
Javanese::ConsonantSignKeret => 'ꦽ',
Javanese::ConsonantSignPengkal => 'ꦾ',
Javanese::ConsonantSignCakra => 'ꦿ',
Javanese::Pangkon => '꧀',
Javanese::LeftRerenggan => '꧁',
Javanese::RightRerenggan => '꧂',
Javanese::PadaAndap => '꧃',
Javanese::PadaMadya => '꧄',
Javanese::PadaLuhur => '꧅',
Javanese::PadaWindu => '꧆',
Javanese::PadaPangkat => '꧇',
Javanese::PadaLingsa => '꧈',
Javanese::PadaLungsi => '꧉',
Javanese::PadaAdeg => '꧊',
Javanese::PadaAdegAdeg => '꧋',
Javanese::PadaPiseleh => '꧌',
Javanese::TurnedPadaPiseleh => '꧍',
Javanese::Pangrangkep => 'ꧏ',
Javanese::DigitZero => '꧐',
Javanese::DigitOne => '꧑',
Javanese::DigitTwo => '꧒',
Javanese::DigitThree => '꧓',
Javanese::DigitFour => '꧔',
Javanese::DigitFive => '꧕',
Javanese::DigitSix => '꧖',
Javanese::DigitSeven => '꧗',
Javanese::DigitEight => '꧘',
Javanese::DigitNine => '꧙',
Javanese::PadaTirtaTumetes => '꧞',
}
}
}
impl std::convert::TryFrom<char> for Javanese {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'ꦀ' => Ok(Javanese::SignPanyangga),
'ꦁ' => Ok(Javanese::SignCecak),
'ꦂ' => Ok(Javanese::SignLayar),
'ꦃ' => Ok(Javanese::SignWignyan),
'ꦄ' => Ok(Javanese::LetterA),
'ꦅ' => Ok(Javanese::LetterIKawi),
'ꦆ' => Ok(Javanese::LetterI),
'ꦇ' => Ok(Javanese::LetterIi),
'ꦈ' => Ok(Javanese::LetterU),
'ꦉ' => Ok(Javanese::LetterPaCerek),
'ꦊ' => Ok(Javanese::LetterNgaLelet),
'ꦋ' => Ok(Javanese::LetterNgaLeletRaswadi),
'ꦌ' => Ok(Javanese::LetterE),
'ꦍ' => Ok(Javanese::LetterAi),
'ꦎ' => Ok(Javanese::LetterO),
'ꦏ' => Ok(Javanese::LetterKa),
'ꦐ' => Ok(Javanese::LetterKaSasak),
'ꦑ' => Ok(Javanese::LetterKaMurda),
'ꦒ' => Ok(Javanese::LetterGa),
'ꦓ' => Ok(Javanese::LetterGaMurda),
'ꦔ' => Ok(Javanese::LetterNga),
'ꦕ' => Ok(Javanese::LetterCa),
'ꦖ' => Ok(Javanese::LetterCaMurda),
'ꦗ' => Ok(Javanese::LetterJa),
'ꦘ' => Ok(Javanese::LetterNyaMurda),
'ꦙ' => Ok(Javanese::LetterJaMahaprana),
'ꦚ' => Ok(Javanese::LetterNya),
'ꦛ' => Ok(Javanese::LetterTta),
'ꦜ' => Ok(Javanese::LetterTtaMahaprana),
'ꦝ' => Ok(Javanese::LetterDda),
'ꦞ' => Ok(Javanese::LetterDdaMahaprana),
'ꦟ' => Ok(Javanese::LetterNaMurda),
'ꦠ' => Ok(Javanese::LetterTa),
'ꦡ' => Ok(Javanese::LetterTaMurda),
'ꦢ' => Ok(Javanese::LetterDa),
'ꦣ' => Ok(Javanese::LetterDaMahaprana),
'ꦤ' => Ok(Javanese::LetterNa),
'ꦥ' => Ok(Javanese::LetterPa),
'ꦦ' => Ok(Javanese::LetterPaMurda),
'ꦧ' => Ok(Javanese::LetterBa),
'ꦨ' => Ok(Javanese::LetterBaMurda),
'ꦩ' => Ok(Javanese::LetterMa),
'ꦪ' => Ok(Javanese::LetterYa),
'ꦫ' => Ok(Javanese::LetterRa),
'ꦬ' => Ok(Javanese::LetterRaAgung),
'ꦭ' => Ok(Javanese::LetterLa),
'ꦮ' => Ok(Javanese::LetterWa),
'ꦯ' => Ok(Javanese::LetterSaMurda),
'ꦰ' => Ok(Javanese::LetterSaMahaprana),
'ꦱ' => Ok(Javanese::LetterSa),
'ꦲ' => Ok(Javanese::LetterHa),
'꦳' => Ok(Javanese::SignCecakTelu),
'ꦴ' => Ok(Javanese::VowelSignTarung),
'ꦵ' => Ok(Javanese::VowelSignTolong),
'ꦶ' => Ok(Javanese::VowelSignWulu),
'ꦷ' => Ok(Javanese::VowelSignWuluMelik),
'ꦸ' => Ok(Javanese::VowelSignSuku),
'ꦹ' => Ok(Javanese::VowelSignSukuMendut),
'ꦺ' => Ok(Javanese::VowelSignTaling),
'ꦻ' => Ok(Javanese::VowelSignDirgaMure),
'ꦼ' => Ok(Javanese::VowelSignPepet),
'ꦽ' => Ok(Javanese::ConsonantSignKeret),
'ꦾ' => Ok(Javanese::ConsonantSignPengkal),
'ꦿ' => Ok(Javanese::ConsonantSignCakra),
'꧀' => Ok(Javanese::Pangkon),
'꧁' => Ok(Javanese::LeftRerenggan),
'꧂' => Ok(Javanese::RightRerenggan),
'꧃' => Ok(Javanese::PadaAndap),
'꧄' => Ok(Javanese::PadaMadya),
'꧅' => Ok(Javanese::PadaLuhur),
'꧆' => Ok(Javanese::PadaWindu),
'꧇' => Ok(Javanese::PadaPangkat),
'꧈' => Ok(Javanese::PadaLingsa),
'꧉' => Ok(Javanese::PadaLungsi),
'꧊' => Ok(Javanese::PadaAdeg),
'꧋' => Ok(Javanese::PadaAdegAdeg),
'꧌' => Ok(Javanese::PadaPiseleh),
'꧍' => Ok(Javanese::TurnedPadaPiseleh),
'ꧏ' => Ok(Javanese::Pangrangkep),
'꧐' => Ok(Javanese::DigitZero),
'꧑' => Ok(Javanese::DigitOne),
'꧒' => Ok(Javanese::DigitTwo),
'꧓' => Ok(Javanese::DigitThree),
'꧔' => Ok(Javanese::DigitFour),
'꧕' => Ok(Javanese::DigitFive),
'꧖' => Ok(Javanese::DigitSix),
'꧗' => Ok(Javanese::DigitSeven),
'꧘' => Ok(Javanese::DigitEight),
'꧙' => Ok(Javanese::DigitNine),
'꧞' => Ok(Javanese::PadaTirtaTumetes),
_ => Err(()),
}
}
}
impl Into<u32> for Javanese {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for Javanese {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for Javanese {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl Javanese {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
Javanese::SignPanyangga
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("Javanese{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use crate::lisp_object::{EvalError};
pub fn apply_unimpl() -> EvalError {
EvalError::new("apply only implemented for Native, Lambda and Special Form".to_string())
}
pub fn apply_empty() -> EvalError {
EvalError::new("apply received empty form".to_string())
}
pub fn unbound_symbol(sym: Option<&str>) -> EvalError {
EvalError::new(format!("Unbound symbol '{}'",
sym.unwrap_or("~~uninterned~~")))
}
pub fn unexpected_special_form() -> EvalError {
EvalError::new(
format!("Unexpected special form. You are maybe missing a quote."))
}
|
use anyhow::Result;
use console::{Emoji, Style};
use dialoguer::Password;
use git2::{Cred, RemoteCallbacks, Repository};
use std::env;
use std::path::PathBuf;
pub(crate) fn clone(repository: &str, target_dir: &PathBuf, passphrase_needed: bool) -> Result<()> {
let cyan = Style::new().cyan();
println!(
"{} {}",
Emoji("🔄", ""),
cyan.apply_to("Cloning repository…"),
);
if repository.contains("http") {
Repository::clone(repository, &target_dir)?;
} else {
let mut callbacks = RemoteCallbacks::new();
let passphrase = if passphrase_needed {
Password::new()
.with_prompt("Enter passphrase for .ssh/id_rsa")
.interact()?
.into()
} else {
None
};
callbacks.credentials(move |_url, username_from_url, _allowed_types| {
Cred::ssh_key(
username_from_url.unwrap(),
None,
std::path::Path::new(&format!(
"{}/.ssh/id_rsa", // TODO: add flag to specify
env::var("HOME").expect("cannot fetch $HOME")
)),
passphrase.as_deref(),
)
});
// Prepare fetch options.
let mut fo = git2::FetchOptions::new();
fo.remote_callbacks(callbacks);
// Prepare builder.
let mut builder = git2::build::RepoBuilder::new();
builder.fetch_options(fo);
// Clone the project.
builder.clone(repository, &target_dir)?;
}
Ok(())
}
|
use crate::constraints::{JobSkills, SkillsModule};
use crate::extensions::create_typed_actor_groups;
use crate::helpers::*;
use hashbrown::HashSet;
use std::iter::FromIterator;
use std::sync::Arc;
use vrp_core::construction::constraints::{ConstraintPipeline, RouteConstraintViolation};
use vrp_core::construction::heuristics::{RouteContext, RouteState};
use vrp_core::models::common::ValueDimension;
use vrp_core::models::problem::{Fleet, Job, Vehicle};
fn create_job_with_skills(all_of: Option<Vec<&str>>, one_of: Option<Vec<&str>>, none_of: Option<Vec<&str>>) -> Job {
let mut single = create_single_with_location(None);
single.dimens.set_value(
"skills",
JobSkills {
all_of: all_of.map(|skills| skills.iter().map(|s| s.to_string()).collect()),
one_of: one_of.map(|skills| skills.iter().map(|s| s.to_string()).collect()),
none_of: none_of.map(|skills| skills.iter().map(|s| s.to_string()).collect()),
},
);
Job::Single(Arc::new(single))
}
fn create_vehicle_with_skills(skills: Option<Vec<&str>>) -> Vehicle {
let mut vehicle = test_vehicle("v1");
if let Some(skills) = skills {
vehicle.dimens.set_value("skills", HashSet::<String>::from_iter(skills.iter().map(|s| s.to_string())));
}
vehicle
}
fn failure() -> Option<RouteConstraintViolation> {
Some(RouteConstraintViolation { code: 0 })
}
parameterized_test! {can_check_skills, (all_of, one_of, none_of, vehicle_skills, expected), {
can_check_skills_impl(all_of, one_of, none_of, vehicle_skills, expected);
}}
can_check_skills! {
case01: (None, None, None, None, None),
case_all_of_01: (Some(vec!["s1"]), None, None, None, failure()),
case_all_of_02: (Some(vec![]), None, None, None, None),
case_all_of_03: (Some(vec!["s1"]), None, None, Some(vec!["s1"]), None),
case_all_of_04: (Some(vec!["s1"]), None, None, Some(vec!["s2"]), failure()),
case_all_of_05: (Some(vec!["s1", "s2"]), None, None, Some(vec!["s2"]), failure()),
case_all_of_06: (Some(vec!["s1"]), None, None, Some(vec!["s1", "s2"]), None),
case_one_of_01: (None, Some(vec!["s1"]), None, None, failure()),
case_one_of_02: (None, Some(vec![]), None, None, None),
case_one_of_03: (None, Some(vec!["s1"]), None, Some(vec!["s1"]), None),
case_one_of_04: (None, Some(vec!["s1"]), None, Some(vec!["s2"]), failure()),
case_one_of_05: (None, Some(vec!["s1", "s2"]), None, Some(vec!["s2"]), None),
case_one_of_06: (None, Some(vec!["s1"]), None, Some(vec!["s1", "s2"]), None),
case_none_of_01: (None, None, Some(vec!["s1"]), None, None),
case_none_of_02: (None, None, Some(vec![]), None, None),
case_none_of_03: (None, None, Some(vec!["s1"]), Some(vec!["s1"]), failure()),
case_none_of_04: (None, None, Some(vec!["s1"]), Some(vec!["s2"]), None),
case_none_of_05: (None, None, Some(vec!["s1", "s2"]), Some(vec!["s2"]), failure()),
case_none_of_06: (None, None, Some(vec!["s1"]), Some(vec!["s1", "s2"]), failure()),
case_combine_01: (Some(vec!["s1"]), None, Some(vec!["s2"]), Some(vec!["s1", "s2"]), failure()),
case_combine_02: (None, Some(vec!["s1"]), Some(vec!["s2"]), Some(vec!["s1", "s2"]), failure()),
case_combine_03: (Some(vec!["s1"]), Some(vec!["s2"]), None, Some(vec!["s1", "s2"]), None),
case_combine_04: (Some(vec!["s1"]), Some(vec!["s2", "s3"]), None, Some(vec!["s1", "s2"]), None),
case_combine_05: (Some(vec!["s1", "s2"]), Some(vec!["s3"]), None, Some(vec!["s1", "s2", "s3"]), None),
case_combine_06: (Some(vec!["s1", "s2"]), Some(vec!["s3"]), None, Some(vec!["s1", "s2"]), failure()),
case_combine_07: (Some(vec!["s1"]), Some(vec!["s2"]), Some(vec!["s3"]), Some(vec!["s1", "s2", "s3"]), failure()),
}
fn can_check_skills_impl(
all_of: Option<Vec<&str>>,
one_of: Option<Vec<&str>>,
none_of: Option<Vec<&str>>,
vehicle_skills: Option<Vec<&str>>,
expected: Option<RouteConstraintViolation>,
) {
let fleet = Fleet::new(
vec![Arc::new(test_driver())],
vec![Arc::new(create_vehicle_with_skills(vehicle_skills))],
Box::new(|actors| create_typed_actor_groups(actors)),
);
let route_ctx = RouteContext::new_with_state(
Arc::new(create_route_with_activities(&fleet, "v1", vec![])),
Arc::new(RouteState::default()),
);
let actual = ConstraintPipeline::default().add_module(Box::new(SkillsModule::new(0))).evaluate_hard_route(
&create_solution_context_for_fleet(&fleet),
&route_ctx,
&create_job_with_skills(all_of, one_of, none_of),
);
assert_eq!(actual, expected)
}
|
/*
* Copyright Stalwart Labs Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
use crate::Error;
use ahash::AHashMap;
use chrono::{DateTime, NaiveDateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display, Formatter};
use super::{request::ResultReference, Object, RequestParams};
pub trait SetObject: Object {
type SetArguments: Default;
fn new(create_id: Option<usize>) -> Self;
fn create_id(&self) -> Option<String>;
}
#[derive(Debug, Clone, Serialize)]
pub struct SetRequest<O: SetObject> {
#[serde(rename = "accountId")]
#[serde(skip_serializing_if = "Option::is_none")]
account_id: Option<String>,
#[serde(rename = "ifInState")]
#[serde(skip_serializing_if = "Option::is_none")]
if_in_state: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
create: Option<AHashMap<String, O>>,
#[serde(skip_serializing_if = "Option::is_none")]
update: Option<AHashMap<String, O>>,
#[serde(skip_serializing_if = "Option::is_none")]
destroy: Option<Vec<String>>,
#[serde(rename = "#destroy")]
#[serde(skip_deserializing)]
#[serde(skip_serializing_if = "Option::is_none")]
destroy_ref: Option<ResultReference>,
#[serde(flatten)]
arguments: O::SetArguments,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SetResponse<O: SetObject> {
#[serde(rename = "accountId")]
account_id: Option<String>,
#[serde(rename = "oldState")]
old_state: Option<String>,
#[serde(rename = "newState")]
new_state: Option<String>,
#[serde(rename = "created")]
created: Option<AHashMap<String, O>>,
#[serde(rename = "updated")]
updated: Option<AHashMap<String, Option<O>>>,
#[serde(rename = "destroyed")]
destroyed: Option<Vec<String>>,
#[serde(rename = "notCreated")]
not_created: Option<AHashMap<String, SetError<O::Property>>>,
#[serde(rename = "notUpdated")]
not_updated: Option<AHashMap<String, SetError<O::Property>>>,
#[serde(rename = "notDestroyed")]
not_destroyed: Option<AHashMap<String, SetError<O::Property>>>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SetError<U>
where
U: Display,
{
#[serde(rename = "type")]
pub type_: SetErrorType,
description: Option<String>,
properties: Option<Vec<U>>,
}
#[derive(Debug, Clone, Deserialize, Eq, PartialEq)]
pub enum SetErrorType {
#[serde(rename = "forbidden")]
Forbidden,
#[serde(rename = "overQuota")]
OverQuota,
#[serde(rename = "tooLarge")]
TooLarge,
#[serde(rename = "rateLimit")]
RateLimit,
#[serde(rename = "notFound")]
NotFound,
#[serde(rename = "invalidPatch")]
InvalidPatch,
#[serde(rename = "willDestroy")]
WillDestroy,
#[serde(rename = "invalidProperties")]
InvalidProperties,
#[serde(rename = "singleton")]
Singleton,
#[serde(rename = "mailboxHasChild")]
MailboxHasChild,
#[serde(rename = "mailboxHasEmail")]
MailboxHasEmail,
#[serde(rename = "blobNotFound")]
BlobNotFound,
#[serde(rename = "tooManyKeywords")]
TooManyKeywords,
#[serde(rename = "tooManyMailboxes")]
TooManyMailboxes,
#[serde(rename = "forbiddenFrom")]
ForbiddenFrom,
#[serde(rename = "invalidEmail")]
InvalidEmail,
#[serde(rename = "tooManyRecipients")]
TooManyRecipients,
#[serde(rename = "noRecipients")]
NoRecipients,
#[serde(rename = "invalidRecipients")]
InvalidRecipients,
#[serde(rename = "forbiddenMailFrom")]
ForbiddenMailFrom,
#[serde(rename = "forbiddenToSend")]
ForbiddenToSend,
#[serde(rename = "cannotUnsend")]
CannotUnsend,
#[serde(rename = "alreadyExists")]
AlreadyExists,
#[serde(rename = "invalidScript")]
InvalidScript,
#[serde(rename = "scriptIsActive")]
ScriptIsActive,
}
impl<O: SetObject> SetRequest<O> {
pub fn new(params: RequestParams) -> Self {
Self {
account_id: if O::requires_account_id() {
params.account_id.into()
} else {
None
},
if_in_state: None,
create: None,
update: None,
destroy: None,
destroy_ref: None,
arguments: Default::default(),
}
}
pub fn account_id(&mut self, account_id: impl Into<String>) -> &mut Self {
if O::requires_account_id() {
self.account_id = Some(account_id.into());
}
self
}
pub fn if_in_state(&mut self, if_in_state: impl Into<String>) -> &mut Self {
self.if_in_state = Some(if_in_state.into());
self
}
pub fn create(&mut self) -> &mut O {
let create_id = self.create.as_ref().map_or(0, |c| c.len());
let create_id_str = format!("c{}", create_id);
self.create
.get_or_insert_with(AHashMap::new)
.insert(create_id_str.clone(), O::new(create_id.into()));
self.create
.as_mut()
.unwrap()
.get_mut(&create_id_str)
.unwrap()
}
pub fn create_with_id(&mut self, create_id: impl Into<String>) -> &mut O {
let create_id = create_id.into();
self.create
.get_or_insert_with(AHashMap::new)
.insert(create_id.clone(), O::new(0.into()));
self.create.as_mut().unwrap().get_mut(&create_id).unwrap()
}
pub fn create_item(&mut self, item: O) -> String {
let create_id = self.create.as_ref().map_or(0, |c| c.len());
let create_id_str = format!("c{}", create_id);
self.create
.get_or_insert_with(AHashMap::new)
.insert(create_id_str.clone(), item);
create_id_str
}
pub fn update(&mut self, id: impl Into<String>) -> &mut O {
let id: String = id.into();
self.update
.get_or_insert_with(AHashMap::new)
.insert(id.clone(), O::new(None));
self.update.as_mut().unwrap().get_mut(&id).unwrap()
}
pub fn update_item(&mut self, id: impl Into<String>, item: O) {
self.update
.get_or_insert_with(AHashMap::new)
.insert(id.into(), item);
}
pub fn destroy<U, V>(&mut self, ids: U) -> &mut Self
where
U: IntoIterator<Item = V>,
V: Into<String>,
{
self.destroy
.get_or_insert_with(Vec::new)
.extend(ids.into_iter().map(|id| id.into()));
self.destroy_ref = None;
self
}
pub fn destroy_ref(&mut self, reference: ResultReference) -> &mut Self {
self.destroy_ref = reference.into();
self.destroy = None;
self
}
pub fn arguments(&mut self) -> &mut O::SetArguments {
&mut self.arguments
}
}
impl<O: SetObject> SetResponse<O> {
pub fn account_id(&self) -> Option<&str> {
self.account_id.as_deref()
}
pub fn old_state(&self) -> Option<&str> {
self.old_state.as_deref()
}
pub fn new_state(&self) -> &str {
self.new_state.as_deref().unwrap_or("")
}
pub fn take_new_state(&mut self) -> String {
self.new_state.take().unwrap_or_default()
}
pub fn created(&mut self, id: &str) -> crate::Result<O> {
if let Some(result) = self.created.as_mut().and_then(|r| r.remove(id)) {
Ok(result)
} else if let Some(error) = self.not_created.as_mut().and_then(|r| r.remove(id)) {
Err(error.to_string_error().into())
} else {
Err(Error::Internal(format!("Id {} not found.", id)))
}
}
pub fn updated(&mut self, id: &str) -> crate::Result<Option<O>> {
if let Some(result) = self.updated.as_mut().and_then(|r| r.remove(id)) {
Ok(result)
} else if let Some(error) = self.not_updated.as_mut().and_then(|r| r.remove(id)) {
Err(error.to_string_error().into())
} else {
Err(Error::Internal(format!("Id {} not found.", id)))
}
}
pub fn destroyed(&mut self, id: &str) -> crate::Result<()> {
if self
.destroyed
.as_ref()
.map_or(false, |r| r.iter().any(|i| i == id))
{
Ok(())
} else if let Some(error) = self.not_destroyed.as_mut().and_then(|r| r.remove(id)) {
Err(error.to_string_error().into())
} else {
Err(Error::Internal(format!("Id {} not found.", id)))
}
}
pub fn created_ids(&self) -> Option<impl Iterator<Item = &String>> {
self.created.as_ref().map(|map| map.keys())
}
pub fn updated_ids(&self) -> Option<impl Iterator<Item = &String>> {
self.updated.as_ref().map(|map| map.keys())
}
pub fn take_updated_ids(&mut self) -> Option<Vec<String>> {
self.updated
.take()
.map(|map| map.into_iter().map(|(k, _)| k).collect())
}
pub fn destroyed_ids(&self) -> Option<impl Iterator<Item = &String>> {
self.destroyed.as_ref().map(|list| list.iter())
}
pub fn take_destroyed_ids(&mut self) -> Option<Vec<String>> {
self.destroyed.take()
}
pub fn not_created_ids(&self) -> Option<impl Iterator<Item = &String>> {
self.not_created.as_ref().map(|map| map.keys())
}
pub fn not_updated_ids(&self) -> Option<impl Iterator<Item = &String>> {
self.not_updated.as_ref().map(|map| map.keys())
}
pub fn not_destroyed_ids(&self) -> Option<impl Iterator<Item = &String>> {
self.not_destroyed.as_ref().map(|map| map.keys())
}
pub fn has_updated(&self) -> bool {
self.updated.as_ref().map_or(false, |m| !m.is_empty())
}
pub fn has_created(&self) -> bool {
self.created.as_ref().map_or(false, |m| !m.is_empty())
}
pub fn has_destroyed(&self) -> bool {
self.destroyed.as_ref().map_or(false, |m| !m.is_empty())
}
pub fn unwrap_update_errors(&self) -> crate::Result<()> {
if let Some(errors) = &self.not_updated {
if let Some(err) = errors.values().next() {
return Err(err.to_string_error().into());
}
}
Ok(())
}
pub fn unwrap_create_errors(&self) -> crate::Result<()> {
if let Some(errors) = &self.not_created {
if let Some(err) = errors.values().next() {
return Err(err.to_string_error().into());
}
}
Ok(())
}
}
impl<U: Display> SetError<U> {
pub fn error(&self) -> &SetErrorType {
&self.type_
}
pub fn description(&self) -> Option<&str> {
self.description.as_deref()
}
pub fn properties(&self) -> Option<&[U]> {
self.properties.as_deref()
}
pub fn to_string_error(&self) -> SetError<String> {
SetError {
type_: self.type_.clone(),
description: self.description.as_ref().map(|s| s.to_string()),
properties: self
.properties
.as_ref()
.map(|s| s.iter().map(|s| s.to_string()).collect()),
}
}
}
impl<U: Display> Display for SetError<U> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.type_.fmt(f)?;
if let Some(description) = &self.description {
write!(f, ": {}", description)?;
}
if let Some(properties) = &self.properties {
write!(
f,
" (properties: {})",
properties
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(", ")
)?;
}
Ok(())
}
}
impl Display for SetErrorType {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
SetErrorType::Forbidden => write!(f, "forbidden"),
SetErrorType::OverQuota => write!(f, "overQuota"),
SetErrorType::TooLarge => write!(f, "tooLarge"),
SetErrorType::RateLimit => write!(f, "rateLimit"),
SetErrorType::NotFound => write!(f, "notFound"),
SetErrorType::InvalidPatch => write!(f, "invalidPatch"),
SetErrorType::WillDestroy => write!(f, "willDestroy"),
SetErrorType::InvalidProperties => write!(f, "invalidProperties"),
SetErrorType::Singleton => write!(f, "singleton"),
SetErrorType::MailboxHasChild => write!(f, "mailboxHasChild"),
SetErrorType::MailboxHasEmail => write!(f, "mailboxHasEmail"),
SetErrorType::BlobNotFound => write!(f, "blobNotFound"),
SetErrorType::TooManyKeywords => write!(f, "tooManyKeywords"),
SetErrorType::TooManyMailboxes => write!(f, "tooManyMailboxes"),
SetErrorType::ForbiddenFrom => write!(f, "forbiddenFrom"),
SetErrorType::InvalidEmail => write!(f, "invalidEmail"),
SetErrorType::TooManyRecipients => write!(f, "tooManyRecipients"),
SetErrorType::NoRecipients => write!(f, "noRecipients"),
SetErrorType::InvalidRecipients => write!(f, "invalidRecipients"),
SetErrorType::ForbiddenMailFrom => write!(f, "forbiddenMailFrom"),
SetErrorType::ForbiddenToSend => write!(f, "forbiddenToSend"),
SetErrorType::CannotUnsend => write!(f, "cannotUnsend"),
SetErrorType::AlreadyExists => write!(f, "alreadyExists"),
SetErrorType::InvalidScript => write!(f, "invalidScript"),
SetErrorType::ScriptIsActive => write!(f, "scriptIsActive"),
}
}
}
pub fn from_timestamp(timestamp: i64) -> DateTime<Utc> {
DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp_opt(timestamp, 0).unwrap_or_default(),
Utc,
)
}
pub fn string_not_set(string: &Option<String>) -> bool {
matches!(string, Some(string) if string.is_empty())
}
pub fn date_not_set(date: &Option<DateTime<Utc>>) -> bool {
matches!(date, Some(date) if date.timestamp() == 0)
}
pub fn list_not_set<O>(list: &Option<Vec<O>>) -> bool {
matches!(list, Some(list) if list.is_empty() )
}
pub fn map_not_set<K, V>(list: &Option<AHashMap<K, V>>) -> bool {
matches!(list, Some(list) if list.is_empty() )
}
|
#![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 ApiEndpoint {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
#[serde(rename = "majorVersion", default, skip_serializing_if = "Option::is_none")]
pub major_version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApiError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityInput {
pub name: String,
#[serde(rename = "type")]
pub type_: ResourceType,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ResourceType {
#[serde(rename = "mediaservices")]
Mediaservices,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityOutput {
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<check_name_availability_output::Reason>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
pub mod check_name_availability_output {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Reason {
None,
Invalid,
AlreadyExists,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MediaService {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MediaServiceProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MediaServiceCollection {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<MediaService>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MediaServiceProperties {
#[serde(rename = "apiEndpoints", default, skip_serializing_if = "Vec::is_empty")]
pub api_endpoints: Vec<ApiEndpoint>,
#[serde(rename = "storageAccounts", default, skip_serializing_if = "Vec::is_empty")]
pub storage_accounts: Vec<StorageAccount>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegenerateKeyInput {
#[serde(rename = "keyType")]
pub key_type: regenerate_key_input::KeyType,
}
pub mod regenerate_key_input {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeyType {
Primary,
Secondary,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegenerateKeyOutput {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServiceKeys {
#[serde(rename = "primaryAuthEndpoint", default, skip_serializing_if = "Option::is_none")]
pub primary_auth_endpoint: Option<String>,
#[serde(rename = "secondaryAuthEndpoint", default, skip_serializing_if = "Option::is_none")]
pub secondary_auth_endpoint: Option<String>,
#[serde(rename = "primaryKey", default, skip_serializing_if = "Option::is_none")]
pub primary_key: Option<String>,
#[serde(rename = "secondaryKey", default, skip_serializing_if = "Option::is_none")]
pub secondary_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageAccount {
pub id: String,
#[serde(rename = "isPrimary")]
pub is_primary: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyncStorageKeysInput {
pub id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
}
}
|
use clap::Parser;
use rand::prelude::*;
/// Prints the evolution of the state of a cellular automaton to standard out.
///
/// The cellular automaton is one dimensional with each Cell being in one of two states. The next
/// state of each cell is only influenced by its state and the state of its two neighbours. The
/// leftmost and rightmost cells at the borders are considered to be neighbours.
/// Each cells next state therefore depends on 3 current states. This means 2^3=8 rules are
/// required to evolve the state of the automaton. Each Rule can have two outcomes, which amounts
/// to 2^8=256 rule sets in total.
#[derive(Parser)]
struct Opt {
/// The ruleset used to evolve the automatons state. Any number between 0 and 255.
#[clap()]
rule: u8,
/// Number of steps to evolve the cellular automaton
#[clap(long, short = 's', default_value = "100")]
steps: usize,
/// Number of cells within the Automaton
#[clap(long, short = 'w', default_value = "80")]
width: usize,
/// Random initial state
#[clap(long, short = 'r')]
random: bool,
}
#[derive(Clone, Copy)]
enum Cell {
X,
O,
}
fn rule_from_byte(byte: u8) -> [Cell; 8] {
let mut rule = [Cell::O; 8];
for (i, cell) in rule.iter_mut().enumerate() {
*cell = if 2_u8.pow(i as u32) & byte != 0 {
Cell::X
} else {
Cell::O
}
}
rule
}
fn main() {
let Opt {
rule,
steps,
width,
random,
} = Opt::from_args();
let rule = rule_from_byte(rule);
let mut state1;
let mut state2 = vec![Cell::O; width];
// set initial state
if random {
state1 = rand::thread_rng()
.sample_iter(&rand::distributions::Standard)
.take(width)
.collect();
} else {
state1 = vec![Cell::O; width];
state1[width / 2] = Cell::X;
}
print_state(&state1);
for generation in 0..steps {
let (current, previous) = if generation % 2 == 0 {
(&mut state2, &state1)
} else {
(&mut state1, &state2)
};
apply_rules(previous, current, &rule);
print_state(current);
}
}
fn apply_rules(previous: &[Cell], next: &mut [Cell], rule: &[Cell; 8]) {
for (index, cell) in next.iter_mut().enumerate() {
let neighbours = [
previous[(index + previous.len() - 1) % previous.len()],
previous[index],
previous[(index + 1) % previous.len()],
];
*cell = apply_rule(neighbours, rule);
}
}
fn apply_rule(neighbours: [Cell; 3], rule: &[Cell; 8]) -> Cell {
use crate::Cell::*;
match neighbours {
[O, O, O] => rule[0],
[O, O, X] => rule[1],
[O, X, O] => rule[2],
[O, X, X] => rule[3],
[X, O, O] => rule[4],
[X, O, X] => rule[5],
[X, X, O] => rule[6],
[X, X, X] => rule[7],
}
}
fn print_state(state: &[Cell]) {
for cell in state {
match cell {
Cell::O => print!("░"),
Cell::X => print!("█"),
}
}
println!();
}
impl Distribution<Cell> for rand::distributions::Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Cell {
if rng.gen() {
Cell::X
} else {
Cell::O
}
}
}
|
#[macro_use]
extern crate log;
use rust_tdlib::{client::Client, types::*};
#[tokio::main]
async fn main() {
env_logger::init();
let tdlib_parameters = TdlibParameters::builder()
.database_directory("tdlib")
.use_test_dc(false)
.api_id(env!("API_ID").parse::<i64>().unwrap())
.api_hash(env!("API_HASH"))
.system_language_code("en")
.device_model("Desktop")
.system_version("Unknown")
.application_version(env!("CARGO_PKG_VERSION"))
.enable_storage_optimizer(true)
.build();
let mut client = Client::builder()
.with_tdlib_parameters(tdlib_parameters)
.build()
.unwrap();
let waiter = client.start().await.unwrap();
let api = client.api();
let me = api.get_me(GetMe::builder().build()).await.unwrap();
info!("me: {:?}", me);
let chats = api
.search_public_chats(SearchPublicChats::builder().query("@rust").build())
.await
.unwrap();
info!("found chats: {}", chats.chat_ids().len());
for chat_id in chats.chat_ids() {
let chat = api
.get_chat(GetChat::builder().chat_id(*chat_id))
.await
.unwrap();
info!("{:?}", chat)
}
client.stop();
waiter.await.unwrap();
info!("client closed");
}
|
use crate::custom_types::exceptions::value_error;
use crate::custom_types::range::Range;
use crate::custom_var::CustomVar;
use crate::int_var::IntVar;
use crate::method::StdMethod;
use crate::name::Name;
use crate::operator::Operator;
use crate::runtime::Runtime;
use crate::std_type::Type;
use crate::string_var::StringVar;
use crate::variable::{FnResult, InnerVar, Variable};
use crate::{first, first_n};
use num::{One, Signed, Zero};
use std::borrow::Cow;
use std::rc::Rc;
#[derive(Debug)]
pub struct Slice {
start: Option<IntVar>,
stop: Option<IntVar>,
step: Option<IntVar>,
}
impl Slice {
pub fn new(start: Option<IntVar>, stop: Option<IntVar>, step: Option<IntVar>) -> Slice {
Slice { start, stop, step }
}
pub fn from_vars(start: Variable, stop: Variable, step: Variable) -> Rc<Slice> {
Rc::new(Slice::new(
unwrapped_to_int(start),
unwrapped_to_int(stop),
unwrapped_to_int(step),
))
}
fn str(self: Rc<Self>, args: Vec<Variable>, runtime: &mut Runtime) -> FnResult {
debug_assert!(args.is_empty());
runtime.return_1(self.str_value().into())
}
fn str_value(&self) -> StringVar {
format!(
"slice({}, {}, {})",
stringify(&self.start),
stringify(&self.stop),
stringify(&self.step),
)
.into()
}
fn make_range(self: Rc<Self>, args: Vec<Variable>, runtime: &mut Runtime) -> FnResult {
debug_assert_eq!(args.len(), 1);
/*
[::] or [:] -> [0:len:1]
[:x:] or [:x] -> [0:x:1]
[x::] or [x:] -> [x:len:1]
[x:y:] or [x:y] -> [x:y:1]
[:-x:] or [:-x] -> [0:len-x:1]
[-x::] or [-x:] -> [len-x:len:1]
[::-y] -> [len-1:-1:-y]
[x::-y] -> [x:-1:-y]
[:x:-y] -> [len-1:x:-y]
*/
let len = IntVar::from(first(args));
let step = self.step.clone().unwrap_or_else(One::one);
if step.is_zero() {
runtime.throw_quick(value_error(), "Step cannot be 0")
} else if step.is_positive() {
let start = self
.start
.as_ref()
.map(|x| if x.is_negative() { &len + x } else { x.clone() })
.unwrap_or_else(Zero::zero);
let stop = self
.stop
.as_ref()
.map(|x| if x.is_negative() { &len + x } else { x.clone() })
.unwrap_or(len);
runtime.return_1(Rc::new(Range::new(start, stop, step)).into())
} else {
// step.is_negative()
let start = self
.start
.as_ref()
.map(|x| if x.is_negative() { &len + x } else { x.clone() })
.unwrap_or_else(|| &len - &1.into());
let stop = self
.start
.as_ref()
.map(|x| if x.is_negative() { &len + x } else { x.clone() })
.unwrap_or_else(|| (-1).into());
runtime.return_1(Rc::new(Range::new(start, stop, step)).into())
}
}
fn create(args: Vec<Variable>, runtime: &mut Runtime) -> FnResult {
debug_assert_eq!(args.len(), 3);
let [start, stop, step] = first_n(args);
let val = Slice::new(var_to_int(start), var_to_int(stop), var_to_int(step));
if val.step.as_ref().map_or_else(|| false, Zero::is_zero) {
runtime.throw_quick(value_error(), "Step cannot be 0")
} else {
runtime.return_1(Rc::new(val).into())
}
}
pub fn slice_type() -> Type {
custom_class!(Slice, create, "Slice")
}
}
impl CustomVar for Slice {
fn set(self: Rc<Self>, _name: Name, _object: Variable) {
unimplemented!()
}
fn get_type(&self) -> Type {
Self::slice_type()
}
fn get_operator(self: Rc<Self>, op: Operator) -> Variable {
match op {
Operator::Str | Operator::Repr => StdMethod::new_native(self, Self::str).into(),
_ => unimplemented!(),
}
}
fn get_attribute(self: Rc<Self>, name: &str) -> Variable {
match name {
"start" => int_to_var(self.start.clone()),
"stop" => int_to_var(self.stop.clone()),
"step" => int_to_var(self.step.clone()),
"toRange" => StdMethod::new_native(self, Self::make_range).into(),
_ => unimplemented!(),
}
}
fn str(self: Rc<Self>, _runtime: &mut Runtime) -> Result<StringVar, ()> {
Result::Ok(self.str_value())
}
fn repr(self: Rc<Self>, _runtime: &mut Runtime) -> Result<StringVar, ()> {
Result::Ok(self.str_value())
}
}
fn int_to_var(value: Option<IntVar>) -> Variable {
value.map(Variable::from).into()
}
fn var_to_int(value: Variable) -> Option<IntVar> {
if let Variable::Option(var) = value {
if var.depth == 1 {
var.value.map(InnerVar::into).map(Variable::into)
} else {
panic!(
"var_to_int expected a one-deep option, not {:?}",
Variable::Option(var)
)
}
} else {
panic!("var_to_int expected an option, not {:?}", value)
}
}
fn unwrapped_to_int(value: Variable) -> Option<IntVar> {
match value {
Variable::Normal(InnerVar::Null()) => Option::None,
x => Option::Some(x.into()),
}
}
fn stringify(val: &Option<IntVar>) -> Cow<'static, str> {
match val {
Option::Some(x) => format!("Some({})", x).into(),
Option::None => "None".into(),
}
}
|
extern crate vaas_server;
use actix_codec::Framed;
use actix_http::ws::Codec;
use actix_web::{test, App};
use actix_web_actors::ws;
use futures::{SinkExt, StreamExt};
use insta::assert_ron_snapshot;
use std::env;
use std::sync::Once;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::time::timeout;
use vaas_server::{server, websocket};
use websocket::{IncomingLogin, IncomingMessage, IncomingReconnect, IncomingVote, OutgoingMessage};
mod integration_db;
use integration_db::IntegrationTestDb;
const READ_TIMEOUT_MS: u64 = 400;
static INIT: Once = Once::new();
fn setup_once() {
use tracing_error::ErrorLayer;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{filter::LevelFilter, EnvFilter};
INIT.call_once(|| {
// Global tracing subscriber
let subscriber = tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::from_default_env()
.add_directive("[test_db]=trace".parse().unwrap())
.add_directive(LevelFilter::INFO.into()),
)
.finish()
.with(ErrorLayer::default());
tracing::subscriber::set_global_default(subscriber).unwrap();
color_eyre::install().unwrap();
});
}
macro_rules! frame_message_type {
($framed:expr, $message_type:path) => {
match read_message(&mut $framed)
.await
.expect("Unable to read ws frame")
{
$message_type(message_type) => message_type,
_ => panic!("Wrong outgoing message type"),
}
};
}
async fn read_message(
framed: &mut Framed<impl AsyncRead + AsyncWrite, Codec>,
) -> Option<OutgoingMessage> {
let frame = timeout(Duration::from_millis(READ_TIMEOUT_MS), framed.next()).await;
// ???
match frame.ok()??.unwrap() {
ws::Frame::Text(item) => Some(serde_json::from_slice(&item[..]).unwrap()),
f => panic!("Got unexpected frame {:?}", f),
}
}
async fn read_messages(
mut framed: &mut Framed<impl AsyncRead + AsyncWrite, Codec>,
) -> Vec<OutgoingMessage> {
let mut messages = vec![];
while let Some(message) = read_message(&mut framed).await {
messages.push(message);
}
messages
}
#[actix_rt::test]
async fn test_login_user() {
setup_once();
// Setup test serve
let test_db = IntegrationTestDb::new().await;
let pool = test_db.pool();
let mut srv = test::start(move || {
server::register_db_actor(pool.clone());
server::register_system_actors();
App::new().configure(|app| server::configure(app))
});
let mut framed = srv.ws_at("/ws/").await.unwrap();
// Wait until issue has been sent
frame_message_type!(framed, OutgoingMessage::Issue);
// Send user login
let message = IncomingMessage::Login(IncomingLogin {
username: "user".to_owned(),
});
let message = serde_json::to_string(&message).unwrap();
framed.send(ws::Message::Text(message)).await.unwrap();
let messages = read_messages(&mut framed).await;
assert_ron_snapshot!(messages, { ".**.id" => "[uuid]" });
}
#[actix_rt::test]
async fn test_reconnect() {
setup_once();
// Setup test server
let test_db = IntegrationTestDb::new().await;
let pool = test_db.pool();
let mut srv = test::start(move || {
server::register_db_actor(pool.clone());
server::register_system_actors();
App::new().configure(|app| server::configure(app))
});
let mut framed = srv.ws_at("/ws/").await.unwrap();
// Wait until issue has been sent
frame_message_type!(framed, OutgoingMessage::Issue);
// Send user login
let message = IncomingMessage::Login(IncomingLogin {
username: "user".to_owned(),
});
let message = serde_json::to_string(&message).unwrap();
framed.send(ws::Message::Text(message)).await.unwrap();
let messages = read_messages(&mut framed).await;
assert_ron_snapshot!("reconnect - initial login", messages, { ".**.id" => "[uuid]" });
// TODO: rewrite to filter?
let mut session_id = None;
for message in messages {
match message {
OutgoingMessage::Client(client) => {
session_id = Some(client.id);
break;
}
_ => continue,
}
}
let mut framed = srv.ws_at("/ws/").await.unwrap();
// Wait until issue has been sent
frame_message_type!(framed, OutgoingMessage::Issue);
let message = IncomingMessage::Reconnect(IncomingReconnect {
session_id: session_id.expect("Session id should exist"),
});
let message = serde_json::to_string(&message).unwrap();
framed.send(ws::Message::Text(message)).await.unwrap();
let messages = read_messages(&mut framed).await;
assert_ron_snapshot!("reconnect - reload", messages, { ".**.id" => "[uuid]" });
}
#[actix_rt::test]
async fn test_vote() {
setup_once();
// Setup test server
let test_db = IntegrationTestDb::new().await;
let pool = test_db.pool();
let mut srv = test::start(move || {
server::register_db_actor(pool.clone());
server::register_system_actors();
App::new().configure(|app| server::configure(app))
});
let mut framed = srv.ws_at("/ws/").await.unwrap();
let issue = frame_message_type!(framed, OutgoingMessage::Issue);
assert_eq!(issue.title, "coronvorus bad??");
let alternative_id = issue.alternatives[0].id.clone().unwrap();
// Login
let message = IncomingMessage::Login(IncomingLogin {
username: "user".to_owned(),
});
let message = serde_json::to_string(&message).unwrap();
framed.send(ws::Message::Text(message)).await.unwrap();
frame_message_type!(framed, OutgoingMessage::Client);
// Send vote
let message = IncomingMessage::Vote(IncomingVote {
user_id: None,
issue_id: issue.id.clone().unwrap(),
alternative_id: alternative_id.clone(),
});
let message = serde_json::to_string(&message).unwrap();
framed.send(ws::Message::Text(message)).await.unwrap();
let vote = frame_message_type!(framed, OutgoingMessage::Vote);
assert_eq!(vote.alternative_id, alternative_id);
// Close connection
framed
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
.await
.unwrap();
let item = timeout(Duration::from_millis(READ_TIMEOUT_MS), framed.next())
.await
.expect("timeout")
.unwrap()
.unwrap();
assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
}
#[actix_rt::test]
async fn test_connect() {
setup_once();
// Setup test server
let test_db = IntegrationTestDb::new().await;
let pool = test_db.pool();
let mut srv = test::start(move || {
server::register_db_actor(pool.clone());
server::register_system_actors();
App::new().configure(|app| server::configure(app))
});
let mut framed = srv.ws_at("/ws/").await.unwrap();
let messages = read_messages(&mut framed).await;
assert_ron_snapshot!(messages, { ".**.id" => "[uuid]" });
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::BLEBUCKTONADJ {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `ZEROLENDETECTEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ZEROLENDETECTENR {
#[doc = "Disable Zero Length Detect value."]
DIS,
#[doc = "Enable Zero Length Detect value."]
EN,
}
impl ZEROLENDETECTENR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
ZEROLENDETECTENR::DIS => false,
ZEROLENDETECTENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> ZEROLENDETECTENR {
match value {
false => ZEROLENDETECTENR::DIS,
true => ZEROLENDETECTENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == ZEROLENDETECTENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == ZEROLENDETECTENR::EN
}
}
#[doc = "Possible values of the field `ZEROLENDETECTTRIM`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ZEROLENDETECTTRIMR {
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 81us (10 percent margin of error) or more value."]
SETF,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 75.6us (10 percent margin of error) or more value."]
SETE,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 70.2us (10 percent margin of error) or more value."]
SETD,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 64.8us (10 percent margin of error) or more value."]
SETC,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 59.4us (10 percent margin of error) or more value."]
SETB,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 54.0us (10 percent margin of error) or more value."]
SETA,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 48.6us (10 percent margin of error) or more value."]
SET9,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 43.2us (10 percent margin of error) or more value."]
SET8,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 37.8us (10 percent margin of error) or more value."]
SET7,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 32.4us (10 percent margin of error) or more value."]
SET6,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 27.0us (10 percent margin of error) or more value."]
SET5,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 21.6us (10 percent margin of error) or more value."]
SET4,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 16.2us (10 percent margin of error) or more value."]
SET3,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 10.8us (10 percent margin of error) or more value."]
SET2,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 5.4us (10 percent margin of error) or more value."]
SET1,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 2.0us (10 percent margin of error) or more value."]
SET0,
}
impl ZEROLENDETECTTRIMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
ZEROLENDETECTTRIMR::SETF => 15,
ZEROLENDETECTTRIMR::SETE => 14,
ZEROLENDETECTTRIMR::SETD => 13,
ZEROLENDETECTTRIMR::SETC => 12,
ZEROLENDETECTTRIMR::SETB => 11,
ZEROLENDETECTTRIMR::SETA => 10,
ZEROLENDETECTTRIMR::SET9 => 9,
ZEROLENDETECTTRIMR::SET8 => 8,
ZEROLENDETECTTRIMR::SET7 => 7,
ZEROLENDETECTTRIMR::SET6 => 6,
ZEROLENDETECTTRIMR::SET5 => 5,
ZEROLENDETECTTRIMR::SET4 => 4,
ZEROLENDETECTTRIMR::SET3 => 3,
ZEROLENDETECTTRIMR::SET2 => 2,
ZEROLENDETECTTRIMR::SET1 => 1,
ZEROLENDETECTTRIMR::SET0 => 0,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> ZEROLENDETECTTRIMR {
match value {
15 => ZEROLENDETECTTRIMR::SETF,
14 => ZEROLENDETECTTRIMR::SETE,
13 => ZEROLENDETECTTRIMR::SETD,
12 => ZEROLENDETECTTRIMR::SETC,
11 => ZEROLENDETECTTRIMR::SETB,
10 => ZEROLENDETECTTRIMR::SETA,
9 => ZEROLENDETECTTRIMR::SET9,
8 => ZEROLENDETECTTRIMR::SET8,
7 => ZEROLENDETECTTRIMR::SET7,
6 => ZEROLENDETECTTRIMR::SET6,
5 => ZEROLENDETECTTRIMR::SET5,
4 => ZEROLENDETECTTRIMR::SET4,
3 => ZEROLENDETECTTRIMR::SET3,
2 => ZEROLENDETECTTRIMR::SET2,
1 => ZEROLENDETECTTRIMR::SET1,
0 => ZEROLENDETECTTRIMR::SET0,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `SETF`"]
#[inline]
pub fn is_set_f(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SETF
}
#[doc = "Checks if the value of the field is `SETE`"]
#[inline]
pub fn is_set_e(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SETE
}
#[doc = "Checks if the value of the field is `SETD`"]
#[inline]
pub fn is_set_d(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SETD
}
#[doc = "Checks if the value of the field is `SETC`"]
#[inline]
pub fn is_set_c(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SETC
}
#[doc = "Checks if the value of the field is `SETB`"]
#[inline]
pub fn is_set_b(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SETB
}
#[doc = "Checks if the value of the field is `SETA`"]
#[inline]
pub fn is_set_a(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SETA
}
#[doc = "Checks if the value of the field is `SET9`"]
#[inline]
pub fn is_set9(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET9
}
#[doc = "Checks if the value of the field is `SET8`"]
#[inline]
pub fn is_set8(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET8
}
#[doc = "Checks if the value of the field is `SET7`"]
#[inline]
pub fn is_set7(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET7
}
#[doc = "Checks if the value of the field is `SET6`"]
#[inline]
pub fn is_set6(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET6
}
#[doc = "Checks if the value of the field is `SET5`"]
#[inline]
pub fn is_set5(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET5
}
#[doc = "Checks if the value of the field is `SET4`"]
#[inline]
pub fn is_set4(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET4
}
#[doc = "Checks if the value of the field is `SET3`"]
#[inline]
pub fn is_set3(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET3
}
#[doc = "Checks if the value of the field is `SET2`"]
#[inline]
pub fn is_set2(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET2
}
#[doc = "Checks if the value of the field is `SET1`"]
#[inline]
pub fn is_set1(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET1
}
#[doc = "Checks if the value of the field is `SET0`"]
#[inline]
pub fn is_set0(&self) -> bool {
*self == ZEROLENDETECTTRIMR::SET0
}
}
#[doc = "Possible values of the field `TONADJUSTEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TONADJUSTENR {
#[doc = "Disable Adjust for BLE BUCK TON trim value."]
DIS,
#[doc = "Enable Adjust for BLE BUCK TON trim value."]
EN,
}
impl TONADJUSTENR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TONADJUSTENR::DIS => false,
TONADJUSTENR::EN => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TONADJUSTENR {
match value {
false => TONADJUSTENR::DIS,
true => TONADJUSTENR::EN,
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == TONADJUSTENR::DIS
}
#[doc = "Checks if the value of the field is `EN`"]
#[inline]
pub fn is_en(&self) -> bool {
*self == TONADJUSTENR::EN
}
}
#[doc = "Possible values of the field `TONADJUSTPERIOD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TONADJUSTPERIODR {
#[doc = "Adjust done for every 1 3KHz period value."]
HFRC_3KHZ,
#[doc = "Adjust done for every 1 12KHz period value."]
HFRC_12KHZ,
#[doc = "Adjust done for every 1 47KHz period value."]
HFRC_47KHZ,
#[doc = "Adjust done for every 1 94KHz period value."]
HFRC_94KHZ,
}
impl TONADJUSTPERIODR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
TONADJUSTPERIODR::HFRC_3KHZ => 3,
TONADJUSTPERIODR::HFRC_12KHZ => 2,
TONADJUSTPERIODR::HFRC_47KHZ => 1,
TONADJUSTPERIODR::HFRC_94KHZ => 0,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> TONADJUSTPERIODR {
match value {
3 => TONADJUSTPERIODR::HFRC_3KHZ,
2 => TONADJUSTPERIODR::HFRC_12KHZ,
1 => TONADJUSTPERIODR::HFRC_47KHZ,
0 => TONADJUSTPERIODR::HFRC_94KHZ,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `HFRC_3KHZ`"]
#[inline]
pub fn is_hfrc_3khz(&self) -> bool {
*self == TONADJUSTPERIODR::HFRC_3KHZ
}
#[doc = "Checks if the value of the field is `HFRC_12KHZ`"]
#[inline]
pub fn is_hfrc_12khz(&self) -> bool {
*self == TONADJUSTPERIODR::HFRC_12KHZ
}
#[doc = "Checks if the value of the field is `HFRC_47KHZ`"]
#[inline]
pub fn is_hfrc_47khz(&self) -> bool {
*self == TONADJUSTPERIODR::HFRC_47KHZ
}
#[doc = "Checks if the value of the field is `HFRC_94KHZ`"]
#[inline]
pub fn is_hfrc_94khz(&self) -> bool {
*self == TONADJUSTPERIODR::HFRC_94KHZ
}
}
#[doc = r" Value of the field"]
pub struct TONHIGHTHRESHOLDR {
bits: u16,
}
impl TONHIGHTHRESHOLDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u16 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct TONLOWTHRESHOLDR {
bits: u16,
}
impl TONLOWTHRESHOLDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u16 {
self.bits
}
}
#[doc = "Values that can be written to the field `ZEROLENDETECTEN`"]
pub enum ZEROLENDETECTENW {
#[doc = "Disable Zero Length Detect value."]
DIS,
#[doc = "Enable Zero Length Detect value."]
EN,
}
impl ZEROLENDETECTENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
ZEROLENDETECTENW::DIS => false,
ZEROLENDETECTENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _ZEROLENDETECTENW<'a> {
w: &'a mut W,
}
impl<'a> _ZEROLENDETECTENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: ZEROLENDETECTENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable Zero Length Detect value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(ZEROLENDETECTENW::DIS)
}
#[doc = "Enable Zero Length Detect value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(ZEROLENDETECTENW::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 27;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `ZEROLENDETECTTRIM`"]
pub enum ZEROLENDETECTTRIMW {
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 81us (10 percent margin of error) or more value."]
SETF,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 75.6us (10 percent margin of error) or more value."]
SETE,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 70.2us (10 percent margin of error) or more value."]
SETD,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 64.8us (10 percent margin of error) or more value."]
SETC,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 59.4us (10 percent margin of error) or more value."]
SETB,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 54.0us (10 percent margin of error) or more value."]
SETA,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 48.6us (10 percent margin of error) or more value."]
SET9,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 43.2us (10 percent margin of error) or more value."]
SET8,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 37.8us (10 percent margin of error) or more value."]
SET7,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 32.4us (10 percent margin of error) or more value."]
SET6,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 27.0us (10 percent margin of error) or more value."]
SET5,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 21.6us (10 percent margin of error) or more value."]
SET4,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 16.2us (10 percent margin of error) or more value."]
SET3,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 10.8us (10 percent margin of error) or more value."]
SET2,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 5.4us (10 percent margin of error) or more value."]
SET1,
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 2.0us (10 percent margin of error) or more value."]
SET0,
}
impl ZEROLENDETECTTRIMW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
ZEROLENDETECTTRIMW::SETF => 15,
ZEROLENDETECTTRIMW::SETE => 14,
ZEROLENDETECTTRIMW::SETD => 13,
ZEROLENDETECTTRIMW::SETC => 12,
ZEROLENDETECTTRIMW::SETB => 11,
ZEROLENDETECTTRIMW::SETA => 10,
ZEROLENDETECTTRIMW::SET9 => 9,
ZEROLENDETECTTRIMW::SET8 => 8,
ZEROLENDETECTTRIMW::SET7 => 7,
ZEROLENDETECTTRIMW::SET6 => 6,
ZEROLENDETECTTRIMW::SET5 => 5,
ZEROLENDETECTTRIMW::SET4 => 4,
ZEROLENDETECTTRIMW::SET3 => 3,
ZEROLENDETECTTRIMW::SET2 => 2,
ZEROLENDETECTTRIMW::SET1 => 1,
ZEROLENDETECTTRIMW::SET0 => 0,
}
}
}
#[doc = r" Proxy"]
pub struct _ZEROLENDETECTTRIMW<'a> {
w: &'a mut W,
}
impl<'a> _ZEROLENDETECTTRIMW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: ZEROLENDETECTTRIMW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 81us (10 percent margin of error) or more value."]
#[inline]
pub fn set_f(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SETF)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 75.6us (10 percent margin of error) or more value."]
#[inline]
pub fn set_e(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SETE)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 70.2us (10 percent margin of error) or more value."]
#[inline]
pub fn set_d(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SETD)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 64.8us (10 percent margin of error) or more value."]
#[inline]
pub fn set_c(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SETC)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 59.4us (10 percent margin of error) or more value."]
#[inline]
pub fn set_b(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SETB)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 54.0us (10 percent margin of error) or more value."]
#[inline]
pub fn set_a(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SETA)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 48.6us (10 percent margin of error) or more value."]
#[inline]
pub fn set9(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET9)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 43.2us (10 percent margin of error) or more value."]
#[inline]
pub fn set8(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET8)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 37.8us (10 percent margin of error) or more value."]
#[inline]
pub fn set7(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET7)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 32.4us (10 percent margin of error) or more value."]
#[inline]
pub fn set6(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET6)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 27.0us (10 percent margin of error) or more value."]
#[inline]
pub fn set5(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET5)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 21.6us (10 percent margin of error) or more value."]
#[inline]
pub fn set4(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET4)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 16.2us (10 percent margin of error) or more value."]
#[inline]
pub fn set3(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET3)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 10.8us (10 percent margin of error) or more value."]
#[inline]
pub fn set2(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET2)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 5.4us (10 percent margin of error) or more value."]
#[inline]
pub fn set1(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET1)
}
#[doc = "Indicator send when the BLE BUCK asserts blebuck_comp1 for about 2.0us (10 percent margin of error) or more value."]
#[inline]
pub fn set0(self) -> &'a mut W {
self.variant(ZEROLENDETECTTRIMW::SET0)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 23;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TONADJUSTEN`"]
pub enum TONADJUSTENW {
#[doc = "Disable Adjust for BLE BUCK TON trim value."]
DIS,
#[doc = "Enable Adjust for BLE BUCK TON trim value."]
EN,
}
impl TONADJUSTENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TONADJUSTENW::DIS => false,
TONADJUSTENW::EN => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TONADJUSTENW<'a> {
w: &'a mut W,
}
impl<'a> _TONADJUSTENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TONADJUSTENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable Adjust for BLE BUCK TON trim value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(TONADJUSTENW::DIS)
}
#[doc = "Enable Adjust for BLE BUCK TON trim value."]
#[inline]
pub fn en(self) -> &'a mut W {
self.variant(TONADJUSTENW::EN)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 22;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `TONADJUSTPERIOD`"]
pub enum TONADJUSTPERIODW {
#[doc = "Adjust done for every 1 3KHz period value."]
HFRC_3KHZ,
#[doc = "Adjust done for every 1 12KHz period value."]
HFRC_12KHZ,
#[doc = "Adjust done for every 1 47KHz period value."]
HFRC_47KHZ,
#[doc = "Adjust done for every 1 94KHz period value."]
HFRC_94KHZ,
}
impl TONADJUSTPERIODW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
TONADJUSTPERIODW::HFRC_3KHZ => 3,
TONADJUSTPERIODW::HFRC_12KHZ => 2,
TONADJUSTPERIODW::HFRC_47KHZ => 1,
TONADJUSTPERIODW::HFRC_94KHZ => 0,
}
}
}
#[doc = r" Proxy"]
pub struct _TONADJUSTPERIODW<'a> {
w: &'a mut W,
}
impl<'a> _TONADJUSTPERIODW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TONADJUSTPERIODW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Adjust done for every 1 3KHz period value."]
#[inline]
pub fn hfrc_3khz(self) -> &'a mut W {
self.variant(TONADJUSTPERIODW::HFRC_3KHZ)
}
#[doc = "Adjust done for every 1 12KHz period value."]
#[inline]
pub fn hfrc_12khz(self) -> &'a mut W {
self.variant(TONADJUSTPERIODW::HFRC_12KHZ)
}
#[doc = "Adjust done for every 1 47KHz period value."]
#[inline]
pub fn hfrc_47khz(self) -> &'a mut W {
self.variant(TONADJUSTPERIODW::HFRC_47KHZ)
}
#[doc = "Adjust done for every 1 94KHz period value."]
#[inline]
pub fn hfrc_94khz(self) -> &'a mut W {
self.variant(TONADJUSTPERIODW::HFRC_94KHZ)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 20;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _TONHIGHTHRESHOLDW<'a> {
w: &'a mut W,
}
impl<'a> _TONHIGHTHRESHOLDW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
const MASK: u16 = 1023;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _TONLOWTHRESHOLDW<'a> {
w: &'a mut W,
}
impl<'a> _TONLOWTHRESHOLDW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
const MASK: u16 = 1023;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 27 - BLEBUCK ZERO LENGTH DETECT ENABLE"]
#[inline]
pub fn zerolendetecten(&self) -> ZEROLENDETECTENR {
ZEROLENDETECTENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 27;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 23:26 - BLEBUCK ZERO LENGTH DETECT TRIM"]
#[inline]
pub fn zerolendetecttrim(&self) -> ZEROLENDETECTTRIMR {
ZEROLENDETECTTRIMR::_from({
const MASK: u8 = 15;
const OFFSET: u8 = 23;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 22 - TON ADJUST ENABLE"]
#[inline]
pub fn tonadjusten(&self) -> TONADJUSTENR {
TONADJUSTENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 22;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 20:21 - TON ADJUST PERIOD"]
#[inline]
pub fn tonadjustperiod(&self) -> TONADJUSTPERIODR {
TONADJUSTPERIODR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 10:19 - TON ADJUST HIGH THRESHOLD. Suggested values are #15(94KHz) #2A(47Khz) #A6(12Khz) #29A(3Khz)"]
#[inline]
pub fn tonhighthreshold(&self) -> TONHIGHTHRESHOLDR {
let bits = {
const MASK: u16 = 1023;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) as u16
};
TONHIGHTHRESHOLDR { bits }
}
#[doc = "Bits 0:9 - TON ADJUST LOW THRESHOLD. Suggested values are #A(94KHz) #15(47KHz) #53(12Khz) #14D(3Khz)"]
#[inline]
pub fn tonlowthreshold(&self) -> TONLOWTHRESHOLDR {
let bits = {
const MASK: u16 = 1023;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u16
};
TONLOWTHRESHOLDR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 27 - BLEBUCK ZERO LENGTH DETECT ENABLE"]
#[inline]
pub fn zerolendetecten(&mut self) -> _ZEROLENDETECTENW {
_ZEROLENDETECTENW { w: self }
}
#[doc = "Bits 23:26 - BLEBUCK ZERO LENGTH DETECT TRIM"]
#[inline]
pub fn zerolendetecttrim(&mut self) -> _ZEROLENDETECTTRIMW {
_ZEROLENDETECTTRIMW { w: self }
}
#[doc = "Bit 22 - TON ADJUST ENABLE"]
#[inline]
pub fn tonadjusten(&mut self) -> _TONADJUSTENW {
_TONADJUSTENW { w: self }
}
#[doc = "Bits 20:21 - TON ADJUST PERIOD"]
#[inline]
pub fn tonadjustperiod(&mut self) -> _TONADJUSTPERIODW {
_TONADJUSTPERIODW { w: self }
}
#[doc = "Bits 10:19 - TON ADJUST HIGH THRESHOLD. Suggested values are #15(94KHz) #2A(47Khz) #A6(12Khz) #29A(3Khz)"]
#[inline]
pub fn tonhighthreshold(&mut self) -> _TONHIGHTHRESHOLDW {
_TONHIGHTHRESHOLDW { w: self }
}
#[doc = "Bits 0:9 - TON ADJUST LOW THRESHOLD. Suggested values are #A(94KHz) #15(47KHz) #53(12Khz) #14D(3Khz)"]
#[inline]
pub fn tonlowthreshold(&mut self) -> _TONLOWTHRESHOLDW {
_TONLOWTHRESHOLDW { w: self }
}
}
|
use quick_xml::{XmlReader, XmlWriter, Element, Event};
use quick_xml::error::Error as XmlError;
use fromxml::FromXml;
use toxml::{ToXml, XmlWriterExt};
use error::Error;
/// A representation of the `<textInput>` element.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct TextInput {
/// The label of the Submit button for the text input.
pub title: String,
/// A description of the text input.
pub description: String,
/// The name of the text object.
pub name: String,
/// The URL of the CGI script that processes the text input request.
pub link: String,
}
impl FromXml for TextInput {
fn from_xml<R: ::std::io::BufRead>(mut reader: XmlReader<R>,
_: Element)
-> Result<(Self, XmlReader<R>), Error> {
let mut title = None;
let mut description = None;
let mut name = None;
let mut link = None;
while let Some(e) = reader.next() {
match e {
Ok(Event::Start(element)) => {
match element.name() {
b"title" => title = element_text!(reader),
b"description" => description = element_text!(reader),
b"name" => name = element_text!(reader),
b"link" => link = element_text!(reader),
_ => skip_element!(reader),
}
}
Ok(Event::End(_)) => {
let title = title.unwrap_or_default();
let description = description.unwrap_or_default();
let name = name.unwrap_or_default();
let link = link.unwrap_or_default();
return Ok((TextInput {
title: title,
description: description,
name: name,
link: link,
}, reader))
}
Err(err) => return Err(err.into()),
_ => {}
}
}
Err(Error::EOF)
}
}
impl ToXml for TextInput {
fn to_xml<W: ::std::io::Write>(&self, writer: &mut XmlWriter<W>) -> Result<(), XmlError> {
let element = Element::new("textInput");
try!(writer.write(Event::Start(element.clone())));
try!(writer.write_text_element(b"title", &self.title));
try!(writer.write_text_element(b"description", &self.description));
try!(writer.write_text_element(b"name", &self.name));
try!(writer.write_text_element(b"link", &self.link));
writer.write(Event::End(element))
}
}
|
use std::io;
const BASE_PATTERN: [isize; 4] = [0, 1, 0, -1];
fn generate_multiplier(inpos: usize, outpos: usize) -> isize {
let inpos = inpos + 1; // since we always want to skip the first output
BASE_PATTERN[(inpos / (outpos + 1) % 4) as usize]
}
fn main() -> io::Result<()> {
for y in 0..30 {
for x in 0..30 {
print!("{} ", generate_multiplier(x, y));
}
println!();
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_generator() {
let multipliers: [[isize; 8]; 8] = [[1, 0, -1, 0, 1, 0, -1, 0],
[0, 1, 1, 0, 0, -1, -1, 0],
[0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 1]];
for y in 0..8 {
for x in 0..8 {
assert_eq!(generate_multiplier(x, y), multipliers[y][x]);
}
}
}
} |
/// An enum to represent all characters in the BassaVah block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum BassaVah {
/// \u{16ad0}: '𖫐'
LetterEnni,
/// \u{16ad1}: '𖫑'
LetterKa,
/// \u{16ad2}: '𖫒'
LetterSe,
/// \u{16ad3}: '𖫓'
LetterFa,
/// \u{16ad4}: '𖫔'
LetterMbe,
/// \u{16ad5}: '𖫕'
LetterYie,
/// \u{16ad6}: '𖫖'
LetterGah,
/// \u{16ad7}: '𖫗'
LetterDhii,
/// \u{16ad8}: '𖫘'
LetterKpah,
/// \u{16ad9}: '𖫙'
LetterJo,
/// \u{16ada}: '𖫚'
LetterHwah,
/// \u{16adb}: '𖫛'
LetterWa,
/// \u{16adc}: '𖫜'
LetterZo,
/// \u{16add}: '𖫝'
LetterGbu,
/// \u{16ade}: '𖫞'
LetterDo,
/// \u{16adf}: '𖫟'
LetterCe,
/// \u{16ae0}: '𖫠'
LetterUwu,
/// \u{16ae1}: '𖫡'
LetterTo,
/// \u{16ae2}: '𖫢'
LetterBa,
/// \u{16ae3}: '𖫣'
LetterVu,
/// \u{16ae4}: '𖫤'
LetterYein,
/// \u{16ae5}: '𖫥'
LetterPa,
/// \u{16ae6}: '𖫦'
LetterWadda,
/// \u{16ae7}: '𖫧'
LetterA,
/// \u{16ae8}: '𖫨'
LetterO,
/// \u{16ae9}: '𖫩'
LetterOo,
/// \u{16aea}: '𖫪'
LetterU,
/// \u{16aeb}: '𖫫'
LetterEe,
/// \u{16aec}: '𖫬'
LetterE,
/// \u{16aed}: '𖫭'
LetterI,
/// \u{16af0}: '𖫰'
CombiningHighTone,
/// \u{16af1}: '𖫱'
CombiningLowTone,
/// \u{16af2}: '𖫲'
CombiningMidTone,
/// \u{16af3}: '𖫳'
CombiningLowDashMidTone,
/// \u{16af4}: '𖫴'
CombiningHighDashLowTone,
/// \u{16af5}: '𖫵'
FullStop,
}
impl Into<char> for BassaVah {
fn into(self) -> char {
match self {
BassaVah::LetterEnni => '𖫐',
BassaVah::LetterKa => '𖫑',
BassaVah::LetterSe => '𖫒',
BassaVah::LetterFa => '𖫓',
BassaVah::LetterMbe => '𖫔',
BassaVah::LetterYie => '𖫕',
BassaVah::LetterGah => '𖫖',
BassaVah::LetterDhii => '𖫗',
BassaVah::LetterKpah => '𖫘',
BassaVah::LetterJo => '𖫙',
BassaVah::LetterHwah => '𖫚',
BassaVah::LetterWa => '𖫛',
BassaVah::LetterZo => '𖫜',
BassaVah::LetterGbu => '𖫝',
BassaVah::LetterDo => '𖫞',
BassaVah::LetterCe => '𖫟',
BassaVah::LetterUwu => '𖫠',
BassaVah::LetterTo => '𖫡',
BassaVah::LetterBa => '𖫢',
BassaVah::LetterVu => '𖫣',
BassaVah::LetterYein => '𖫤',
BassaVah::LetterPa => '𖫥',
BassaVah::LetterWadda => '𖫦',
BassaVah::LetterA => '𖫧',
BassaVah::LetterO => '𖫨',
BassaVah::LetterOo => '𖫩',
BassaVah::LetterU => '𖫪',
BassaVah::LetterEe => '𖫫',
BassaVah::LetterE => '𖫬',
BassaVah::LetterI => '𖫭',
BassaVah::CombiningHighTone => '𖫰',
BassaVah::CombiningLowTone => '𖫱',
BassaVah::CombiningMidTone => '𖫲',
BassaVah::CombiningLowDashMidTone => '𖫳',
BassaVah::CombiningHighDashLowTone => '𖫴',
BassaVah::FullStop => '𖫵',
}
}
}
impl std::convert::TryFrom<char> for BassaVah {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'𖫐' => Ok(BassaVah::LetterEnni),
'𖫑' => Ok(BassaVah::LetterKa),
'𖫒' => Ok(BassaVah::LetterSe),
'𖫓' => Ok(BassaVah::LetterFa),
'𖫔' => Ok(BassaVah::LetterMbe),
'𖫕' => Ok(BassaVah::LetterYie),
'𖫖' => Ok(BassaVah::LetterGah),
'𖫗' => Ok(BassaVah::LetterDhii),
'𖫘' => Ok(BassaVah::LetterKpah),
'𖫙' => Ok(BassaVah::LetterJo),
'𖫚' => Ok(BassaVah::LetterHwah),
'𖫛' => Ok(BassaVah::LetterWa),
'𖫜' => Ok(BassaVah::LetterZo),
'𖫝' => Ok(BassaVah::LetterGbu),
'𖫞' => Ok(BassaVah::LetterDo),
'𖫟' => Ok(BassaVah::LetterCe),
'𖫠' => Ok(BassaVah::LetterUwu),
'𖫡' => Ok(BassaVah::LetterTo),
'𖫢' => Ok(BassaVah::LetterBa),
'𖫣' => Ok(BassaVah::LetterVu),
'𖫤' => Ok(BassaVah::LetterYein),
'𖫥' => Ok(BassaVah::LetterPa),
'𖫦' => Ok(BassaVah::LetterWadda),
'𖫧' => Ok(BassaVah::LetterA),
'𖫨' => Ok(BassaVah::LetterO),
'𖫩' => Ok(BassaVah::LetterOo),
'𖫪' => Ok(BassaVah::LetterU),
'𖫫' => Ok(BassaVah::LetterEe),
'𖫬' => Ok(BassaVah::LetterE),
'𖫭' => Ok(BassaVah::LetterI),
'𖫰' => Ok(BassaVah::CombiningHighTone),
'𖫱' => Ok(BassaVah::CombiningLowTone),
'𖫲' => Ok(BassaVah::CombiningMidTone),
'𖫳' => Ok(BassaVah::CombiningLowDashMidTone),
'𖫴' => Ok(BassaVah::CombiningHighDashLowTone),
'𖫵' => Ok(BassaVah::FullStop),
_ => Err(()),
}
}
}
impl Into<u32> for BassaVah {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for BassaVah {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for BassaVah {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl BassaVah {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
BassaVah::LetterEnni
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("BassaVah{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
fn main() {
cc::Build::new()
.cpp(true)
.file("include/farmhash.cc")
.flag("-O3")
.compile("libfarmhash.a");
}
|
use rppal::i2c::I2c;
use ssd1306::{Builder, mode::GraphicsMode, interface::DisplayInterface};
use rppal::gpio::Gpio;
use rppal::gpio::InputPin;
use rppal::gpio::Level;
mod launchkey;
mod menu;
struct Button {
pin: Box<InputPin>,
last_state: Level,
has_been_pressed: bool
}
impl Button {
fn new(pin: InputPin) -> Button {
let v = pin.read();
Button {
pin: Box::new(pin),
last_state: v,
has_been_pressed: v == Level::High
}
}
fn poll(&mut self) {
if self.pin.is_low() && self.last_state == Level::High {
self.has_been_pressed = true;
self.last_state = Level::Low;
} else if self.pin.is_high() {
self.has_been_pressed = false;
self.last_state = Level::High;
}
}
fn was_pressed(&mut self) -> bool {
if self.has_been_pressed {
self.has_been_pressed = false;
return true;
} else {
return false;
}
}
}
struct ButtonSet {
a: Button,
b: Button,
c: Button,
up: Button,
down: Button,
left: Button,
right: Button
}
impl ButtonSet {
fn poll_all(&mut self) {
self.a.poll();
self.b.poll();
self.c.poll();
self.up.poll();
self.down.poll();
self.left.poll();
self.right.poll();
}
}
fn main() {
let mut last_pin = false;
let mut i2c = I2c::new().expect("Could not create I2C Device");
i2c.set_slave_address(0x3c).expect("Could not select device");
let mut disp: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into();
disp.init().expect("Could not init device");
let launchkey = launchkey::LaunchKey::new();
let mut main_menu = menu::Menu::new();
main_menu.add_entry("Terminal");
main_menu.add_entry("Network");
main_menu.add_entry("USBs");
main_menu.add_entry("Shutdown");
let gpio = Gpio::new().expect("Could not init board");
let get_button = |n: u8| {
return Button::new(gpio.get(n)
.expect("Could not get pin")
.into_input_pullup());
};
let mut buttons: ButtonSet = ButtonSet {
a: get_button(5),
b: get_button(6),
c: get_button(4),
up: get_button(17),
down: get_button(22),
left: get_button(23),
right: get_button(27) // ???
};
loop {
buttons.poll_all();
if buttons.a.was_pressed() { }
if buttons.b.was_pressed() { }
if buttons.c.was_pressed() { }
if buttons.left.was_pressed() { }
if buttons.right.was_pressed() { }
if buttons.up.was_pressed() { main_menu.prev_entry() }
if buttons.down.was_pressed() { main_menu.next_entry() }
disp.clear();
main_menu.render(&mut disp);
disp.flush();
}
}
|
use crate::{
backend::Token,
data::{SharedDataDispatcher, SharedDataOps},
examples::{data::ExampleData, note_local_certs},
utils::{shell_quote, shell_single_quote, url_encode},
};
use drogue_cloud_service_api::endpoints::Endpoints;
use patternfly_yew::*;
use yew::prelude::*;
#[derive(Clone, Debug, Properties, PartialEq, Eq)]
pub struct Props {
pub endpoints: Endpoints,
pub data: ExampleData,
pub token: Token,
}
pub struct CommandAndControl {
props: Props,
link: ComponentLink<Self>,
data_agent: SharedDataDispatcher<ExampleData>,
}
#[derive(Clone, Debug)]
pub enum Msg {
SetDrgToken(bool),
SetCommandEmptyMessage(bool),
SetCommandName(String),
SetCommandPayload(String),
}
impl Component for CommandAndControl {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
props,
link,
data_agent: SharedDataDispatcher::new(),
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Self::Message::SetCommandEmptyMessage(cmd_empty_message) => self
.data_agent
.update(move |data| data.cmd_empty_message = cmd_empty_message),
Self::Message::SetDrgToken(drg_token) => self
.data_agent
.update(move |data| data.drg_token = drg_token),
Self::Message::SetCommandName(name) => {
self.data_agent.update(|mut data| data.cmd_name = name)
}
Self::Message::SetCommandPayload(payload) => self
.data_agent
.update(|mut data| data.cmd_payload = payload),
}
true
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props != props {
self.props = props;
true
} else {
false
}
}
fn view(&self) -> Html {
let mut cards: Vec<_> = vec![html! {
<Alert
title="Command & control"
r#type=Type::Info inline=true
>
<Content>
<p>
{r#"Command & control, also known as "cloud-to-device messaging", is used to send messages back to a device. In order to test this,
you will need simulate a device, connecting to the cloud, and at the same time, a cloud side application, which sends data to a device"#}
</p>
<p>
{"For this you will need to have two different terminals open at the same time."}
</p>
</Content>
</Alert>
}];
let local_certs = self
.props
.data
.local_certs(self.props.endpoints.local_certs);
if let Some(http) = &self.props.endpoints.http {
let payload = match self.props.data.cmd_empty_message {
true => "".into(),
false => format!(
"echo {payload} | ",
payload = shell_single_quote(&self.props.data.payload)
),
};
let publish_http_cmd = format!(
r#"{payload}http --auth {auth} {certs}POST {url}/v1/foo?ct=30"#,
payload = payload,
url = http.url,
auth = shell_quote(format!(
"{device_id}@{app_id}:{password}",
app_id = self.props.data.app_id,
device_id = url_encode(&self.props.data.device_id),
password = &self.props.data.password,
)),
certs = local_certs
.then(|| "--verify build/certs/endpoints/root-cert.pem ")
.unwrap_or("")
);
cards.push(html!{
<Card title={html!{"Receive commands using HTTP long-polling"}}>
<div>
{r#"
A device can receive commands using HTTP long-polling, when it publishes data to the cloud. To do this, a device needs to inform the HTTP endpoint,
that it will wait for some seconds for the cloud to receive a command message, which then gets reported in the response of the publish message.
"#}
</div>
<div>
<Switch
checked=self.props.data.cmd_empty_message
label="Send empty message" label_off="Send example payload"
on_change=self.link.callback(|data| Msg::SetCommandEmptyMessage(data))
/>
</div>
<Alert title="Hurry up!" inline=true>
{r#"
This example will wait 30 seconds for the cloud side to send a command. If you don't execute the "send command" step before this timeout
expires, the device will stop waiting and return with an empty response.
"#}
</Alert>
<Clipboard code=true readonly=true variant=ClipboardVariant::Expandable value=publish_http_cmd/>
{note_local_certs(local_certs)}
</Card>
});
}
if let Some(mqtt) = &self.props.endpoints.mqtt {
let publish_mqtt_cmd = format!(
r#"mqtt sub -h {host} -p {port} -u '{device_id}@{app_id}' -pw '{password}' -s {certs}-t command/inbox/#"#,
host = mqtt.host,
port = mqtt.port,
app_id = &self.props.data.app_id,
device_id = shell_quote(url_encode(&self.props.data.device_id)),
password = shell_quote(&self.props.data.password),
certs = local_certs
.then(|| "--cafile build/certs/endpoints/root-cert.pem ")
.unwrap_or("")
);
cards.push(html!{
<Card title={html!{"Receive commands using MQTT subscriptions"}}>
<div>
{"Using MQTT, you can simply subscribe to commands."}
</div>
<Clipboard code=true readonly=true variant=ClipboardVariant::Expandable value=publish_mqtt_cmd/>
{note_local_certs(local_certs)}
</Card>
});
}
if let Some(cmd) = &self.props.endpoints.command_url {
let v = |value: &str| match value {
"" => InputState::Error,
_ => InputState::Default,
};
let token = match self.props.data.drg_token {
true => "$(drg whoami -t)",
false => self.props.token.access_token.as_str(),
};
let send_command_cmd = format!(
r#"echo {payload} | http POST {url}/api/command/v1alpha1/apps/{app}/devices/{device} command=={cmd} "Authorization:Bearer {token}""#,
payload = shell_single_quote(&self.props.data.cmd_payload),
url = cmd,
app = url_encode(&self.props.data.app_id),
device = url_encode(&self.props.data.device_id),
token = token,
cmd = shell_quote(&self.props.data.cmd_name),
);
cards.push(html!{
<Card title={html!{"Send a command"}}>
<div>
{r#"
Once the device is waiting for commands, you can send one.
"#}
</div>
<Form>
<FormGroup label="Command name">
<TextInput
value=&self.props.data.cmd_name
required=true
onchange=self.link.callback(|name|Msg::SetCommandName(name))
validator=Validator::from(v)
/>
</FormGroup>
<FormGroup label="Command payload">
<TextArea
value=&self.props.data.cmd_payload
onchange=self.link.callback(|payload|Msg::SetCommandPayload(payload))
/>
</FormGroup>
<FormGroup>
<Switch
checked=self.props.data.drg_token
label="Use 'drg' to get the access token" label_off="Show current token in example"
on_change=self.link.callback(|data| Msg::SetDrgToken(data))
/>
</FormGroup>
</Form>
<Clipboard code=true readonly=true variant=ClipboardVariant::Expandable value=send_command_cmd/>
</Card>
});
}
cards
.iter()
.map(|card| {
html! {<StackItem> { card.clone() } </StackItem>}
})
.collect()
}
}
|
pub trait TimeSystemExt {
/// Create a new time system. The time the system is created is used as the time
/// of the 0th frame.
fn new() -> Self;
/// Update the time system state, marking the beginning of a the next frame.
///
/// The instant that this method is called is taken as the reference time for
/// the frame that is about to be executed.
///
/// Timers will also be triggered during this function call if they are due
/// to trigger.
///
/// **Do not** call this function directly if you are using this through the
/// `riddle` crate.
///
/// # Example
///
/// ```
/// # use riddle_time::*; doctest::simple(|time_system| {
/// let frame_1 = time_system.frame_instant();
///
/// // A while later
/// # doctest::pump_for_secs(time_system, 1);
/// let frame_n = time_system.frame_instant();
///
/// assert_eq!(true, frame_n - frame_1 > std::time::Duration::from_secs(0));
/// # });
/// ```
fn process_frame(&self);
}
|
use bs58;
use super::validation::ValidationError;
pub trait FromBase58 {
fn from_base58(&self) -> Result<Vec<u8>, ValidationError>;
}
impl FromBase58 for str {
fn from_base58(&self) -> Result<Vec<u8>, ValidationError> {
bs58::decode(self)
.into_vec()
.map_err(|_| ValidationError(Some("Error decoding base58 string".to_owned())))
}
}
pub trait ToBase58 {
fn to_base58(&self) -> String;
}
impl ToBase58 for [u8] {
fn to_base58(&self) -> String {
bs58::encode(self).into_string()
}
}
|
//! Wires up the application.
#![feature(associated_consts)]
#![allow(warnings)]
#![feature(plugin)]
#![cfg_attr(test, plugin(stainless))]
#[macro_use] extern crate conrod;
extern crate yaml_rust;
extern crate notify;
mod data;
mod interface;
mod util;
pub fn main() {
let data = data::Data::new();
interface::Interface::new(&data)
.show();
}
|
// Copyright 2019 The vault713 Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(test)]
use super::is_test_mode;
use super::message::*;
use super::swap;
use super::swap::{tx_add_input, tx_add_output, Swap};
use super::types::*;
use super::{ErrorKind, Keychain, CURRENT_VERSION};
use crate::api_impl::owner_eth::get_eth_balance;
use crate::grin_core::core::Committed;
use crate::grin_core::core::KernelFeatures;
use crate::grin_core::libtx::{build, proof, tx_fee};
use crate::grin_keychain::{BlindSum, BlindingFactor, SwitchCommitmentType};
use crate::grin_util::secp::aggsig;
use crate::grin_util::secp::key::{PublicKey, SecretKey};
use crate::grin_util::secp::pedersen::RangeProof;
use crate::swap::bitcoin::BtcData;
use crate::swap::ethereum::{EthData, EthereumWallet};
use crate::swap::fsm::state::StateId;
use crate::swap::multisig::{Builder as MultisigBuilder, ParticipantData as MultisigParticipant};
use crate::{NodeClient, ParticipantData as TxParticipant, Slate, SlateVersion, VersionedSlate};
use rand::thread_rng;
use std::mem;
use uuid::Uuid;
/// Buyer API. Bunch of methods that cover buyer action for MWC swap
/// This party is Buying MWC and selling BTC
pub struct BuyApi {}
impl BuyApi {
/// Accepting Seller offer and create Swap instance
pub fn accept_swap_offer<C: NodeClient, K: Keychain>(
ethereum_wallet: Option<EthereumWallet>,
keychain: &K,
context: &Context,
id: Uuid,
offer: OfferUpdate,
secondary_update: SecondaryUpdate,
node_client: &C,
) -> Result<Swap, ErrorKind> {
if offer.version != CURRENT_VERSION {
return Err(ErrorKind::IncompatibleVersion(
offer.version,
CURRENT_VERSION,
));
}
// Checking if the network match expected value
if offer.network != Network::current_network()? {
return Err(ErrorKind::UnexpectedNetwork(format!(
", get offer for wrong network {:?}",
offer.network
)));
}
context.unwrap_buyer()?;
let now_ts = swap::get_cur_time();
// Tolerating 15 seconds clock difference. We don't want surprises with clocks.
if offer.start_time.timestamp() > (now_ts + 15) {
return Err(ErrorKind::InvalidMessageData(
"Buyer/Seller clock are out of sync".to_string(),
));
}
// Multisig tx needs to be unlocked and valid. Let's take a look at what we get.
let lock_slate: Slate = offer.lock_slate.into_slate_plain()?;
if lock_slate.lock_height > 0 {
return Err(ErrorKind::InvalidLockHeightLockTx);
}
if lock_slate.amount != offer.primary_amount {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate amount doesn't match offer".to_string(),
));
}
if lock_slate.fee
!= tx_fee(
lock_slate.tx.body.inputs.len(),
lock_slate.tx.body.outputs.len() + 1,
1,
None,
) {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate fee doesn't match expected value".to_string(),
));
}
if lock_slate.num_participants != 2 {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate participans doesn't match expected value".to_string(),
));
}
if lock_slate.tx.body.kernels.len() != 1 {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate invalid kernels".to_string(),
));
}
match lock_slate.tx.body.kernels[0].features {
KernelFeatures::Plain { fee } => {
if fee != lock_slate.fee {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate invalid kernel fee".to_string(),
));
}
}
_ => {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate invalid kernel feature".to_string(),
))
}
}
// Let's check inputs. They must exist, we want real inspent coins. We can't check amount, that will be later when we cound validate the sum.
// Height of the inputs is not important, we are relaying on locking transaction confirmations that is weaker.
if lock_slate.tx.body.inputs.is_empty() {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate empty inputs".to_string(),
));
}
let res = node_client.get_outputs_from_node(&lock_slate.tx.inputs_committed())?;
if res.len() != lock_slate.tx.body.inputs.len() {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate inputs are not found at the chain".to_string(),
));
}
let height = node_client.get_chain_tip()?.0;
if lock_slate.height > height {
return Err(ErrorKind::InvalidMessageData(
"Lock Slate height is invalid".to_string(),
));
}
// Checking Refund slate.
// Refund tx needs to be locked until exactly as offer specify. For MWC we are expecting one block every 1 minute.
// So numbers should match with accuracy of few blocks.
// Note!!! We can't valiry exact number because we don't know what height seller get when he created the offer
let refund_slate: Slate = offer.refund_slate.into_slate_plain()?;
// expecting at least half of the interval
// Lock_height will be verified later
if refund_slate.tx.body.kernels.len() != 1 {
return Err(ErrorKind::InvalidMessageData(
"Refund Slate invalid kernel".to_string(),
));
}
match refund_slate.tx.body.kernels[0].features {
KernelFeatures::HeightLocked { fee, lock_height } => {
if fee != refund_slate.fee || lock_height != refund_slate.lock_height {
return Err(ErrorKind::InvalidMessageData(
"Refund Slate invalid kernel fee or height".to_string(),
));
}
}
_ => {
return Err(ErrorKind::InvalidMessageData(
"Refund Slate invalid kernel feature".to_string(),
))
}
}
if refund_slate.num_participants != 2 {
return Err(ErrorKind::InvalidMessageData(
"Refund Slate participans doesn't match expected value".to_string(),
));
}
if refund_slate.amount + refund_slate.fee != lock_slate.amount {
return Err(ErrorKind::InvalidMessageData(
"Refund Slate amount doesn't match offer".to_string(),
));
}
if refund_slate.fee != tx_fee(1, 1, 1, None) {
return Err(ErrorKind::InvalidMessageData(
"Refund Slate fee doesn't match expected value".to_string(),
));
}
// Checking Secondary data. Focus on timing issues
match offer.secondary_currency {
Currency::Btc
| Currency::Bch
| Currency::Ltc
| Currency::Dash
| Currency::ZCash
| Currency::Doge
| Currency::Ether
| Currency::Busd
| Currency::Bnb
| Currency::Link
| Currency::Dai
| Currency::Tusd
| Currency::Usdp
| Currency::Wbtc
| Currency::Usdt
| Currency::Usdc
| Currency::Trx
| Currency::Tst => (),
}
// Start redeem slate
let mut redeem_slate = Slate::blank(2, false);
#[cfg(test)]
if is_test_mode() {
redeem_slate.id = Uuid::parse_str("78aa5af1-048e-4c49-8776-a2e66d4a460c").unwrap()
}
redeem_slate.fee = tx_fee(1, 1, 1, None);
redeem_slate.height = height;
redeem_slate.amount = offer.primary_amount.saturating_sub(redeem_slate.fee);
redeem_slate.participant_data.push(offer.redeem_participant);
let multisig = MultisigBuilder::new(
2,
offer.primary_amount, // !!! It is amount that will be put into transactions. It is primary what need to be validated
false,
1,
context.multisig_nonce.clone(),
None,
);
let started = offer.start_time.clone();
let secondary_fee = offer.secondary_currency.get_default_fee(&offer.network);
if !offer.secondary_currency.is_btc_family() {
let balance_gwei = get_eth_balance(ethereum_wallet.unwrap())?;
if secondary_fee > balance_gwei as f32 {
return Err(
ErrorKind::Generic("No enough ether as gas for swap".to_string()).into(),
);
}
}
let mut swap = match offer.secondary_currency.is_btc_family() {
true => {
let btc_data = BtcData::from_offer(
keychain,
secondary_update.unwrap_btc()?.unwrap_offer()?,
context.unwrap_buyer()?.unwrap_btc()?,
)?;
let redeem_public = Some(PublicKey::from_secret_key(
keychain.secp(),
&Self::redeem_secret(keychain, context)?,
)?);
Swap {
id,
version: CURRENT_VERSION,
network: offer.network,
role: Role::Buyer(None),
communication_method: offer.communication_method,
communication_address: offer.from_address,
seller_lock_first: offer.seller_lock_first,
started,
state: StateId::BuyerOfferCreated,
primary_amount: offer.primary_amount,
secondary_amount: offer.secondary_amount,
secondary_currency: offer.secondary_currency,
secondary_data: SecondaryData::Btc(btc_data),
redeem_public,
participant_id: 1,
multisig,
lock_slate,
refund_slate,
redeem_slate,
redeem_kernel_updated: false,
adaptor_signature: None,
mwc_confirmations: offer.mwc_confirmations,
secondary_confirmations: offer.secondary_confirmations,
message_exchange_time_sec: offer.message_exchange_time_sec,
redeem_time_sec: offer.redeem_time_sec,
message1: None,
message2: None,
posted_msg1: None,
posted_msg2: None,
posted_lock: None,
posted_redeem: None,
posted_refund: None,
posted_secondary_height: None,
journal: Vec::new(),
secondary_fee,
electrum_node_uri1: None, // User need to review the offer first. Then to electrumX uri can be updated
electrum_node_uri2: None,
eth_swap_contract_address: None,
erc20_swap_contract_address: None,
eth_infura_project_id: None,
eth_redirect_to_private_wallet: Some(false),
last_process_error: None,
last_check_error: None,
wait_for_backup1: false,
tag: None,
other_lock_first_done: false,
}
}
_ => {
let eth_data = EthData::from_offer(
secondary_update.unwrap_eth()?.unwrap_offer()?,
context.unwrap_buyer()?.unwrap_eth()?,
)?;
let redeem_public = Some(PublicKey::from_secret_key(
keychain.secp(),
&Self::redeem_secret(keychain, context)?,
)?);
Swap {
id,
version: CURRENT_VERSION,
network: offer.network,
role: Role::Buyer(None),
communication_method: offer.communication_method,
communication_address: offer.from_address,
seller_lock_first: offer.seller_lock_first,
started,
state: StateId::BuyerOfferCreated,
primary_amount: offer.primary_amount,
secondary_amount: offer.secondary_amount,
secondary_currency: offer.secondary_currency,
secondary_data: SecondaryData::Eth(eth_data),
redeem_public,
participant_id: 1,
multisig,
lock_slate,
refund_slate,
redeem_slate,
redeem_kernel_updated: false,
adaptor_signature: None,
mwc_confirmations: offer.mwc_confirmations,
secondary_confirmations: offer.secondary_confirmations,
message_exchange_time_sec: offer.message_exchange_time_sec,
redeem_time_sec: offer.redeem_time_sec,
message1: None,
message2: None,
posted_msg1: None,
posted_msg2: None,
posted_lock: None,
posted_redeem: None,
posted_refund: None,
posted_secondary_height: None,
journal: Vec::new(),
secondary_fee,
electrum_node_uri1: None, // User need to review the offer first. Then to electrumX uri can be updated
electrum_node_uri2: None,
eth_swap_contract_address: None,
erc20_swap_contract_address: None,
eth_infura_project_id: None,
eth_redirect_to_private_wallet: Some(false),
last_process_error: None,
last_check_error: None,
wait_for_backup1: false,
tag: None,
other_lock_first_done: false,
}
}
};
swap.add_journal_message("Received a swap offer".to_string());
// Minimum mwc heights
let expected_lock_height = height + (swap.get_time_mwc_lock() - now_ts) as u64 / 60;
if swap.refund_slate.lock_height < expected_lock_height * 9 / 10 {
return Err(ErrorKind::InvalidMessageData(
"Refund lock slate doesn't meet required number of confirmations".to_string(),
));
}
Self::build_multisig(keychain, &mut swap, context, offer.multisig)?;
Self::sign_lock_slate(keychain, &mut swap, context)?;
Self::sign_refund_slate(keychain, &mut swap, context)?;
Ok(swap)
}
/// Buyer builds swap.redeem_slate
pub fn init_redeem<K: Keychain>(
keychain: &K,
swap: &mut Swap,
context: &Context,
) -> Result<(), ErrorKind> {
assert!(!swap.is_seller());
Self::build_redeem_slate(keychain, swap, context)?;
Self::calculate_adaptor_signature(keychain, swap, context)?;
Ok(())
}
/// Generate 'Accept offer' massage
pub fn accept_offer_message(
swap: &Swap,
inner_secondary: SecondaryUpdate,
) -> Result<Message, ErrorKind> {
let id = swap.participant_id;
swap.message(
Update::AcceptOffer(AcceptOfferUpdate {
multisig: swap.multisig.export()?,
redeem_public: swap
.redeem_public
.clone()
.ok_or(ErrorKind::Generic("redeem_public is empty".to_string()))?,
lock_participant: swap.lock_slate.participant_data[id].clone(),
refund_participant: swap.refund_slate.participant_data[id].clone(),
}),
inner_secondary,
)
}
/// Generate 'InitRedeem' slate message
pub fn init_redeem_message(swap: &Swap) -> Result<Message, ErrorKind> {
swap.message(
Update::InitRedeem(InitRedeemUpdate {
redeem_slate: VersionedSlate::into_version_plain(
swap.redeem_slate.clone(),
SlateVersion::V2, // V2 should satify our needs, dont adding extra
)?,
adaptor_signature: swap.adaptor_signature.ok_or(ErrorKind::UnexpectedAction(
"Buyer Fn init_redeem_message(), multisig is empty".to_string(),
))?,
}),
SecondaryUpdate::Empty,
)
}
/// Secret that unlocks the funds on both chains
pub fn redeem_secret<K: Keychain>(
keychain: &K,
context: &Context,
) -> Result<SecretKey, ErrorKind> {
let bcontext = context.unwrap_buyer()?;
let sec_key = keychain.derive_key(0, &bcontext.redeem, SwitchCommitmentType::None)?;
Ok(sec_key)
}
fn build_multisig<K: Keychain>(
keychain: &K,
swap: &mut Swap,
context: &Context,
part: MultisigParticipant,
) -> Result<(), ErrorKind> {
let multisig_secret = swap.multisig_secret(keychain, context)?;
let multisig = &mut swap.multisig;
// Import participant
multisig.import_participant(0, &part)?;
multisig.create_participant(keychain.secp(), &multisig_secret)?;
multisig.round_1_participant(0, &part)?;
// Round 1 + round 2
multisig.round_1(keychain.secp(), &multisig_secret)?;
let common_nonce = swap.common_nonce()?;
let multisig = &mut swap.multisig;
multisig.common_nonce = Some(common_nonce);
multisig.round_2(keychain.secp(), &multisig_secret)?;
Ok(())
}
/// Convenience function to calculate the secret that is used for signing the lock slate
fn lock_tx_secret<K: Keychain>(
keychain: &K,
swap: &Swap,
context: &Context,
) -> Result<SecretKey, ErrorKind> {
// Partial multisig output
let sum = BlindSum::new().add_blinding_factor(BlindingFactor::from_secret_key(
swap.multisig_secret(keychain, context)?,
));
let sec_key = keychain.blind_sum(&sum)?.secret_key()?;
Ok(sec_key)
}
fn sign_lock_slate<K: Keychain>(
keychain: &K,
swap: &mut Swap,
context: &Context,
) -> Result<(), ErrorKind> {
let mut sec_key = Self::lock_tx_secret(keychain, swap, context)?;
// This function should only be called once
let slate = &mut swap.lock_slate;
if slate.participant_data.len() > 1 {
return Err(ErrorKind::OneShot(
"Buyer Fn sign_lock_slate(), lock slate participant data is already initialized"
.to_string(),
)
.into());
}
// Add multisig output to slate (with invalid proof)
let mut proof = RangeProof::zero();
proof.plen = crate::grin_util::secp::constants::MAX_PROOF_SIZE;
tx_add_output(slate, swap.multisig.commit(keychain.secp())?, proof);
// Sign slate
slate.fill_round_1(
keychain,
&mut sec_key,
&context.lock_nonce,
swap.participant_id,
None,
false,
)?;
slate.fill_round_2(
keychain.secp(),
&sec_key,
&context.lock_nonce,
swap.participant_id,
)?;
Ok(())
}
/// Convenience function to calculate the secret that is used for signing the refund slate
fn refund_tx_secret<K: Keychain>(
keychain: &K,
swap: &Swap,
context: &Context,
) -> Result<SecretKey, ErrorKind> {
// Partial multisig input
let sum = BlindSum::new().sub_blinding_factor(BlindingFactor::from_secret_key(
swap.multisig_secret(keychain, context)?,
));
let sec_key = keychain.blind_sum(&sum)?.secret_key()?;
Ok(sec_key)
}
fn sign_refund_slate<K: Keychain>(
keychain: &K,
swap: &mut Swap,
context: &Context,
) -> Result<(), ErrorKind> {
let commit = swap.multisig.commit(keychain.secp())?;
let mut sec_key = Self::refund_tx_secret(keychain, swap, context)?;
// This function should only be called once
let slate = &mut swap.refund_slate;
if slate.participant_data.len() > 1 {
return Err(ErrorKind::OneShot("Buyer Fn sign_refund_slate(), refund slate participant data is already initialized".to_string()).into());
}
// Add multisig input to slate
tx_add_input(slate, commit);
// Sign slate
slate.fill_round_1(
keychain,
&mut sec_key,
&context.refund_nonce,
swap.participant_id,
None,
false,
)?;
slate.fill_round_2(
keychain.secp(),
&sec_key,
&context.refund_nonce,
swap.participant_id,
)?;
Ok(())
}
/// Convenience function to calculate the secret that is used for signing the redeem slate
pub fn redeem_tx_secret<K: Keychain>(
keychain: &K,
swap: &Swap,
context: &Context,
) -> Result<SecretKey, ErrorKind> {
let bcontext = context.unwrap_buyer()?;
// Partial multisig input, redeem output, offset
let sum = BlindSum::new()
.add_key_id(bcontext.output.to_value_path(swap.redeem_slate.amount))
.sub_blinding_factor(BlindingFactor::from_secret_key(
swap.multisig_secret(keychain, context)?,
))
.sub_blinding_factor(swap.redeem_slate.tx.offset.clone());
let sec_key = keychain.blind_sum(&sum)?.secret_key()?;
Ok(sec_key)
}
fn build_redeem_slate<K: Keychain>(
keychain: &K,
swap: &mut Swap,
context: &Context,
) -> Result<(), ErrorKind> {
let bcontext = context.unwrap_buyer()?;
// This function should only be called once
let slate = &mut swap.redeem_slate;
if slate.participant_data.len() > 1 {
return Err(ErrorKind::OneShot(
"Buyer Fn build_redeem_slate(), redeem slate participant data is not empty"
.to_string(),
));
}
// Build slate
slate.fee = tx_fee(1, 1, 1, None);
slate.amount = swap.primary_amount - slate.fee;
let mut elems = Vec::new();
elems.push(build::output(slate.amount, bcontext.output.clone()));
slate.add_transaction_elements(keychain, &proof::ProofBuilder::new(keychain), elems)?;
#[cfg(test)]
{
slate.tx.offset = if is_test_mode() {
BlindingFactor::from_hex(
"90de4a3812c7b78e567548c86926820d838e7e0b43346b1ba63066cd5cc7d999",
)
.unwrap()
} else {
BlindingFactor::from_secret_key(SecretKey::new(&mut thread_rng()))
};
}
// Release Doesn't have any tweaking
#[cfg(not(test))]
{
slate.tx.offset = BlindingFactor::from_secret_key(SecretKey::new(&mut thread_rng()));
}
// Add multisig input to slate
tx_add_input(slate, swap.multisig.commit(keychain.secp())?);
let mut sec_key = Self::redeem_tx_secret(keychain, swap, context)?;
let slate = &mut swap.redeem_slate;
// Add participant to slate
slate.fill_round_1(
keychain,
&mut sec_key,
&context.redeem_nonce,
swap.participant_id,
None,
false,
)?;
Ok(())
}
/// Finalize redeem slate with a data from the message
pub fn finalize_redeem_slate<K: Keychain>(
keychain: &K,
swap: &mut Swap,
context: &Context,
part: TxParticipant,
) -> Result<(), ErrorKind> {
let id = swap.participant_id;
let other_id = swap.other_participant_id();
let sec_key = Self::redeem_tx_secret(keychain, swap, context)?;
// This function should only be called once
let slate = &mut swap.redeem_slate;
if slate
.participant_data
.get(id)
.ok_or(ErrorKind::UnexpectedAction("Buyer Fn finalize_redeem_slate() redeem slate participant data is not initialized for this party".to_string()))?
.is_complete()
{
return Err(ErrorKind::OneShot("Buyer Fn finalize_redeem_slate() redeem slate is already initialized".to_string()).into());
}
// Replace participant
let _ = mem::replace(
slate
.participant_data
.get_mut(other_id)
.ok_or(ErrorKind::UnexpectedAction("Buyer Fn finalize_redeem_slate() redeem slate participant data is not initialized for other party".to_string()))?,
part,
);
// Sign + finalize slate
slate.fill_round_2(
keychain.secp(),
&sec_key,
&context.redeem_nonce,
swap.participant_id,
)?;
slate.finalize(keychain)?;
Ok(())
}
fn calculate_adaptor_signature<K: Keychain>(
keychain: &K,
swap: &mut Swap,
context: &Context,
) -> Result<(), ErrorKind> {
// This function should only be called once
if swap.adaptor_signature.is_some() {
return Err(ErrorKind::OneShot(
"Buyer calculate_adaptor_signature(), miltisig is already initialized".to_string(),
));
}
let sec_key = Self::redeem_tx_secret(keychain, swap, context)?;
let (pub_nonce_sum, pub_blind_sum, message) = swap.redeem_tx_fields(&swap.redeem_slate)?;
let adaptor_signature = aggsig::sign_single(
keychain.secp(),
&message,
&sec_key,
Some(&context.redeem_nonce),
Some(&Self::redeem_secret(keychain, context)?),
Some(&pub_nonce_sum),
Some(&pub_blind_sum),
Some(&pub_nonce_sum),
)?;
swap.adaptor_signature = Some(adaptor_signature);
Ok(())
}
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
#![warn(missing_docs)]
//! Disk graph storage
use std::sync::Arc;
use crate::{model::{WindowsAlignedFileReader, IOContext, AlignedRead}, common::ANNResult};
/// Graph storage for disk index
/// One thread has one storage instance
pub struct DiskGraphStorage {
/// Disk graph reader
disk_graph_reader: Arc<WindowsAlignedFileReader>,
/// IOContext of current thread
ctx: Arc<IOContext>,
}
impl DiskGraphStorage {
/// Create a new DiskGraphStorage instance
pub fn new(disk_graph_reader: Arc<WindowsAlignedFileReader>) -> ANNResult<Self> {
let ctx = disk_graph_reader.get_ctx()?;
Ok(Self {
disk_graph_reader,
ctx,
})
}
/// Read disk graph data
pub fn read<T>(&self, read_requests: &mut [AlignedRead<T>]) -> ANNResult<()> {
self.disk_graph_reader.read(read_requests, &self.ctx)
}
}
|
fn bottle_count<'a>(count: u8) -> String {
match count {
1 => String::from("1 bottle"),
_ => format!("{} bottles", count),
}
}
pub fn verse<'a>(count: u8) -> String {
match count {
0 => String::from("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"),
1 => String::from("1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n"),
_ => format!("{0} of beer on the wall, {0} of beer.\nTake one down and pass it around, {1} of beer on the wall.\n", bottle_count(count), bottle_count(count - 1)),
}
}
pub fn sing<'a>(start: u8, end: u8) -> String {
(end..start + 1)
.map(|count| verse(count))
.rev()
.collect::<Vec<String>>()
.join("\n")
} |
use super::ExtractedSyntaxGrammar;
use crate::generate::grammars::{Variable, VariableType};
use crate::generate::rules::{Rule, Symbol};
use std::collections::HashMap;
use std::mem;
struct Expander {
variable_name: String,
repeat_count_in_variable: usize,
preceding_symbol_count: usize,
auxiliary_variables: Vec<Variable>,
existing_repeats: HashMap<Rule, Symbol>,
}
impl Expander {
fn expand_variable(&mut self, index: usize, variable: &mut Variable) -> bool {
self.variable_name.clear();
self.variable_name.push_str(&variable.name);
self.repeat_count_in_variable = 0;
let mut rule = Rule::Blank;
mem::swap(&mut rule, &mut variable.rule);
// In the special case of a hidden variable with a repetition at its top level,
// convert that rule itself into a binary tree structure instead of introducing
// another auxiliary rule.
if let (VariableType::Hidden, Rule::Repeat(repeated_content)) = (variable.kind, &rule) {
let inner_rule = self.expand_rule(&repeated_content);
variable.rule = self.wrap_rule_in_binary_tree(Symbol::non_terminal(index), inner_rule);
variable.kind = VariableType::Auxiliary;
return true;
}
variable.rule = self.expand_rule(&rule);
false
}
fn expand_rule(&mut self, rule: &Rule) -> Rule {
match rule {
// For choices, sequences, and metadata, descend into the child rules,
// replacing any nested repetitions.
Rule::Choice(elements) => Rule::Choice(
elements
.iter()
.map(|element| self.expand_rule(element))
.collect(),
),
Rule::Seq(elements) => Rule::Seq(
elements
.iter()
.map(|element| self.expand_rule(element))
.collect(),
),
Rule::Metadata { rule, params } => Rule::Metadata {
rule: Box::new(self.expand_rule(rule)),
params: params.clone(),
},
// For repetitions, introduce an auxiliary rule that contains the the
// repeated content, but can also contain a recursive binary tree structure.
Rule::Repeat(content) => {
let inner_rule = self.expand_rule(content);
if let Some(existing_symbol) = self.existing_repeats.get(&inner_rule) {
return Rule::Symbol(*existing_symbol);
}
self.repeat_count_in_variable += 1;
let rule_name = format!(
"{}_repeat{}",
self.variable_name, self.repeat_count_in_variable
);
let repeat_symbol = Symbol::non_terminal(
self.preceding_symbol_count + self.auxiliary_variables.len(),
);
self.existing_repeats
.insert(inner_rule.clone(), repeat_symbol);
self.auxiliary_variables.push(Variable {
name: rule_name,
kind: VariableType::Auxiliary,
rule: self.wrap_rule_in_binary_tree(repeat_symbol, inner_rule),
});
Rule::Symbol(repeat_symbol)
}
// For primitive rules, don't change anything.
_ => rule.clone(),
}
}
fn wrap_rule_in_binary_tree(&self, symbol: Symbol, rule: Rule) -> Rule {
Rule::choice(vec![
Rule::Seq(vec![Rule::Symbol(symbol), Rule::Symbol(symbol)]),
rule,
])
}
}
pub(super) fn expand_repeats(mut grammar: ExtractedSyntaxGrammar) -> ExtractedSyntaxGrammar {
let mut expander = Expander {
variable_name: String::new(),
repeat_count_in_variable: 0,
preceding_symbol_count: grammar.variables.len(),
auxiliary_variables: Vec::new(),
existing_repeats: HashMap::new(),
};
for (i, mut variable) in grammar.variables.iter_mut().enumerate() {
let expanded_top_level_repetition = expander.expand_variable(i, &mut variable);
// If a hidden variable had a top-level repetition and it was converted to
// a recursive rule, then it can't be inlined.
if expanded_top_level_repetition {
grammar
.variables_to_inline
.retain(|symbol| *symbol != Symbol::non_terminal(i));
}
}
grammar
.variables
.extend(expander.auxiliary_variables.into_iter());
grammar
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_repeat_expansion() {
// Repeats nested inside of sequences and choices are expanded.
let grammar = expand_repeats(build_grammar(vec![Variable::named(
"rule0",
Rule::seq(vec![
Rule::terminal(10),
Rule::choice(vec![
Rule::repeat(Rule::terminal(11)),
Rule::repeat(Rule::terminal(12)),
]),
Rule::terminal(13),
]),
)]));
assert_eq!(
grammar.variables,
vec![
Variable::named(
"rule0",
Rule::seq(vec![
Rule::terminal(10),
Rule::choice(vec![Rule::non_terminal(1), Rule::non_terminal(2),]),
Rule::terminal(13),
])
),
Variable::auxiliary(
"rule0_repeat1",
Rule::choice(vec![
Rule::seq(vec![Rule::non_terminal(1), Rule::non_terminal(1),]),
Rule::terminal(11),
])
),
Variable::auxiliary(
"rule0_repeat2",
Rule::choice(vec![
Rule::seq(vec![Rule::non_terminal(2), Rule::non_terminal(2),]),
Rule::terminal(12),
])
),
]
);
}
#[test]
fn test_repeat_deduplication() {
// Terminal 4 appears inside of a repeat in three different places.
let grammar = expand_repeats(build_grammar(vec![
Variable::named(
"rule0",
Rule::choice(vec![
Rule::seq(vec![Rule::terminal(1), Rule::repeat(Rule::terminal(4))]),
Rule::seq(vec![Rule::terminal(2), Rule::repeat(Rule::terminal(4))]),
]),
),
Variable::named(
"rule1",
Rule::seq(vec![Rule::terminal(3), Rule::repeat(Rule::terminal(4))]),
),
]));
// Only one auxiliary rule is created for repeating terminal 4.
assert_eq!(
grammar.variables,
vec![
Variable::named(
"rule0",
Rule::choice(vec![
Rule::seq(vec![Rule::terminal(1), Rule::non_terminal(2)]),
Rule::seq(vec![Rule::terminal(2), Rule::non_terminal(2)]),
])
),
Variable::named(
"rule1",
Rule::seq(vec![Rule::terminal(3), Rule::non_terminal(2),])
),
Variable::auxiliary(
"rule0_repeat1",
Rule::choice(vec![
Rule::seq(vec![Rule::non_terminal(2), Rule::non_terminal(2),]),
Rule::terminal(4),
])
)
]
);
}
#[test]
fn test_expansion_of_nested_repeats() {
let grammar = expand_repeats(build_grammar(vec![Variable::named(
"rule0",
Rule::seq(vec![
Rule::terminal(10),
Rule::repeat(Rule::seq(vec![
Rule::terminal(11),
Rule::repeat(Rule::terminal(12)),
])),
]),
)]));
assert_eq!(
grammar.variables,
vec![
Variable::named(
"rule0",
Rule::seq(vec![Rule::terminal(10), Rule::non_terminal(2),])
),
Variable::auxiliary(
"rule0_repeat1",
Rule::choice(vec![
Rule::seq(vec![Rule::non_terminal(1), Rule::non_terminal(1),]),
Rule::terminal(12),
])
),
Variable::auxiliary(
"rule0_repeat2",
Rule::choice(vec![
Rule::seq(vec![Rule::non_terminal(2), Rule::non_terminal(2),]),
Rule::seq(vec![Rule::terminal(11), Rule::non_terminal(1),]),
])
),
]
);
}
#[test]
fn test_expansion_of_repeats_at_top_of_hidden_rules() {
let grammar = expand_repeats(build_grammar(vec![
Variable::named("rule0", Rule::non_terminal(1)),
Variable::hidden(
"_rule1",
Rule::repeat(Rule::choice(vec![Rule::terminal(11), Rule::terminal(12)])),
),
]));
assert_eq!(
grammar.variables,
vec![
Variable::named("rule0", Rule::non_terminal(1),),
Variable::auxiliary(
"_rule1",
Rule::choice(vec![
Rule::seq(vec![Rule::non_terminal(1), Rule::non_terminal(1)]),
Rule::terminal(11),
Rule::terminal(12),
]),
),
]
);
}
fn build_grammar(variables: Vec<Variable>) -> ExtractedSyntaxGrammar {
ExtractedSyntaxGrammar {
variables,
..Default::default()
}
}
}
|
/*
* Copyright (C) 2019 Intel Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
use std::collections::HashMap;
use std::collections::VecDeque;
use std::cell::RefCell;
fn main() {
let mut vector = Vec::from([1, 2, 3, 4]);
vector.push(12);
let mut map: HashMap<&str, f64> = HashMap::from([
("Mercury", 0.4),
("Venus", 0.7),
("Earth", 1.0),
("Mars", 1.5),
]);
map.insert("Venus", 2.5);
map.insert("Sun", 312.2);
let string = "this is a string";
let tmp = String::from("hello world");
let slice = &tmp[1..5];
let mut deque = VecDeque::from([1, 2, 3]);
deque.push_back(4);
deque.push_back(5);
let ref_cell = RefCell::new(5);
println!("Hello, world!"); // BP_MARKER_1
} |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//
// In an ideal world there would be a stable well documented set of crates containing a specific
// version of the Rust compiler along with its sources and debug information. We'd then just get
// those from crate.io and merely go on our way as just another Rust application. Rust compiler
// upgrades will be non events for Mirai until it is ready to jump to another release and old
// versions of Mirai will continue to work just as before.
//
// In the current world, however, we have to use the following hacky feature to get access to a
// private and not very stable set of APIs from whatever compiler is in the path when we run Mirai.
// While pretty bad, it is a lot less bad than having to write our own compiler, so here goes.
#![feature(rustc_private)]
#![feature(box_syntax)]
#![feature(vec_remove_item)]
extern crate mirai;
extern crate rustc_data_structures;
extern crate rustc_driver;
extern crate rustc_rayon;
extern crate syntax;
extern crate tempdir;
use mirai::callbacks;
use mirai::utils;
use rustc_rayon::iter::IntoParallelIterator;
use rustc_rayon::iter::ParallelIterator;
use std::fs;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use syntax::errors::{Diagnostic, DiagnosticBuilder};
use tempdir::TempDir;
// Run the tests in the tests/run-pass directory.
// Eventually, there will be separate test cases for other directories such as compile-fail.
#[test]
fn run_pass() {
let run_pass_path = PathBuf::from_str("tests/run-pass").unwrap();
assert_eq!(run_directory(run_pass_path), 0);
}
// Iterates through the files in the directory at the given path and runs each as a separate test
// case. For each case, a temporary output directory is created. The cases are then iterated in
// parallel and run via invoke_driver.
fn run_directory(directory_path: PathBuf) -> usize {
let sys_root = utils::find_sysroot();
let mut files_and_temp_dirs = Vec::new();
for entry in fs::read_dir(directory_path).expect("failed to read run-pass dir") {
let entry = entry.unwrap();
if !entry.file_type().unwrap().is_file() {
continue;
};
let file_path = entry.path();
let file_name = entry.file_name();
let temp_dir = TempDir::new("miraiTest").expect("failed to create a temp dir");
let temp_dir_path_buf = temp_dir.into_path();
let output_dir_path_buf = temp_dir_path_buf.join(file_name.into_string().unwrap());
fs::create_dir(output_dir_path_buf.as_path()).expect("failed to create test output dir");
files_and_temp_dirs.push((
file_path.into_os_string().into_string().unwrap(),
output_dir_path_buf.into_os_string().into_string().unwrap(),
));
}
files_and_temp_dirs
.into_par_iter()
.fold(
|| 0,
|acc, (file_name, temp_dir_path)| {
acc + self::invoke_driver(file_name, temp_dir_path, sys_root.clone())
},
)
.reduce(|| 0, |acc, code| acc + code)
}
// Runs the single test case found in file_name, using temp_dir_path as the place
// to put compiler output, which for Mirai includes the persistent summary store.
fn invoke_driver(file_name: String, temp_dir_path: String, sys_root: String) -> usize {
let f_name = file_name.clone();
let result = std::panic::catch_unwind(|| {
rustc_driver::run(|| {
let f_name = file_name.clone();
let command_line_arguments: Vec<String> = vec![
String::from("--crate-name mirai"),
file_name,
String::from("--crate-type"),
String::from("lib"),
String::from("-C"),
String::from("debuginfo=2"),
String::from("--out-dir"),
temp_dir_path,
String::from("--sysroot"),
sys_root,
String::from("-Z"),
String::from("span_free_formats"),
String::from("-Z"),
String::from("mir-emit-retag"),
String::from("-Z"),
String::from("mir-opt-level=0"),
];
let call_backs = callbacks::MiraiCallbacks::with_buffered_diagnostics(
box move |diagnostics| {
let mut expected_errors = ExpectedErrors::new(&f_name);
expected_errors.check_messages(diagnostics)
},
|db: &mut DiagnosticBuilder, buf: &mut Vec<Diagnostic>| {
db.cancel();
db.clone().buffer(buf);
},
);
rustc_driver::run_compiler(
&command_line_arguments,
box call_backs,
None, // use default file loader
None, // emit output to default destination
)
})
});
match result {
Ok(_) => 0,
Err(_) => {
println!("{} failed", f_name);
1
}
}
}
/// A collection of error strings that are expected for a test case.
struct ExpectedErrors {
messages: Vec<String>,
}
impl ExpectedErrors {
/// Reads the file at the given path and scans it for instances of "//~ message".
/// Each message becomes an element of ExpectedErrors.messages.
pub fn new(path: &str) -> ExpectedErrors {
let exp = load_errors(&PathBuf::from_str(&path).unwrap());
ExpectedErrors { messages: exp }
}
/// Checks if the given set of diagnostics matches the expected diagnostics.
pub fn check_messages(&mut self, diagnostics: &Vec<Diagnostic>) {
diagnostics.iter().for_each(|diag| {
self.remove_message(&diag.message());
for child in &diag.children {
self.remove_message(&child.message());
}
});
if self.messages.len() > 0 {
panic!("Expected errors not reported: {:?}", self.messages);
}
}
/// Removes the first element of self.messages and checks if it matches msg.
fn remove_message(&mut self, msg: &str) {
if self.messages.remove_item(&String::from(msg)).is_none() {
panic!("Unexpected error: {} Expected: {:?}", msg, self.messages);
}
}
}
/// Scans the contents of test file for patterns of the form "//~ message"
/// and returns a vector of the matching messages.
fn load_errors(testfile: &Path) -> Vec<String> {
let rdr = BufReader::new(File::open(testfile).unwrap());
let tag = "//~";
rdr.lines()
.enumerate()
.filter_map(|(_line_num, line)| parse_expected(&line.unwrap(), &tag))
.collect()
}
/// Returns the message part of the pattern "//~ message" if there is a match, otherwise None.
fn parse_expected(line: &str, tag: &str) -> Option<String> {
let start = line.find(tag)? + tag.len();
Some(String::from(line[start..].trim()))
}
|
use bevy::math::Vec3;
use bevy::reflect::TypeUuid;
use bevy::render::renderer::RenderResources;
#[derive(RenderResources, Default, TypeUuid)]
#[repr(C)]
#[uuid = "463e4b8a-d555-4fc2-ba9f-4c880063ba92"]
pub struct RayUniform {
pub camera_position: Vec3,
pub model_translation: Vec3,
pub light_translation: Vec3,
pub time: f32,
}
|
use std::os::raw::{c_int, c_uint, c_ulong};
use std::{ptr, slice};
use vpx_sys::vp8e_enc_control_id::*;
use vpx_sys::vpx_codec_cx_pkt_kind::VPX_CODEC_CX_FRAME_PKT;
use vpx_sys::*;
const ABI_VERSION: c_int = 14;
const DEADLINE: c_ulong = 1;
pub struct Encoder {
ctx: vpx_codec_ctx_t,
width: usize,
height: usize,
}
impl Encoder {
pub fn new(config: Config) -> Self {
let i = unsafe { vpx_codec_vp9_cx() };
assert!(config.width % 2 == 0);
assert!(config.height % 2 == 0);
let mut c = Default::default();
unsafe { vpx_codec_enc_config_default(i, &mut c, 0) }; //TODO: Error.
c.g_w = config.width;
c.g_h = config.height;
c.g_timebase.num = config.timebase[0];
c.g_timebase.den = config.timebase[1];
c.rc_target_bitrate = config.bitrate;
c.g_threads = 8;
c.g_error_resilient = VPX_ERROR_RESILIENT_DEFAULT;
let mut ctx = Default::default();
unsafe {
vpx_codec_enc_init_ver(&mut ctx, i, &c, 0, ABI_VERSION); //TODO: Error.
vpx_codec_control_(&mut ctx, VP8E_SET_CPUUSED as _, 6 as c_int); //TODO: Error.
vpx_codec_control_(&mut ctx, VP9E_SET_ROW_MT as _, 1 as c_int); //TODO: Error.
}
Self {
ctx,
width: config.width as usize,
height: config.height as usize,
}
}
pub fn encode(&mut self, pts: i64, data: &[u8]) -> Packets {
assert!(2 * data.len() >= 3 * self.width * self.height);
let mut image = Default::default();
unsafe {
vpx_img_wrap(
&mut image,
vpx_img_fmt::VPX_IMG_FMT_I420,
self.width as _,
self.height as _,
1,
data.as_ptr() as _,
);
}
unsafe {
vpx_codec_encode(
&mut self.ctx,
&image,
pts,
1, // Alignment
0, // Flags
DEADLINE,
); //TODO: Error.
}
Packets {
ctx: &mut self.ctx,
iter: ptr::null(),
}
}
pub fn finish(mut self) -> Finish {
unsafe {
vpx_codec_encode(
&mut self.ctx,
ptr::null(),
-1, // PTS
1, // Alignment
0, // Flags
DEADLINE,
); //TODO: Error.
}
Finish {
enc: self,
iter: ptr::null(),
}
}
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe {
let _ = vpx_codec_destroy(&mut self.ctx);
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct Frame<'a> {
/// Compressed data.
pub data: &'a [u8],
/// Whether the frame is a keyframe.
pub key: bool,
/// Presentation timestamp (in timebase units).
pub pts: i64,
}
#[derive(Clone, Copy, Debug)]
pub struct Config {
/// The width (in pixels).
pub width: c_uint,
/// The height (in pixels).
pub height: c_uint,
/// The timebase (in seconds).
pub timebase: [c_int; 2],
/// The target bitrate (in kilobits per second).
pub bitrate: c_uint,
}
pub struct Packets<'a> {
ctx: &'a mut vpx_codec_ctx_t,
iter: vpx_codec_iter_t,
}
impl<'a> Iterator for Packets<'a> {
type Item = Frame<'a>;
fn next(&mut self) -> Option<Self::Item> {
loop {
unsafe {
let pkt = vpx_codec_get_cx_data(self.ctx, &mut self.iter);
if pkt.is_null() {
return None;
} else if (*pkt).kind == VPX_CODEC_CX_FRAME_PKT {
let f = &(*pkt).data.frame;
return Some(Frame {
data: slice::from_raw_parts(f.buf as _, f.sz),
key: (f.flags & VPX_FRAME_IS_KEY) != 0,
pts: f.pts,
});
} else {
// Ignore the packet.
}
}
}
}
}
pub struct Finish {
enc: Encoder,
iter: vpx_codec_iter_t,
}
impl Finish {
pub fn next(&mut self) -> Option<Frame> {
let mut tmp = Packets {
ctx: &mut self.enc.ctx,
iter: self.iter,
};
if let Some(packet) = tmp.next() {
self.iter = tmp.iter;
Some(packet)
} else {
unsafe {
vpx_codec_encode(
tmp.ctx,
ptr::null(),
-1, // PTS
1, // Alignment
0, // Flags
DEADLINE,
); //TODO: Error.
}
tmp.iter = ptr::null();
if let Some(packet) = tmp.next() {
self.iter = tmp.iter;
Some(packet)
} else {
None
}
}
}
}
|
extern crate actix;
extern crate futures;
extern crate tokio_core;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use futures::{future, Future};
use tokio_core::reactor::Timeout;
use actix::prelude::*;
#[derive(Debug)]
struct Ping(usize);
impl actix::ResponseType for Ping {
type Item = ();
type Error = ();
}
struct MyActor(Arc<AtomicUsize>);
impl Actor for MyActor {
type Context = actix::Context<Self>;
}
impl actix::Handler<Ping> for MyActor {
type Result = ();
fn handle(&mut self, msg: Ping, _: &mut Self::Context) {
println!("PING: {:?}", msg);
self.0.store(self.0.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
}
}
struct MyActor2(Option<Address<MyActor>>, Option<SyncAddress<MyActor>>);
impl Actor for MyActor2 {
type Context = actix::Context<Self>;
fn started(&mut self, ctx: &mut actix::Context<Self>) {
self.0.take().unwrap().upgrade()
.actfuture()
.then(move |addr, act: &mut Self, _: &mut _| {
let addr = addr.unwrap();
addr.send(Ping(10));
act.1 = Some(addr);
Arbiter::system().send(actix::msgs::SystemExit(0));
actix::fut::ok(())
}).spawn(ctx);
}
}
struct MyActor3;
impl Actor for MyActor3 {
type Context = Context<Self>;
}
impl actix::Handler<Ping> for MyActor3 {
type Result = MessageResult<Ping>;
fn handle(&mut self, _: Ping, _: &mut actix::Context<MyActor3>) -> Self::Result {
Arbiter::system().send(actix::msgs::SystemExit(0));
Err(())
}
}
#[test]
fn test_address() {
let sys = System::new("test");
let count = Arc::new(AtomicUsize::new(0));
let addr: Address<_> = MyActor(Arc::clone(&count)).start();
let addr2 = addr.clone();
addr.send(Ping(0));
Arbiter::handle().spawn_fn(move || {
addr2.send(Ping(1));
Timeout::new(Duration::new(0, 100), Arbiter::handle()).unwrap()
.then(move |_| {
addr2.send(Ping(2));
Arbiter::system().send(actix::msgs::SystemExit(0));
future::result(Ok(()))
})
});
sys.run();
assert_eq!(count.load(Ordering::Relaxed), 3);
}
#[test]
fn test_sync_address() {
let sys = System::new("test");
let count = Arc::new(AtomicUsize::new(0));
let arbiter = Arbiter::new("sync-test");
let addr: SyncAddress<_> = MyActor(Arc::clone(&count)).start();
let addr2 = addr.clone();
let addr3 = addr.clone();
addr.send(Ping(1));
arbiter.send(actix::msgs::Execute::new(move || -> Result<(), ()> {
addr3.send(Ping(2));
Arbiter::system().send(actix::msgs::SystemExit(0));
Ok(())
}));
Arbiter::handle().spawn_fn(move || {
addr2.send(Ping(3));
Timeout::new(Duration::new(0, 100), Arbiter::handle()).unwrap()
.then(move |_| {
addr2.send(Ping(4));
future::result(Ok(()))
})
});
sys.run();
assert_eq!(count.load(Ordering::Relaxed), 4);
}
#[test]
fn test_address_upgrade() {
let sys = System::new("test");
let count = Arc::new(AtomicUsize::new(0));
let addr: Address<_> = MyActor(Arc::clone(&count)).start();
addr.send(Ping(0));
let addr2 = addr.clone();
let _addr3: Address<_> = MyActor2(Some(addr2), None).start();
Arbiter::handle().spawn_fn(move || {
Timeout::new(Duration::new(0, 1000), Arbiter::handle()).unwrap()
.then(move |_| {
addr.send(Ping(3));
Arbiter::handle().spawn_fn(move || {
Arbiter::system().send(actix::msgs::SystemExit(0));
future::result(Ok(()))
});
future::result(Ok(()))
})
});
sys.run();
assert_eq!(count.load(Ordering::Relaxed), 3);
}
#[test]
fn test_error_result() {
let sys = System::new("test");
let addr: Address<_> = MyActor3.start();
Arbiter::handle().spawn_fn(move || {
addr.call_fut(Ping(0)).then(|res| {
match res {
Ok(Err(_)) => (),
_ => panic!("Should not happen"),
}
futures::future::result(Ok(()))
})
});
sys.run();
}
|
use std::{thread, time};
pub use spacepacket::SpacePacket;
pub use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::net::{ UdpSocket};
use std::net::{ SocketAddr, Ipv4Addr, TcpStream};
use std::collections::HashMap;
use Config;
use std::io::prelude::*;
pub enum TlmCmds {
ShutdownCommand,
DestinationCommand{ addr: TcpStream},
SleepCommand{interval: u16},
RawCommand{raw: Vec<u8>},
}
// fn open_socket(address: String) -> Option<UdpSocket> {
// let socket = std::net::UdpSocket::bind(address);
// match socket {
// Ok(n) => Some(n),
// Err(_e) => None,
// }
// }
fn check_telemetry_service() -> bool {
let mut map = HashMap::new();
map.insert("query", "{ping}");
let client = reqwest::blocking::Client::new();
let telemetry_response = match client.post("http://127.0.0.1:8020/").json(&map).send() {
Ok(n) => match n.text() {
Ok(n) => n,
Err(_e) => return false,
},
Err(_e) => return false,
};
eprintln!("Telemetry service results:");
eprintln!("{:#?}", telemetry_response);
if telemetry_response.contains("pong") {
return true;
}
else {
return false;
}
}
fn get_eps_data(config: &Config) -> Option<Vec<u8>> {
if check_telemetry_service() == false {
eprintln!("Telemetry service is not running");
return None;
}
let bind_str = config.flag.ip.clone();
let eps_address_v4: Ipv4Addr = bind_str.parse().unwrap();
let socket = match eps_address_v4.is_loopback() {
true => match UdpSocket::bind("127.0.0.1:0") {
Ok(n) => n,
Err(_e) => { eprintln!("Unable to bind socket for flag data");
return None
},
},
false => match UdpSocket::bind("0.0.0.0:0") {
Ok(n) => n,
Err(_e) => { eprintln!("Unable to bind socket for flag data");
return None
},
},
};
let duration = std::time::Duration::new(4, 0);
let _res = socket.set_read_timeout(Some(duration));
let cmd = String::from("TELEMETRY");
let addr = SocketAddr::from((eps_address_v4, 6667));
match socket.send_to(cmd.as_bytes(), &addr) {
Ok(_n) => (),
Err(_e) => return None,
}
let mut buf = [0; 1024];
match socket.recv(&mut buf) {
Ok(_n) => Some(buf.to_vec()),
Err(_e) => None,
}
}
fn save_eps_to_db(_config: &Config, data: Vec<u8>) {
let mut_string = format!("{{\"query\":\"mutation {{insert(subsystem:\\\"eps\\\",parameter:\\\"current\\\",value:\\\"{}\\\"){{success}}}}\"}}", data[0]);
let client = reqwest::blocking::Client::new();
let telemetry_response = match client.post("http://127.0.0.1:8020/").body(mut_string).send() {
Ok(n) => match n.text() {
Ok(n) => n,
Err(_e) => return ,
},
Err(_e) => return ,
};
eprintln!("{:#?}", telemetry_response);
}
pub fn do_telemetry( service_config: Config, tlm2send: std::sync::mpsc::Receiver<Vec<u8>>, cmds: std::sync::mpsc::Receiver<TlmCmds>, _responses: std::sync::mpsc::Sender<TlmCmds>) {
const SLEEP_INTERVAL: time::Duration = time::Duration::from_millis(1000);
let mut telemetry_interval = time::Duration::new(5, 0);
// let socket = open_socket(String::from("0.0.0.0:34343")).expect("Unable to initially open socket");
let mut dest_host = None;
// let remote_host = String::with_capacity(128);
let mut now = time::Instant::now();
// let done = false;
loop {
thread::sleep(SLEEP_INTERVAL);
// eprintln!("TLM woke up from sleep");
let result = cmds.try_recv();
match result {
Ok(n) => {
// eprintln!("Received a new command");
match n {
TlmCmds::SleepCommand{interval} => {
eprintln!("now should sleep for {}", interval);
telemetry_interval = time::Duration::from_millis( interval as u64);
},
TlmCmds::DestinationCommand{addr} => {
eprintln!("set destination command");
dest_host = Some(addr); // addr.to_socket_addrs().unwrap().next();
},
TlmCmds::ShutdownCommand => {
eprintln!("Time to shutdown this TLM thread");
return;
},
TlmCmds::RawCommand{raw: _bytes} => {
eprintln!("Got a raw command to execute");
},
}
},
Err(_e) => (),
};
if now.elapsed() >= telemetry_interval {
eprintln!("Its time to collect and send telemetry");
// get_eps_data(&service_config);
match get_eps_data(&service_config) {
Some(n) => save_eps_to_db(&service_config, n),
None => (),
};
loop {
let telemetry_data = tlm2send.try_recv();
match telemetry_data {
Ok(n) => {
match &dest_host {
Some(x) => { let socket = x.try_clone();
match socket.unwrap().write(&n) {
Ok(_n) => (),
Err(_e) => { eprintln!("Error writing to socket"); dest_host = None},
};
},
None => {eprintln!("destination is not set"); },
};
},
Err(_e) => break,
};
now = time::Instant::now();
}
}
}
}
|
//! Types used to describe bitfields. These describe structure and do not hold any actual values.
use std::collections::HashMap;
/// The size of a single bit field.
pub type FieldSize = usize;
/// The name of a bit field.
pub type FieldName = String;
/// A mapping between enum values and descriptions
pub type EnumMapping = HashMap<usize, String>;
/// A bit field.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Field {
/// Reserved/unused field with the given width
Reserved(FieldSize),
/// One-bit boolean - 1 is true, 0 is false.
Boolean(FieldName),
/// An unsigned integer field with the given width.
Integer(FieldName, FieldSize),
/// An enumeration with a particular size and value-name mapping.
Enum(FieldName, FieldSize, EnumMapping),
}
impl Field {
/// Create a new Field::Reserved.
pub fn reserved(size: FieldSize) -> Field {
Field::Reserved(size)
}
/// Create a new Field::Boolean
pub fn boolean(name: &str) -> Field {
Field::Boolean(name.into())
}
/// Create a new Field::Integer
pub fn integer(name: &str, size: FieldSize) -> Field {
Field::Integer(name.into(), size)
}
/// Create a new Field::Enum
pub fn enumeration(name: &str, size: FieldSize, map: EnumMapping) -> Field {
Field::Enum(name.into(), size, map)
}
/// Get the size in bits.
///
/// ```
/// use bitview::Field;
/// let res_act: Field = Field::Boolean("res_act".into());
/// assert_eq!(res_act.size(), 1);
/// ```
pub fn size(&self) -> FieldSize {
match *self {
Field::Reserved(n) => n,
Field::Boolean(_) => 1,
Field::Integer(_, n) => n,
Field::Enum(_, n, _) => n,
}
}
/// Get the name of the field, unless it's Field::Reserved
pub fn get_name(&self) -> Option<String> {
match *self {
Field::Reserved(_) => None,
Field::Boolean(ref name)
| Field::Integer(ref name, _)
| Field::Enum(ref name, _, _) => Some(name.clone()),
}
}
}
/// A type made up of bit fields.
///
/// ```
/// use bitview::{Structure, Field};
///
/// let reg = Structure::new(
/// "REG_1",
/// &[
/// Field::boolean("bob"),
/// Field::reserved(4),
/// Field::integer("jim", 3)
/// ],
/// );
/// ```
#[derive(Debug)]
pub struct Structure {
/// The name of the structure. Generally the name of the represented register.
pub name: String,
/// List of components, starting with the most significant bits
pub fields: Vec<Field>,
}
impl Structure {
/// Create a new Structure with the given name.
pub fn new(name: &str, fields: &[Field]) -> Structure {
Structure {
name: name.into(),
fields: fields.into(),
}
}
/// Append a field to an existing Structure. The new field becomes the least-significant one.
pub fn append(&mut self, field: Field) {
self.fields.push(field);
}
/// Get the size of all the fields combined. This is distinct from the size of the (integer)
/// value the structure is created from.
///
/// ```
/// use bitview::{Structure, Field};
///
/// let mut reg = Structure::new("reg", &[]);
/// reg.fields.push(Field::Boolean("res_act".into()));
/// reg.fields.push(Field::Reserved(4));
///
/// assert_eq!(reg.size(), 5);
/// ```
pub fn size(&self) -> FieldSize {
self.fields.iter().fold(0, |acc, field| acc + field.size())
}
/// Retrieve a specific field description
///
/// ```
/// use bitview::{Structure, Field};
///
/// let reg = Structure::new("reg", &[
/// Field::boolean("res_act"),
/// Field::integer("rsm", 3),
/// Field::boolean("dbgm"),
/// ]);
///
/// assert_eq!(reg.get_field("rsm"), Some(Field::integer("rsm", 3)));
/// assert_eq!(reg.get_field("intm"), None);
/// ```
pub fn get_field(&self, field_name: &str) -> Option<Field> {
for field in &self.fields {
if let Some(name) = field.get_name() {
if name == field_name {
return Some(field.clone());
}
}
}
None
}
/// Get the range of bits for the specified field, if it exists.
///
/// The resulting range is in downto notation, so (3, 0) means the four least significant bits.
///
/// # Example
/// ```
/// use bitview::{Structure, Field};
///
/// let reg = Structure::new("reg", &[
/// Field::boolean("active"),
/// Field::integer("lifetime", 4),
/// ]);
///
/// assert_eq!(reg.get_range("lifetime"), Some((4, 1)));
/// ```
pub fn get_range(&self, field_name: &str) -> Option<(usize, usize)> {
if let Some(field_match) = self.get_field(field_name) {
let mut low: FieldSize = 0;
for field in &self.fields {
if *field == field_match {
let high = low + field.size() - 1;
return Some((high, low));
}
low += field.size();
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fieldsize_reserved() {
assert_eq!(Field::Reserved(4).size(), 4);
}
#[test]
fn fieldsize_bool() {
assert_eq!(Field::Boolean("Any".into()).size(), 1);
}
#[test]
fn fieldsize_integer() {
assert_eq!(Field::Integer("Any".into(), 14).size(), 14);
}
#[test]
fn fieldsize_enum() {
assert_eq!(Field::Enum("Any".into(), 36, HashMap::new()).size(), 36);
}
#[test]
fn structure_empty() {
assert_eq!(Structure::new("Any", &[]).size(), 0);
}
#[test]
fn structure_with_fields() {
assert_eq!(
8,
Structure::new(
"Any",
&[
Field::boolean("bob"),
Field::reserved(4),
Field::integer("jim", 3)
],
).size()
)
}
}
|
#[doc = "Register `SECBB1R4` reader"]
pub type R = crate::R<SECBB1R4_SPEC>;
#[doc = "Register `SECBB1R4` writer"]
pub type W = crate::W<SECBB1R4_SPEC>;
#[doc = "Field `SECBB1` reader - Secure/non-secure 8�Kbytes flash Bank 1 sector attributes"]
pub type SECBB1_R = crate::FieldReader<u32>;
#[doc = "Field `SECBB1` writer - Secure/non-secure 8�Kbytes flash Bank 1 sector attributes"]
pub type SECBB1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>;
impl R {
#[doc = "Bits 0:31 - Secure/non-secure 8�Kbytes flash Bank 1 sector attributes"]
#[inline(always)]
pub fn secbb1(&self) -> SECBB1_R {
SECBB1_R::new(self.bits)
}
}
impl W {
#[doc = "Bits 0:31 - Secure/non-secure 8�Kbytes flash Bank 1 sector attributes"]
#[inline(always)]
#[must_use]
pub fn secbb1(&mut self) -> SECBB1_W<SECBB1R4_SPEC, 0> {
SECBB1_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 = "FLASH secure block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb1r4::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 [`secbb1r4::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SECBB1R4_SPEC;
impl crate::RegisterSpec for SECBB1R4_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`secbb1r4::R`](R) reader structure"]
impl crate::Readable for SECBB1R4_SPEC {}
#[doc = "`write(|w| ..)` method takes [`secbb1r4::W`](W) writer structure"]
impl crate::Writable for SECBB1R4_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SECBB1R4 to value 0"]
impl crate::Resettable for SECBB1R4_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#![warn(rust_2018_idioms)]
use ::log::{debug, error, info};
use env_logger;
use std::env;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::str;
use tokio;
use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use tokio::net::{
lookup_host,
tcp::{ReadHalf, WriteHalf},
TcpListener, TcpStream,
};
use tokio::stream::StreamExt;
use tokio::time::{delay_for, Duration};
use futures::{future, FutureExt, TryFutureExt};
#[tokio::main]
async fn main() -> io::Result<()> {
drop(env_logger::init());
// Take the first command line argument as an address to listen on, or fall
// back to just some localhost default.
let addr = env::args().nth(1).unwrap_or("127.0.0.1:1080".to_string());
let addr = addr.parse::<SocketAddr>().unwrap();
// Initialize the various data structures we're going to use in our server.
// Here we create the event loop, the global buffer that all threads will
// read/write into, and the bound TCP listener itself.
let mut listener = TcpListener::bind(&addr).await?;
// This is the address of the DNS server we'll send queries to. If
// external servers can't be used in your environment, you can substitue
// your own.
// let dns = "8.8.8.8:53".parse().unwrap();
// let client = UdpClientStream::<UdpSocket>::new(dns);
// let (bg, mut client) = ClientFuture::connect(client);
// Construct a future representing our server. This future processes all
// incoming connections and spawns a new task for each client which will do
// the proxy work.
//
// This essentially means that for all incoming connections, those received
// from `listener`, we'll create an instance of `Client` and convert it to a
// future representing the completion of handling that client. This future
// itself is then *spawned* onto the event loop to ensure that it can
// progress concurrently with all other connections.
println!("Listening for socks5 proxy connections on {}", addr);
let mut incoming = listener.incoming();
while let Some(Ok(stream)) = incoming.next().await {
let peer_addr = stream.peer_addr()?;
tokio::spawn(async move {
let mut client = Client {};
match client.serve(stream).await {
Ok((a, b, addr)) => {
info!("proxied {} --> {}: {}/{} bytes", peer_addr, *addr, a, b,)
}
Err(e) => error!("error for {}: {}", peer_addr, e),
};
io::Result::Ok(())
});
}
Ok(())
}
// Data used to when processing a client to perform various operations over its
// lifetime.
struct Client {}
impl Client {
/// This is the main entry point for starting a SOCKS proxy connection.
///
/// This function is responsible for constructing the future which
/// represents the final result of the proxied connection. In this case
/// we're going to return an `IoFuture<T>`, an alias for
/// `Future<Item=T, Error=io::Error>`, which indicates how many bytes were
/// proxied on each half of the connection.
///
/// The first part of the SOCKS protocol with a remote connection is for the
/// server to read one byte, indicating the version of the protocol. The
/// `read_exact` combinator is used here to entirely fill the specified
/// buffer, and we can use it to conveniently read off one byte here.
///
/// Once we've got the version byte, we then delegate to the below
/// `serve_vX` methods depending on which version we found.
async fn serve(&mut self, mut conn: TcpStream) -> io::Result<(u64, u64, Box<String>)> {
let mut buf = [0u8; 1];
conn.read_exact(&mut buf).await?;
let res = match buf[0] {
v5::VERSION => self.serve_v5(conn).await,
v4::VERSION => self.serve_v4(conn),
// If we hit an unknown version, we return a "terminal future"
// which represents that this future has immediately failed. In
// this case the type of the future is `io::Error`, so we use a
// helper function, `other`, to create an error quickly.
n => Err(other(&format!("unknown version {}", n))),
};
res
}
async fn serve_v5(&mut self, mut conn: TcpStream) -> io::Result<(u64, u64, Box<String>)> {
// First part of the SOCKSv5 protocol is to negotiate a number of
// "methods". These methods can typically be used for various kinds of
// proxy authentication and such, but for this server we only implement
// the `METH_NO_AUTH` method, indicating that we only implement
// connections that work with no authentication.
//
// First here we do the same thing as reading the version byte, we read
// a byte indicating how many methods. Afterwards we then read all the
// methods into a temporary buffer.
//
// Note that we use `and_then` here to chain computations after one
// another, but it also serves to simply have fallible computations,
// such as checking whether the list of methods contains `METH_NO_AUTH`.
let num_methods = async move {
let mut buf = [0u8; 1];
conn.read_exact(&mut buf).await?;
io::Result::Ok((buf, conn))
}
.boxed();
let authenticated = num_methods
.and_then(|(buf, mut conn)| {
async move {
let mut buf = vec![0u8; buf[0] as usize];
let _ = conn.read_exact(&mut buf).await?;
if buf.contains(&v5::METH_NO_AUTH) {
io::Result::Ok(conn)
} else {
io::Result::Err(other("no supported method given"))
}
}
})
.boxed();
// After we've concluded that one of the client's supported methods is
// `METH_NO_AUTH`, we "ack" this to the client by sending back that
// information. Here we make use of the `write_all` combinator which
// works very similarly to the `read_exact` combinator.
let part1 = authenticated
.and_then(|mut conn| {
async move {
conn.write_all(&[v5::VERSION, v5::METH_NO_AUTH]).await?;
io::Result::Ok(conn)
}
})
.boxed();
// Next up, we get a selected protocol version back from the client, as
// well as a command indicating what they'd like to do. We just verify
// that the version is still v5, and then we only implement the
// "connect" command so we ensure the proxy sends that.
//
// As above, we're using `and_then` not only for chaining "blocking
// computations", but also to perform fallible computations.
let ack = part1
.and_then(|mut conn| {
async move {
let mut buf = [0u8; 1];
let _ = conn.read_exact(&mut buf).await?;
if buf[0] == v5::VERSION {
io::Result::Ok(conn)
} else {
io::Result::Err(other("didn't confirm with v5 version"))
}
}
})
.boxed();
let command = ack
.and_then(|mut conn| {
async move {
let mut buf = [0u8; 1];
let _ = conn.read_exact(&mut buf).await?;
if buf[0] == v5::CMD_CONNECT {
io::Result::Ok(conn)
} else {
io::Result::Err(other("unsupported command"))
}
}
})
.boxed();
// After we've negotiated a command, there's one byte which is reserved
// for future use, so we read it and discard it. The next part of the
// protocol is to read off the address that we're going to proxy to.
// This address can come in a number of forms, so we read off a byte
// which indicates the address type (ATYP).
//
// Depending on the address type, we then delegate to different futures
// to implement that particular address format.
let atyp = command
.and_then(|mut conn| {
async move {
let mut buf = [0u8; 1];
conn.read_exact(&mut buf).await?;
conn.read_exact(&mut buf).await?;
io::Result::Ok((buf, conn))
}
})
.boxed();
let addr = atyp
.and_then(|(buf, mut conn)| {
async move {
match buf[0] {
// For IPv4 addresses, we read the 4 bytes for the address as
// well as 2 bytes for the port.
v5::ATYP_IPV4 => {
let mut buf = [0u8; 6];
conn.read_exact(&mut buf).await?;
let addr = Ipv4Addr::new(buf[0], buf[1], buf[2], buf[3]);
let port = ((buf[4] as u16) << 8) | (buf[5] as u16);
let addr = SocketAddrV4::new(addr, port);
Ok((SocketAddr::V4(addr), conn, Box::new(addr.to_string())))
}
v5::ATYP_IPV6 => {
let mut buf = [0u8; 18];
conn.read_exact(&mut buf).await?;
let a = ((buf[0] as u16) << 8) | (buf[1] as u16);
let b = ((buf[2] as u16) << 8) | (buf[3] as u16);
let c = ((buf[4] as u16) << 8) | (buf[5] as u16);
let d = ((buf[6] as u16) << 8) | (buf[7] as u16);
let e = ((buf[8] as u16) << 8) | (buf[9] as u16);
let f = ((buf[10] as u16) << 8) | (buf[11] as u16);
let g = ((buf[12] as u16) << 8) | (buf[13] as u16);
let h = ((buf[14] as u16) << 8) | (buf[15] as u16);
let addr = Ipv6Addr::new(a, b, c, d, e, f, g, h);
let port = ((buf[16] as u16) << 8) | (buf[17] as u16);
let addr = SocketAddrV6::new(addr, port, 0, 0);
Ok((SocketAddr::V6(addr), conn, Box::new(addr.to_string())))
}
// The SOCKSv5 protocol not only supports proxying to specific
// IP addresses, but also arbitrary hostnames. This allows
// clients to perform hostname lookups within the context of the
// proxy server rather than the client itself.
//
// Since the first publication of this code, several
// futures-based DNS libraries appeared, and as a demonstration
// of integrating third-party asynchronous code into our chain,
// we will use one of them, TRust-DNS.
//
// The protocol here is to have the next byte indicate how many
// bytes the hostname contains, followed by the hostname and two
// bytes for the port. To read this data, we execute two
// respective `read_exact` operations to fill up a buffer for
// the hostname.
//
// Finally, to perform the "interesting" part, we process the
// buffer and pass the retrieved hostname to a query future if
// it wasn't already recognized as an IP address. The query is
// very basic: it asks for an IPv4 address with a timeout of
// five seconds. We're using TRust-DNS at the protocol level,
// so we don't have the functionality normally expected from a
// stub resolver, such as sorting of answers according to RFC
// 6724, more robust timeout handling, or resolving CNAME
// lookups.
v5::ATYP_DOMAIN => {
let mut buf = [0u8; 1];
conn.read_exact(&mut buf).await?;
let mut buf = vec![0u8; (buf[0] as usize) + 2];
conn.read_exact(&mut buf).await?;
let (socket_addr, addr) = name_port(&buf).await?;
Ok((socket_addr, conn, addr))
}
n => {
let msg = format!("unknown ATYP received: {}", n);
io::Result::Err(other(&msg))
}
}
}
})
.boxed();
// Now that we've got a socket address to connect to, let's actually
// create a connection to that socket!
//
// To do this, we use our `handle` field, a handle to the event loop, to
// issue a connection to the address we've figured out we're going to
// connect to. Note that this `tcp_connect` method itself returns a
// future resolving to a `TcpStream`, representing how long it takes to
// initiate a TCP connection to the remote.
//
// We wait for the TCP connect to get fully resolved before progressing
// to the next stage of the SOCKSv5 handshake, but we keep a hold of any
// possible error in the connection phase to handle it in a moment.
let connected = addr
.and_then(|(socket_addr, conn, dest_addr)| {
async move {
debug!("proxying to {}", socket_addr);
Ok((conn, TcpStream::connect(socket_addr).await, dest_addr))
}
})
.boxed();
// Once we've gotten to this point, we're ready for the final part of
// the SOCKSv5 handshake. We've got in our hands (c2) the client we're
// going to proxy data to, so we write out relevant information to the
// original client (c1) the "response packet" which is the final part of
// this handshake.
let handshake_finish = connected
.and_then(|(mut conn, c2, dest_addr)| {
async move {
let mut resp = [0u8; 32];
// VER - protocol version
resp[0] = 5;
// REP - "reply field" -- what happened with the actual connect.
//
// In theory this should reply back with a bunch more kinds of
// errors if possible, but for now we just recognize a few concrete
// errors.
resp[1] = match c2 {
Ok(..) => 0,
Err(ref e) if e.kind() == io::ErrorKind::ConnectionRefused => 5,
Err(..) => 1,
};
// RSV - reserved
resp[2] = 0;
// ATYP, BND.ADDR, and BND.PORT
//
// These three fields, when used with a "connect" command
// (determined above), indicate the address that our proxy
// connection was bound to remotely. There's a variable length
// encoding of what's actually written depending on whether we're
// using an IPv4 or IPv6 address, but otherwise it's pretty
// standard.
let addr = match c2.as_ref().map(|r| r.local_addr()) {
Ok(Ok(addr)) => Ok(addr),
Ok(Err(e)) => io::Result::Err(e),
Err(e) => io::Result::Err(io::Error::new(e.kind(), e.to_string().as_str())),
}?;
let pos = match addr {
SocketAddr::V4(ref a) => {
resp[3] = 1;
resp[4..8].copy_from_slice(&a.ip().octets()[..]);
8
}
SocketAddr::V6(ref a) => {
resp[3] = 4;
let mut pos = 4;
for &segment in a.ip().segments().iter() {
resp[pos] = (segment >> 8) as u8;
resp[pos + 1] = segment as u8;
pos += 2;
}
pos
}
};
resp[pos] = (addr.port() >> 8) as u8;
resp[pos + 1] = addr.port() as u8;
// Slice our 32-byte `resp` buffer to the actual size, as it's
// variable depending on what address we just encoding. Once that's
// done, write out the whole buffer to our client.
//
// The returned type of the future here will be `(TcpStream,
// TcpStream)` representing the client half and the proxy half of
// the connection.
conn.write_all(&resp[..(pos + 2)]).await?;
io::Result::Ok((conn, c2?, dest_addr))
}
})
.boxed();
// Phew! If you've gotten this far, then we're now entirely done with
// the entire SOCKSv5 handshake!
//
// In order to handle ill-behaved clients, however, we have an added
// feature here where we'll time out any initial connect operations
// which take too long.
//
// Here we create a timeout future, using the `Timeout::new` method,
// which will create a future that will resolve to `()` in 10 seconds.
// We then apply this timeout to the entire handshake all at once by
// performing a `select` between the timeout and the handshake itself.
let delay = delay_for(Duration::new(20, 0));
let pair = future::select(handshake_finish, delay)
.then(|either| {
async move {
match either {
future::Either::Left((Ok(pair), _)) => Ok(pair),
future::Either::Left((Err(e), _)) => Err(e),
future::Either::Right(((), _)) => {
io::Result::Err(other("timeout during handshake"))
}
}
}
})
.boxed();
// At this point we've *actually* finished the handshake. Not only have
// we read/written all the relevant bytes, but we've also managed to
// complete in under our allotted timeout.
//
// At this point the remainder of the SOCKSv5 proxy is shuttle data back
// and for between the two connections. That is, data is read from `c1`
// and written to `c2`, and vice versa.
//
// To accomplish this, we put both sockets into their own `Rc` and then
// create two independent `Transfer` futures representing each half of
// the connection. These two futures are `join`ed together to represent
// the proxy operation happening.
pair.and_then(|(mut c1, mut c2, dest_addr)| {
async move {
let (c1_read, c1_write) = c1.split();
let (c2_read, c2_write) = c2.split();
let half1 = transfer(c1_read, c2_write);
let half2 = transfer(c2_read, c1_write);
let (res1, res2) = future::try_join(half1, half2).await?;
io::Result::Ok((res1, res2, dest_addr))
}
})
.await
}
fn serve_v4(&mut self, mut _conn: TcpStream) -> io::Result<(u64, u64, Box<String>)> {
Err(other("Socks version 4 not implemented"))
}
}
/// A transfer representing reading all data from one side of a proxy connection
/// and writing it to another. Use async transfer instead of Transfer Future to
/// avoid complicated polling process.
///
async fn transfer(mut reader: ReadHalf<'_>, mut writer: WriteHalf<'_>) -> io::Result<u64> {
let mut buf = vec![0u8; 64 * 1024];
let mut amt = 0 as u64;
loop {
let read_size = match reader.read(&mut buf).await {
Ok(n) => {
if n == 0 {
if let Err(e) = writer.shutdown().await {
debug!(
"shutdown {} error: {}",
writer.as_ref().peer_addr().unwrap(),
e
);
}
return Ok(amt);
} else {
n
}
}
Err(e) => {
debug!(
"Read from {} error: {}",
(reader).as_ref().peer_addr().unwrap(),
e
);
if let Err(e) = writer.shutdown().await {
debug!(
"shutdown {} error: {}",
writer.as_ref().peer_addr().unwrap(),
e
);
}
return Ok(amt);
}
};
const MAX_LEN: usize = 1024 * 1024 * 10;
if read_size >= buf.len() && buf.len() <= MAX_LEN {
buf.resize_with(buf.len() * 2, Default::default);
debug!(
"Expand the read buffer size to {} for {}",
buf.len(),
reader.as_ref().peer_addr().unwrap()
);
}
if let Err(e) = writer.write_all(&buf[..read_size]).await {
debug!(
"Write to {} error: {}",
writer.as_ref().peer_addr().unwrap(),
e
);
if let Err(e) = writer.shutdown().await {
debug!(
"shutdown {} error: {}",
writer.as_ref().peer_addr().unwrap(),
e
);
}
return Ok(amt);
}
amt += read_size as u64;
}
}
fn other(desc: &str) -> io::Error {
io::Error::new(io::ErrorKind::Other, desc)
}
// Extracts the name and port from addr_buf and returns them, converting
// the name to the form that the trust-dns client can use. If the original
// name can be parsed as an IP address, makes a SocketAddr from that
// address and the port and returns it; we skip DNS resolution in that
// case.
async fn name_port(addr_buf: &[u8]) -> io::Result<(SocketAddr, Box<String>)> {
// The last two bytes of the buffer are the port, and the other parts of it
// are the hostname.
let hostname = &addr_buf[..addr_buf.len() - 2];
let hostname = str::from_utf8(hostname)
.map_err(|_e| other("hostname buffer provided was not valid utf-8"))?;
let pos = addr_buf.len() - 2;
let port = ((addr_buf[pos] as u16) << 8) | (addr_buf[pos + 1] as u16);
let dest_addr = format!("{}:{}", hostname, port);
if let Ok(ip) = hostname.parse() {
return Ok((SocketAddr::new(ip, port), Box::new(dest_addr)));
}
debug!("lookup_host {}", hostname);
let hostname = &format!("{}:{}", hostname, port);
let mut addrs = lookup_host(hostname).await?;
debug!("lookup_host {} success", hostname);
let first = addrs
.next()
.ok_or(other(&format!("wrong hostname {}", hostname)))?;
Ok((SocketAddr::new(first.ip(), port), Box::new(dest_addr)))
}
#[allow(dead_code)]
mod v5 {
pub const VERSION: u8 = 5;
pub const METH_NO_AUTH: u8 = 0;
pub const METH_GSSAPI: u8 = 1;
pub const METH_USER_PASS: u8 = 2;
pub const CMD_CONNECT: u8 = 1;
pub const CMD_BIND: u8 = 2;
pub const CMD_UDP_ASSOCIATE: u8 = 3;
pub const ATYP_IPV4: u8 = 1;
pub const ATYP_IPV6: u8 = 4;
pub const ATYP_DOMAIN: u8 = 3;
}
#[allow(dead_code)]
mod v4 {
pub const VERSION: u8 = 4;
pub const CMD_CONNECT: u8 = 1;
pub const CMD_BIND: u8 = 2;
}
|
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate time;
mod api;
|
use std::collections::HashSet;
pub struct CodeBlock {
pub declared_variables: HashSet<String>,
}
impl CodeBlock {
pub fn new() -> CodeBlock {
CodeBlock {
declared_variables: HashSet::new(),
}
}
}
|
use SCHEDULER;
use pi::timer;
use traps::TrapFrame;
use process::{Process, State};
use pi::console::kprintln;
/// Sleep for `ms` milliseconds.
///
/// This system call takes one parameter: the number of milliseconds to sleep.
///
/// In addition to the usual status value, this system call returns one
/// parameter: the approximate true elapsed time from when `sleep` was called to
/// when `sleep` returned.
pub fn sleep(ms: u32, tf: &mut TrapFrame) {
let start_time = timer::current_time();
let start_time_outside = start_time.clone();
let poll_fn = Box::new(move |_p: &mut Process| {
let diff = timer::current_time().wrapping_sub(start_time);
if diff as u32 > (ms * 1000) {
return true;
} else {
return false;
}
});
SCHEDULER.switch(State::Waiting(poll_fn), tf);
tf.x7 = 0;
let diff = (timer::current_time().wrapping_sub(start_time_outside)) / 1000;
tf.x0 = diff.into();
}
pub fn handle_syscall(num: u16, tf: &mut TrapFrame) {
match num {
1 => {
kprintln!("sleep syscall");
sleep(tf.x0 as u32, tf);
tf.elr = tf.elr + 0x04;
},
_ => {
tf.x7 = 1;
tf.elr = tf.elr + 0x04;
}
}
}
|
//! Write a function that accepts an array of 10 integers
//! (between 0 and 9), that returns a string of those numbers
//! in the form of a phone number.
use std::fmt::format;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn returns_correct() {
assert_eq!(create_phone_number(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), "(123) 456-7890");
assert_eq!(create_phone_number(&[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), "(111) 111-1111");
assert_eq!(create_phone_number(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 9]), "(123) 456-7899");
}
}
// # Same solution, but more concise
// let s: String = numbers.into_iter().map(|i| i.to_string()).collect();
// //use slice to fill {}
// format!("({}) {}-{}", &s[..3], &s[3..6], &s[6..])
// # and a more ... version
// format!("({}{}{}) {}{}{}-{}{}{}{}", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9])
// input &[1,2,3,4,5,6,7,8,9,0] => (123) 456-7890
fn create_phone_number(numbers:&[u8])->String{
let number:Vec<_> = numbers.iter().map(|x| x.to_string()).collect();
format!("({}) {}-{}",number[0..3].join(""),number[3..6].join(""),number[6..10].join(""))
}
|
use library::lexeme::definition::TokenType::*;
use library::lexeme::token::Token;
/**
* skip_stmt:
* forwards the lookahead by one statement
* returns the lookahead at the lexeme after the semi-colon
*/
pub fn skip_stmt(lexeme: &Vec<Token>, mut lookahead: usize) -> usize {
while lexeme[lookahead].get_token_type() != Semicolon {
lookahead += 1;
}
lookahead + 1
}
/**
* skip_block:
* forwards the lookahead by one block
* returns the lookahead at the lexeme after the closing brace
*/
pub fn skip_block(lexeme: &Vec<Token>, mut lookahead: usize) -> usize {
let mut paren = 1;
// while all braces are not closed
// skip nested blocks if any
while paren != 0 && lookahead < lexeme.len() {
if lexeme[lookahead].get_token_type() == LeftCurlyBrace {
paren += 1;
}
if lexeme[lookahead].get_token_type() == RightCurlyBrace {
paren -= 1;
}
lookahead += 1;
}
lookahead
}
/**
* skip_block:
* forwards the lookahead by one block
* returns the lookahead at the lexeme after the closing brace
*/
pub fn skip_paranthised_block(lexeme: &Vec<Token>, mut lookahead: usize) -> usize {
let mut paren = 1;
// while all braces are not closed
// skip nested blocks if any
while paren != 0 && lookahead < lexeme.len() {
if lexeme[lookahead].get_token_type() == LeftBracket {
paren += 1;
}
if lexeme[lookahead].get_token_type() == RightBracket {
paren -= 1;
}
lookahead += 1;
}
lookahead
}
|
//
// imports
//
use std::fmt;
use std::fs::File;
use std::path::Path;
use std::result;
use std::io::Read;
pub type Result<T> = result::Result<T, &'static str>;
//
// Thermocouple struct
//
pub struct Thermocouple {
spi: File, // the spidev interface to this thermocouple
}
//
// Sample struct
//
#[allow(dead_code)]
pub struct Sample {
oc_fault: bool, // open (no connections)
scg_fault: bool, // short-circuited to GND
scv_fault: bool, // short-circuited to VCC
internal_temperature: u16, // reference junction temperature (in degrees C * 4)
fault: bool, // set if any fault is present
thermocouple_temperature: u16 // thermocouple temperature (in degrees C * 4)
}
impl Thermocouple {
//
// open(path) - open thermocouple attached to the specified spidev file
//
pub fn open<P: AsRef<Path>>(path: P) -> Result<Thermocouple> {
match File::open(path) {
Ok(f) => Ok(Thermocouple { spi: f }),
Err(_) => Err("unable to open thermocouple")
}
}
//
// read_sample() - read and return a sample from the thermocouple
//
pub fn read_sample(&mut self) -> Result<Sample> {
let mut buf = [0u8; 4];
match self.spi.read(&mut buf) {
Err(_) => Err("unable to read from thermocouple"),
Ok(bytes_read) =>
if bytes_read != 4 {
Err("no more samples")
} else {
Ok(Sample::new(
(buf[0] as u32) << 24 |
(buf[1] as u32) << 16 |
(buf[2] as u32) << 8 |
(buf[3] as u32)))
}
}
}
}
impl Sample {
//
// new(raw) - constructs a sample from the 32-bit value read from the thermocouple
//
pub fn new(raw: u32) -> Sample {
Sample {
oc_fault: (raw >> 0) & 0x01 == 0x01,
scg_fault: (raw >> 1) & 0x01 == 0x01,
scv_fault: (raw >> 2) & 0x01 == 0x01,
internal_temperature: ((raw >> 3) & 0xFFF) as u16,
fault: (raw >> 15) & 0x01 == 0x01,
thermocouple_temperature: (raw >> 18) as u16,
}
}
//
// get_temp_celcius() - calculate and return the temperature in celcius
//
pub fn get_temp_celcius(&self) -> Option<f32> {
if self.fault {
None
} else {
Some(self.thermocouple_temperature as f32 / 4f32)
}
}
//
// get_temp_fahrenheit() - calculate and return the temperature in fahrenheit
//
pub fn get_temp_fahrenheit(&self) -> Option<f32> {
if self.fault {
None
} else {
Some(self.thermocouple_temperature as f32 * 0.45f32 + 32f32)
}
}
}
impl fmt::Display for Sample {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.fault {
if self.oc_fault {
write!(f, "fault (open connection)")
} else if self.scg_fault {
write!(f, "fault (shorted to GND)")
} else if self.scv_fault {
write!(f, "fault (shorted to VCC)")
} else {
write!(f, "fault (unknown)")
}
} else {
write!(f, "{} (F)", self.get_temp_fahrenheit().unwrap())
}
}
}
|
use crate::{BoxFuture, Entity, Result};
#[derive(Debug, Default)]
pub struct LoadArgs {
pub use_transaction: bool,
}
pub trait LoadAll<E: Entity, FILTER: Send + Sync, C>: Send + Sync
where
C: Default + Extend<(E::Key, E)> + Send,
{
fn load_all_with_args<'a>(
&'a self,
filter: &'a FILTER,
args: LoadArgs,
) -> BoxFuture<'a, Result<C>>;
fn load_all<'a>(&'a self, filter: &'a FILTER) -> BoxFuture<'a, Result<C>> {
self.load_all_with_args(filter, LoadArgs::default())
}
}
impl<C, E, FILTER, P> LoadAll<E, FILTER, C> for &P
where
C: Default + Extend<(E::Key, E)> + Send + 'static,
E: Entity + 'static,
FILTER: Send + Sync,
P: LoadAll<E, FILTER, C>,
{
fn load_all_with_args<'a>(
&'a self,
filter: &'a FILTER,
args: LoadArgs,
) -> BoxFuture<'a, Result<C>> {
(**self).load_all_with_args(filter, args)
}
}
pub struct LoadAllKeyOnly<E: Entity>(Vec<E::Key>);
impl<E: Entity> LoadAllKeyOnly<E> {
pub fn into_inner(self) -> Vec<E::Key> {
self.0
}
}
impl<E: Entity> Default for LoadAllKeyOnly<E> {
fn default() -> Self {
Self(Vec::new())
}
}
impl<E: Entity> Extend<(E::Key, E)> for LoadAllKeyOnly<E> {
fn extend<T: IntoIterator<Item = (E::Key, E)>>(&mut self, iter: T) {
self.0.extend(iter.into_iter().map(|t| t.0))
}
}
|
extern crate cc;
use std::env;
use std::path::PathBuf;
fn main() {
// let bindings = bindgen::Builder::default()
// // The input header we would like to generate
// // bindings for.
// .header("wrapper.h")
// // Finish the builder and generate the bindings.
// .generate()
// // Unwrap the Result and panic on failure.
// .expect("Unable to generate bindings");
// // Write the bindings to the $OUT_DIR/bindings.rs file.
// let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
// bindings
// .write_to_file(out_path.join("bindings.rs"))
// .expect("Couldn't write bindings!");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("bindings.rs");
#[cfg(feature = "buildtime_bindgen")]
{
bindings::write_to_out_dir("wrapper.h", &out_path);
}
#[cfg(not(feature = "buildtime_bindgen"))]
{
use std::fs;
fs::copy("bindings/duktape_binding.rs", out_path)
.expect("Could not copy bindings to output directory");
}
let mut builder = cc::Build::new();
builder
.file("duktape-2.3.0/src/duktape.c")
.flag_if_supported("-fomit-frame-pointer")
.flag_if_supported("-fstrict-aliasing");
// .flag_if_supported("-fprofile-generate")
let profile = env::var("PROFILE").unwrap();
if profile == "release" {
builder.opt_level(2);
}
builder.compile("libduktape.a");
}
#[cfg(feature = "buildtime_bindgen")]
mod bindings {
extern crate bindgen;
use std::path::{Path};
use std::fs;
pub fn write_to_out_dir(header: &str, out_path: &Path) {
let bindings = bindgen::Builder::default()
// The input header we would like to generate
// bindings for.
.header(header)
// Finish the builder and generate the bindings.
.generate()
// Unwrap the Result and panic on failure.
.expect("Unable to generate bindings");
// Write the bindings to the $OUT_DIR/bindings.rs file.
// let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path)
.expect("Couldn't write bindings!");
fs::create_dir("bindings").unwrap_or(());
fs::copy(out_path, "bindings/duktape_binding.rs").expect("could not copy bindings");
}
} |
use std::{collections::HashMap, str::FromStr};
/// Reserved long flag name for help
pub const HELP_LONG: &str = "help";
/// Reserved short flag name for help
pub const HELP_SHORT: &str = "h";
/// Trait for types that can be converted from a flag.
/// The parse_from function was made specific due to the dynamic nature of the flag set.
/// But if there is some way to make it more generic that would be appreciated.
pub trait Flaggable {
/// Whether or not this flag expects a value.
/// In the case this is overriden, the parse_from method should ignore the input value.
fn expects_value(&self) -> bool { true }
/// Parses a string into this flag.
/// The string is value subsequently after the flag
fn parse_from(&mut self, s: &str) -> Result<(), String>;
}
/// Implements flaggable for Option types that wrap things that can be parsed.
impl<T: FromStr> Flaggable for Option<T> {
fn parse_from(&mut self, s: &str) -> Result<(), String> {
match T::from_str(s) {
Err(_) => Err(s.to_string()),
Ok(v) => {
self.replace(v);
Ok(())
},
}
}
}
/// Simple indicator for a flag which definitely contains a value.
#[derive(Debug)]
pub struct Preset<T>(pub T);
impl<T> From<T> for Preset<T> {
fn from(t: T) -> Self { Preset(t) }
}
impl<T> Preset<T> {
#[inline]
pub fn into_inner(self) -> T { self.0 }
}
impl<T: FromStr> Flaggable for Preset<T> {
fn parse_from(&mut self, s: &str) -> Result<(), String> {
match T::from_str(s) {
Err(_) => Err(s.to_string()),
Ok(v) => {
self.0 = v;
Ok(())
},
}
}
}
/// Implements a togglable bool
/// If the flag is passed, it toggles the input value.
impl Flaggable for bool {
fn expects_value(&self) -> bool { false }
fn parse_from(&mut self, _: &str) -> Result<(), String> {
*self = !*self;
Ok(())
}
}
#[derive(Default)]
pub struct FlagSet<'a> {
mappings: HashMap<&'static str, &'a mut dyn Flaggable>,
help_info: HashMap<&'static str, &'static str>,
}
fn show_help(h: &HashMap<&str, &str>) {
eprintln!("Usage:");
h.iter().for_each(|(flag, info)| {
eprintln!(" -{}", flag);
eprintln!("\t {}", info);
});
}
/// Multiple flags that will be parsed together.
/// Contains help info and maps names to destination.
impl<'a> FlagSet<'a> {
/// Creates a new empty FlagSet
pub fn new() -> Self {
Self {
mappings: HashMap::new(),
help_info: HashMap::new(),
}
}
/// Adds something flaggable with a given name and help message to the flag set.
/// Panics if the name is one of the reserved help flags(help or h).
pub fn add<F: Flaggable>(&mut self, name: &'static str, help: &'static str, f: &'a mut F) {
self.mappings.insert(name, f);
self.help_info.insert(name, help);
}
/// Parses an iterator of strings into this flag set.
/// Returns unmatched values from parsing or an error.
pub fn parse<I>(&mut self, mut i: I) -> Result<Vec<String>, ParseError>
where
I: Iterator<Item = String>, {
let mut out = vec![];
while let Some(v) = i.next() {
if !v.starts_with('-') {
out.push(v);
continue;
}
let v = v.trim_start_matches('-');
match self.mappings.get_mut(&*v) {
Some(ref mut flag) => {
if !flag.expects_value() {
flag
.parse_from("")
.map_err(|e| ParseError::ParseFromFailure(v.to_string(), e))?;
continue;
}
let flag_val = match i.next() {
None => return Err(ParseError::MissingValue(v.to_string())),
Some(flag_val) => flag_val,
};
flag
.parse_from(&flag_val)
.map_err(|e| ParseError::ParseFromFailure(v.to_string(), e))?;
},
None if v == HELP_LONG || v == HELP_SHORT => return Err(ParseError::HelpRequested),
None => return Err(ParseError::UnknownFlag(v.to_string())),
};
}
Ok(out)
}
/// Parses argument from env::args without the program name.
/// Exits on failure, and displays help info to stderr.
/// Returns extra arguments which were not used in parsing.
pub fn parse_args(&mut self) -> Vec<String> {
use std::env::args;
const OK: i32 = 0;
const FAILURE: i32 = 1;
match self.parse(args().skip(1)) {
Ok(rem) => rem,
Err(e) => {
let status = match e {
ParseError::HelpRequested => OK,
ParseError::ParseFromFailure(f, v) => {
eprintln!("Invalid value \"{}\" for flag -{}", f, v);
FAILURE
},
ParseError::UnknownFlag(f) => {
eprintln!("flag provided but not defined: -{}", f);
FAILURE
},
ParseError::MissingValue(f) => {
eprintln!("Missing value for flag: -{}", f);
FAILURE
},
};
show_help(&self.help_info);
std::process::exit(status);
},
}
}
}
/// Errors that can occur while parsing into flags.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParseError {
/// Failed to parse a value,
/// Returns error message from parsing and flag that it failed to parse into.
ParseFromFailure(String, String),
/// Missing value for a flag that expected one
/// Specifies flag that was missing a value.
MissingValue(String),
/// Help flag was passed, parsing stopped.
HelpRequested,
/// Unknown flag was passed.
UnknownFlag(String),
}
use std::fmt;
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) }
}
|
#![allow(dead_code, unused_imports, unused_variables)]
use std::collections::*;
const DATA: &'static str = include_str!("../../../data/16");
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
struct Device {
registers: [usize; 4],
}
impl Device {
fn parse(input: &str) -> Option<Device> {
let parsed: Vec<usize> = input
.trim_matches(|ch| ch == '[' || ch == ']')
.split(", ")
.map(|s: &str| str::parse(s).unwrap())
.collect();
match parsed.as_slice() {
[a, b, c, d] => Some(Device { registers: [*a, *b, *c, *d] }),
_ => None
}
}
fn register(&mut self, num: usize) -> Option<&mut usize> {
self.registers.get_mut(num)
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum OpCode {
Addr, Addi,
Mulr, Muli,
Banr, Bani,
Borr, Bori,
Setr, Seti,
Gtir, Gtri,
Gtrr, Eqir,
Eqri, Eqrr,
}
impl OpCode {
/// Iterate over all variants.
fn variants() -> impl Iterator<Item = OpCode> {
use self::OpCode::*;
[
Addr, Addi,
Mulr, Muli,
Banr, Bani,
Borr, Bori,
Setr, Seti,
Gtir, Gtri,
Gtrr, Eqir,
Eqri, Eqrr,
].into_iter().cloned()
}
fn apply(&self, d: &mut Device, inputs: &[usize; 2], o: usize) -> Option<()> {
use self::OpCode::*;
let [a, b] = *inputs;
*d.register(o)? = match *self {
Addr => *d.register(a)? + *d.register(b)?,
Addi => *d.register(a)? + b,
Mulr => *d.register(a)? * *d.register(b)?,
Muli => *d.register(a)? * b,
Banr => *d.register(a)? & *d.register(b)?,
Bani => *d.register(a)? & b,
Borr => *d.register(a)? | *d.register(b)?,
Bori => *d.register(a)? | b,
Setr => *d.register(a)?,
Seti => a,
Gtir => if a > *d.register(b)? { 1 } else { 0 },
Gtri => if *d.register(a)? > b { 1 } else { 0 },
Gtrr => if *d.register(a)? > *d.register(b)? { 1 } else { 0 },
Eqir => if a == *d.register(b)? { 1 } else { 0 },
Eqri => if *d.register(a)? == b { 1 } else { 0 },
Eqrr => if *d.register(a)? == *d.register(b)? { 1 } else { 0 },
};
Some(())
}
}
#[derive(Debug)]
pub struct Instruction {
op_code: usize,
inputs: [usize; 2],
output: usize,
}
impl Instruction {
pub fn parse(input: &str) -> Option<Instruction> {
let mut input = input.split(" ").flat_map(|d| str::parse(d));
let op_code = input.next()?;
let inputs = [input.next()?, input.next()?];
let output = input.next()?;
Some(Instruction { op_code, inputs, output })
}
}
#[derive(Debug)]
struct Test {
before: Device,
instruction: Instruction,
after: Device,
}
impl Test {
fn parse(input: &[&str]) -> Option<Test> {
let before = input[0];
let after = input[2];
let before = Device::parse(before.split(": ").nth(1)?.trim())?;
let instruction = Instruction::parse(input[1])?;
let after = Device::parse(after.split(": ").nth(1)?.trim())?;
Some(Test { before, instruction, after })
}
}
fn main() {
let lines: Vec<_> = DATA.lines().collect();
let (first, second) = lines.split_at(3095);
let tests: Vec<Test> = first.chunks(4).flat_map(Test::parse).collect();
let instructions: Vec<Instruction> = second.into_iter().cloned().flat_map(Instruction::parse).collect();
println!("Part 1: {:?}", part1(&tests));
println!("Part 2: {:?}", part2(&tests, &instructions));
}
fn part1(tests: &Vec<Test>) -> usize {
let mut score = 0;
for test in tests {
let mut matches = HashSet::new();
for op in OpCode::variants() {
let mut device = test.before.clone();
op.apply(&mut device, &test.instruction.inputs, test.instruction.output);
if device == test.after {
matches.insert(op);
}
}
if matches.len() >= 3 {
score += 1;
}
}
score
}
fn part2(tests: &Vec<Test>, instructions: &Vec<Instruction>) -> usize {
let mut mapping: HashMap<usize, HashSet<OpCode>> = HashMap::new();
// initially, all codes are possible for all numbers
for n in 0..16 {
for op in OpCode::variants() {
mapping.entry(n).or_default().insert(op);
}
}
// use tests to reduce possibility space
for test in tests {
let mut matches = HashSet::new();
for op in OpCode::variants() {
let mut device = test.before.clone();
op.apply(&mut device, &test.instruction.inputs, test.instruction.output);
if device == test.after {
matches.insert(op);
} else {
// does not match, can be removed from mapping
if let Some(codes) = mapping.get_mut(&test.instruction.op_code) {
codes.remove(&op);
}
}
}
// if only one match, this is the only possible opcode for this digit
if matches.len() == 1 {
if let Some(op) = matches.into_iter().next() {
if let Some(codes) = mapping.get_mut(&test.instruction.op_code) {
codes.clear();
codes.insert(op);
}
}
}
}
// regress mappings recursively to resolve
{
let mut identified = vec![];
let mut current = 0;
extract_identified(&mapping, &mut identified);
while current != identified.len() {
current = identified.len();
for (identified_num, identified_code) in &identified {
for (num, codes) in mapping.iter_mut() {
if num == identified_num {
codes.clear();
codes.insert(*identified_code);
continue;
}
codes.remove(&identified_code);
}
}
identified.clear();
extract_identified(&mapping, &mut identified);
}
}
let mapping: HashMap<usize, OpCode> = mapping
.into_iter()
.map(|(key, value)| (key, value.into_iter().next().unwrap()))
.collect();
let mut device = Device::default();
for instruction in instructions {
let op = mapping.get(&instruction.op_code).cloned().unwrap();
op.apply(&mut device, &instruction.inputs, instruction.output);
}
*device.register(0).unwrap()
}
fn extract_identified(input: &HashMap<usize, HashSet<OpCode>>, output: &mut Vec<(usize, OpCode)>) {
for (key, value) in input.iter().filter(|(key, value)| value.len() == 1) {
output.push((*key, value.iter().cloned().next().unwrap()));
}
}
|
//! An abstraction for Wasm benchmarks; this can verify whether the benchmark can be executed within the sightglass
//! benchmarking infrastructure.
use anyhow::Result;
use std::{fmt, fs};
use std::{
fmt::{Display, Formatter},
fs::File,
};
use std::{
io::Write,
path::{Path, PathBuf},
};
use thiserror::Error;
use wasmparser::{Import, Payload, TypeRef};
use wasmprinter;
pub struct WasmBenchmark(PathBuf);
impl WasmBenchmark {
/// Return the expected source location of a Wasm benchmark inside a benchmark Docker image.
pub fn source() -> PathBuf {
PathBuf::from("/benchmark.wasm")
}
pub fn from<P: AsRef<Path>>(path: P) -> Self {
Self(path.as_ref().canonicalize().expect("a valid path"))
}
/// Verify that the Wasm file is a valid benchmark, runnable in sightglass.
pub fn is_valid(&self) -> Result<(), ValidationError> {
// Check that the file actually exists.
if !self.0.exists() {
return ValidationErrorKind::DoesNotExist.with(&self);
}
// Check that the contents are readable.
let bytes = match fs::read(&self.0) {
Ok(b) => b,
Err(_) => {
return ValidationErrorKind::Unreadable.with(&self);
}
};
// Check that it contains valid Wasm.
let mut features = wasmparser::WasmFeatures::default();
features.simd = true;
let mut validator = wasmparser::Validator::new_with_features(features);
if let Err(_) = validator.validate_all(&bytes) {
return ValidationErrorKind::InvalidWasm.with(&self);
}
// Check that it has the expected imports/exports.
if !has_import_function(&bytes, "bench", "start").unwrap() {
return ValidationErrorKind::MissingImport("bench.end").with(&self);
}
if !has_import_function(&bytes, "bench", "end").unwrap() {
return ValidationErrorKind::MissingImport("bench.end").with(&self);
}
Ok(())
}
/// Emit the WebAssembly Text (WAT) version of the Wasm benchmark. This will calculate a path to
/// write to by replacing the benchmark's `.wasm` extension with `.wat`. On success, this will
/// return the path to the written WAT.
pub fn emit_wat(&self) -> Result<PathBuf> {
let stem = self
.0
.file_stem()
.expect("the Wasm benchmark should have a file stem (i.e. basename)");
let mut wat = self
.0
.parent()
.expect("the Wasm benchmark should have a parent directory")
.to_path_buf();
wat.push(format!(
"{}.wat",
stem.to_str()
.expect("a valid Unicode file name for the Wasm benchmark")
));
let mut file = File::create(&wat)?;
file.write_all(wasmprinter::print_file(&self.0)?.as_bytes())?;
file.write(&['\n' as u8])?; // Append a newline on the end.
Ok(wat)
}
}
impl AsRef<Path> for WasmBenchmark {
fn as_ref(&self) -> &Path {
&self.0
}
}
impl Into<PathBuf> for WasmBenchmark {
fn into(self) -> PathBuf {
self.0
}
}
#[derive(Debug, Error)]
#[error("invalid wasmfile {path}: {source}")]
pub struct ValidationError {
path: String,
#[source]
source: ValidationErrorKind,
}
#[derive(Debug, Error)]
pub enum ValidationErrorKind {
#[error("the file does not exist")]
DoesNotExist,
#[error("cannot read the file")]
Unreadable,
#[error("the file is not a valid Wasm module")]
InvalidWasm,
#[error("the Wasm module is missing an import: {0}")]
MissingImport(&'static str),
}
impl ValidationErrorKind {
fn with(self, wasmfile: &WasmBenchmark) -> Result<(), ValidationError> {
Err(ValidationError {
path: wasmfile.to_string(),
source: self,
})
}
}
impl Display for WasmBenchmark {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0.display())
}
}
fn has_import_function(bytes: &[u8], expected_module: &str, expected_field: &str) -> Result<bool> {
let parser = wasmparser::Parser::new(0);
for payload in parser.parse_all(&bytes) {
match payload? {
Payload::ImportSection(imports) => {
for import in imports {
match import? {
Import {
module,
name: field,
ty: TypeRef::Func(_),
} => {
if module == expected_module && field == expected_field {
return Ok(true);
}
}
_ => {}
}
}
}
_ => {}
}
}
Ok(false)
}
|
#![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 CheckNameAvailabilityInput {
pub name: String,
#[serde(rename = "type")]
pub type_: check_name_availability_input::Type,
}
pub mod check_name_availability_input {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "searchServices")]
SearchServices,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckNameAvailabilityOutput {
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<check_name_availability_output::Reason>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
pub mod check_name_availability_output {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Reason {
Invalid,
AlreadyExists,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AdminKeyResult {
#[serde(rename = "primaryKey", default, skip_serializing_if = "Option::is_none")]
pub primary_key: Option<String>,
#[serde(rename = "secondaryKey", default, skip_serializing_if = "Option::is_none")]
pub secondary_key: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryKey {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListQueryKeysResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<QueryKey>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<sku::Name>,
}
pub mod sku {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
#[serde(rename = "free")]
Free,
#[serde(rename = "basic")]
Basic,
#[serde(rename = "standard")]
Standard,
#[serde(rename = "standard2")]
Standard2,
#[serde(rename = "standard3")]
Standard3,
#[serde(rename = "storage_optimized_l1")]
StorageOptimizedL1,
#[serde(rename = "storage_optimized_l2")]
StorageOptimizedL2,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SearchService {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SearchServiceProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SearchServiceProperties {
#[serde(rename = "replicaCount", default, skip_serializing_if = "Option::is_none")]
pub replica_count: Option<i32>,
#[serde(rename = "partitionCount", default, skip_serializing_if = "Option::is_none")]
pub partition_count: Option<i32>,
#[serde(rename = "hostingMode", default, skip_serializing_if = "Option::is_none")]
pub hosting_mode: Option<search_service_properties::HostingMode>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<search_service_properties::Status>,
#[serde(rename = "statusDetails", default, skip_serializing_if = "Option::is_none")]
pub status_details: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<search_service_properties::ProvisioningState>,
}
pub mod search_service_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HostingMode {
#[serde(rename = "default")]
Default,
#[serde(rename = "highDensity")]
HighDensity,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "running")]
Running,
#[serde(rename = "provisioning")]
Provisioning,
#[serde(rename = "deleting")]
Deleting,
#[serde(rename = "degraded")]
Degraded,
#[serde(rename = "disabled")]
Disabled,
#[serde(rename = "error")]
Error,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
#[serde(rename = "succeeded")]
Succeeded,
#[serde(rename = "provisioning")]
Provisioning,
#[serde(rename = "failed")]
Failed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SearchServiceListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SearchService>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<Identity>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<CloudErrorBody>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloudErrorBody {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<CloudErrorBody>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Identity {
#[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")]
pub principal_id: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
#[serde(rename = "type")]
pub type_: identity::Type,
}
pub mod identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
None,
SystemAssigned,
}
}
|
#![no_std]
#![feature(fn_traits, unboxed_closures)]
use core::ptr;
/// A version of FnOnce that takes `self` by `&mut` reference instead of by value.
///
/// This allows you to implement FnOnce on a type owning an FnMove trait object, as long as the wrapper type is Sized.
///
/// This trait will be obsolete once the [unsized rvalues RFC](https://github.com/rust-lang/rfcs/pull/1909) is implemented.
#[rustc_paren_sugar]
pub trait FnMove<Args>: FnOnce<Args> {
/// # Unsafety
/// Unsafe because this takes `self` by reference, but treats it as moved.
/// The caller must somehow stop the closure's destructor from running afterwards,
/// whether that's by calling `mem::forget` on it or something else.
unsafe fn call_move(&mut self, args: Args) -> Self::Output;
}
impl<F, Args> FnMove<Args> for F where F: FnOnce<Args> {
unsafe fn call_move(&mut self, args: Args) -> Self::Output {
ptr::read(self).call_once(args)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.