text stringlengths 8 4.13M |
|---|
pub mod error;
pub mod manager;
pub mod provider;
pub mod template;
|
#[doc = "Reader of register FLOW_CTL"]
pub type R = crate::R<u32, super::FLOW_CTL>;
#[doc = "Writer for register FLOW_CTL"]
pub type W = crate::W<u32, super::FLOW_CTL>;
#[doc = "Register FLOW_CTL `reset()`'s with value 0"]
impl crate::ResetValue for super::FLOW_CTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `EP1_ERR_RESP`"]
pub type EP1_ERR_RESP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EP1_ERR_RESP`"]
pub struct EP1_ERR_RESP_W<'a> {
w: &'a mut W,
}
impl<'a> EP1_ERR_RESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `EP2_ERR_RESP`"]
pub type EP2_ERR_RESP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EP2_ERR_RESP`"]
pub struct EP2_ERR_RESP_W<'a> {
w: &'a mut W,
}
impl<'a> EP2_ERR_RESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `EP3_ERR_RESP`"]
pub type EP3_ERR_RESP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EP3_ERR_RESP`"]
pub struct EP3_ERR_RESP_W<'a> {
w: &'a mut W,
}
impl<'a> EP3_ERR_RESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `EP4_ERR_RESP`"]
pub type EP4_ERR_RESP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EP4_ERR_RESP`"]
pub struct EP4_ERR_RESP_W<'a> {
w: &'a mut W,
}
impl<'a> EP4_ERR_RESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `EP5_ERR_RESP`"]
pub type EP5_ERR_RESP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EP5_ERR_RESP`"]
pub struct EP5_ERR_RESP_W<'a> {
w: &'a mut W,
}
impl<'a> EP5_ERR_RESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `EP6_ERR_RESP`"]
pub type EP6_ERR_RESP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EP6_ERR_RESP`"]
pub struct EP6_ERR_RESP_W<'a> {
w: &'a mut W,
}
impl<'a> EP6_ERR_RESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `EP7_ERR_RESP`"]
pub type EP7_ERR_RESP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EP7_ERR_RESP`"]
pub struct EP7_ERR_RESP_W<'a> {
w: &'a mut W,
}
impl<'a> EP7_ERR_RESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `EP8_ERR_RESP`"]
pub type EP8_ERR_RESP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EP8_ERR_RESP`"]
pub struct EP8_ERR_RESP_W<'a> {
w: &'a mut W,
}
impl<'a> EP8_ERR_RESP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
impl R {
#[doc = "Bit 0 - End Point 1 error response 0: do nothing (backward compatibility mode) 1: if this is an IN EP and an underflow occurs then cause a CRC error, if this is an OUT EP and an overflow occurs then send a NAK"]
#[inline(always)]
pub fn ep1_err_resp(&self) -> EP1_ERR_RESP_R {
EP1_ERR_RESP_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - End Point 2 error response"]
#[inline(always)]
pub fn ep2_err_resp(&self) -> EP2_ERR_RESP_R {
EP2_ERR_RESP_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - End Point 3 error response"]
#[inline(always)]
pub fn ep3_err_resp(&self) -> EP3_ERR_RESP_R {
EP3_ERR_RESP_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - End Point 4 error response"]
#[inline(always)]
pub fn ep4_err_resp(&self) -> EP4_ERR_RESP_R {
EP4_ERR_RESP_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - End Point 5 error response"]
#[inline(always)]
pub fn ep5_err_resp(&self) -> EP5_ERR_RESP_R {
EP5_ERR_RESP_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - End Point 6 error response"]
#[inline(always)]
pub fn ep6_err_resp(&self) -> EP6_ERR_RESP_R {
EP6_ERR_RESP_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - End Point 7 error response"]
#[inline(always)]
pub fn ep7_err_resp(&self) -> EP7_ERR_RESP_R {
EP7_ERR_RESP_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - End Point 8 error response"]
#[inline(always)]
pub fn ep8_err_resp(&self) -> EP8_ERR_RESP_R {
EP8_ERR_RESP_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - End Point 1 error response 0: do nothing (backward compatibility mode) 1: if this is an IN EP and an underflow occurs then cause a CRC error, if this is an OUT EP and an overflow occurs then send a NAK"]
#[inline(always)]
pub fn ep1_err_resp(&mut self) -> EP1_ERR_RESP_W {
EP1_ERR_RESP_W { w: self }
}
#[doc = "Bit 1 - End Point 2 error response"]
#[inline(always)]
pub fn ep2_err_resp(&mut self) -> EP2_ERR_RESP_W {
EP2_ERR_RESP_W { w: self }
}
#[doc = "Bit 2 - End Point 3 error response"]
#[inline(always)]
pub fn ep3_err_resp(&mut self) -> EP3_ERR_RESP_W {
EP3_ERR_RESP_W { w: self }
}
#[doc = "Bit 3 - End Point 4 error response"]
#[inline(always)]
pub fn ep4_err_resp(&mut self) -> EP4_ERR_RESP_W {
EP4_ERR_RESP_W { w: self }
}
#[doc = "Bit 4 - End Point 5 error response"]
#[inline(always)]
pub fn ep5_err_resp(&mut self) -> EP5_ERR_RESP_W {
EP5_ERR_RESP_W { w: self }
}
#[doc = "Bit 5 - End Point 6 error response"]
#[inline(always)]
pub fn ep6_err_resp(&mut self) -> EP6_ERR_RESP_W {
EP6_ERR_RESP_W { w: self }
}
#[doc = "Bit 6 - End Point 7 error response"]
#[inline(always)]
pub fn ep7_err_resp(&mut self) -> EP7_ERR_RESP_W {
EP7_ERR_RESP_W { w: self }
}
#[doc = "Bit 7 - End Point 8 error response"]
#[inline(always)]
pub fn ep8_err_resp(&mut self) -> EP8_ERR_RESP_W {
EP8_ERR_RESP_W { w: self }
}
}
|
//! The module describes DB and playback statistics
use chrono::{Duration, NaiveDateTime};
use convert::FromIter;
use error::Error;
use format::{duration_secs, time_secs};
use serde::{Serialize, Serializer};
/// DB and playback statistics
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Stats {
/// number of artists in DB
pub artists: u32,
/// number of albums in DB
pub albums: u32,
/// number of songs in DB
pub songs: u32,
/// total MPD uptime, seconds resolution
#[serde(with = "duration_secs")]
pub uptime: Duration,
/// total playback time, seconds resolution
#[serde(with = "duration_secs")]
pub playtime: Duration,
/// total playback time for all songs in DB, seconds resolution
#[serde(with = "duration_secs")]
pub db_playtime: Duration,
/// last DB update timestamp, seconds resolution
#[serde(with = "time_secs")]
pub db_update: NaiveDateTime,
}
impl Default for Stats {
fn default() -> Stats {
Stats {
artists: 0,
albums: 0,
songs: 0,
uptime: Duration::seconds(0),
playtime: Duration::seconds(0),
db_playtime: Duration::seconds(0),
db_update: NaiveDateTime::from_timestamp(0, 0),
}
}
}
impl FromIter for Stats {
/// build stats from iterator
fn from_iter<I: Iterator<Item = Result<(String, String), Error>>>(iter: I) -> Result<Stats, Error> {
let mut result = Stats::default();
for res in iter {
let line = try!(res);
match &*line.0 {
"artists" => result.artists = try!(line.1.parse()),
"albums" => result.albums = try!(line.1.parse()),
"songs" => result.songs = try!(line.1.parse()),
"uptime" => result.uptime = Duration::seconds(try!(line.1.parse())),
"playtime" => result.playtime = Duration::seconds(try!(line.1.parse())),
"db_playtime" => result.db_playtime = Duration::seconds(try!(line.1.parse())),
"db_update" => result.db_update = NaiveDateTime::from_timestamp(try!(line.1.parse()), 0),
_ => (),
}
}
Ok(result)
}
}
|
#![warn(clippy::all)]
//! This crate aims to provide a minimalist and high-performance actor framework
//! for Rust with significantly less complexity than other frameworks like
//! [Actix](https://docs.rs/actix/).
//!
//! In this framework, each `Actor` is its own OS-level thread. This makes debugging
//! noticeably simpler, and is suitably performant when the number of actors
//! is less than or equal to the number of CPU threads.
//!
//! # Example
//! ```rust
//! use tonari_actor::{Actor, Context, System};
//!
//! struct TestActor {}
//! impl Actor for TestActor {
//! type Context = Context<Self::Message>;
//! type Error = ();
//! type Message = usize;
//!
//! fn name() -> &'static str {
//! "TestActor"
//! }
//!
//! fn handle(&mut self, _context: &mut Self::Context, message: Self::Message) -> Result<(), ()> {
//! println!("message: {}", message);
//!
//! Ok(())
//! }
//! }
//!
//! let mut system = System::new("default");
//!
//! // will spin up a new thread running this actor
//! let addr = system.spawn(TestActor {}).unwrap();
//!
//! // send messages to actors to spin off work...
//! addr.send(1usize).unwrap();
//!
//! // ask the actors to finish and join the threads.
//! system.shutdown().unwrap();
//! ```
//!
use flume::{select::SelectError, Receiver, RecvError, Selector, Sender};
use log::*;
use parking_lot::{Mutex, RwLock};
use std::{
fmt,
ops::Deref,
sync::Arc,
thread,
time::{Duration, Instant},
};
pub mod timed;
#[cfg(test)]
pub mod testing;
// Default capacity for channels unless overridden by `.with_capacity()`.
static DEFAULT_CHANNEL_CAPACITY: usize = 5;
#[derive(Debug)]
pub enum ActorError {
/// The system has stopped, and a new actor can not be started.
SystemStopped { actor_name: &'static str },
/// Failed to spawn an actor thread.
SpawnFailed { actor_name: &'static str },
/// A panic occurred inside an actor thread.
ActorPanic,
}
impl fmt::Display for ActorError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ActorError::SystemStopped { actor_name } => {
write!(f, "The system is not running. The actor {} can not be started.", actor_name)
},
ActorError::SpawnFailed { actor_name } => {
write!(f, "Failed to spawn a thread for the actor {}.", actor_name)
},
ActorError::ActorPanic => {
write!(f, "A panic inside an actor thread. See above for more verbose logs.")
},
}
}
}
impl std::error::Error for ActorError {}
/// Failures that can occur when sending a message to an actor.
#[derive(Debug, Clone, Copy)]
pub struct SendError {
/// The name of the intended recipient.
pub recipient_name: &'static str,
/// The reason why sending has failed.
pub reason: SendErrorReason,
}
impl fmt::Display for SendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let recipient_name = self.recipient_name;
match self.reason {
SendErrorReason::Full => {
write!(f, "The capacity of {}'s channel is full.", recipient_name)
},
SendErrorReason::Disconnected => DisconnectedError { recipient_name }.fmt(f),
}
}
}
impl std::error::Error for SendError {}
/// The actor message channel is disconnected.
#[derive(Debug, Clone, Copy)]
pub struct DisconnectedError {
/// The name of the intended recipient.
pub recipient_name: &'static str,
}
impl fmt::Display for DisconnectedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "The recipient of the message ({}) no longer exists.", self.recipient_name)
}
}
impl std::error::Error for DisconnectedError {}
/// Reasons why sending a message to an actor can fail.
#[derive(Debug, Clone, Copy)]
pub enum SendErrorReason {
/// The channel's capacity is full.
Full,
/// The recipient of the message no longer exists.
Disconnected,
}
impl<M> From<flume::TrySendError<M>> for SendErrorReason {
fn from(orig: flume::TrySendError<M>) -> Self {
match orig {
flume::TrySendError::Full(_) => Self::Full,
flume::TrySendError::Disconnected(_) => Self::Disconnected,
}
}
}
/// Systems are responsible for keeping track of their spawned actors, and managing
/// their lifecycles appropriately.
///
/// You may run multiple systems in the same application, each system being responsible
/// for its own pool of actors.
#[derive(Default)]
pub struct System {
handle: SystemHandle,
}
type SystemCallback = Box<dyn Fn() -> Result<(), ActorError> + Send + Sync>;
#[derive(Default)]
pub struct SystemCallbacks {
pub preshutdown: Option<SystemCallback>,
pub postshutdown: Option<SystemCallback>,
}
#[derive(Debug, PartialEq)]
enum SystemState {
/// The system is running and able to spawn new actors, or be asked to shut down
Running,
/// The system is in the process of shutting down, actors cannot be spawned
/// or request for the system to shut down again
ShuttingDown,
/// The system has finished shutting down and is no longer running.
/// All actors have stopped and their threads have been joined. No actors
/// may be spawned at this point.
Stopped,
}
impl Default for SystemState {
fn default() -> Self {
SystemState::Running
}
}
/// Contains the "metadata" of the system, including information about the registry
/// of actors currently existing within the system.
#[derive(Default, Clone)]
pub struct SystemHandle {
name: String,
registry: Arc<Mutex<Vec<RegistryEntry>>>,
system_state: Arc<RwLock<SystemState>>,
callbacks: Arc<SystemCallbacks>,
}
/// An execution context for a specific actor. Specifically, this is useful for managing
/// the lifecycle of itself (through the `myself` field) and other actors via the `SystemHandle`
/// provided. A time-based deadline for receiving a message can be set using
/// [`Self::set_deadline()`] and friends.
pub struct Context<M> {
pub system_handle: SystemHandle,
pub myself: Recipient<M>,
receive_deadline: Option<Instant>,
}
impl<M> Context<M> {
fn new(system_handle: SystemHandle, myself: Recipient<M>) -> Self {
Self { system_handle, myself, receive_deadline: None }
}
/// Get the deadline previously set using [`Self::set_deadline()`] or [`Self::set_timeout()`].
/// The deadline is cleared just before [`Actor::deadline_passed()`] is called.
pub fn deadline(&self) -> &Option<Instant> {
&self.receive_deadline
}
/// Schedule a future one-shot call to [`Actor::deadline_passed()`], or cancel the schedule.
/// A deadline in the past is considered to expire right in the next iteration (possibly after
/// receiving new messages).
pub fn set_deadline(&mut self, deadline: Option<Instant>) {
self.receive_deadline = deadline;
}
/// Schedule or cancel a call to [`Actor::deadline_passed()`] after `timeout` from now.
/// Convenience variant of [`Self::set_deadline()`].
pub fn set_timeout(&mut self, timeout: Option<Duration>) {
self.set_deadline(timeout.map(|t| Instant::now() + t));
}
}
/// Capacity of actor's normal- and high-priority inboxes.
/// For each inbox type, `None` signifies default capacity. Converts from [`usize`].
#[derive(Clone, Copy, Debug, Default)]
pub struct Capacity {
normal: Option<usize>,
high: Option<usize>,
}
impl Capacity {
/// Set capacity of the normal priority channel, and use default for the high priority one.
pub fn of_normal_priority(capacity: usize) -> Self {
Self { normal: Some(capacity), ..Default::default() }
}
/// Set capacity of the high priority channel, and use default for the normal priority one.
pub fn of_high_priority(capacity: usize) -> Self {
Self { high: Some(capacity), ..Default::default() }
}
}
/// Set capacity of both normal and high priority channels to the same amount of messages.
impl From<usize> for Capacity {
fn from(capacity: usize) -> Self {
Self { normal: Some(capacity), high: Some(capacity) }
}
}
/// A builder for specifying how to spawn an [`Actor`].
/// You can specify your own [`Addr`] for the Actor,
/// the capacity of the Actor's inbox, and you can specify
/// whether to spawn the Actor into its own thread or block
/// on the current calling thread.
#[must_use = "You must call .spawn() or .block_on() to run this actor"]
pub struct SpawnBuilder<'a, A: Actor, F: FnOnce() -> A> {
system: &'a mut System,
capacity: Capacity,
addr: Option<Addr<A>>,
factory: F,
}
impl<'a, A: 'static + Actor<Context = Context<<A as Actor>::Message>>, F: FnOnce() -> A>
SpawnBuilder<'a, A, F>
{
/// Specify a capacity for the actor's receiving channel. Accepts [`Capacity`] or [`usize`].
pub fn with_capacity(self, capacity: impl Into<Capacity>) -> Self {
Self { capacity: capacity.into(), ..self }
}
/// Specify an existing [`Addr`] to use with this Actor.
pub fn with_addr(self, addr: Addr<A>) -> Self {
Self { addr: Some(addr), ..self }
}
/// Run this Actor on the current calling thread. This is a
/// blocking call. This function will exit when the Actor
/// has stopped.
pub fn run_and_block(self) -> Result<(), ActorError> {
let factory = self.factory;
let capacity = self.capacity;
let addr = self.addr.unwrap_or_else(|| Addr::with_capacity(capacity));
self.system.block_on(factory(), addr)
}
}
impl<
'a,
A: 'static + Actor<Context = Context<<A as Actor>::Message>>,
F: FnOnce() -> A + Send + 'static,
> SpawnBuilder<'a, A, F>
{
/// Spawn this Actor into a new thread managed by the [`System`].
pub fn spawn(self) -> Result<Addr<A>, ActorError> {
let factory = self.factory;
let capacity = self.capacity;
let addr = self.addr.unwrap_or_else(|| Addr::with_capacity(capacity));
self.system.spawn_fn_with_addr(factory, addr.clone()).map(move |_| addr)
}
}
impl System {
/// Creates a new System with a given name.
pub fn new(name: &str) -> Self {
System::with_callbacks(name, Default::default())
}
pub fn with_callbacks(name: &str, callbacks: SystemCallbacks) -> Self {
Self {
handle: SystemHandle {
name: name.to_owned(),
callbacks: Arc::new(callbacks),
..SystemHandle::default()
},
}
}
/// Prepare an actor to be spawned. Returns a [`SpawnBuilder`]
/// which can be used to customize the spawning of the actor.
pub fn prepare<A>(&mut self, actor: A) -> SpawnBuilder<A, impl FnOnce() -> A>
where
A: Actor + 'static,
{
SpawnBuilder {
system: self,
capacity: Default::default(),
addr: None,
factory: move || actor,
}
}
/// Similar to `prepare`, but an actor factory is passed instead
/// of an [`Actor`] itself. This is used when an actor needs to be
/// created on its own thread instead of the calling thread.
/// Returns a [`SpawnBuilder`] which can be used to customize the
/// spawning of the actor.
pub fn prepare_fn<A, F>(&mut self, factory: F) -> SpawnBuilder<A, F>
where
A: Actor + 'static,
F: FnOnce() -> A + Send + 'static,
{
SpawnBuilder { system: self, capacity: Default::default(), addr: None, factory }
}
/// Spawn a normal [`Actor`] in the system, returning its address when successful.
pub fn spawn<A>(&mut self, actor: A) -> Result<Addr<A>, ActorError>
where
A: Actor<Context = Context<<A as Actor>::Message>> + Send + 'static,
{
self.prepare(actor).spawn()
}
/// Spawn a normal Actor in the system, using a factory that produces an [`Actor`],
/// and an address that will be assigned to the Actor.
///
/// This method is useful if you need to model circular dependencies between `Actor`s.
fn spawn_fn_with_addr<F, A>(&mut self, factory: F, addr: Addr<A>) -> Result<(), ActorError>
where
F: FnOnce() -> A + Send + 'static,
A: Actor<Context = Context<<A as Actor>::Message>> + 'static,
{
// Hold the lock until the end of the function to prevent the race
// condition between spawn and shutdown.
let system_state_lock = self.handle.system_state.read();
match *system_state_lock {
SystemState::ShuttingDown | SystemState::Stopped => {
return Err(ActorError::SystemStopped { actor_name: A::name() });
},
SystemState::Running => {},
}
let system_handle = self.handle.clone();
let mut context = Context::new(system_handle.clone(), addr.recipient.clone());
let control_addr = addr.control_tx.clone();
let thread_handle = thread::Builder::new()
.name(A::name().into())
.spawn(move || {
let mut actor = factory();
actor.started(&mut context);
debug!("[{}] started actor: {}", system_handle.name, A::name());
Self::run_actor_select_loop(actor, addr, &mut context, &system_handle);
})
.map_err(|_| ActorError::SpawnFailed { actor_name: A::name() })?;
self.handle
.registry
.lock()
.push(RegistryEntry::BackgroundThread(control_addr, thread_handle));
Ok(())
}
/// Block the current thread until the system is shutdown.
pub fn run(&mut self) -> Result<(), ActorError> {
while *self.system_state.read() != SystemState::Stopped {
thread::sleep(Duration::from_millis(10));
}
Ok(())
}
/// Takes an actor and its address and runs it on the calling thread. This function
/// will exit once the actor has stopped.
fn block_on<A>(&mut self, mut actor: A, addr: Addr<A>) -> Result<(), ActorError>
where
A: Actor<Context = Context<<A as Actor>::Message>>,
{
// Prevent race condition of spawn and shutdown.
if !self.is_running() {
return Err(ActorError::SystemStopped { actor_name: A::name() });
}
let system_handle = &self.handle;
let mut context = Context::new(system_handle.clone(), addr.recipient.clone());
self.handle.registry.lock().push(RegistryEntry::CurrentThread(addr.control_tx.clone()));
actor.started(&mut context);
debug!("[{}] started actor: {}", system_handle.name, A::name());
Self::run_actor_select_loop(actor, addr, &mut context, system_handle);
// Wait for the system to shutdown before we exit, otherwise the process
// would exit before the system is completely shutdown
// TODO(bschwind) - We could possibly use a parking_lot::CondVar here
// for more efficient waiting
while *self.system_state.read() != SystemState::Stopped {
thread::sleep(Duration::from_millis(10));
}
Ok(())
}
fn run_actor_select_loop<A>(
mut actor: A,
addr: Addr<A>,
context: &mut Context<A::Message>,
system_handle: &SystemHandle,
) where
A: Actor<Context = Context<<A as Actor>::Message>>,
{
/// What can be received during one actor event loop.
enum Received<M> {
Control(Control),
Message(M),
Timeout,
}
loop {
// We don't handle the messages (control and actor's) directly in .recv(), that would
// lead to mutably borrowing actor multiple times. Read into intermediate enum instead.
// The order of .recv() calls is significant and determines priority.
let selector = Selector::new()
.recv(&addr.control_rx, |msg| match msg {
Ok(control) => Received::Control(control),
Err(RecvError::Disconnected) => {
panic!("We keep control_tx alive through addr, should not happen.")
},
})
.recv(&addr.priority_rx, |msg| match msg {
Ok(msg) => Received::Message(msg),
Err(RecvError::Disconnected) => {
panic!("We keep message_tx alive through addr, should not happen.")
},
})
.recv(&addr.message_rx, |msg| match msg {
Ok(msg) => Received::Message(msg),
Err(RecvError::Disconnected) => {
panic!("We keep message_tx alive through addr, should not happen.")
},
});
// Wait for some event to happen, with a timeout if set.
let received = if let Some(deadline) = context.receive_deadline {
match selector.wait_deadline(deadline) {
Ok(received) => received,
Err(SelectError::Timeout) => Received::Timeout,
}
} else {
selector.wait()
};
// Process the event. Returning ends actor loop, the normal operation is to fall through.
match received {
Received::Control(Control::Stop) => {
actor.stopped(context);
debug!("[{}] stopped actor: {}", system_handle.name, A::name());
return;
},
Received::Message(msg) => {
trace!("[{}] message received by {}", system_handle.name, A::name());
if let Err(err) = actor.handle(context, msg) {
error!(
"[{}] {} handle error: {:?}, shutting down.",
system_handle.name,
A::name(),
err
);
let _ = system_handle.shutdown();
return;
}
},
Received::Timeout => {
let deadline = context.receive_deadline.take().expect("implied by timeout");
if let Err(err) = actor.deadline_passed(context, deadline) {
error!(
"[{}] {} deadline_passed error: {:?}, shutting down.",
system_handle.name,
A::name(),
err
);
let _ = system_handle.shutdown();
return;
}
},
}
}
}
}
impl Drop for System {
fn drop(&mut self) {
self.shutdown().unwrap();
}
}
impl Deref for System {
type Target = SystemHandle;
fn deref(&self) -> &Self::Target {
&self.handle
}
}
impl SystemHandle {
/// Stops all actors spawned by this system.
pub fn shutdown(&self) -> Result<(), ActorError> {
let current_thread = thread::current();
let current_thread_name = current_thread.name().unwrap_or("Unknown thread id");
info!("Thread [{}] shutting down the actor system", current_thread_name);
// Use an inner scope to prevent holding the lock for the duration of shutdown
{
let mut system_state_lock = self.system_state.write();
match *system_state_lock {
SystemState::ShuttingDown | SystemState::Stopped => {
debug!("Thread [{}] called system.shutdown() but the system is already shutting down or stopped", current_thread_name);
return Ok(());
},
SystemState::Running => {
debug!(
"Thread [{}] setting the system_state value to ShuttingDown",
current_thread_name
);
*system_state_lock = SystemState::ShuttingDown;
},
}
}
info!("[{}] system shutting down.", self.name);
if let Some(callback) = self.callbacks.preshutdown.as_ref() {
info!("[{}] calling pre-shutdown callback.", self.name);
if let Err(err) = callback() {
warn!("[{}] pre-shutdown callback failed, reason: {}", self.name, err);
}
}
let err_count = {
let mut registry = self.registry.lock();
debug!("[{}] joining {} actor threads.", self.name, registry.len());
// Joining actors in the reverse order in which they are spawn.
registry
.drain(..)
.rev()
.enumerate()
.filter_map(|(i, mut entry)| {
let actor_name = entry.name();
if let Err(e) = entry.control_addr().send(Control::Stop) {
warn!("control channel is closed: {} ({})", actor_name, e);
}
match entry {
RegistryEntry::CurrentThread(_) => None,
RegistryEntry::BackgroundThread(_control_addr, thread_handle) => {
if thread_handle.thread().id() == current_thread.id() {
return None;
}
debug!("[{}] [{}] joining actor thread: {}", self.name, i, actor_name);
let join_result = thread_handle.join().map_err(|e| {
error!("a panic inside actor thread {}: {:?}", actor_name, e)
});
debug!("[{}] [{}] joined actor thread: {}", self.name, i, actor_name);
join_result.err()
},
}
})
.count()
};
info!("[{}] system finished shutting down.", self.name);
if let Some(callback) = self.callbacks.postshutdown.as_ref() {
info!("[{}] calling post-shutdown callback.", self.name);
if let Err(err) = callback() {
warn!("[{}] post-shutdown callback failed, reason: {}", self.name, err);
}
}
*self.system_state.write() = SystemState::Stopped;
if err_count > 0 {
Err(ActorError::ActorPanic)
} else {
Ok(())
}
}
pub fn is_running(&self) -> bool {
*self.system_state.read() == SystemState::Running
}
}
enum RegistryEntry {
CurrentThread(Sender<Control>),
BackgroundThread(Sender<Control>, thread::JoinHandle<()>),
}
impl RegistryEntry {
fn name(&self) -> String {
match self {
RegistryEntry::CurrentThread(_) => {
thread::current().name().unwrap_or("unnamed").to_owned()
},
RegistryEntry::BackgroundThread(_, thread_handle) => {
thread_handle.thread().name().unwrap_or("unnamed").to_owned()
},
}
}
fn control_addr(&mut self) -> &mut Sender<Control> {
match self {
RegistryEntry::CurrentThread(control_addr) => control_addr,
RegistryEntry::BackgroundThread(control_addr, _) => control_addr,
}
}
}
/// The set of available control messages that all actors respond to.
pub enum Control {
/// Stop the actor
Stop,
}
/// The base actor trait.
pub trait Actor {
/// The expected type of a message to be received.
// 'static required to create trait object in Addr, https://stackoverflow.com/q/29740488/4345715
type Message: Send + 'static;
/// The type to return on error in the handle method.
type Error: std::fmt::Debug;
/// What kind of context this actor accepts. Usually [`Context<Self::Message>`].
type Context;
/// The primary function of this trait, allowing an actor to handle incoming messages of a certain type.
fn handle(
&mut self,
context: &mut Self::Context,
message: Self::Message,
) -> Result<(), Self::Error>;
/// The name of the Actor - used only for logging/debugging.
fn name() -> &'static str;
/// Determine priority of a `message` before it is sent to this actor.
/// Default implementation returns [`Priority::Normal`].
fn priority(_message: &Self::Message) -> Priority {
Priority::Normal
}
/// An optional callback when the Actor has been started.
fn started(&mut self, _context: &mut Self::Context) {}
/// An optional callback when the Actor has been stopped.
fn stopped(&mut self, _context: &mut Self::Context) {}
/// An optional callback when a deadline has passed.
///
/// The deadline has to be set via [`Context::set_deadline()`] or [`Context::set_timeout()`]
/// first. The instant to which the deadline was originally set is passed via the `deadline`
/// argument; it is normally close to [`Instant::now()`], but can be later if the actor was busy.
///
/// # Periodic tick example
/// ```
/// # use {std::{cmp::max, time::{Duration, Instant}}, tonari_actor::{Actor, Context}};
/// # struct TickingActor;
/// impl Actor for TickingActor {
/// # type Context = Context<Self::Message>;
/// # type Error = ();
/// # type Message = ();
/// # fn name() -> &'static str { "TickingActor" }
/// # fn handle(&mut self, _: &mut Self::Context, _: ()) -> Result<(), ()> { Ok(()) }
/// // ...
///
/// fn deadline_passed(&mut self, context: &mut Self::Context, deadline: Instant) -> Result<(), ()> {
/// // do_periodic_housekeeping();
///
/// // A: Schedule one second from now (even if delayed); drifting tick.
/// context.set_timeout(Some(Duration::from_secs(1)));
///
/// // B: Schedule one second from deadline; non-drifting tick.
/// context.set_deadline(Some(deadline + Duration::from_secs(1)));
///
/// // C: Schedule one second from deadline, but don't fire multiple times if delayed.
/// context.set_deadline(Some(max(deadline + Duration::from_secs(1), Instant::now())));
///
/// Ok(())
/// }
/// }
/// ```
fn deadline_passed(
&mut self,
_context: &mut Self::Context,
_deadline: Instant,
) -> Result<(), Self::Error> {
Ok(())
}
}
pub struct Addr<A: Actor + ?Sized> {
recipient: Recipient<A::Message>,
priority_rx: Receiver<A::Message>,
message_rx: Receiver<A::Message>,
control_rx: Receiver<Control>,
}
impl<A: Actor> Default for Addr<A> {
fn default() -> Self {
Self::with_capacity(DEFAULT_CHANNEL_CAPACITY)
}
}
impl<A: Actor> Clone for Addr<A> {
fn clone(&self) -> Self {
Self {
recipient: self.recipient.clone(),
priority_rx: self.priority_rx.clone(),
message_rx: self.message_rx.clone(),
control_rx: self.control_rx.clone(),
}
}
}
impl<A, M> Deref for Addr<A>
where
A: Actor<Message = M>,
{
type Target = Recipient<M>;
fn deref(&self) -> &Self::Target {
&self.recipient
}
}
impl<A: Actor> Addr<A> {
/// Create address for an actor, specifying its inbox size. Accepts [`Capacity`] or [`usize`].
pub fn with_capacity(capacity: impl Into<Capacity>) -> Self {
let capacity: Capacity = capacity.into();
let prio_capacity = capacity.high.unwrap_or(DEFAULT_CHANNEL_CAPACITY);
let normal_capacity = capacity.normal.unwrap_or(DEFAULT_CHANNEL_CAPACITY);
let (priority_tx, priority_rx) = flume::bounded::<A::Message>(prio_capacity);
let (message_tx, message_rx) = flume::bounded::<A::Message>(normal_capacity);
let (control_tx, control_rx) = flume::bounded(DEFAULT_CHANNEL_CAPACITY);
let message_tx = Arc::new(MessageSender {
high: priority_tx,
normal: message_tx,
get_priority: A::priority,
});
let name = A::name();
Self {
recipient: Recipient { message_tx, control_tx, name },
priority_rx,
message_rx,
control_rx,
}
}
/// "Genericize" an address to, rather than point to a specific actor,
/// be applicable to any actor that handles a given message-response type.
/// Allows you to create recipient not only of `A::Message`, but of any `M: Into<A::Message>`.
pub fn recipient<M: Into<A::Message>>(&self) -> Recipient<M> {
Recipient {
// Each level of boxing adds one .into() call, so box here to convert A::Message to M.
message_tx: Arc::new(self.recipient.message_tx.clone()),
control_tx: self.recipient.control_tx.clone(),
name: A::name(),
}
}
}
/// Urgency of a given message. All high-priority messages are delivered before normal priority.
#[derive(Clone, Copy, Debug)]
pub enum Priority {
Normal,
High,
}
/// Similar to [`Addr`], but rather than pointing to a specific actor,
/// it is typed for any actor that handles a given message-response type.
pub struct Recipient<M> {
message_tx: Arc<dyn SenderTrait<M>>,
control_tx: Sender<Control>,
name: &'static str,
}
// #[derive(Clone)] adds Clone bound to M, which is not necessary.
// https://github.com/rust-lang/rust/issues/26925
impl<M> Clone for Recipient<M> {
fn clone(&self) -> Self {
Self {
message_tx: self.message_tx.clone(),
control_tx: self.control_tx.clone(),
name: self.name,
}
}
}
impl<M> Recipient<M> {
/// Send a message to an actor. Returns [`SendError`] if the channel is full; does not block.
/// See [`SendResultExt`] trait for convenient handling of errors.
pub fn send(&self, message: M) -> Result<(), SendError> {
self.message_tx
.try_send(message)
.map_err(|reason| SendError { recipient_name: self.name, reason })
}
}
pub trait SendResultExt {
/// Don't return an `Err` when the recipient is at full capacity, run `func(receiver_name)`
/// in such a case instead. `receiver_name` is the name of the intended recipient.
fn on_full<F: FnOnce(&'static str)>(self, func: F) -> Result<(), DisconnectedError>;
/// Don't return an `Err` when the recipient is at full capacity.
fn ignore_on_full(self) -> Result<(), DisconnectedError>;
}
impl SendResultExt for Result<(), SendError> {
fn on_full<F: FnOnce(&'static str)>(self, callback: F) -> Result<(), DisconnectedError> {
self.or_else(|e| match e.reason {
SendErrorReason::Full => {
callback(e.recipient_name);
Ok(())
},
_ => Err(DisconnectedError { recipient_name: e.recipient_name }),
})
}
fn ignore_on_full(self) -> Result<(), DisconnectedError> {
self.on_full(|_| ())
}
}
/// Internal struct to encapsulate ability to send message with priority to an actor.
struct MessageSender<M> {
high: Sender<M>,
normal: Sender<M>,
get_priority: fn(&M) -> Priority,
}
/// Internal trait to generalize over [`Sender`].
trait SenderTrait<M>: Send + Sync {
fn try_send(&self, message: M) -> Result<(), SendErrorReason>;
}
/// [`SenderTrait`] is implemented for our [`MessageSender`].
impl<M: Send> SenderTrait<M> for MessageSender<M> {
fn try_send(&self, message: M) -> Result<(), SendErrorReason> {
let priority = (self.get_priority)(&message);
let sender = match priority {
Priority::Normal => &self.normal,
Priority::High => &self.high,
};
sender.try_send(message).map_err(SendErrorReason::from)
}
}
/// [`SenderTrait`] is also implemented for boxed version of itself, including M -> N conversion.
impl<M: Into<N>, N> SenderTrait<M> for Arc<dyn SenderTrait<N>> {
fn try_send(&self, message: M) -> Result<(), SendErrorReason> {
self.deref().try_send(message.into())
}
}
#[cfg(test)]
mod tests {
use std::{
rc::Rc,
sync::atomic::{AtomicU32, Ordering},
time::Duration,
};
use super::*;
struct TestActor;
impl Actor for TestActor {
type Context = Context<Self::Message>;
type Error = ();
type Message = usize;
fn name() -> &'static str {
"TestActor"
}
fn handle(&mut self, _: &mut Self::Context, message: usize) -> Result<(), ()> {
println!("message: {}", message);
Ok(())
}
fn started(&mut self, _: &mut Self::Context) {
println!("started");
}
fn stopped(&mut self, _: &mut Self::Context) {
println!("stopped");
}
}
#[test]
fn it_works() {
let mut system = System::new("hi");
let address = system.spawn(TestActor).unwrap();
let _ = system.spawn(TestActor).unwrap();
let _ = system.spawn(TestActor).unwrap();
let _ = system.spawn(TestActor).unwrap();
let _ = system.spawn(TestActor).unwrap();
address.send(1337usize).unwrap();
address.send(666usize).unwrap();
address.send(1usize).unwrap();
thread::sleep(Duration::from_millis(100));
system.shutdown().unwrap();
thread::sleep(Duration::from_millis(100));
}
#[test]
fn test_ignore_on_full() {
let mut system = System::new("hi");
let address = system.prepare(TestActor).with_capacity(1).spawn().unwrap();
address.send(1337usize).unwrap();
assert!(address.send(666usize).is_err());
address.send(666usize).ignore_on_full().unwrap();
thread::sleep(Duration::from_millis(100));
system.shutdown().unwrap();
thread::sleep(Duration::from_millis(100));
}
#[test]
fn send_constraints() {
#[derive(Default)]
struct LocalActor(Rc<()>);
impl Actor for LocalActor {
type Context = Context<Self::Message>;
type Error = ();
type Message = ();
fn name() -> &'static str {
"LocalActor"
}
fn handle(&mut self, _: &mut Self::Context, _: ()) -> Result<(), ()> {
Ok(())
}
/// We just need this test to compile, not run.
fn started(&mut self, ctx: &mut Self::Context) {
ctx.system_handle.shutdown().unwrap();
}
}
let mut system = System::new("main");
// Allowable, as the struct will be created on the new thread.
let _ = system.prepare_fn(LocalActor::default).spawn().unwrap();
// Allowable, as the struct will be run on the current thread.
let _ = system.prepare(LocalActor::default()).run_and_block().unwrap();
system.shutdown().unwrap();
}
#[test]
fn timeouts() {
struct TimeoutActor {
handle_count: Arc<AtomicU32>,
timeout_count: Arc<AtomicU32>,
}
impl Actor for TimeoutActor {
type Context = Context<Self::Message>;
type Error = ();
type Message = Option<Instant>;
fn name() -> &'static str {
"TimeoutActor"
}
fn handle(&mut self, ctx: &mut Self::Context, msg: Self::Message) -> Result<(), ()> {
self.handle_count.fetch_add(1, Ordering::SeqCst);
if msg.is_some() {
ctx.receive_deadline = msg;
}
Ok(())
}
fn deadline_passed(&mut self, _: &mut Self::Context, _: Instant) -> Result<(), ()> {
self.timeout_count.fetch_add(1, Ordering::SeqCst);
Ok(())
}
}
let mut system = System::new("timeouts");
let (handle_count, timeout_count) = (Default::default(), Default::default());
let actor = TimeoutActor {
handle_count: Arc::clone(&handle_count),
timeout_count: Arc::clone(&timeout_count),
};
let addr = system.spawn(actor).unwrap();
// Test that setting deadline to past triggers the deadline immediately.
addr.send(Some(Instant::now() - Duration::from_secs(1))).unwrap();
thread::sleep(Duration::from_millis(10));
assert_eq!(handle_count.load(Ordering::SeqCst), 1);
assert_eq!(timeout_count.load(Ordering::SeqCst), 1);
// Test the normal case.
addr.send(Some(Instant::now() + Duration::from_millis(20))).unwrap();
thread::sleep(Duration::from_millis(10));
assert_eq!(handle_count.load(Ordering::SeqCst), 2);
assert_eq!(timeout_count.load(Ordering::SeqCst), 1);
thread::sleep(Duration::from_millis(20));
assert_eq!(handle_count.load(Ordering::SeqCst), 2);
assert_eq!(timeout_count.load(Ordering::SeqCst), 2);
// Test that receiving a message doesn't reset the deadline.
addr.send(Some(Instant::now() + Duration::from_millis(40))).unwrap();
thread::sleep(Duration::from_millis(20));
assert_eq!(handle_count.load(Ordering::SeqCst), 3);
assert_eq!(timeout_count.load(Ordering::SeqCst), 2);
addr.send(None).unwrap();
thread::sleep(Duration::from_millis(30));
assert_eq!(handle_count.load(Ordering::SeqCst), 4);
assert_eq!(timeout_count.load(Ordering::SeqCst), 3);
system.shutdown().unwrap();
}
#[test]
fn errors() {
let mut system = System::new("hi");
let full_actor = system.prepare(TestActor).with_capacity(0).spawn().unwrap();
// Convert to `Recipient` so that we don't keep the receiving side of `Addr` alive.
let stopped_actor = system.spawn(TestActor).unwrap().recipient();
let error = full_actor.send(123).unwrap_err();
assert_eq!(error.to_string(), "The capacity of TestActor's channel is full.");
assert_eq!(
format!("{:?}", error),
r#"SendError { recipient_name: "TestActor", reason: Full }"#
);
system.shutdown().unwrap();
let error = stopped_actor.send(456usize).unwrap_err();
assert_eq!(error.to_string(), "The recipient of the message (TestActor) no longer exists.");
assert_eq!(
format!("{:?}", error),
r#"SendError { recipient_name: "TestActor", reason: Disconnected }"#
);
}
#[test]
fn message_priorities() {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init();
struct PriorityActor {
received: Arc<Mutex<Vec<usize>>>,
}
impl Actor for PriorityActor {
type Context = Context<Self::Message>;
type Error = ();
type Message = usize;
fn handle(
&mut self,
context: &mut Self::Context,
message: Self::Message,
) -> Result<(), Self::Error> {
let mut received = self.received.lock();
received.push(message);
if received.len() >= 20 {
context.system_handle.shutdown().unwrap();
}
Ok(())
}
fn name() -> &'static str {
"PriorityActor"
}
fn priority(message: &Self::Message) -> Priority {
if *message >= 10 {
Priority::High
} else {
Priority::Normal
}
}
}
let addr = Addr::with_capacity(10);
let received = Arc::new(Mutex::new(Vec::<usize>::new()));
// Send messages before even actor starts.
for message in 0..20usize {
addr.send(message).unwrap();
}
let mut system = System::new("priorities");
system
.prepare(PriorityActor { received: Arc::clone(&received) })
.with_addr(addr)
.run_and_block()
.unwrap();
assert_eq!(
*received.lock(),
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
);
}
}
|
use pyo3::prelude::*;
pub fn register_module(py: Python<'_>, parent_module: &PyModule) -> PyResult<()>
{
let isometric = PyModule::new(py, "isometric")?;
super::legendre::py::register_module(py, isometric)?;
parent_module.add_submodule(isometric)?;
isometric.add_class::<SWFJC>()?;
Ok(())
}
/// The square-well freely-jointed chain (SWFJC) model thermodynamics in the isometric ensemble.
#[pyclass]
#[derive(Copy, Clone)]
pub struct SWFJC
{
/// The mass of each hinge in the chain in units of kg/mol.
#[pyo3(get)]
pub hinge_mass: f64,
/// The length of each link in the chain in units of nm.
#[pyo3(get)]
pub link_length: f64,
/// The number of links in the chain.
#[pyo3(get)]
pub number_of_links: u8,
/// The width of the well in units of nm.
#[pyo3(get)]
pub well_width: f64,
/// The thermodynamic functions of the model in the isometric ensemble approximated using a Legendre transformation.
#[pyo3(get)]
pub legendre: super::legendre::py::SWFJC
}
#[pymethods]
impl SWFJC
{
#[new]
pub fn init(number_of_links: u8, link_length: f64, hinge_mass: f64, well_width: f64) -> Self
{
SWFJC
{
hinge_mass,
link_length,
number_of_links,
well_width,
legendre: super::legendre::py::SWFJC::init(number_of_links, link_length, hinge_mass, well_width)
}
}
} |
#[link(name = "emlib")]
extern {
pub fn CHIP_Init();
}
pub fn init() {
unsafe { CHIP_Init(); }
}
|
use vulkano::framebuffer::{LayoutAttachmentDescription, LayoutPassDependencyDescription,
LayoutPassDescription, LoadOp, RenderPassDesc,
RenderPassDescClearValues, StoreOp};
use vulkano::image::ImageLayout;
use vulkano::format::{ClearValue, Format};
use vulkano::sync::{AccessFlagBits, PipelineStages};
pub struct CustomRenderPassDesc;
unsafe impl RenderPassDesc for CustomRenderPassDesc {
#[inline]
fn num_attachments(&self) -> usize {
4
}
#[inline]
fn attachment_desc(&self, id: usize) -> Option<LayoutAttachmentDescription> {
match id {
// Colors
0 => Some(LayoutAttachmentDescription {
format: Format::R8G8B8A8Uint,
samples: 1,
load: LoadOp::Clear,
store: StoreOp::Store,
stencil_load: LoadOp::Clear,
stencil_store: StoreOp::Store,
initial_layout: ImageLayout::Undefined,
final_layout: ImageLayout::ColorAttachmentOptimal,
}),
// Erasers
1 => Some(LayoutAttachmentDescription {
format: Format::R8Uint,
samples: 1,
load: LoadOp::Clear,
store: StoreOp::Store,
stencil_load: LoadOp::Clear,
stencil_store: StoreOp::Store,
initial_layout: ImageLayout::Undefined,
final_layout: ImageLayout::ColorAttachmentOptimal,
}),
// Depth buffer
2 => Some(LayoutAttachmentDescription {
format: Format::D16Unorm,
samples: 1,
load: LoadOp::Clear,
store: StoreOp::DontCare,
stencil_load: LoadOp::Clear,
stencil_store: StoreOp::DontCare,
initial_layout: ImageLayout::Undefined,
final_layout: ImageLayout::DepthStencilAttachmentOptimal,
}),
// HUD depth buffer
3 => Some(LayoutAttachmentDescription {
format: Format::D16Unorm,
samples: 1,
load: LoadOp::Clear,
store: StoreOp::DontCare,
stencil_load: LoadOp::Clear,
stencil_store: StoreOp::DontCare,
initial_layout: ImageLayout::Undefined,
final_layout: ImageLayout::DepthStencilAttachmentOptimal,
}),
_ => None,
}
}
#[inline]
fn num_subpasses(&self) -> usize {
3
}
#[inline]
fn subpass_desc(&self, id: usize) -> Option<LayoutPassDescription> {
match id {
// draw
0 => Some(LayoutPassDescription {
color_attachments: vec![(0, ImageLayout::ColorAttachmentOptimal)],
depth_stencil: Some((2, ImageLayout::DepthStencilAttachmentOptimal)),
input_attachments: vec![],
resolve_attachments: vec![],
preserve_attachments: vec![1, 3],
}),
// erase
1 => Some(LayoutPassDescription {
color_attachments: vec![(1, ImageLayout::ColorAttachmentOptimal)],
depth_stencil: Some((2, ImageLayout::DepthStencilAttachmentOptimal)),
input_attachments: vec![],
resolve_attachments: vec![],
preserve_attachments: vec![0, 3],
}),
// draw HUD
2 => Some(LayoutPassDescription {
color_attachments: vec![(0, ImageLayout::ColorAttachmentOptimal)],
depth_stencil: Some((3, ImageLayout::DepthStencilAttachmentOptimal)),
input_attachments: vec![],
resolve_attachments: vec![],
preserve_attachments: vec![1, 2],
}),
_ => None,
}
}
#[inline]
fn num_dependencies(&self) -> usize {
2
}
#[inline]
fn dependency_desc(&self, id: usize) -> Option<LayoutPassDependencyDescription> {
match id {
0 => Some(LayoutPassDependencyDescription {
source_subpass: 0,
destination_subpass: 1,
source_stages: PipelineStages {
late_fragment_tests: true,
..PipelineStages::none()
},
destination_stages: PipelineStages {
early_fragment_tests: true,
..PipelineStages::none()
},
source_access: AccessFlagBits {
// TODO: color attachment ?
depth_stencil_attachment_write: true,
depth_stencil_attachment_read: true,
..AccessFlagBits::none()
},
destination_access: AccessFlagBits {
// TODO: color attachment ?
depth_stencil_attachment_write: true,
depth_stencil_attachment_read: true,
..AccessFlagBits::none()
},
by_region: true,
}),
1 => Some(LayoutPassDependencyDescription {
source_subpass: 0,
destination_subpass: 2,
source_stages: PipelineStages {
late_fragment_tests: true,
..PipelineStages::none()
},
destination_stages: PipelineStages {
early_fragment_tests: true,
..PipelineStages::none()
},
source_access: AccessFlagBits {
color_attachment_write: true,
..AccessFlagBits::none()
},
destination_access: AccessFlagBits {
color_attachment_write: true,
..AccessFlagBits::none()
},
by_region: true,
}),
_ => None,
}
}
}
unsafe impl RenderPassDescClearValues<Vec<ClearValue>> for CustomRenderPassDesc {
fn convert_clear_values(&self, values: Vec<ClearValue>) -> Box<Iterator<Item = ClearValue>> {
// FIXME: safety checks
Box::new(values.into_iter())
}
}
pub struct SecondCustomRenderPassDesc {
swapchain_format: Format
}
impl SecondCustomRenderPassDesc {
pub fn new(swapchain_format: Format) -> Self {
SecondCustomRenderPassDesc {
swapchain_format,
}
}
}
unsafe impl RenderPassDesc for SecondCustomRenderPassDesc {
#[inline]
fn num_attachments(&self) -> usize {
1
}
#[inline]
fn attachment_desc(&self, id: usize) -> Option<LayoutAttachmentDescription> {
match id {
0 => Some(LayoutAttachmentDescription {
format: self.swapchain_format,
samples: 1,
load: LoadOp::DontCare,
store: StoreOp::Store,
stencil_load: LoadOp::DontCare,
stencil_store: StoreOp::Store,
initial_layout: ImageLayout::Undefined,
final_layout: ImageLayout::ColorAttachmentOptimal,
}),
_ => None,
}
}
#[inline]
fn num_subpasses(&self) -> usize {
1
}
#[inline]
fn subpass_desc(&self, id: usize) -> Option<LayoutPassDescription> {
match id {
0 => Some(LayoutPassDescription {
color_attachments: vec![(0, ImageLayout::ColorAttachmentOptimal)],
depth_stencil: None,
input_attachments: vec![],
resolve_attachments: vec![],
preserve_attachments: vec![],
}),
_ => None,
}
}
#[inline]
fn num_dependencies(&self) -> usize {
0
}
#[inline]
fn dependency_desc(&self, _id: usize) -> Option<LayoutPassDependencyDescription> {
None
}
}
unsafe impl RenderPassDescClearValues<Vec<ClearValue>> for SecondCustomRenderPassDesc {
fn convert_clear_values(&self, values: Vec<ClearValue>) -> Box<Iterator<Item = ClearValue>> {
// FIXME: safety checks
Box::new(values.into_iter())
}
}
|
use std::fmt::Debug;
use std::str::FromStr;
use num_traits::PrimInt;
pub fn parse_iterable<'a, T>(
iter: impl Iterator<Item = &'a str> + 'a,
) -> impl Iterator<Item = T> + 'a
where
T: PrimInt + FromStr,
<T as FromStr>::Err: Debug,
{
iter.map(|elem| elem.parse::<T>().unwrap())
}
// TODO: Once `Pattern` is stablized, consolidate these
pub fn parse_str_delimited_numbers<'a, T: 'a>(
s: &'a str,
delim: &'a str,
) -> impl Iterator<Item = T> + 'a
where
T: PrimInt + FromStr,
<T as FromStr>::Err: Debug,
{
parse_iterable(s.split(delim))
}
pub fn parse_char_delimited_numbers<'a, T: 'a>(
s: &'a str,
delim: char,
) -> impl Iterator<Item = T> + 'a
where
T: PrimInt + FromStr,
<T as FromStr>::Err: Debug,
{
parse_iterable(s.split(delim))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_iterable() {
assert_eq!(parse_iterable([].into_iter()).collect::<Vec<u32>>(), vec![]);
assert_eq!(
parse_iterable(["1", "2", "3", "4"].into_iter()).collect::<Vec<u32>>(),
vec![1, 2, 3, 4]
);
assert_eq!(
parse_iterable(["100", "-200", "300", "-400"].into_iter()).collect::<Vec<i32>>(),
vec![100, -200, 300, -400]
);
}
#[test]
fn test_parse_str_delimited_numbers() {
assert_eq!(
parse_str_delimited_numbers("1!#2!#3!#4", "!#").collect::<Vec<u32>>(),
vec![1, 2, 3, 4]
);
assert_eq!(
parse_str_delimited_numbers("1!#-2!#3!#-400", "!#").collect::<Vec<i32>>(),
vec![1, -2, 3, -400]
);
}
#[test]
fn test_parse_char_delimited_numbers() {
assert_eq!(
parse_char_delimited_numbers("1,2,3,4", ',').collect::<Vec<u32>>(),
vec![1, 2, 3, 4]
);
assert_eq!(
parse_char_delimited_numbers("1,-2,3,-400", ',').collect::<Vec<i32>>(),
vec![1, -2, 3, -400]
);
}
}
|
use std::fs;
fn main() {
let input = fs::read_to_string("./input.txt").unwrap_or_default();
dbg!(input
.lines()
.filter(|line| line
.chars()
.filter(|&character| character == 'a'
|| character == 'e'
|| character == 'i'
|| character == 'o'
|| character == 'u')
.count()
>= 3)
.filter(|line| line
.chars()
.collect::<Vec<char>>()
.windows(2)
.any(|chars| chars[0] == chars[1]))
.filter(|line| !(line.contains("ab")
|| line.contains("cd")
|| line.contains("pq")
|| line.contains("xy")))
.fold(0, |total, _| total + 1));
}
|
#![allow(
clippy::items_after_statements,
clippy::uninlined_format_args,
clippy::unused_async
)]
use cxx::{let_cxx_string, CxxString};
use std::fmt::Write as _;
#[test]
fn test_async_cxx_string() {
async fn f() {
let_cxx_string!(s = "...");
async fn g(_: &CxxString) {}
g(&s).await;
}
// https://github.com/dtolnay/cxx/issues/693
fn assert_send(_: impl Send) {}
assert_send(f());
}
#[test]
fn test_debug() {
let_cxx_string!(s = "x\"y\'z");
assert_eq!(format!("{:?}", s), r#""x\"y'z""#);
}
#[test]
fn test_fmt_write() {
let_cxx_string!(s = "");
let name = "world";
write!(s, "Hello, {name}!").unwrap();
assert_eq!(s.to_str(), Ok("Hello, world!"));
}
#[test]
fn test_io_write() {
let_cxx_string!(s = "");
let mut reader: &[u8] = b"Hello, world!";
std::io::copy(&mut reader, &mut s).unwrap();
assert_eq!(s.to_str(), Ok("Hello, world!"));
}
|
use crate::RequestContext;
use anyhow::Result;
use rustimate_core::member::MemberRole;
use rustimate_core::poll::{PollStatus, Vote};
use rustimate_core::{RequestMessage, ResponseMessage};
use uuid::Uuid;
/// Core application logic, routing [RequestMessage](rustimate_core::RequestMessage)s and emitting [ResponseMessage](rustimate_core::ResponseMessage)s.
#[derive(Debug)]
pub struct MessageHandler {
connection_id: Uuid,
channel_id: String,
ctx: RequestContext,
log: slog::Logger
}
impl MessageHandler {
pub fn new(connection_id: Uuid, channel_id: String, ctx: RequestContext) -> Self {
let o = slog::o!("connection" => format!("{}", connection_id), "service" => "message_handler", "channel" => channel_id.clone());
let log = ctx.log().new(o);
Self {
connection_id,
channel_id,
ctx,
log
}
}
pub const fn connection_id(&self) -> &Uuid {
&self.connection_id
}
pub const fn channel_id(&self) -> &String {
&self.channel_id
}
pub const fn ctx(&self) -> &RequestContext {
&self.ctx
}
pub fn log(&self) -> &slog::Logger {
&self.log
}
pub fn on_open(&self) -> Result<()> {
self.send_to_self(ResponseMessage::Connected {
connection_id: *self.connection_id(),
user_id: *self.ctx().user_id(),
u: Box::new((*self.ctx.user_profile()).clone()),
b: !self.ctx.app().verbose()
})?;
let svc = self.ctx.app().session_svc();
let role = if svc.read_members(&self.channel_id)?.is_empty() {
MemberRole::Creator
} else {
MemberRole::Participant
};
let member = svc.update_member(
&self.channel_id,
*self.ctx.user_id(),
self.ctx.user_profile().name().clone(),
Some(role)
)?;
self.send_to_channel_except_self(&ResponseMessage::UpdateMember { member })?;
self.send_to_self(ResponseMessage::SessionJoined {
session: Box::new(svc.read_session(&self.channel_id)?),
members: svc.read_members(&self.channel_id)?,
connected: vec![],
polls: svc.read_polls(&self.channel_id)?,
votes: svc.read_votes(&self.channel_id)?
})?;
Ok(())
}
pub fn on_closed(&self) -> Result<()> {
slog::debug!(self.log, "Closing connection for [{}:{}]", self.connection_id, self.channel_id);
Ok(())
}
pub fn on_message(&self, msg: RequestMessage) -> Result<()> {
match msg {
RequestMessage::Ping { v } => self.send_to_self(ResponseMessage::Pong { v }),
RequestMessage::SetPollTitle { id, title } => self.set_poll_title(id, &title),
RequestMessage::SetPollStatus { poll, status } => self.set_poll_status(poll, status),
RequestMessage::SubmitVote { poll, vote } => self.on_submit_vote(poll, vote),
RequestMessage::UpdateSelf { name } => self.on_update_self(&name),
RequestMessage::UpdateSession { name, choices } => self.on_update_session(name, choices),
msg => {
slog::warn!(self.log, "Unhandled RequestMessage [{:?}]", msg);
Ok(())
}
}
}
fn set_poll_title(&self, id: Uuid, title: &str) -> Result<()> {
let svc = self.ctx().app().session_svc();
let poll = svc.update_poll(self.channel_id(), id, Some(title.into()), None, *self.ctx().user_id())?;
self.send_to_channel(&ResponseMessage::UpdatePoll { poll })?;
slog::info!(self.log(), "Updated poll [{}: {}] for session [{}]", id, title, self.channel_id());
Ok(())
}
fn set_poll_status(&self, id: Uuid, status: PollStatus) -> Result<()> {
let svc = self.ctx().app().session_svc();
let poll = svc.update_poll(self.channel_id(), id, None, Some(status), *self.ctx().user_id())?;
self.send_to_channel(&ResponseMessage::UpdatePoll { poll })?;
slog::info!(self.log(), "Updated poll [{}] for session [{}]", id, self.channel_id());
Ok(())
}
fn on_submit_vote(&self, poll: Uuid, vote: String) -> Result<()> {
let svc = self.ctx().app().session_svc();
let vote = Vote::new(poll, *self.ctx().user_id(), vote);
let vote = svc.update_vote(self.channel_id(), vote)?;
self.send_to_channel(&ResponseMessage::UpdateVote { vote })
}
fn on_update_self(&self, name: &str) -> Result<()> {
let svc = self.ctx().app().session_svc();
let member = svc.update_member(self.channel_id(), *self.ctx().user_id(), name.into(), None)?;
self.send_to_channel(&ResponseMessage::UpdateMember { member })?;
Ok(())
}
fn on_update_session(&self, title: String, choices: Vec<String>) -> Result<()> {
let svc = self.ctx().app().session_svc();
let mut session = svc.read_session(self.channel_id())?;
session.set_title(title);
session.set_choices(choices);
svc.write_session(&session)?;
self.send_to_channel(&ResponseMessage::UpdateSession { session })?;
Ok(())
}
fn send_to_self(&self, msg: ResponseMessage) -> Result<()> {
self.ctx().app().connections().send_connection(self.connection_id(), msg);
Ok(())
}
fn send_to_channel(&self, msg: &ResponseMessage) -> Result<()> {
self.ctx().app().connections().send_channel(self.channel_id(), msg);
Ok(())
}
fn send_to_channel_except_self(&self, msg: &ResponseMessage) -> Result<()> {
self
.ctx()
.app()
.connections()
.send_channel_except(self.channel_id(), &[self.connection_id()], msg);
Ok(())
}
}
|
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
pub struct GlobalLifeState {
life: AtomicBool
}
impl GlobalLifeState {
pub fn new() -> Self {
Self {
life: AtomicBool::new(true)
}
}
pub fn is_alive(&self) -> bool {
self.life.load(atomic::Ordering::Relaxed)
}
pub fn kill(&self) {
self.life.store(false, atomic::Ordering::SeqCst)
}
pub fn revive(&self) {
self.life.store(true, atomic::Ordering::SeqCst)
}
pub fn get_current_state(&self) -> LifeStateInstance {
LifeStateInstance::new(self.life.load(Ordering::Relaxed))
}
}
#[derive(Serialize)]
pub struct LifeStateInstance {
life: bool
}
impl LifeStateInstance {
fn new(life: bool) -> Self {
Self {
life
}
}
pub fn get_life(&self) -> bool {
self.life
}
}
#[cfg(test)]
mod tests {
use super::*;
impl GlobalLifeState {
fn create_dead() -> Self {
Self {
life: AtomicBool::new(false)
}
}
}
#[test]
fn test_constructor() {
let status = GlobalLifeState::new();
assert!(status.is_alive());
}
#[test]
fn test_kill() {
let status = GlobalLifeState::new();
status.kill();
assert!(!status.is_alive());
}
#[test]
fn test_revive() {
let status = GlobalLifeState::create_dead();
status.kill();
status.revive();
assert!(status.is_alive());
}
} |
use super::*;
use guion::{constraint, widget::{resolvable::{ResolvableMut, Resolvable}, as_widget::{AsWidgetMut, AsWidget}}, widgets::{label::Label, textbox::{state::Cursor, TextBox}, util::remote_state::RemoteState}};
use guion::widget::WBaseMut; //baka import
use guion::{validation::validated::Validated, widget::WBase};
pub struct ImmediateLabel {
pub id: StdID,
pub text: String,
}
pub struct ImmediateTextBox {
pub id: StdID,
pub text: String,
}
impl AsWidget<SimpleEnv> for ImmediateLabel {
fn as_ref(&self) -> guion::widget::resolvable::Resolvable<SimpleEnv> {
Resolvable::from_widget(
Label::immediate(self.id.clone(),&self.text)
.with_size(constraint!(~0-|24))
)
}
fn into_ref<'w>(self) -> guion::widget::resolvable::Resolvable<'w,SimpleEnv> where Self: 'w {
Resolvable::from_widget(
Label::immediate(self.id.clone(),self.text)
.with_size(constraint!(~0-|24))
)
}
}
impl AsWidgetMut<SimpleEnv> for ImmediateLabel {
fn as_mut(&mut self) -> guion::widget::resolvable::ResolvableMut<SimpleEnv> {
ResolvableMut::from_widget(
Label::immediate(self.id.clone(),&mut self.text)
.with_size(constraint!(~0-|24))
)
}
fn into_mut<'w>(self) -> guion::widget::resolvable::ResolvableMut<'w,SimpleEnv> where Self: 'w {
ResolvableMut::from_widget(
Label::immediate(self.id.clone(),self.text)
.with_size(constraint!(~0-|24))
)
}
}
impl AsWidget<SimpleEnv> for ImmediateTextBox {
fn as_ref(&self) -> guion::widget::resolvable::Resolvable<SimpleEnv> {
Resolvable::from_widget(
TextBox::immediate(self.id.clone(),&self.text)
)
}
fn into_ref<'w>(self) -> guion::widget::resolvable::Resolvable<'w,SimpleEnv> where Self: 'w {
Resolvable::from_widget(
TextBox::immediate(self.id.clone(),self.text)
)
}
}
impl AsWidgetMut<SimpleEnv> for ImmediateTextBox {
fn as_mut(&mut self) -> guion::widget::resolvable::ResolvableMut<SimpleEnv> {
ResolvableMut::from_widget(
TextBox::immediate(self.id.clone(),&mut self.text)
)
}
fn into_mut<'w>(self) -> guion::widget::resolvable::ResolvableMut<'w,SimpleEnv> where Self: 'w {
ResolvableMut::from_widget(
TextBox::immediate(self.id.clone(),self.text)
)
}
}
|
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
mod buffer;
mod bytes;
mod dict;
mod fragment;
mod list;
pub use buffer::*;
pub use bytes::*;
pub use dict::*;
pub use fragment::{orjson_fragmenttype_new, Fragment};
pub use list::PyListIter;
|
#![feature(array_map)]
use crossbeam;
pub mod mat_mul;
pub struct PredictiveCodingNodeData<Float> {
node_val: Float,
error_val: Float,
}
pub struct InputWithErrorBackProp<Input> {
pub forward_data: crossbeam::channel::Receiver<Input>,
pub reverse_error_prop: crossbeam::channel::Sender<Input>,
}
pub struct OutputWithErrorBackProp<Output> {
pub forward_data: crossbeam::channel::Sender<Output>,
pub reverse_error_prop: crossbeam::channel::Receiver<Output>,
}
pub struct RootNode<RootInput, Output> {
// pub node_err: Output,
pub forward_input: crossbeam::channel::Receiver<RootInput>,
pub forward_output: OutputWithErrorBackProp<Output>,
}
pub struct BranchNode<Input, Output> {
// pub node_mus: Input,
// pub node_err: Output,
pub input_channels: InputWithErrorBackProp<Input>,
pub output_channels: OutputWithErrorBackProp<Output>,
}
pub struct LeafNode<Input, Labels> {
pub node_data: Input,
// pub node_mus: Input,
pub input_channels: InputWithErrorBackProp<Input>,
pub ground_truth_channel: crossbeam::channel::Receiver<Labels>,
}
//pub struct BranchNode<Float, Input, Output, ErrorInput, ErrorOutput> {
// data: PredictiveCodingNodeData<Float>,
// forward_input: crossbeam::channel::Receiver<RootInput>,
// forward_output
//}
//
//pub struct Branch<Float
//pub enum PredictiveCodingNode<Float> {
// Root {
// },
// Branch {},
// Leaf {
// output_channel:
// },
//}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
extern crate needletail;
extern crate murmurhash3;
extern crate serde;
#[macro_use] extern crate serde_derive;
extern crate serde_json;
use std::io::{Read, Seek};
use std::path::Path;
use needletail::fastx::{fastx_cli, fastx_stream};
use filtering::{FilterParams, filter_sketch};
use minhashes::MinHashKmers;
use serialization::{JSONSketch, JSONMultiSketch};
pub mod minhashes;
pub mod filtering;
pub mod distance;
pub mod serialization;
pub mod statistics;
pub fn mash_files(filenames: Vec<&str>, n_hashes: usize, final_size: usize, kmer_length: u8, filters: &mut FilterParams, no_strict: bool, seed: u64) -> Result<JSONMultiSketch, String> {
let mut sketches = Vec::with_capacity(filenames.len());
for filename in &filenames {
let mut seq_len = 0u64;
let mut n_kmers = 0u64;
let path = Path::new(filename);
let mut minhash = match filters.filter_on {
Some(true) | None => MinHashKmers::new(n_hashes, seed),
Some(false) => MinHashKmers::new(final_size, seed),
};
fastx_cli(path.to_str().ok_or("Couldn't make path into string")?, |seq_type| {
// disable filtering for FASTA files unless it was explicitly specified
if let None = filters.filter_on {
filters.filter_on = match seq_type {
"FASTA" => Some(false),
"FASTQ" => Some(true),
_ => panic!("Unknown sequence type"),
};
}
}, |seq| {
seq_len += seq.seq.len() as u64;
for (_, kmer, is_rev_complement) in seq.normalize(false).kmers(kmer_length, true) {
let rc_count = match is_rev_complement {
true => 1u8,
false => 0u8,
};
n_kmers += 1;
minhash.push(kmer, rc_count);
}
}).map_err(|e| e.to_string())?;
let hashes = minhash.into_vec();
let (mut filtered_hashes, filter_stats) = filter_sketch(&hashes, &filters);
filtered_hashes.truncate(final_size);
if !no_strict && filtered_hashes.len() < final_size {
return Err(format!("{} had too few kmers ({}) to sketch", filename, filtered_hashes.len()));
}
// directory should be clipped from filename
let basename = path.file_name().ok_or("Couldn't get filename from path")?;
let sketch = JSONSketch::new(basename.to_str().ok_or("Couldn't make filename into string")?,
seq_len, n_kmers, filtered_hashes, &filter_stats);
sketches.push(sketch);
}
Ok(JSONMultiSketch {
kmer: kmer_length,
alphabet: String::from("ACGT"),
preserveCase: false,
canonical: true,
sketchSize: final_size as u32,
hashType: String::from("MurmurHash3_x64_128"),
hashBits: 64u16,
hashSeed: seed,
sketches: sketches,
})
}
pub fn mash_stream<R>(reader: R, n_hashes: usize, final_size: usize, kmer_length: u8,
filters: &mut FilterParams, no_strict: bool, seed: u64) -> Result<JSONSketch, String> where
R: Read + Seek,
{
let mut seq_len = 0u64;
let mut n_kmers = 0u64;
let mut minhash = match filters.filter_on {
Some(true) | None => MinHashKmers::new(n_hashes, seed),
Some(false) => MinHashKmers::new(final_size, seed),
};
fastx_stream(reader, |seq_type| {
// disable filtering for FASTA files unless it was explicitly specified
if let None = filters.filter_on {
filters.filter_on = match seq_type {
"FASTA" => Some(false),
"FASTQ" => Some(true),
_ => panic!("Unknown sequence type"),
};
}
}, |seq| {
seq_len += seq.seq.len() as u64;
for (_, kmer, is_rev_complement) in seq.normalize(false).kmers(kmer_length, true) {
let rc_count = match is_rev_complement {
true => 1u8,
false => 0u8,
};
n_kmers += 1;
minhash.push(kmer, rc_count);
}
}).map_err(|e| e.to_string())?;
let hashes = minhash.into_vec();
let (mut filtered_hashes, filter_stats) = filter_sketch(&hashes, &filters);
filtered_hashes.truncate(final_size);
if !no_strict && filtered_hashes.len() < final_size {
return Err(format!("Stream had too few kmers ({}) to sketch", filtered_hashes.len()));
}
Ok(JSONSketch::new("", seq_len, n_kmers, filtered_hashes, &filter_stats))
}
|
#![feature(proc_macro_hygiene)]
#![feature(decl_macro)]
#[macro_use]
extern crate rocket;
mod controllers;
mod models;
mod mapper;
mod services;
mod errors;
mod logic;
fn main() {
rocket::ignite()
.mount("/communities", controllers::community::router())
.mount("/users", controllers::user::router())
.mount("/restaurants", controllers::restaurant::router())
.mount("/me", controllers::me::router())
.mount("/reviews", controllers::review::router())
.mount("/docs", rocket_contrib::serve::StaticFiles::new("./docs", rocket_contrib::serve::Options::Index))
.register(controllers::err::router())
.launch();
} |
// Copyright (c) 2018 Alexander Færøy. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use std::fmt;
use expression::{Evaluate, Generator};
use math::{tan, PI};
pub struct TanPi {
expression: Box<dyn Evaluate>,
}
impl TanPi {
pub fn new(expression: Box<dyn Evaluate>) -> TanPi {
TanPi { expression }
}
pub fn generate(generator: &mut Generator, probability: f64) -> Box<dyn Evaluate> {
let expression = generator.generate_expression(probability * probability);
Box::new(TanPi::new(expression))
}
}
impl Evaluate for TanPi {
fn evaluate(&self, x: f64, y: f64) -> f64 {
tan(PI * self.expression.evaluate(x, y))
}
}
impl fmt::Display for TanPi {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "tan(pi * {})", self.expression)
}
}
#[cfg(test)]
mod tests {
use super::*;
use expression::{X, Y};
#[test]
fn format() {
assert_eq!("tan(pi * x)", format!("{}", TanPi::new(X::generate())));
assert_eq!("tan(pi * y)", format!("{}", TanPi::new(Y::generate())));
}
}
|
use crate::request_pipeline::executor::execute_query_plan;
use crate::request_pipeline::service_definition::ServiceDefinition;
use crate::transports::http::{GraphQLResponse, RequestContext};
use apollo_query_planner::helpers::directive_args_as_map;
use apollo_query_planner::{QueryPlanner, QueryPlanningOptionsBuilder};
use graphql_parser::schema;
use reqwest::Client;
use std::collections::HashMap;
use tracing::instrument;
pub mod common;
mod request_pipeline;
pub mod transports;
mod utilities;
#[derive(Debug)]
pub struct Stargate<'app> {
service_list: HashMap<String, ServiceDefinition>,
pub planner: QueryPlanner<'app>,
pub options: StargateOptions,
}
#[derive(Debug)]
pub struct StargateOptions {
pub propagate_request_headers: Vec<String>,
}
impl Default for StargateOptions {
fn default() -> Self {
Self {
propagate_request_headers: vec![],
}
}
}
impl<'app> Stargate<'app> {
pub fn new(schema: &'app str, options: StargateOptions) -> Stargate<'app> {
// TODO(ran) FIXME: gql validation on schema
let planner = QueryPlanner::new(schema);
let service_list = get_service_list(&planner.schema);
Stargate {
planner,
service_list,
options,
}
}
#[instrument(skip(self, request_context))]
pub async fn execute_query<'req>(
&'app self,
request_context: &'req RequestContext<'req>,
) -> Result<GraphQLResponse> {
// TODO(ran) FIXME: gql validation on query
// TODO(james) actual request pipeline here
let options = QueryPlanningOptionsBuilder::default().build().unwrap();
let plan = self
.planner
.plan(&request_context.graphql_request.query, options)
.unwrap_or_else(|_| todo!("convert QueryPlanError to generic error"));
execute_query_plan(&plan, &self.service_list, &request_context).await
}
}
fn get_service_list(schema: &schema::Document) -> HashMap<String, ServiceDefinition> {
let schema_defintion: Option<&schema::SchemaDefinition> = schema
.definitions
.iter()
.filter_map(|d| match d {
schema::Definition::Schema(schema) => Some(schema),
_ => None,
})
.last();
if schema_defintion.is_none() {
todo!("handle error case")
}
apollo_query_planner::get_directive!(schema_defintion.unwrap().directives, "graph")
.map(|owner_dir| directive_args_as_map(&owner_dir.arguments))
.map(|args| {
(
String::from(args["name"]),
ServiceDefinition {
url: String::from(args["url"]),
client: Client::new(),
},
)
})
.collect()
}
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync + 'static>>;
|
pub fn number(user_number: &str) -> Option<String> {
let mut number: String = user_number.chars()
.filter(|ch| ch.is_digit(11))
.collect::<Vec<_>>()
.rchunks(11)
.next()
.unwrap()
.to_vec()
.into_iter()
.collect::<String>();
let mut international_code_vec = Vec::new();
let mut international_code = ' ';
if number.len() > 10 {
international_code_vec.append(&mut number.drain(0..1).collect::<Vec<_>>());
international_code = *international_code_vec.get(0).unwrap();
}
let area_code_digit = number.chars().nth(0).unwrap();
let area_code_digit_check = area_code_digit != '1' && area_code_digit != '0';
let exchange_code_digit = number.chars().nth(3).unwrap();
let exchange_code_digit_check = exchange_code_digit != '1' && exchange_code_digit != '0';
println!("{:?} number {:?} international_code = {:?}", area_code_digit_check, exchange_code_digit_check, international_code);
if exchange_code_digit_check && area_code_digit_check {
if international_code_vec.len() > 0 && international_code != '1' {
None
} else {
Some(number)
}
} else {
None
}
}
|
use aoc::*;
use itertools::Itertools;
use regex::Regex;
use std::collections::{HashMap, HashSet};
fn main() -> Result<()> {
let passports = get_passports();
println!("Day 4 part 1 result is {}", part1(&passports));
println!("Day 4 part 2 result is {}", part2(&passports));
Ok(())
}
fn get_passports() -> Vec<HashMap<String, String>> {
let x: Vec<Vec<String>> = input("4.txt")
.unwrap()
.split("\n\n")
.map(|s| s.replace("\n", " "))
.map(|s| {
s.split(' ')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
})
.collect();
let mut passports = Vec::new();
for row in x.iter() {
let mut passport: HashMap<String, String> = HashMap::new();
for entry in row.iter() {
let kv: (&str, &str) = entry.splitn(2, ':').collect_tuple().unwrap();
passport.insert(kv.0.to_string(), kv.1.to_string());
}
passports.push(passport);
}
passports
}
fn get_required_fields() -> HashMap<String, regex::Regex> {
[
(
"byr".to_string(),
Regex::new(r"^19[2-9]\d|200[0-2]$").unwrap(),
),
("iyr".to_string(), Regex::new(r"^201\d|2020$").unwrap()),
("eyr".to_string(), Regex::new(r"^202\d|2030$").unwrap()),
(
"hgt".to_string(),
Regex::new(r"^(1[5-8]\d|19[0-3])cm$|^(59|6\d|7[0-6])in$").unwrap(),
),
("hcl".to_string(), Regex::new(r"^#[0-9a-f]{6}$").unwrap()),
(
"ecl".to_string(),
Regex::new(r"^amb|blu|brn|gry|grn|hzl|oth$").unwrap(),
),
("pid".to_string(), Regex::new(r"^\d{9}$").unwrap()),
]
.iter()
.cloned()
.collect()
}
fn valid_part1(passports: &[HashMap<String, String>]) -> Vec<HashMap<String, String>> {
let requried_keys = &get_required_fields()
.keys()
.cloned()
.collect::<HashSet<String>>();
passports
.iter()
.filter(|p| {
p.keys()
.cloned()
.collect::<HashSet<String>>()
.intersection(&requried_keys)
.count()
== 7
})
.cloned()
.collect()
}
fn part1(passports: &[HashMap<String, String>]) -> usize {
valid_part1(passports).len()
}
fn part2(passports: &[HashMap<String, String>]) -> usize {
let mut count = 0;
let required = &get_required_fields();
let valid = valid_part1(passports);
for vp1 in valid {
let mut is_valid = true;
for (k, v) in vp1.iter() {
if let Some(regex) = required.get(k) {
if !regex.is_match(v) {
is_valid = false;
break;
}
}
}
if is_valid {
count += 1;
}
}
count
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
assert!(part1(&get_passports()) == 260);
}
#[test]
fn test_part2() {
assert!(part2(&get_passports()) == 153);
}
}
|
#![no_main]
#![no_std]
#![deny(warnings)]
// to use the global allocator
#![feature(alloc_error_handler)]
#[cfg(test)]
#[macro_use]
extern crate std;
mod allocator;
mod clock;
mod logging;
mod util;
use core::{
alloc::Layout,
mem::MaybeUninit,
num::{NonZeroU16, NonZeroU8},
};
use allocator::MyAllocator;
use clock::StmClock;
use cortex_m_rt::entry;
use embedded_time::Clock;
use hal::{
delay::SYSTDelayExt,
fdcan::{
config::{ClockDivider, NominalBitTiming},
filter::{StandardFilter, StandardFilterSlot},
frame::TxFrameHeader,
id::ExtendedId,
id::Id,
FdCan, NormalOperationMode,
},
gpio::{GpioExt, Speed},
nb::block,
prelude::*,
rcc::{Config, PLLSrc, PllConfig, Rcc, RccExt, SysClockSrc},
stm32::{Peripherals, FDCAN1},
};
use stm32g4xx_hal as hal;
use uavcan::{
session::HeapSessionManager,
transfer::Transfer,
transport::can::{Can, CanMetadata},
Node, Priority, StreamingIterator, Subscription, TransferKind,
};
use util::insert_u8_array_in_u32_array;
static mut POOL: MaybeUninit<[u8; 1024]> = MaybeUninit::uninit();
#[global_allocator]
static ALLOCATOR: MyAllocator = MyAllocator::init();
#[entry]
fn main() -> ! {
// init heap
let cursor = unsafe { POOL.as_mut_ptr() } as *mut u8;
let size = 1024;
unsafe { ALLOCATOR.set_pool(cursor, size) };
// define peripherals of the board
let dp = Peripherals::take().unwrap();
let cp = cortex_m::Peripherals::take().expect("cannot take core peripherals");
let rcc = dp.RCC.constrain();
let mut rcc = config_rcc(rcc);
let gpioa = dp.GPIOA.split(&mut rcc);
let mut led = gpioa.pa5.into_push_pull_output();
let mut delay_syst = cp.SYST.delay(&rcc.clocks);
// init can
let mut can = {
let rx = gpioa.pa11.into_alternate().set_speed(Speed::VeryHigh);
let tx = gpioa.pa12.into_alternate().set_speed(Speed::VeryHigh);
let can = FdCan::new_with_clock_source(
dp.FDCAN1,
tx,
rx,
&rcc,
hal::fdcan::FdCanClockSource::PCLK,
);
let mut can = can.into_config_mode();
can.set_protocol_exception_handling(false);
can.set_clock_divider(ClockDivider::_2);
can.set_frame_transmit(hal::fdcan::config::FrameTransmissionConfig::AllowFdCan);
let btr = NominalBitTiming {
prescaler: NonZeroU16::new(5).unwrap(),
seg1: NonZeroU8::new(14).unwrap(),
seg2: NonZeroU8::new(2).unwrap(),
sync_jump_width: NonZeroU8::new(1).unwrap(),
};
can.set_nominal_bit_timing(btr);
can.set_standard_filter(
StandardFilterSlot::_0,
StandardFilter::accept_all_into_fifo0(),
);
// can.into_external_loopback()
can.into_normal()
};
// init clock
let clock = StmClock::new(dp.TIM7, &rcc.clocks);
let mut session_manager = HeapSessionManager::<CanMetadata, StmClock>::new();
session_manager
.subscribe(Subscription::new(
TransferKind::Message,
7509, // TODO check
7,
embedded_time::duration::Milliseconds(500),
))
.unwrap();
let mut node = Node::<_, Can, StmClock>::new(Some(42), session_manager);
let mut transfer_id = 0u8;
let mut last_published = clock.try_now().unwrap();
loop {
let now = clock.try_now().unwrap();
if now - last_published
> embedded_time::duration::Generic::new(1000, StmClock::SCALING_FACTOR)
{
// Publish string
let hello = "Hello!";
let mut str = heapless::Vec::<u8, 6>::new();
str.extend_from_slice(hello.as_bytes()).unwrap();
let transfer = Transfer {
timestamp: clock.try_now().unwrap(),
priority: Priority::Nominal,
transfer_kind: TransferKind::Message,
port_id: 100,
remote_node_id: None,
transfer_id,
payload: &str,
};
// unchecked_add is unstable :(
// unsafe { transfer_id.unchecked_add(1); }
transfer_id += 1;
publish(&mut node, transfer, &mut can);
last_published = clock.try_now().unwrap();
led.toggle().unwrap();
delay_syst.delay(1000.ms());
led.toggle().unwrap();
}
}
}
pub fn publish(
node: &mut Node<HeapSessionManager<CanMetadata, StmClock>, Can, StmClock>,
transfer: Transfer<StmClock>,
can: &mut FdCan<FDCAN1, NormalOperationMode>,
) {
let mut iter = node.transmit(&transfer).unwrap();
while let Some(frame) = iter.next() {
let header = TxFrameHeader {
bit_rate_switching: false,
frame_format: hal::fdcan::frame::FrameFormat::Standard,
id: Id::Extended(ExtendedId::new(frame.id.as_raw()).unwrap()),
len: frame.payload.len() as u8,
marker: None,
};
block!(can.transmit(header, &mut |b| {
insert_u8_array_in_u32_array(&frame.payload, b)
},))
.unwrap();
}
}
fn config_rcc(rcc: Rcc) -> Rcc {
rcc.freeze(
Config::new(SysClockSrc::PLL)
.pll_cfg(PllConfig {
mux: PLLSrc::HSI,
m: 4,
n: 85,
r: 2,
q: Some(2),
p: Some(2),
})
.ahb_psc(hal::rcc::Prescaler::NotDivided)
.apb_psc(hal::rcc::Prescaler::NotDivided),
)
}
#[allow(clippy::empty_loop)]
#[alloc_error_handler]
fn oom(_: Layout) -> ! {
loop {}
}
|
// src/lib.rs
extern crate wasm_bindgen;
use std::io::Cursor;
use wasm_bindgen::prelude::*;
use js_sys::Error as JsError;
use murmur3::murmur3_x64_128;
#[wasm_bindgen]
pub fn hex128(source: &str, seed :u32) -> Result<String, JsValue> {
let hashed = match murmur3_x64_128(&mut Cursor::new(source), seed) {
Ok(u128) => u128,
Err(_) => return Err(
JsError::new("InternalError: Execute murmur3::murmur3_x64_128 faild").into()
),
};
let bytes = hashed.to_be_bytes();
let len = bytes.len();
let half_len = len / 2;
let out = format!(
"{}{}",
hex::encode(&bytes[half_len..len]),
hex::encode(&bytes[0..half_len])
);
Ok(out)
}
|
pub mod base;
pub mod reconciler;
|
use std::ops::Add;
fn main() {
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option<i32> = None;
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
}
fn plus_one(x: Option<i32>) -> Option<i32> {
// match x {
// None => None,
// Some(i) => Some(i + 1),
// }
x.map(|n| n.add(1))
}
|
use crate::{
binary::{Encoder, ReadEx},
errors::Result,
types::{
column::{column_data::{BoxColumnData, ArcColumnData}, ArcColumnWrapper, ColumnData},
SqlType, Value, ValueRef, SimpleAggFunc,
},
};
use chrono_tz::Tz;
use std::sync::Arc;
pub(crate) struct SimpleAggregateFunctionColumnData {
pub(crate) inner: ArcColumnData,
pub(crate) func: SimpleAggFunc,
}
impl SimpleAggregateFunctionColumnData {
pub(crate) fn load<R: ReadEx>(
reader: &mut R,
func: SimpleAggFunc,
type_name: &str,
size: usize,
tz: Tz,
) -> Result<Self> {
let inner = <dyn ColumnData>::load_data::<ArcColumnWrapper, _>(reader, type_name, size, tz)?;
Ok(SimpleAggregateFunctionColumnData { inner, func })
}
}
impl ColumnData for SimpleAggregateFunctionColumnData {
fn sql_type(&self) -> SqlType {
let inner_type = self.inner.sql_type();
SqlType::SimpleAggregateFunction(self.func, inner_type.into())
}
fn save(&self, encoder: &mut Encoder, start: usize, end: usize) {
self.inner.save(encoder, start, end);
}
fn len(&self) -> usize {
self.inner.len()
}
fn push(&mut self, value: Value) {
let inner_column: &mut dyn ColumnData = Arc::get_mut(&mut self.inner).unwrap();
inner_column.push(value);
}
fn at(&self, index: usize) -> ValueRef {
self.inner.at(index)
}
fn clone_instance(&self) -> BoxColumnData {
Box::new(Self {
inner: self.inner.clone(),
func: self.func,
})
}
unsafe fn get_internal(&self, pointers: &[*mut *const u8], level: u8, props: u32) -> Result<()> {
self.inner.get_internal(pointers, level, props)
}
fn cast_to(&self, _this: &ArcColumnData, target: &SqlType) -> Option<ArcColumnData> {
if let SqlType::SimpleAggregateFunction(func, inner_target) = target {
if let Some(inner) = self.inner.cast_to(&self.inner, inner_target) {
return Some(Arc::new(SimpleAggregateFunctionColumnData {
inner,
func: *func,
}))
}
}
None
}
}
|
#[doc = "Register `PR` reader"]
pub type R = crate::R<PR_SPEC>;
#[doc = "Register `PR` writer"]
pub type W = crate::W<PR_SPEC>;
#[doc = "Field `PR0` reader - Pending bit 0"]
pub type PR0_R = crate::BitReader<PR0R_A>;
#[doc = "Pending bit 0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PR0R_A {
#[doc = "0: No trigger request occurred"]
NotPending = 0,
#[doc = "1: Selected trigger request occurred"]
Pending = 1,
}
impl From<PR0R_A> for bool {
#[inline(always)]
fn from(variant: PR0R_A) -> Self {
variant as u8 != 0
}
}
impl PR0_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PR0R_A {
match self.bits {
false => PR0R_A::NotPending,
true => PR0R_A::Pending,
}
}
#[doc = "No trigger request occurred"]
#[inline(always)]
pub fn is_not_pending(&self) -> bool {
*self == PR0R_A::NotPending
}
#[doc = "Selected trigger request occurred"]
#[inline(always)]
pub fn is_pending(&self) -> bool {
*self == PR0R_A::Pending
}
}
#[doc = "Pending bit 0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PR0W_AW {
#[doc = "1: Clears pending bit"]
Clear = 1,
}
impl From<PR0W_AW> for bool {
#[inline(always)]
fn from(variant: PR0W_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `PR0` writer - Pending bit 0"]
pub type PR0_W<'a, REG, const O: u8> = crate::BitWriter1C<'a, REG, O, PR0W_AW>;
impl<'a, REG, const O: u8> PR0_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Clears pending bit"]
#[inline(always)]
pub fn clear(self) -> &'a mut crate::W<REG> {
self.variant(PR0W_AW::Clear)
}
}
#[doc = "Field `PR1` reader - Pending bit 1"]
pub use PR0_R as PR1_R;
#[doc = "Field `PR2` reader - Pending bit 2"]
pub use PR0_R as PR2_R;
#[doc = "Field `PR3` reader - Pending bit 3"]
pub use PR0_R as PR3_R;
#[doc = "Field `PR4` reader - Pending bit 4"]
pub use PR0_R as PR4_R;
#[doc = "Field `PR5` reader - Pending bit 5"]
pub use PR0_R as PR5_R;
#[doc = "Field `PR6` reader - Pending bit 6"]
pub use PR0_R as PR6_R;
#[doc = "Field `PR7` reader - Pending bit 7"]
pub use PR0_R as PR7_R;
#[doc = "Field `PR8` reader - Pending bit 8"]
pub use PR0_R as PR8_R;
#[doc = "Field `PR9` reader - Pending bit 9"]
pub use PR0_R as PR9_R;
#[doc = "Field `PR10` reader - Pending bit 10"]
pub use PR0_R as PR10_R;
#[doc = "Field `PR11` reader - Pending bit 11"]
pub use PR0_R as PR11_R;
#[doc = "Field `PR12` reader - Pending bit 12"]
pub use PR0_R as PR12_R;
#[doc = "Field `PR13` reader - Pending bit 13"]
pub use PR0_R as PR13_R;
#[doc = "Field `PR14` reader - Pending bit 14"]
pub use PR0_R as PR14_R;
#[doc = "Field `PR15` reader - Pending bit 15"]
pub use PR0_R as PR15_R;
#[doc = "Field `PR16` reader - Pending bit 16"]
pub use PR0_R as PR16_R;
#[doc = "Field `PR17` reader - Pending bit 17"]
pub use PR0_R as PR17_R;
#[doc = "Field `PR1` writer - Pending bit 1"]
pub use PR0_W as PR1_W;
#[doc = "Field `PR2` writer - Pending bit 2"]
pub use PR0_W as PR2_W;
#[doc = "Field `PR3` writer - Pending bit 3"]
pub use PR0_W as PR3_W;
#[doc = "Field `PR4` writer - Pending bit 4"]
pub use PR0_W as PR4_W;
#[doc = "Field `PR5` writer - Pending bit 5"]
pub use PR0_W as PR5_W;
#[doc = "Field `PR6` writer - Pending bit 6"]
pub use PR0_W as PR6_W;
#[doc = "Field `PR7` writer - Pending bit 7"]
pub use PR0_W as PR7_W;
#[doc = "Field `PR8` writer - Pending bit 8"]
pub use PR0_W as PR8_W;
#[doc = "Field `PR9` writer - Pending bit 9"]
pub use PR0_W as PR9_W;
#[doc = "Field `PR10` writer - Pending bit 10"]
pub use PR0_W as PR10_W;
#[doc = "Field `PR11` writer - Pending bit 11"]
pub use PR0_W as PR11_W;
#[doc = "Field `PR12` writer - Pending bit 12"]
pub use PR0_W as PR12_W;
#[doc = "Field `PR13` writer - Pending bit 13"]
pub use PR0_W as PR13_W;
#[doc = "Field `PR14` writer - Pending bit 14"]
pub use PR0_W as PR14_W;
#[doc = "Field `PR15` writer - Pending bit 15"]
pub use PR0_W as PR15_W;
#[doc = "Field `PR16` writer - Pending bit 16"]
pub use PR0_W as PR16_W;
#[doc = "Field `PR17` writer - Pending bit 17"]
pub use PR0_W as PR17_W;
impl R {
#[doc = "Bit 0 - Pending bit 0"]
#[inline(always)]
pub fn pr0(&self) -> PR0_R {
PR0_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Pending bit 1"]
#[inline(always)]
pub fn pr1(&self) -> PR1_R {
PR1_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Pending bit 2"]
#[inline(always)]
pub fn pr2(&self) -> PR2_R {
PR2_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Pending bit 3"]
#[inline(always)]
pub fn pr3(&self) -> PR3_R {
PR3_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Pending bit 4"]
#[inline(always)]
pub fn pr4(&self) -> PR4_R {
PR4_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Pending bit 5"]
#[inline(always)]
pub fn pr5(&self) -> PR5_R {
PR5_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Pending bit 6"]
#[inline(always)]
pub fn pr6(&self) -> PR6_R {
PR6_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Pending bit 7"]
#[inline(always)]
pub fn pr7(&self) -> PR7_R {
PR7_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - Pending bit 8"]
#[inline(always)]
pub fn pr8(&self) -> PR8_R {
PR8_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Pending bit 9"]
#[inline(always)]
pub fn pr9(&self) -> PR9_R {
PR9_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Pending bit 10"]
#[inline(always)]
pub fn pr10(&self) -> PR10_R {
PR10_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Pending bit 11"]
#[inline(always)]
pub fn pr11(&self) -> PR11_R {
PR11_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - Pending bit 12"]
#[inline(always)]
pub fn pr12(&self) -> PR12_R {
PR12_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - Pending bit 13"]
#[inline(always)]
pub fn pr13(&self) -> PR13_R {
PR13_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - Pending bit 14"]
#[inline(always)]
pub fn pr14(&self) -> PR14_R {
PR14_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - Pending bit 15"]
#[inline(always)]
pub fn pr15(&self) -> PR15_R {
PR15_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - Pending bit 16"]
#[inline(always)]
pub fn pr16(&self) -> PR16_R {
PR16_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - Pending bit 17"]
#[inline(always)]
pub fn pr17(&self) -> PR17_R {
PR17_R::new(((self.bits >> 17) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Pending bit 0"]
#[inline(always)]
#[must_use]
pub fn pr0(&mut self) -> PR0_W<PR_SPEC, 0> {
PR0_W::new(self)
}
#[doc = "Bit 1 - Pending bit 1"]
#[inline(always)]
#[must_use]
pub fn pr1(&mut self) -> PR1_W<PR_SPEC, 1> {
PR1_W::new(self)
}
#[doc = "Bit 2 - Pending bit 2"]
#[inline(always)]
#[must_use]
pub fn pr2(&mut self) -> PR2_W<PR_SPEC, 2> {
PR2_W::new(self)
}
#[doc = "Bit 3 - Pending bit 3"]
#[inline(always)]
#[must_use]
pub fn pr3(&mut self) -> PR3_W<PR_SPEC, 3> {
PR3_W::new(self)
}
#[doc = "Bit 4 - Pending bit 4"]
#[inline(always)]
#[must_use]
pub fn pr4(&mut self) -> PR4_W<PR_SPEC, 4> {
PR4_W::new(self)
}
#[doc = "Bit 5 - Pending bit 5"]
#[inline(always)]
#[must_use]
pub fn pr5(&mut self) -> PR5_W<PR_SPEC, 5> {
PR5_W::new(self)
}
#[doc = "Bit 6 - Pending bit 6"]
#[inline(always)]
#[must_use]
pub fn pr6(&mut self) -> PR6_W<PR_SPEC, 6> {
PR6_W::new(self)
}
#[doc = "Bit 7 - Pending bit 7"]
#[inline(always)]
#[must_use]
pub fn pr7(&mut self) -> PR7_W<PR_SPEC, 7> {
PR7_W::new(self)
}
#[doc = "Bit 8 - Pending bit 8"]
#[inline(always)]
#[must_use]
pub fn pr8(&mut self) -> PR8_W<PR_SPEC, 8> {
PR8_W::new(self)
}
#[doc = "Bit 9 - Pending bit 9"]
#[inline(always)]
#[must_use]
pub fn pr9(&mut self) -> PR9_W<PR_SPEC, 9> {
PR9_W::new(self)
}
#[doc = "Bit 10 - Pending bit 10"]
#[inline(always)]
#[must_use]
pub fn pr10(&mut self) -> PR10_W<PR_SPEC, 10> {
PR10_W::new(self)
}
#[doc = "Bit 11 - Pending bit 11"]
#[inline(always)]
#[must_use]
pub fn pr11(&mut self) -> PR11_W<PR_SPEC, 11> {
PR11_W::new(self)
}
#[doc = "Bit 12 - Pending bit 12"]
#[inline(always)]
#[must_use]
pub fn pr12(&mut self) -> PR12_W<PR_SPEC, 12> {
PR12_W::new(self)
}
#[doc = "Bit 13 - Pending bit 13"]
#[inline(always)]
#[must_use]
pub fn pr13(&mut self) -> PR13_W<PR_SPEC, 13> {
PR13_W::new(self)
}
#[doc = "Bit 14 - Pending bit 14"]
#[inline(always)]
#[must_use]
pub fn pr14(&mut self) -> PR14_W<PR_SPEC, 14> {
PR14_W::new(self)
}
#[doc = "Bit 15 - Pending bit 15"]
#[inline(always)]
#[must_use]
pub fn pr15(&mut self) -> PR15_W<PR_SPEC, 15> {
PR15_W::new(self)
}
#[doc = "Bit 16 - Pending bit 16"]
#[inline(always)]
#[must_use]
pub fn pr16(&mut self) -> PR16_W<PR_SPEC, 16> {
PR16_W::new(self)
}
#[doc = "Bit 17 - Pending bit 17"]
#[inline(always)]
#[must_use]
pub fn pr17(&mut self) -> PR17_W<PR_SPEC, 17> {
PR17_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 = "Pending register (EXTI_PR)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pr::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 [`pr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PR_SPEC;
impl crate::RegisterSpec for PR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pr::R`](R) reader structure"]
impl crate::Readable for PR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`pr::W`](W) writer structure"]
impl crate::Writable for PR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0x0003_ffff;
}
#[doc = "`reset()` method sets PR to value 0"]
impl crate::Resettable for PR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::common::*;
pub(crate) fn entries(path: &Path) -> Result<Vec<DirEntry>, Error> {
fs::read_dir(path)
.map_err(|io_error| Error::Io {
path: path.to_owned(),
io_error,
})?
.map(|entry| {
entry.map_err(|io_error| Error::Io {
path: path.to_owned(),
io_error,
})
})
.collect()
}
|
use crate::{command::Command, define_node_command, get_set_swap, scene::commands::SceneContext};
use rg3d::{
core::{algebra::Vector3, numeric_range::NumericRange, pool::Handle},
resource::texture::Texture,
scene::{
graph::Graph,
node::Node,
particle_system::{emitter::Emitter, ParticleLimit, ParticleSystem},
},
};
#[derive(Debug)]
pub struct AddParticleSystemEmitterCommand {
particle_system: Handle<Node>,
emitter: Option<Emitter>,
}
impl AddParticleSystemEmitterCommand {
pub fn new(particle_system: Handle<Node>, emitter: Emitter) -> Self {
Self {
particle_system,
emitter: Some(emitter),
}
}
}
impl<'a> Command<'a> for AddParticleSystemEmitterCommand {
type Context = SceneContext<'a>;
fn name(&mut self, _context: &Self::Context) -> String {
"Add Particle System Emitter".to_owned()
}
fn execute(&mut self, context: &mut Self::Context) {
context.scene.graph[self.particle_system]
.as_particle_system_mut()
.emitters
.push(self.emitter.take().unwrap());
}
fn revert(&mut self, context: &mut Self::Context) {
self.emitter = Some(
context.scene.graph[self.particle_system]
.as_particle_system_mut()
.emitters
.pop()
.unwrap(),
);
}
}
#[derive(Debug)]
pub struct DeleteEmitterCommand {
particle_system: Handle<Node>,
emitter: Option<Emitter>,
emitter_index: usize,
}
impl DeleteEmitterCommand {
pub fn new(particle_system: Handle<Node>, emitter_index: usize) -> Self {
Self {
particle_system,
emitter: None,
emitter_index,
}
}
}
impl<'a> Command<'a> for DeleteEmitterCommand {
type Context = SceneContext<'a>;
fn name(&mut self, _context: &Self::Context) -> String {
"Delete Particle System Emitter".to_owned()
}
fn execute(&mut self, context: &mut Self::Context) {
self.emitter = Some(
context.scene.graph[self.particle_system]
.as_particle_system_mut()
.emitters
.remove(self.emitter_index),
);
}
fn revert(&mut self, context: &mut Self::Context) {
let particle_system: &mut ParticleSystem =
context.scene.graph[self.particle_system].as_particle_system_mut();
if self.emitter_index == 0 {
particle_system.emitters.push(self.emitter.take().unwrap());
} else {
particle_system
.emitters
.insert(self.emitter_index, self.emitter.take().unwrap());
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum EmitterNumericParameter {
SpawnRate,
MaxParticles,
MinLifetime,
MaxLifetime,
MinSizeModifier,
MaxSizeModifier,
MinXVelocity,
MaxXVelocity,
MinYVelocity,
MaxYVelocity,
MinZVelocity,
MaxZVelocity,
MinRotationSpeed,
MaxRotationSpeed,
MinRotation,
MaxRotation,
}
impl EmitterNumericParameter {
fn name(self) -> &'static str {
match self {
EmitterNumericParameter::SpawnRate => "SpawnRate",
EmitterNumericParameter::MaxParticles => "MaxParticles",
EmitterNumericParameter::MinLifetime => "MinLifetime",
EmitterNumericParameter::MaxLifetime => "MaxLifetime",
EmitterNumericParameter::MinSizeModifier => "MinSizeModifier",
EmitterNumericParameter::MaxSizeModifier => "MaxSizeModifier",
EmitterNumericParameter::MinXVelocity => "MinXVelocity",
EmitterNumericParameter::MaxXVelocity => "MaxXVelocity",
EmitterNumericParameter::MinYVelocity => "MinYVelocity",
EmitterNumericParameter::MaxYVelocity => "MaxYVelocity",
EmitterNumericParameter::MinZVelocity => "MinZVelocity",
EmitterNumericParameter::MaxZVelocity => "MaxZVelocity",
EmitterNumericParameter::MinRotationSpeed => "MinRotationSpeed",
EmitterNumericParameter::MaxRotationSpeed => "MaxRotationSpeed",
EmitterNumericParameter::MinRotation => "MinRotation",
EmitterNumericParameter::MaxRotation => "MaxRotation",
}
}
}
#[derive(Debug)]
pub struct SetEmitterNumericParameterCommand {
node: Handle<Node>,
parameter: EmitterNumericParameter,
value: f32,
emitter_index: usize,
}
impl SetEmitterNumericParameterCommand {
pub fn new(
node: Handle<Node>,
emitter_index: usize,
parameter: EmitterNumericParameter,
value: f32,
) -> Self {
Self {
node,
parameter,
value,
emitter_index,
}
}
fn swap(&mut self, context: &mut SceneContext) {
let emitter: &mut Emitter = &mut context.scene.graph[self.node]
.as_particle_system_mut()
.emitters[self.emitter_index];
match self.parameter {
EmitterNumericParameter::SpawnRate => {
let old = emitter.spawn_rate();
emitter.set_spawn_rate(self.value as u32);
self.value = old as f32;
}
EmitterNumericParameter::MaxParticles => {
let old = emitter.max_particles();
emitter.set_max_particles(if self.value < 0.0 {
ParticleLimit::Unlimited
} else {
ParticleLimit::Strict(self.value as u32)
});
self.value = match old {
ParticleLimit::Unlimited => -1.0,
ParticleLimit::Strict(value) => value as f32,
};
}
EmitterNumericParameter::MinLifetime => {
let old = emitter.life_time_range();
emitter.set_life_time_range(NumericRange::new(self.value, old.bounds[1]));
self.value = old.bounds[0];
}
EmitterNumericParameter::MaxLifetime => {
let old = emitter.life_time_range();
emitter.set_life_time_range(NumericRange::new(old.bounds[0], self.value));
self.value = old.bounds[1];
}
EmitterNumericParameter::MinSizeModifier => {
let old = emitter.size_modifier_range();
emitter.set_size_modifier_range(NumericRange::new(self.value, old.bounds[1]));
self.value = old.bounds[0];
}
EmitterNumericParameter::MaxSizeModifier => {
let old = emitter.size_modifier_range();
emitter.set_size_modifier_range(NumericRange::new(old.bounds[0], self.value));
self.value = old.bounds[1];
}
EmitterNumericParameter::MinXVelocity => {
let old = emitter.x_velocity_range();
emitter.set_x_velocity_range(NumericRange::new(self.value, old.bounds[1]));
self.value = old.bounds[0];
}
EmitterNumericParameter::MaxXVelocity => {
let old = emitter.x_velocity_range();
emitter.set_x_velocity_range(NumericRange::new(old.bounds[0], self.value));
self.value = old.bounds[1];
}
EmitterNumericParameter::MinYVelocity => {
let old = emitter.y_velocity_range();
emitter.set_y_velocity_range(NumericRange::new(self.value, old.bounds[1]));
self.value = old.bounds[0];
}
EmitterNumericParameter::MaxYVelocity => {
let old = emitter.y_velocity_range();
emitter.set_y_velocity_range(NumericRange::new(old.bounds[0], self.value));
self.value = old.bounds[1];
}
EmitterNumericParameter::MinZVelocity => {
let old = emitter.z_velocity_range();
emitter.set_z_velocity_range(NumericRange::new(self.value, old.bounds[1]));
self.value = old.bounds[0];
}
EmitterNumericParameter::MaxZVelocity => {
let old = emitter.z_velocity_range();
emitter.set_z_velocity_range(NumericRange::new(old.bounds[0], self.value));
self.value = old.bounds[1];
}
EmitterNumericParameter::MinRotationSpeed => {
let old = emitter.rotation_speed_range();
emitter.set_rotation_speed_range(NumericRange::new(self.value, old.bounds[1]));
self.value = old.bounds[0];
}
EmitterNumericParameter::MaxRotationSpeed => {
let old = emitter.rotation_speed_range();
emitter.set_rotation_speed_range(NumericRange::new(old.bounds[0], self.value));
self.value = old.bounds[1];
}
EmitterNumericParameter::MinRotation => {
let old = emitter.rotation_range();
emitter.set_rotation_range(NumericRange::new(self.value, old.bounds[1]));
self.value = old.bounds[0];
}
EmitterNumericParameter::MaxRotation => {
let old = emitter.rotation_range();
emitter.set_rotation_range(NumericRange::new(old.bounds[0], self.value));
self.value = old.bounds[1];
}
};
}
}
impl<'a> Command<'a> for SetEmitterNumericParameterCommand {
type Context = SceneContext<'a>;
fn name(&mut self, _context: &Self::Context) -> String {
format!("Set Emitter F32 Parameter: {}", self.parameter.name())
}
fn execute(&mut self, context: &mut Self::Context) {
self.swap(context);
}
fn revert(&mut self, context: &mut Self::Context) {
self.swap(context);
}
}
macro_rules! define_emitter_command {
($name:ident($human_readable_name:expr, $value_type:ty) where fn swap($self:ident, $emitter:ident) $apply_method:block ) => {
#[derive(Debug)]
pub struct $name {
handle: Handle<Node>,
value: $value_type,
index: usize
}
impl $name {
pub fn new(handle: Handle<Node>, index: usize, value: $value_type) -> Self {
Self { handle, index, value }
}
fn swap(&mut $self, graph: &mut Graph) {
let $emitter = &mut graph[$self.handle].as_particle_system_mut().emitters[$self.index];
$apply_method
}
}
impl<'a> Command<'a> for $name {
type Context = SceneContext<'a>;
fn name(&mut self, _context: &Self::Context) -> String {
$human_readable_name.to_owned()
}
fn execute(&mut self, context: &mut Self::Context) {
self.swap(&mut context.scene.graph);
}
fn revert(&mut self, context: &mut Self::Context) {
self.swap(&mut context.scene.graph);
}
}
};
}
define_node_command!(SetParticleSystemTextureCommand("Set Particle System Texture", Option<Texture>) where fn swap(self, node) {
get_set_swap!(self, node.as_particle_system_mut(), texture, set_texture);
});
define_node_command!(SetParticleSystemAccelerationCommand("Set Particle System Acceleration", Vector3<f32>) where fn swap(self, node) {
get_set_swap!(self, node.as_particle_system_mut(), acceleration, set_acceleration);
});
macro_rules! define_emitter_variant_command {
($name:ident($human_readable_name:expr, $value_type:ty) where fn swap($self:ident, $emitter:ident, $variant:ident, $var:ident) $apply_method:block ) => {
define_emitter_command!($name($human_readable_name, $value_type) where fn swap($self, $emitter) {
if let Emitter::$variant($var) = $emitter {
$apply_method
} else {
unreachable!()
}
});
};
}
define_emitter_variant_command!(SetSphereEmitterRadiusCommand("Set Sphere Emitter Radius", f32) where fn swap(self, emitter, Sphere, sphere) {
get_set_swap!(self, sphere, radius, set_radius);
});
define_emitter_variant_command!(SetCylinderEmitterRadiusCommand("Set Cylinder Emitter Radius", f32) where fn swap(self, emitter, Cylinder, cylinder) {
get_set_swap!(self, cylinder, radius, set_radius);
});
define_emitter_variant_command!(SetCylinderEmitterHeightCommand("Set Cylinder Emitter Radius", f32) where fn swap(self, emitter, Cylinder, cylinder) {
get_set_swap!(self, cylinder, height, set_height);
});
define_emitter_variant_command!(SetBoxEmitterHalfWidthCommand("Set Box Emitter Half Width", f32) where fn swap(self, emitter, Cuboid, box_emitter) {
get_set_swap!(self, box_emitter, half_width, set_half_width);
});
define_emitter_variant_command!(SetBoxEmitterHalfHeightCommand("Set Box Emitter Half Height", f32) where fn swap(self, emitter, Cuboid, box_emitter) {
get_set_swap!(self, box_emitter, half_height, set_half_height);
});
define_emitter_variant_command!(SetBoxEmitterHalfDepthCommand("Set Box Emitter Half Depth", f32) where fn swap(self, emitter, Cuboid, box_emitter) {
get_set_swap!(self, box_emitter, half_depth, set_half_depth);
});
define_emitter_command!(SetEmitterPositionCommand("Set Emitter Position", Vector3<f32>) where fn swap(self, emitter) {
get_set_swap!(self, emitter, position, set_position);
});
define_emitter_command!(SetEmitterResurrectParticlesCommand("Set Emitter Resurrect Particles", bool) where fn swap(self, emitter) {
get_set_swap!(self, emitter, is_particles_resurrects, enable_particle_resurrection);
});
|
#[allow(unused_variables)] //Allows to create variables not used in any function
fn main() {
let mut some_string: String = String::from("Howdy"); //Strings are always on the heap
let some_str: &str = "Partner"; //&str is pointer... to either stack or heap
some_procedure(&mut some_string, &some_str);
println!("{} {}", some_string, some_str);
}
//Só usar String se for para passar uma mutable String, senão usar sempre str slices
fn some_procedure(param_a: &mut String, param_b: &str ) {
param_a.insert(5, '!');
println!("{} {}", param_a, param_b);
}
// para alterar a var no procedimento, a mesma tem de ser mut
// o argumento enviado tem de levar mut
// e o argumento pedido tem de levar mut |
use std::hash::Hash;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use anyhow::Result;
use itertools::Itertools;
use once_cell::sync::Lazy;
use structopt::StructOpt;
use filter::subprocess::Exec;
use super::SharedParams;
use crate::app::Params;
use crate::paths::AbsPathBuf;
#[derive(StructOpt, Debug, Clone)]
struct TagsFileParams {
/// Same with the `--kinds-all` option of ctags.
#[structopt(long, default_value = "*")]
kinds_all: String,
/// Same with the `--fields` option of ctags.
#[structopt(long, default_value = "*")]
fields: String,
/// Same with the `--extras` option of ctags.
#[structopt(long, default_value = "*")]
extras: String,
}
/// Manipulate the tags file.
#[derive(StructOpt, Debug, Clone)]
pub struct TagsFile {
/// Params for creating tags file.
#[structopt(flatten)]
inner: TagsFileParams,
/// Shared parameters arouns ctags.
#[structopt(flatten)]
shared: SharedParams,
/// Search the tag matching the given query.
#[structopt(long)]
query: Option<String>,
/// Search the tag case insensitively
#[structopt(long)]
#[allow(unused)]
ignorecase: bool,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct TagsConfig<'a, P> {
languages: Option<&'a String>,
kinds_all: &'a str,
fields: &'a str,
extras: &'a str,
exclude_opt: String,
files: &'a [AbsPathBuf],
dir: P,
}
/// Represents the manager of tags file.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Tags<'a, P> {
config: TagsConfig<'a, P>,
tags_path: PathBuf,
}
pub static TAGS_DIR: Lazy<PathBuf> = Lazy::new(|| {
let proj_dirs = directories::ProjectDirs::from("org", "vim", "Vim Clap")
.expect("Couldn't create project directory for vim-clap");
let mut tags_dir = proj_dirs.data_dir().to_path_buf();
tags_dir.push("tags");
std::fs::create_dir_all(&tags_dir).expect("Couldn't create data directory for vim-clap");
tags_dir
});
impl<'a, P: AsRef<Path> + Hash> TagsConfig<'a, P> {
pub fn new(
languages: Option<&'a String>,
kinds_all: &'a str,
fields: &'a str,
extras: &'a str,
files: &'a [AbsPathBuf],
dir: P,
exclude_opt: String,
) -> Self {
Self {
languages,
kinds_all,
fields,
extras,
files,
dir,
exclude_opt,
}
}
pub fn with_dir(dir: P) -> Self {
Self {
languages: None,
kinds_all: "*",
fields: "*",
extras: "*",
files: Default::default(),
dir,
exclude_opt: super::EXCLUDE
.split(',')
.map(|x| format!("--exclude={}", x))
.join(" "),
}
}
/// Returns the path of tags file.
///
/// The file path of generated tags is determined by the hash of command itself.
pub fn tags_path(&self) -> PathBuf {
let mut tags_path = TAGS_DIR.deref().clone();
tags_path.push(utility::calculate_hash(self).to_string());
tags_path
}
fn build_command(&self) -> String {
// TODO: detect the languages by dir if not explicitly specified?
let languages_opt = self
.languages
.map(|v| format!("--languages={}", v))
.unwrap_or_default();
let mut cmd = format!(
"ctags {} --kinds-all='{}' --fields='{}' --extras='{}' {} -f '{}' -R",
languages_opt,
self.kinds_all,
self.fields,
self.extras,
self.exclude_opt,
self.tags_path().display()
);
// pass the input files.
if !self.files.is_empty() {
cmd.push(' ');
cmd.push_str(&self.files.iter().map(|f| f.display()).join(" "));
}
cmd
}
/// Executes the command to generate the tags file.
fn create(&self) -> Result<()> {
let command = self.build_command();
let exit_status = Exec::shell(&command).cwd(self.dir.as_ref()).join()?;
if !exit_status.success() {
return Err(anyhow::anyhow!("Error occured when creating tags file"));
}
Ok(())
}
}
impl<'a, P: AsRef<Path> + Hash> Tags<'a, P> {
pub fn new(config: TagsConfig<'a, P>) -> Self {
let tags_path = config.tags_path();
Self { config, tags_path }
}
/// Returns `true` if the tags file already exists.
pub fn exists(&self) -> bool {
self.tags_path.exists()
}
pub fn create(&self) -> Result<()> {
self.config.create()
}
pub fn readtags(&self, query: &str) -> Result<impl Iterator<Item = String>> {
use std::io::BufRead;
// https://docs.ctags.io/en/latest/man/readtags.1.html#examples
let stdout = Exec::cmd("readtags")
.arg("-t")
.arg(&self.tags_path)
.arg("-p")
.arg("-i")
.arg("-ne")
.arg("-")
.arg(query)
.stream_stdout()?;
Ok(std::io::BufReader::new(stdout).lines().flatten())
}
}
impl TagsFile {
pub fn run(&self, _params: Params) -> Result<()> {
let dir = self.shared.dir()?;
let config = TagsConfig::new(
self.shared.languages.as_ref(),
&self.inner.kinds_all,
&self.inner.fields,
&self.inner.extras,
&self.shared.files,
&dir,
self.shared.exclude_opt(),
);
let tags = Tags::new(config);
if !tags.exists() {
tags.create()?;
}
if let Some(ref query) = self.query {
for line in tags.readtags(query)?.collect::<Vec<_>>() {
println!("{}", line);
}
}
Ok(())
}
}
|
use super::shared::{FileOperations, ListenerData, Logs};
use std::collections::HashMap;
// TODO: Fix copying so that it doesn't rewrite when copying
pub struct FileName<'a> {
monitor_paths: &'a Vec<String>,
search: String,
deep: bool,
index: usize,
rule: String,
destinations: &'a HashMap<String, Vec<String>>,
}
impl<'a> FileName<'a> {
pub fn new(data: &'a mut ListenerData) -> Self {
Self {
monitor_paths: &data.monitor_paths,
deep: data.deep,
search: data.search.clone(),
index: data.index,
rule: data.rule.clone(),
destinations: &data.action_paths,
}
}
pub fn sort(&mut self) -> Vec<Logs> {
let mut log: Vec<Logs> = Vec::new();
for basepath in self.monitor_paths {
for path in FileOperations::walk(&format!("{}*", basepath), self.deep) {
if let Some(file) = path.file_name() {
let filename = file.to_str().unwrap().to_owned();
let searches: Vec<&str> = self.search.split_whitespace().collect();
let mut contains = false;
for search in searches {
if filename.contains(search) {
contains = true;
break;
}
contains = false;
}
for (destination, value) in self.destinations {
for action in value {
if self.rule == "Not Includes".to_owned() {
// ignore if extension is ignore list
if contains {
continue;
}
} else {
if !contains {
// ignores if extension is not in ignore list
continue;
}
}
log.push(FileOperations::sort(
action.to_owned(),
filename.to_owned(),
basepath.to_owned(),
destination.to_owned(),
self.index,
));
// (self.logs) = v;
// self.logs = v.clone();
}
}
}
}
}
log
}
}
#[derive(Debug)]
pub struct FileExtension<'a> {
extensions: Vec<String>,
monitor_paths: &'a Vec<String>,
deep: bool,
index: usize,
rule: String,
destinations: &'a HashMap<String, Vec<String>>,
}
impl<'a> FileExtension<'a> {
pub fn new(data: &'a mut ListenerData) -> Self {
let extensions: Vec<String> = data.search.split(" ").map(|s| s.to_owned()).collect();
Self {
extensions,
index: data.index,
monitor_paths: &data.monitor_paths,
deep: data.deep,
rule: data.rule.clone(),
destinations: &data.action_paths,
}
}
// test if all the closures works on folders and not only files [N.B] -> except unlink
pub fn sort(&mut self) -> Vec<Logs> {
let mut log: Vec<Logs> = Vec::new();
for basepath in self.monitor_paths {
// Walks the basepath for all file and folder names
for path in FileOperations::walk(&format!("{}*", basepath), false) {
if let Some(extension) = path.as_path().extension() {
let contains = self
.extensions
.contains(&extension.to_str().unwrap().to_owned());
let filename = match path.file_name() {
Some(name) => name.to_str().unwrap(),
None => "Empty",
};
for (destination, value) in self.destinations {
for action in value {
if self.rule == "Not Includes" {
// ignore if extension is ignore list
if contains {
continue;
}
} else {
if !contains {
// ignores if extension is not in ignore list
continue;
}
}
log.push(FileOperations::sort(
action.to_owned(),
filename.to_owned(),
basepath.to_owned(),
destination.to_owned(),
self.index,
));
}
}
}
}
}
log
}
}
|
use std::io::{self, Read, Seek, SeekFrom, Write};
use byteorder::{BigEndian, ReadBytesExt};
use ::{
align,
extract_section,
format_u64,
format_usize,
NumberStyle,
};
use sections::Section;
pub const APPLOADER_OFFSET: u64 = 0x2440;
const APPLOADER_DATE_SIZE: usize = 0x0A;
const APPLOADER_ENTRY_POINT_ADDR: u64 = 0x2450;
const APPLOADER_ENTRY_POINT_SIZE: u64 = 0xA0;
const APPLOADER_SIZE_ADDR: u64 = 0x2454;
#[derive(Debug)]
pub struct Apploader {
pub date: String,
pub entry_point: u64,
pub code_size: usize,
pub trailer_size: usize,
}
impl Apploader {
pub fn new<R>(mut reader: R, offset: u64) -> io::Result<Apploader>
where
R: Read + Seek,
{
let reader = &mut reader;
reader.seek(SeekFrom::Start(offset))?;
let mut date = String::new();
reader.take(APPLOADER_DATE_SIZE as u64).read_to_string(&mut date)?;
reader.seek(SeekFrom::Current(6))?; // it's just fluff
let entry_point = reader.read_u32::<BigEndian>()? as u64;
let code_size = reader.read_u32::<BigEndian>()? as usize;
let trailer_size = reader.read_u32::<BigEndian>()? as usize;
Ok(Apploader {
date,
entry_point,
code_size,
trailer_size,
})
}
pub fn total_size(&self) -> usize {
// self.code_size + self.trailer_size
align((self.code_size + self.trailer_size) as u64, 32) as usize
}
pub fn extract<R, W>(mut iso: R, file: W) -> io::Result<()>
where
R: Read + Seek,
W: Write,
{
iso.seek(SeekFrom::Start(APPLOADER_SIZE_ADDR))?;
let code_size = iso.read_u32::<BigEndian>()? as u64;
let trailer_size = iso.read_u32::<BigEndian>()? as u64;
iso.seek(SeekFrom::Start(APPLOADER_OFFSET))?;
let aligned_size = align(code_size + trailer_size, 32);
extract_section(iso, aligned_size as usize, file)
}
}
impl Section for Apploader {
fn print_info(&self, style: NumberStyle) {
println!("Offset: {}", format_u64(APPLOADER_OFFSET, style));
println!("Date: {}", self.date);
println!("Code size: {} bytes", format_usize(self.code_size, style));
println!("Trailer size: {} bytes", format_usize(self.trailer_size, style));
println!("Entry point: not yet implemented");
println!(
"Size (including code and trailer, aligned to 32 bytes): {}",
format_usize(self.total_size(), style),
);
}
fn start(&self) -> u64 {
APPLOADER_OFFSET
}
fn size(&self) -> usize {
self.total_size()
}
}
|
use crate::filter;
use crate::reference_library;
use std::io::{Error};
use std::collections::HashMap;
use debruijn::dna_string::DnaString;
use array_tool::vec::Intersect;
use reference_library::ReferenceMetadata;
type PseudoAligner = debruijn_mapping::pseudoaligner::Pseudoaligner<debruijn::kmer::VarIntKmer<u64, debruijn::kmer::K20>>;
pub enum IntersectLevel {
NoIntersect,
IntersectWithFallback,
ForceIntersect
}
pub struct AlignFilterConfig {
pub reference_genome_size: usize,
pub score_threshold: usize,
pub num_mismatches: usize,
pub discard_nonzero_mismatch: bool,
pub discard_multiple_matches: bool,
pub score_filter: i32,
pub intersect_level: IntersectLevel,
pub require_valid_pair: bool,
pub discard_multi_hits: usize
}
/* Takes a set of sequences and optionally, reverse sequences, a debrujin map index of the reference
* genome, the reference library metadata object, and the aligner configuration, and performs a
* debrujin-graph based pseduoalignment, returning a score for each readable reference in the reference
* genome.
* This function does some alignment-time filtration based on the provided configuration. */
pub fn score<I>(sequences: I, mut reverse_sequences: Option<I>, index: PseudoAligner, reference_metadata: &ReferenceMetadata,
config: &AlignFilterConfig) -> Vec<(Vec<String>, i32)>
where
I: Iterator<Item = Result<DnaString, Error>>
{
// HashMap of the alignment results. The keys are either strong hits or equivalence classes of hits
let mut score_map: HashMap<Vec<String>, i32> = HashMap::new();
// Iterate over every read/reverse read pair and align it, incrementing scores for the matching references/equivalence classes
for read in sequences {
let read = read.expect("Error -- could not parse read. Input R1 data malformed.");
/* Generate score and equivalence class for this read by aligning the sequence against
* the current reference, if there is a match.*/
let seq_score = pseudoalign(&read, &index, &config);
// If there's a reversed sequence, do the paired-end alignment
let mut rev_seq_score = None;
if let Some(itr) = &mut reverse_sequences {
let reverse_read = itr.next().expect(
"Error -- read and reverse read files do not have matching lengths: "
).expect("Error -- could not parse reverse read. Input R2 data malformed.");
rev_seq_score = Some(pseudoalign(&reverse_read, &index, &config));
}
// If there are no reverse sequences, ignore the require_valid_pair filter
if reverse_sequences.is_some() {
// Otherwise, check if the user enabled the require_valid_pair filter
if config.require_valid_pair {
// Unpack the data to check if the pairs have the same eq_class. If they both contain data, do the comparison
if let (Some(Some((mut rev_eq_class, _))), Some((mut eq_class, _))) = ((&rev_seq_score).clone(), (&seq_score).clone()) {
// Sort the vectors and compare them by counting matching elements. If they don't match, don't modify the score for this read
rev_eq_class.sort();
eq_class.sort();
let matching = eq_class.iter().zip(&rev_eq_class).filter(|&(classl, classr)| classl == classr).count();
if matching != eq_class.len() || matching != rev_eq_class.len() {
continue;
}
} else { // Otherwise, require_valid_pair is on and rev_score != seq_score, or they're both None. In either case, don't modify score
continue
}
}
}
// Take the "best" alignment. The specific behavior is determined by the intersect level set in the aligner config
let match_eqv_class = match config.intersect_level {
IntersectLevel::NoIntersect => get_best_reads(&seq_score, &rev_seq_score),
IntersectLevel::IntersectWithFallback => get_intersecting_reads(&seq_score, &rev_seq_score, true),
IntersectLevel::ForceIntersect => get_intersecting_reads(&seq_score, &rev_seq_score, false)
};
if !match_eqv_class.is_empty() {
let key = get_score_map_key(match_eqv_class, reference_metadata, &config); // Process the equivalence class into a score key
// Add the key to the score map and increment the score
let accessor = score_map.entry(key).or_insert(0);
*accessor += 1;
}
}
// Update the results map
let mut results = Vec::new();
for (key, value) in score_map.into_iter() {
results.push((key, value));
}
results
}
// Return matches that match in both seq_score and rev_seq_score; if soft intersection is enabled, fall back to best read if one of the reads is empty
fn get_intersecting_reads(seq_score: &Option<(Vec<u32>, usize)>, rev_seq_score: &Option<Option<(Vec<u32>, usize)>>, fallback_on_intersect_fail: bool) -> Vec<u32> {
if let (Some((eqv_class_seq, _)), Some(Some((eqv_class_rev_seq, _)))) = (&seq_score, &rev_seq_score) {
eqv_class_seq.intersect(eqv_class_rev_seq.to_vec())
} else if fallback_on_intersect_fail {
get_best_reads(seq_score, rev_seq_score)
} else {
Vec::new()
}
}
// Return matches from seq_score -- otherwise, return matches from rev_seq_score
fn get_best_reads(seq_score: &Option<(Vec<u32>, usize)>, rev_seq_score: &Option<Option<(Vec<u32>, usize)>>) -> Vec<u32> {
if let Some((eqv_class, _)) = &seq_score {
(*eqv_class).clone()
} else if let Some(Some((eqv_class, _))) = &rev_seq_score {
(*eqv_class).clone()
} else {
Vec::new()
}
}
/* Takes a equivalence class and returns a list of strings. If we're processing allele-level data, the strings will be
* the nt_sequences of the relevant alleles. Otherwise, if we're doing a group_by, the equivalence class will be
* filtered such that there is only one hit per group_by string (e.g. one hit per lineage) and the corresponding strings
* (e.g. lineage name) will be returned. */
fn get_score_map_key(equiv_class: Vec<u32>, reference_metadata: &ReferenceMetadata, config: &AlignFilterConfig) -> Vec<String> {
if reference_metadata.headers[reference_metadata.group_on] == "nt_sequence" {
equiv_class.into_iter().map(|ref_idx| reference_metadata.columns[reference_metadata.group_on][ref_idx as usize].clone()).collect()
} else {
let mut results = Vec::new();
for ref_idx in equiv_class {
let group = &reference_metadata.columns[reference_metadata.group_on][ref_idx as usize];
if !results.contains(group) {
results.push(group.to_string());
}
}
// Filter based on discard_multi_hits
if config.discard_multi_hits > 0 && results.len() > config.discard_multi_hits {
Vec::new()
} else {
results
}
}
}
// Align the given sequence against the given reference with a score threshold
fn pseudoalign(sequence: &DnaString, reference_index: &PseudoAligner, config: &AlignFilterConfig) -> Option<(Vec<u32>, usize)> {
// Perform alignment
match reference_index.map_read_with_mismatch(sequence, config.num_mismatches) {
Some((equiv_class, score, mismatches)) => {
// Filter nonzero mismatch
if config.discard_nonzero_mismatch && mismatches != 0 {
return None
}
// Filter by score and match threshold
filter::align::filter_alignment_by_metrics(score, equiv_class, config.score_threshold, config.discard_multiple_matches)
},
None => None
}
}
|
#[path = "support/macros.rs"]
#[macro_use]
mod macros;
use criterion::{criterion_group, criterion_main, Criterion};
// Note that euclid doesn't have a 4x4 matrix, it has Transform3D which is a
// stored as 4x4 matrix internally. It is included here as a 4x4 matrix is the
// closest point of comparison.
fn bench_mat4_transpose(c: &mut Criterion) {
use criterion::Benchmark;
c.bench(
"mat4 transpose",
Benchmark::new("glam", |b| {
use glam::Mat4;
bench_unop!(b, op => transpose, ty => Mat4);
})
.with_function("cgmath", |b| {
use cgmath::{prelude::*, Matrix4};
bench_unop!(b, op => transpose, ty => Matrix4<f32>);
})
.with_function("nalgebra", |b| {
use nalgebra::Matrix4;
bench_unop!(b, op => transpose, ty => Matrix4<f32>);
}),
);
}
fn bench_mat4_determinant(c: &mut Criterion) {
use criterion::Benchmark;
c.bench(
"mat4 determinant",
Benchmark::new("glam", |b| {
use glam::Mat4;
bench_unop!(b, op => determinant, ty => Mat4)
})
.with_function("cgmath", |b| {
use cgmath::{Matrix4, SquareMatrix};
bench_unop!(b, op => determinant, ty => Matrix4<f32>)
})
.with_function("nalgebra", |b| {
use nalgebra::Matrix4;
bench_unop!(b, op => determinant, ty => Matrix4<f32>)
})
.with_function("euclid", |b| {
use euclid::{Transform3D, UnknownUnit};
bench_unop!(b, op => determinant, ty => Transform3D<f32, UnknownUnit, UnknownUnit>)
}),
);
}
fn bench_mat4_inverse(c: &mut Criterion) {
use criterion::Benchmark;
c.bench(
"mat4 inverse",
Benchmark::new("glam", |b| {
use glam::Mat4;
bench_unop!(b, op => inverse, ty => Mat4)
})
.with_function("cgmath", |b| {
use cgmath::{Matrix4, SquareMatrix};
bench_unop!(b, op => invert, ty => Matrix4<f32>)
})
.with_function("nalgebra", |b| {
use nalgebra::Matrix4;
bench_unop!(b, op => try_inverse, ty => Matrix4<f32>)
})
.with_function("euclid", |b| {
use euclid::{Transform3D, UnknownUnit};
bench_unop!(b, op => inverse, ty => Transform3D<f32, UnknownUnit, UnknownUnit>)
}),
);
}
fn bench_mat4_mul_mat4(c: &mut Criterion) {
use criterion::Benchmark;
use std::ops::Mul;
c.bench(
"mat4 mul mat4",
Benchmark::new("glam", |b| {
use glam::Mat4;
bench_binop!(b, op => mul, ty1 => Mat4, ty2 => Mat4)
})
.with_function("cgmath", |b| {
use cgmath::Matrix4;
bench_binop!(b, op => mul, ty1 => Matrix4<f32>, ty2 => Matrix4<f32>, param => by_ref)
})
.with_function("nalgebra", |b| {
use nalgebra::Matrix4;
bench_binop!(b, op => mul, ty1 => Matrix4<f32>, ty2 => Matrix4<f32>, param => by_ref)
})
.with_function("euclid", |b| {
use euclid::{Transform3D, UnknownUnit};
bench_binop!(b, op => post_transform, ty => Transform3D<f32, UnknownUnit, UnknownUnit>, param => by_ref)
})
);
}
criterion_group!(
mat4_benches,
bench_mat4_transpose,
bench_mat4_determinant,
bench_mat4_inverse,
bench_mat4_mul_mat4,
);
criterion_main!(mat4_benches);
|
pub mod segments;
pub mod parsing;
|
pub struct Mastodon {
instance_url: String,
bearer_token: String,
}
impl Mastodon {
pub fn new(instance_url: String, bearer_token: String) -> Mastodon {
Mastodon {
instance_url,
bearer_token,
}
}
}
pub trait MastodonUpload {
fn spoiler_text(&self) -> String;
fn status(&self) -> String;
}
impl Mastodon {
pub async fn posting<T>(
&self, http_client: &reqwest::Client, msg: &T,
) -> Result<(), Box<dyn std::error::Error>>
where
T: MastodonUpload,
{
println!("[log] UPLOAD MASTODON {}", msg.spoiler_text());
let status = [
("spoiler_text", msg.spoiler_text()),
("status", msg.status()),
("visibility", "unlisted".to_string()),
];
http_client
.post(format!("https://{}/api/v1/statuses", &self.instance_url))
.bearer_auth(&self.bearer_token)
.form(&status)
.send()
.await?;
Ok(())
}
}
|
fn main(){
println!("Hello, world!");
println!("{greeting}, {name}!",greeting="Hello", name="world");
println!("{:?}",[1,2,3]);
println!("{:#?}",[1,2,3]);
//introducing variables
let answer = 42;
assert_eq!(answer,42); //this is checked at runtime
println!("Hello {}", answer);
//introducing loops & conditions
// There are no brackets around the condition, just like in Go, but you must use curly brackets around the block.
for i in 0..5{ //range is not inclusive so it will be 0,1,2,3,4
if i%2==0 {
println!("Even {}",i);
} else{
println!("Odd {}",i);
}
}
for i in 0..5{
let odd_even = if i%2 == 0 {"even"} else {"odd"};
println!("{} {}", odd_even, i);
}
//Variable Bindings
//In Rust variable are immutable by default, so we call them Variable bindings. To make them mutable, mut keyword is used.
// Rust is a statically typed language; It checks data type at compile time. But it doesn’t require you to actually type it when declare variable bindings. On that case compiler checks the usage and set a better data type for it. But for constants and statics you must annotate the type.
let a = true;
let b: bool = true;
let (mut x,y) = (1,2);
let mut z =5; //mut makes it possible for a var to be muttable
x= 7;
z=6;
//const keyword is used to define constants. It lives for the entire lifetime of a program but have no fixed address in memory. static keyword is used to define ‘global variable’ type facility. There is only one instance for each value, and it’s at a fixed location in memory.
}
|
use crate::{Assembler, AssemblerError, DiagCallback, Diagnostic};
use std::cell::RefCell;
use std::fmt::{self, Display, Formatter};
use std::iter::Peekable;
use std::num::Wrapping;
use std::rc::Rc;
// Exported for the parser
type Token = (Location, TokType, Location);
// === Token types ===
#[derive(Debug, Clone)]
pub enum TokType {
// Keywords
Adc,
Add,
And,
Bit,
Call,
Ccf,
Cpl,
Cp,
Daa,
Dec,
Di,
Ei,
Halt,
Inc,
Jp,
Jr,
Ld,
Ldi,
Ldd,
Ldio,
Ldh,
Nop,
Or,
Pop,
Push,
Res,
Reti,
Ret,
Rlca,
Rlc,
Rla,
Rl,
Rrc,
Rrca,
Rra,
Rr,
Rst,
Sbc,
Scf,
Set,
Sla,
Sra,
Srl,
Stop,
Sub,
Swap,
Xor,
Nz,
Z,
Nc,
Af,
Bc,
De,
Hl,
Sp,
Hld,
Hli,
A,
B,
C,
D,
E,
H,
L,
Def,
Fragment,
Bank,
Align,
Round,
Ceil,
Floor,
Div,
Mul,
Sin,
Cos,
Tan,
Asin,
Acos,
Atan,
Atan2,
High,
Low,
Isconst,
Strcmp,
Strin,
Strsub,
Strlen,
Strcat,
Strupr,
Strlwr,
Include,
Printt,
Printi,
Printv,
Printf,
Export,
Xdef,
Global,
Ds,
Db,
Dw,
Dl,
Section,
Purge,
Rsreset,
Rsset,
Incbin,
Charmap,
Newcharmap,
Setcharmap,
Pushc,
Popc,
Fail,
Warn,
Fatal,
Assert,
StaticAssert,
Macro,
Endm,
Shift,
Rept,
Endr,
Load,
Endl,
If,
Else,
Elif,
Endc,
Union,
Nextu,
Endu,
Wram0,
Vram,
Romx,
Rom0,
Hram,
Wramx,
Sram,
Oam,
Rb,
Rw,
Equ,
Equs,
Pushs,
Pops,
Pusho,
Popo,
Opt,
// Punctuation
Lparen,
Rparen,
Lbrack,
Rbrack,
Comma,
Colon,
// Operators
// Boolean
OpNot,
OpAnd,
OpOr,
// Binary
OpBinNot,
OpBinAnd,
OpBinOr,
OpBinXor,
// Arithmetic
OpAdd,
OpSub,
OpMul,
OpDiv,
OpMod,
// Comparison
OpEq,
OpNeq,
OpLt,
OpLte,
OpGt,
OpGte,
// Values
Num(i32),
String(String),
Ident(String),
LocalIdent(String),
Label(String),
LocalLabel(String),
// TODO: categorize
Assign,
CarriageRet,
Newline,
// Hack
Dummy,
}
impl TokType {
fn ident(name: String, is_local: bool, is_label: bool) -> Self {
match (is_label, is_local) {
(false, false) => TokType::Ident(name),
(false, true) => TokType::LocalIdent(name),
(true, false) => TokType::Label(name),
(true, true) => TokType::LocalLabel(name),
}
}
}
// Include token names generated by the build script from the parser token names
include!(concat!(env!("OUT_DIR"), "/token_names.rs"));
// Include the keyword trie, generated like the above
include!(concat!(env!("OUT_DIR"), "/keywords.rs"));
// === Token location ===
#[derive(Debug, Clone)]
pub struct Location {
parent: Option<Rc<Location>>,
line_no: u32,
col_no: u32,
}
impl Default for Location {
fn default() -> Self {
Self {
parent: None,
line_no: 1,
col_no: 1,
}
}
}
impl Display for Location {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
write!(fmt, "???:{}:{}", self.line_no, self.col_no)
}
}
#[derive(Debug)]
pub struct LocationSpan<'a> {
begin: &'a Location,
end: &'a Location,
}
impl<'a> LocationSpan<'a> {
pub fn new(begin: &'a Location, end: &'a Location) -> Self {
Self { begin, end }
}
}
impl Display for LocationSpan<'_> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
write!(
fmt,
"???:{}:{}-{}:{}",
self.begin.line_no, self.begin.col_no, self.end.line_no, self.end.col_no
)
}
}
// === Utilities ===
#[derive(Debug)]
enum InterpType {
Binary,
Decimal,
Upperhex,
Lowerhex,
}
struct InterpFmt {
fmt: InterpType,
}
impl InterpFmt {
fn from_str(fmt: String) -> Result<Self, AssemblerError> {
let mut chars = fmt.chars();
let mut ret = Self {
fmt: InterpType::Binary,
};
match chars.next() {
Some('b') => ret.fmt = InterpType::Binary,
Some('d') => ret.fmt = InterpType::Decimal,
Some('X') => ret.fmt = InterpType::Upperhex,
Some('x') => ret.fmt = InterpType::Lowerhex,
None => {
return Err(AssemblerError::EmptyInterpFmt);
}
Some(_) => {
return Err(AssemblerError::BadInterpFmt(fmt));
}
}
if let Some(_) = chars.next() {
return Err(AssemblerError::BadInterpFmt(fmt));
}
Ok(ret)
}
}
// === The lexer itself ===
pub enum State {
Normal,
Raw,
}
pub struct MutState {
state: State,
bin_digits: [char; 2],
gfx_digits: [char; 4],
}
impl MutState {
pub fn set_state(&mut self, state: State) {
self.state = state;
}
}
pub struct Lexer<'a> {
chars: Peekable<Box<dyn Iterator<Item = char> + 'a>>,
loc: Location,
disable_macro_args: bool,
state: &'a RefCell<MutState>,
diagnose: &'a DiagCallback,
assembler: &'a Assembler<'a>,
}
impl<'a> Lexer<'a> {
pub fn new(
iter: impl Iterator<Item = char> + 'a,
state: &'a RefCell<MutState>,
diagnose: &'a DiagCallback,
assembler: &'a Assembler<'a>,
) -> Self {
let chs = [1, 2];
assert!(chs.len() == 2);
Self {
chars: (Box::new(iter) as Box<dyn Iterator<Item = char>>).peekable(),
loc: Default::default(),
disable_macro_args: false,
state,
diagnose,
assembler,
}
}
pub fn new_state() -> MutState {
MutState {
state: State::Normal,
bin_digits: ['0', '1'],
gfx_digits: ['0', '1', '2', '3'],
}
}
// Some static properties
fn starts_ident(c: char) -> bool {
c.is_ascii_alphabetic() || c == '.' || c == '_'
}
fn is_ident(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '#' || c == '.' || c == '@' || c == '_'
}
fn is_whitespace(c: char) -> bool {
c == ' ' || c == '\t'
}
// Lexer internal management
fn peek(&mut self) -> Option<&char> {
self.chars.peek()
}
fn next(&mut self) -> Option<char> {
let c = self.chars.next();
match c {
Some('\n') => {
self.loc.line_no += 1;
self.loc.col_no = 1;
}
Some(_) => {
self.loc.col_no += 1;
}
None => (),
}
c
}
// Lexer helpers
fn discard_comment(&mut self) {
self.disable_macro_args = true;
loop {
match self.peek() {
Some('\r') => break,
Some('\n') => break,
None => break,
_ => (),
}
self.next();
}
self.disable_macro_args = false;
}
fn discard_block_comment(&mut self) {
self.disable_macro_args = true;
loop {
match self.next() {
Some('*') => {
if let Some('/') = self.peek() {
self.next();
break;
}
}
None => unimplemented!(),
_ => (),
}
}
self.disable_macro_args = false;
}
fn read_num(&mut self, radix: u32, first_char: char) -> Result<i32, AssemblerError> {
// The truncations performed by this function assume that the input radices are at most 16
assert!(radix <= 16);
let mut val = Wrapping(first_char.to_digit(radix).unwrap() as i32); // Truncation guaranteed (single digit)
loop {
let c: char;
match self.peek() {
Some(next) if next.is_digit(radix) => {
c = *next;
self.next();
}
_ => break,
}
match c.to_digit(radix) {
Some(d) => val = val * Wrapping(radix as i32) + Wrapping(d as i32), // Truncation guaranteed (single digit)
None => break,
}
}
Ok(val.0)
}
fn read_prefixed_num(
&mut self,
radix: u32,
alternative: Result<TokType, AssemblerError>,
) -> Result<TokType, AssemblerError> {
match self.peek() {
Some(&c) if c.is_digit(radix) => {
self.next();
Ok(TokType::Num(self.read_num(radix, c)?))
}
_ => alternative,
}
}
fn read_prefixed_custom_num(
&mut self,
digits: &[char],
alternative: Result<TokType, AssemblerError>,
) -> Result<TokType, AssemblerError> {
match self.peek() {
Some(c) if digits.contains(c) => {
// The truncations performed by this function assume that the input radices are at most 16
assert!(digits.len() < 16);
let radix = Wrapping(digits.len() as i32);
let mut c = *c;
let mut val = Wrapping(0_i32);
loop {
self.next();
val = val * radix
+ Wrapping(digits.iter().position(|&ch| ch == c).unwrap() as i32);
match self.peek() {
Some(ch) if digits.contains(ch) => c = *ch,
_ => break,
}
}
Ok(TokType::Num(val.0))
}
_ => alternative,
}
}
fn read_fractional(&mut self, int: i32) -> Result<i32, AssemblerError> {
// TODO: test this
let c = match self.peek() {
Some(c) if c.is_ascii_digit() => c,
_ => return Err(AssemblerError::EmptyFract),
};
let whole = i32::from(int as i16);
if whole != int {
// TODO: emit warning
unimplemented!()
}
let mut frac: u32 = c.to_digit(10).unwrap();
let mut len = 1;
loop {
self.next();
match self.peek().and_then(|c| c.to_digit(10)) {
Some(digit) => frac = frac * 10 + digit,
None => break,
}
len += 1;
}
Ok(whole << 16 | (frac * (2u32.pow(16 - len)) / 5u32.pow(len)) as i32)
}
fn read_interpolation(&mut self) -> Result<String, AssemblerError> {
let mut result = String::new();
let mut fmt = None;
loop {
match self.peek() {
Some('{') => {
self.next();
result.push_str(&self.read_interpolation()?);
}
None => {
(self.diagnose)(Diagnostic::Error(AssemblerError::UntermInterp.into()));
break;
}
Some('\r') => {
(self.diagnose)(Diagnostic::Error(AssemblerError::UntermInterp.into()));
break;
}
Some('\n') => {
(self.diagnose)(Diagnostic::Error(AssemblerError::UntermInterp.into()));
break;
}
Some('"') => {
(self.diagnose)(Diagnostic::Error(AssemblerError::UntermInterp.into()));
break;
}
Some('}') => {
self.next();
break;
}
Some(':') => {
self.next();
match fmt {
Some(_) => (self.diagnose)(Diagnostic::Error(
AssemblerError::MultipleInterpFmt.into(),
)),
None => {
match InterpFmt::from_str(result) {
Ok(f) => fmt = Some(f),
Err(err) => (self.diagnose)(Diagnostic::Error(err.into())),
};
result = String::new();
}
};
}
Some(&c) if Self::is_ident(c) => {
self.next();
result.push(c);
}
Some(&c) => {
self.next();
(self.diagnose)(Diagnostic::Error(
AssemblerError::IllegalInterpChar(c).into(),
));
}
}
}
todo!();
Ok(result)
}
fn read_str(&mut self) -> String {
let mut s = String::new();
loop {
match self.next() {
Some('"') => {
return s;
}
Some('\r') => {
(self.diagnose)(Diagnostic::Error(AssemblerError::UntermString.into()));
return s;
}
Some('\n') => {
(self.diagnose)(Diagnostic::Error(AssemblerError::UntermString.into()));
return s;
}
None => {
(self.diagnose)(Diagnostic::Error(AssemblerError::UntermString.into()));
return s;
}
Some('\\') => match self.peek() {
Some('\\') => s.push('\\'),
Some('"') => s.push('"'),
Some('{') => s.push('{'),
Some('}') => s.push('}'),
Some('n') => s.push('\n'),
Some('r') => s.push('\r'),
Some('t') => s.push('\t'),
Some(&c) if Self::begins_line_cont(c) => self.read_line_cont(),
None => {
(self.diagnose)(Diagnostic::Error(AssemblerError::IllegalEscapeEOF.into()));
return s;
}
Some(&c) => {
(self.diagnose)(Diagnostic::Error(AssemblerError::IllegalEscape(c).into()));
return s;
}
},
// Symbol interpolation
Some('{') => match self.read_interpolation() {
Ok(result) => s.push_str(&result),
Err(err) => (self.diagnose)(Diagnostic::Error(err.into())),
},
Some(c) => s.push(c),
}
}
}
fn begins_line_cont(c: char) -> bool {
c == ' ' || c == '\r' || c == '\n' || c == ';'
}
fn read_line_cont(&mut self) {
loop {
match self.peek() {
Some(&c) if Self::is_whitespace(c) => {
self.next();
}
Some('\r') => {
self.next();
break;
}
Some('\n') => {
self.next();
break;
}
Some(';') => {
self.next();
self.discard_comment();
}
Some(&c) => {
(self.diagnose)(Diagnostic::Error(
AssemblerError::CharAfterLineCont(c).into(),
));
return;
}
None => {
(self.diagnose)(Diagnostic::Error(AssemblerError::LineContEOF.into()));
return;
}
}
}
}
fn read_escape(&mut self) -> Result<(), AssemblerError> {
unimplemented!()
}
fn to_index(c: char) -> usize {
(if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else {
c
}) as usize
- '#' as usize
}
fn read_ident(&mut self, first_char: char) -> Result<Option<TokType>, AssemblerError> {
let mut keyword = Some(&KEYWORDS);
let mut ident = String::new();
let mut c = first_char;
let mut is_local = false;
let begun_at_bol = self.loc.col_no == 2; // `first_char` has been read before this
loop {
ident.push(c);
keyword = keyword.and_then(|node| {
node.children
.get(Self::to_index(c))
.and_then(Option::as_ref)
});
c = match self.peek() {
Some(&ch) if Self::is_ident(ch) => ch,
_ => break,
};
if c == '.' {
// Nested local symbols are illegal
if is_local {
break;
}
is_local = true;
}
self.next();
}
// TODO: expand EQUS, and return Ok(None)
Ok(Some(
keyword
.and_then(|node| node.value.clone())
.unwrap_or(TokType::ident(ident, is_local, begun_at_bol)),
))
}
// The lexer proper
fn next_normal_tok(&mut self) -> Result<Option<Token>, AssemblerError> {
loop {
let begin = self.loc.clone();
if let Some(c) = self.next() {
let tok_type = match c {
// Unambiguous single-char tokens
'^' => TokType::OpBinXor,
'+' => TokType::Add,
'-' => TokType::Sub,
'~' => TokType::OpBinNot,
'[' => TokType::Lbrack,
']' => TokType::Rbrack,
'(' => TokType::Lparen,
')' => TokType::Rparen,
',' => TokType::Comma,
':' => TokType::Colon,
// Ambiguous 1- or 2-char tokens
'/' => {
// Either a division, or block comment
if let Some('*') = self.peek() {
self.discard_block_comment();
continue;
} else {
TokType::Div
}
}
'|' => {
// Either a binary or logical OR
if let Some('|') = self.peek() {
self.next();
TokType::Or
} else {
TokType::OpBinOr
}
}
'=' => {
// Either an assignment, or equality
if let Some('=') = self.peek() {
self.next();
TokType::OpEq
} else {
TokType::Assign
}
}
'<' => {
// Either LT or LTE
if let Some('=') = self.peek() {
self.next();
TokType::OpLte
} else {
TokType::OpLt
}
}
'>' => {
// Either GT or GTE
if let Some('=') = self.peek() {
self.next();
TokType::OpGte
} else {
TokType::OpGt
}
}
'!' => {
// Either a negation, or NEQ
if let Some('=') = self.peek() {
self.next();
TokType::OpNeq
} else {
TokType::OpNot
}
}
// Numbers, two of the prefixes being ambiguous (!)
'$' => self.read_prefixed_num(16, Err(AssemblerError::EmptyHex))?,
c if c.is_ascii_digit() => {
let val = self.read_num(10, c)?;
if let Some('.') = self.peek() {
self.next();
self.read_fractional(val)?;
}
TokType::Num(val)
}
'&' => self.read_prefixed_num(8, Ok(TokType::OpBinAnd)).unwrap(),
'%' => {
let digits = self.state.borrow().bin_digits;
self.read_prefixed_custom_num(&digits, Ok(TokType::OpMod))
.unwrap()
}
'`' => {
let digits = self.state.borrow().gfx_digits;
self.read_prefixed_custom_num(&digits, Err(AssemblerError::EmptyGfx))?
}
// Strings
'"' => TokType::String(self.read_str()),
// End-of-line stuff
'\r' => TokType::CarriageRet,
'\n' => TokType::Newline,
// Escapes
'\\' => {
self.read_escape()?;
continue;
}
// Comments
';' => {
self.discard_comment();
continue;
}
// Discard whitespace
c if Self::is_whitespace(c) => {
continue;
}
// Identifiers, including keywords
c if Self::starts_ident(c) => match self.read_ident(c)? {
Some(tok) => tok,
None => continue,
},
// Catch-all
c => return Err(AssemblerError::GarbageChar(c)),
};
return Ok(Some((begin, tok_type, self.loc.clone())));
} else {
return Ok(None);
}
}
}
fn next_raw_tok(&mut self) -> Result<Option<Token>, AssemblerError> {
// First, trim all leading whitespace
loop {
match self.peek() {
Some(c) if Self::is_whitespace(*c) => (),
_ => break,
}
self.next();
}
let begin = self.loc.clone();
let mut end = None;
let mut arg = String::new();
let mut inside_string = false;
let end_tok = loop {
match self.peek() {
Some('"') => inside_string = !inside_string,
Some(';') if !inside_string => self.discard_comment(),
Some(',') => break Some(TokType::Comma),
Some('\r') => break Some(TokType::Newline),
Some('\n') => break Some(TokType::Newline),
None => break None,
Some('\\') => {
self.next();
match self.next() {
Some(',') => {
end = Some(self.loc.clone());
arg.push(',');
}
Some(c) if Self::begins_line_cont(c) => self.read_line_cont(),
None => {
(self.diagnose)(Diagnostic::Error(
AssemblerError::IllegalEscapeEOF.into(),
));
end = Some(self.loc.clone());
arg.push('\\');
}
Some(c) => {
// Append the following character as-is, without special treatment
end = Some(self.loc.clone());
arg.push('\\');
arg.push(c);
}
}
}
Some('{') => {
self.next();
}
Some(&c) => {
self.next();
if !Self::is_whitespace(c) {
end = Some(self.loc.clone());
}
arg.push(c);
}
}
};
if arg.len() == 0 {
self.next();
Ok(end_tok.map(|tok| (begin, tok, self.loc.clone())))
} else {
// Trim all trailing whitespace
arg.truncate(arg.trim_end_matches(Self::is_whitespace).len());
debug_assert_ne!(arg.len(), 0); // It should leave at least one character
Ok(Some((begin, TokType::String(arg), end.unwrap())))
}
}
}
impl Iterator for Lexer<'_> {
type Item = Result<Token, AssemblerError>;
fn next(&mut self) -> Option<Self::Item> {
match &self.state.borrow().state {
State::Normal => self.next_normal_tok(),
State::Raw => self.next_raw_tok(),
}
.transpose()
}
}
|
use aoc::*;
fn main() -> Result<()> {
let codes = get_codes();
println!("Day 5 part 1 result is {}", part1(&codes));
println!("Day 5 part 2 result is {}", part2(&codes));
Ok(())
}
fn get_codes() -> Vec<String> {
input("5.txt")
.unwrap()
.lines()
.map(|s| s.to_string())
.collect()
}
fn bsearch(code: &str, start: usize, end: usize) -> usize {
if code.is_empty() {
return end;
}
match code.chars().next().unwrap() {
'F' | 'L' => bsearch(&code[1..], start, (start + end) / 2),
_ => bsearch(&code[1..], (start + end) / 2, end),
}
}
fn calculate_id(code: &str) -> usize {
bsearch(&code[..7], 0, 127) * 8 + bsearch(&code[7..], 0, 7)
}
fn part1(codes: &[String]) -> usize {
codes.iter().map(|c| calculate_id(&c)).max().unwrap()
}
fn part2(codes: &[String]) -> usize {
let mut all_codes: Vec<usize> = codes.iter().map(|c| calculate_id(&c)).collect();
all_codes.sort_unstable();
let start = all_codes[0];
let end = all_codes.last().unwrap();
(start..=*end).sum::<usize>() - all_codes.iter().sum::<usize>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
assert!(part1(&get_codes()) == 864);
}
#[test]
fn test_part2() {
assert!(part2(&get_codes()) == 739);
}
#[test]
fn test_decode() {
assert!(calculate_id("FBFBBFFRLR") == 357);
assert!(calculate_id("BFFFBBFRRR") == 567);
assert!(calculate_id("FFFBBBFRRR") == 119);
assert!(calculate_id("BBFFBBFRLL") == 820);
}
}
|
use std::sync::{Arc, Mutex};
use futures::{Async, Poll, Stream};
use futures::task::{self, Task};
type Version = usize;
#[derive(Debug)]
pub struct NotifyCell<T: Clone> {
inner: Arc<Mutex<Inner<T>>>,
}
pub struct NotifyCellObserver<T: Clone> {
last_polled_at: Version,
inner: Arc<Mutex<Inner<T>>>,
}
#[derive(Debug)]
struct Inner<T: Clone> {
value: Option<T>,
last_written_at: Version,
subscribers: Vec<Task>
}
impl<T: Clone> NotifyCell<T> {
pub fn new(value: T) -> Self {
Self {
inner: Arc::new(Mutex::new(Inner {
value: Some(value),
last_written_at: 0,
subscribers: Vec::new()
})),
}
}
pub fn set(&self, value: T) {
let mut inner = self.inner.lock().unwrap();
inner.value = Some(value);
inner.last_written_at += 1;
for subscriber in inner.subscribers.drain(..) {
subscriber.notify();
}
}
pub fn get(&self) -> Option<T> {
let inner = self.inner.lock().unwrap();
inner.value.as_ref().cloned()
}
pub fn observe(&self) -> NotifyCellObserver<T> {
let inner = self.inner.lock().unwrap();
NotifyCellObserver {
last_polled_at: inner.last_written_at,
inner: self.inner.clone(),
}
}
}
impl<T: Clone> Stream for NotifyCellObserver<T> {
type Item = T;
type Error = ();
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let mut inner = self.inner.lock().unwrap();
if let Some(value) = inner.value.as_ref().cloned() {
if self.last_polled_at < inner.last_written_at {
self.last_polled_at = inner.last_written_at;
Ok(Async::Ready(Some(value.clone())))
} else {
inner.subscribers.push(task::current());
Ok(Async::NotReady)
}
} else {
Ok(Async::Ready(None))
}
}
}
impl<T: Clone> Drop for NotifyCell<T> {
fn drop(&mut self) {
let mut inner = self.inner.lock().unwrap();
inner.value.take();
for subscriber in inner.subscribers.drain(..) {
subscriber.notify();
}
}
}
#[cfg(test)]
mod tests {
extern crate rand;
extern crate futures_cpupool;
use super::*;
use std::collections::BTreeSet;
use futures::Future;
use self::rand::Rng;
use self::futures_cpupool::CpuPool;
#[test]
fn test_notify() {
let generated_values = rand::thread_rng()
.gen_iter::<u16>()
.take(1000)
.collect::<BTreeSet<_>>();
let mut generated_values_iter = generated_values.clone().into_iter();
let cell = NotifyCell::new(generated_values_iter.next().unwrap());
let num_threads = 100;
let pool = CpuPool::new(num_threads);
let cpu_futures = (0..num_threads)
.map(|_| pool.spawn(cell.observe().collect()))
.collect::<Vec<_>>();
for value in generated_values_iter {
cell.set(value);
}
drop(cell); // Dropping the cell terminates the stream.
for future in cpu_futures {
let observed_values = future.wait().unwrap();
let mut iter = observed_values.iter().peekable();
while let Some(value) = iter.next() {
assert!(generated_values.contains(value));
if let Some(next_value) = iter.peek() {
assert!(value < next_value);
}
}
}
}
}
|
use async_task::JoinHandle;
use pipe_channel::{channel, Receiver, Sender};
use std::collections::VecDeque;
use std::future::Future;
use std::sync::{Arc, Mutex};
use weechat::{FdHook, FdHookMode, Weechat};
fn executor_cb(future_queue: &FutureQueue, receiver: &mut Receiver<()>) {
receiver
.recv()
.expect("Executor channel has been dropped before unhooking");
let mut queue = future_queue
.lock()
.expect("Future queue has been dropped before unhooking");
let task = queue.pop_front();
// Drop the lock here so we can spawn new futures from the currently running
// one.
drop(queue);
if let Some(task) = task {
task.run();
}
}
type Job = async_task::Task<()>;
static mut _FUTURE_HOOK: Option<FdHook<FutureQueue, Receiver<()>>> = None;
static mut _SENDER: Option<Arc<Mutex<Sender<()>>>> = None;
static mut _FUTURE_QUEUE: Option<FutureQueue> = None;
type FutureQueue = Arc<Mutex<VecDeque<Job>>>;
pub fn spawn_weechat<F, R>(future: F) -> JoinHandle<R, ()>
where
F: Future<Output = R> + 'static,
R: 'static,
{
let weechat = unsafe { Weechat::weechat() };
unsafe {
if _FUTURE_HOOK.is_none() {
let (sender, receiver) = channel();
let sender = Arc::new(Mutex::new(sender));
let queue = Arc::new(Mutex::new(VecDeque::new()));
_SENDER = Some(sender);
_FUTURE_QUEUE = Some(queue.clone());
let fd_hook = weechat.hook_fd(
receiver,
FdHookMode::Read,
executor_cb,
Some(queue),
);
_FUTURE_HOOK = Some(fd_hook);
}
}
let weechat_notify = unsafe {
if let Some(s) = &_SENDER {
s.clone()
} else {
panic!("Future queue wasn't initialized")
}
};
let queue: FutureQueue = unsafe {
if let Some(q) = &_FUTURE_QUEUE {
q.clone()
} else {
panic!("Future queue wasn't initialized")
}
};
let schedule = move |task| {
let mut weechat_notify = weechat_notify
.lock()
.expect("Weechat notification sender lock is poisoned");
let mut queue = queue.lock().expect(
"Lock of the future queue of the Weechat executor is poisoned",
);
queue.push_back(task);
weechat_notify
.send(())
.expect("Can't notify Weechat to run a future");
};
let (task, handle) = async_task::spawn_local(future, schedule, ());
task.schedule();
handle
}
pub fn cleanup_executor() {
unsafe {
let hook = _FUTURE_HOOK.take();
// Drop our fd hook so it doesn't get called because we dropped the
// sender.
drop(hook);
_SENDER.take();
_FUTURE_QUEUE.take();
}
}
|
mod options;
use std::fmt::Debug;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use self::options::FindAndModifyOptions;
use crate::{
bson::{doc, from_document, rawdoc, Bson, Document, RawDocumentBuf},
bson_util,
cmap::{Command, RawCommandResponse, StreamDescription},
coll::{
options::{
FindOneAndDeleteOptions,
FindOneAndReplaceOptions,
FindOneAndUpdateOptions,
UpdateModifications,
},
Namespace,
},
error::{ErrorKind, Result},
operation::{
append_options_to_raw_document,
find_and_modify::options::Modification,
remove_empty_write_concern,
OperationWithDefaults,
Retryability,
},
options::WriteConcern,
};
pub(crate) struct FindAndModify<'a, R, T: DeserializeOwned> {
ns: Namespace,
query: Document,
modification: Modification<'a, R>,
human_readable_serialization: Option<bool>,
options: Option<FindAndModifyOptions>,
_phantom: std::marker::PhantomData<T>,
}
impl<T: DeserializeOwned> FindAndModify<'_, (), T> {
pub fn with_delete(
ns: Namespace,
query: Document,
options: Option<FindOneAndDeleteOptions>,
) -> Self {
FindAndModify {
ns,
query,
modification: Modification::Delete,
human_readable_serialization: None,
options: options.map(Into::into),
_phantom: Default::default(),
}
}
pub fn with_update(
ns: Namespace,
query: Document,
update: UpdateModifications,
options: Option<FindOneAndUpdateOptions>,
) -> Result<Self> {
if let UpdateModifications::Document(ref d) = update {
bson_util::update_document_check(d)?;
};
Ok(FindAndModify {
ns,
query,
modification: Modification::Update(update.into()),
human_readable_serialization: None,
options: options.map(Into::into),
_phantom: Default::default(),
})
}
}
impl<'a, R: Serialize, T: DeserializeOwned> FindAndModify<'a, R, T> {
pub fn with_replace(
ns: Namespace,
query: Document,
replacement: &'a R,
options: Option<FindOneAndReplaceOptions>,
human_readable_serialization: bool,
) -> Result<Self> {
Ok(FindAndModify {
ns,
query,
modification: Modification::Update(replacement.into()),
human_readable_serialization: Some(human_readable_serialization),
options: options.map(Into::into),
_phantom: Default::default(),
})
}
}
impl<'a, R: Serialize, T: DeserializeOwned> OperationWithDefaults for FindAndModify<'a, R, T> {
type O = Option<T>;
type Command = RawDocumentBuf;
const NAME: &'static str = "findAndModify";
fn build(&mut self, description: &StreamDescription) -> Result<Command<Self::Command>> {
if let Some(ref options) = self.options {
if options.hint.is_some() && description.max_wire_version.unwrap_or(0) < 8 {
return Err(ErrorKind::InvalidArgument {
message: "Specifying a hint to find_one_and_x is not supported on server \
versions < 4.4"
.to_string(),
}
.into());
}
}
let mut body = rawdoc! {
Self::NAME: self.ns.coll.clone(),
"query": RawDocumentBuf::from_document(&self.query)?,
};
let (key, modification) = match &self.modification {
Modification::Delete => ("remove", true.into()),
Modification::Update(update_or_replace) => (
"update",
update_or_replace
.to_raw_bson(self.human_readable_serialization.unwrap_or_default())?,
),
};
body.append(key, modification);
if let Some(ref mut options) = self.options {
remove_empty_write_concern!(Some(options));
}
append_options_to_raw_document(&mut body, self.options.as_ref())?;
Ok(Command::new(
Self::NAME.to_string(),
self.ns.db.clone(),
body,
))
}
fn serialize_command(&mut self, cmd: Command<Self::Command>) -> Result<Vec<u8>> {
cmd.into_bson_bytes()
}
fn handle_response(
&self,
response: RawCommandResponse,
_description: &StreamDescription,
) -> Result<Self::O> {
let response: Response = response.body()?;
match response.value {
Bson::Document(doc) => Ok(Some(from_document(doc)?)),
Bson::Null => Ok(None),
other => Err(ErrorKind::InvalidResponse {
message: format!(
"expected document for value field of findAndModify response, but instead got \
{:?}",
other
),
}
.into()),
}
}
fn write_concern(&self) -> Option<&WriteConcern> {
self.options.as_ref().and_then(|o| o.write_concern.as_ref())
}
fn retryability(&self) -> Retryability {
Retryability::Write
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct Response {
value: Bson,
}
|
use super::super::super::super::{awesome, btn, modal};
use super::Msg;
use crate::block;
use kagura::prelude::*;
mod common {
pub use super::super::super::common::*;
pub use super::super::common::*;
}
pub fn render(block_field: &block::Field, chat: &block::Chat) -> Html {
modal::container(
Attributes::new(),
Events::new(),
vec![modal::frame(
6,
Attributes::new(),
Events::new(),
vec![
common::header("チャットタブを編集"),
modal::body(
Attributes::new()
.class("scroll-v")
.class("pure-form")
.class("keyvalue")
.class("keyvalue-rev"),
Events::new(),
vec![
block_field
.listed::<block::chat::Tab>(chat.iter().collect())
.map(|(tab_id, tab)| {
vec![
Html::input(
Attributes::new().value(tab.name()),
Events::new().on_input({
let tab_id = tab_id.clone();
move |name| Msg::SetChatTabName(tab_id, name)
}),
vec![],
),
btn::danger(
Attributes::new(),
Events::new().on_click({
let tab_id = tab_id.clone();
move |_| Msg::RemoveChatTab(tab_id)
}),
vec![awesome::i("fa-times")],
),
]
})
.flatten()
.collect(),
vec![btn::secondary(
Attributes::new(),
Events::new().on_click(|_| Msg::AddChatTab),
vec![awesome::i("fa-plus")],
)],
]
.into_iter()
.flatten()
.collect(),
),
modal::footer(Attributes::new(), Events::new(), vec![]),
],
)],
)
}
|
use serde_derive::Deserialize;
#[derive(Deserialize, Debug)]
pub struct HealthCheck {
#[serde(rename(deserialize = "directory-server"))]
pub directory_server: String,
pub interval: f64, // in seconds
#[serde(rename(deserialize = "resolution-timeout"))]
pub resolution_timeout: f64, // in seconds
#[serde(rename(deserialize = "test-packets-per-node"))]
pub num_test_packets: usize,
}
|
/// <summary>
/// The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
/// Find the sum of all the primes below two million.
/// </summary>
/// <returns></returns>
pub fn compute() -> String {
let prime_numbers: Vec<u64> = ::euler_library::math_library::get_prime(2000000);
(::euler_library::math_library::series_sum(prime_numbers)).to_string()
}
|
use std::convert::Infallible;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
// OpenSSL
use openssl::ssl::{SslAcceptor, SslAcceptorBuilder, SslFiletype, SslMethod};
type Res<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
async fn hello(_: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from("Hello World!")))
}
//f/ Builds an SSL implementation for Simple HTTPS rom some hard-coded file names
/// @see https://docs.rs/openssl/0.10.26/openssl/ssl/index.html
#[allow(dead_code)]
fn ssl() -> Res<SslAcceptorBuilder> {
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls())?;
acceptor.set_private_key_file("keys/hyper-localhost.key", SslFiletype::PEM)?;
acceptor.set_certificate_chain_file("keys/hyper-localhost.crt")?;
acceptor.check_private_key()?;
Ok(acceptor)
}
#[tokio::main]
pub async fn main() -> Res<()> {
pretty_env_logger::init();
// For every connection, we must make a `Service` to handle all
// incoming HTTP requests on said connection.
let make_svc = make_service_fn(|_conn| {
// This is the `Service` that will handle the connection.
// `service_fn` is a helper to convert a function that
// returns a Response into a `Service`.
async { Ok::<_, Infallible>(service_fn(hello)) }
});
let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr).serve(make_svc);
println!("Listening on http://{}", addr);
server.await?;
Ok(())
}
|
//! Main utilities for high-level datatypes from the `azul_css` crate.
use azul_css::{
Css,
CssContentGroup,
CssDeclaration,
CssPath,
CssPathSelector,
CssPathPseudoSelector
};
use {
traits::Layout,
ui_description::{UiDescription, StyledNode},
dom::NodeData,
ui_state::UiState,
id_tree::{NodeId, NodeHierarchy, NodeDataContainer},
};
/// Has all the necessary information about the style xpath
pub struct HtmlCascadeInfo<'a, T: 'a + Layout> {
node_data: &'a NodeData<T>,
index_in_parent: usize,
is_last_child: bool,
is_hovered_over: bool,
is_focused: bool,
is_active: bool,
}
/// Returns if the style xpath matches the DOM node (i.e. if the DOM node should be styled by that element)
pub fn matches_html_element<'a, T: Layout>(
xpath: &CssPath,
node_id: NodeId,
node_hierarchy: &NodeHierarchy,
html_node_tree: &NodeDataContainer<HtmlCascadeInfo<'a, T>>)
-> bool
{
use self::CssGroupSplitReason::*;
if xpath.selectors.is_empty() {
return false;
}
let mut current_node = Some(node_id);
let mut direct_parent_has_to_match = false;
let mut last_selector_matched = false;
for (content_group, reason) in CssGroupIterator::new(&xpath.selectors) {
let cur_node_id = match current_node {
Some(c) => c,
None => {
// The node has no parent, but the CSS path
// still has an extra limitation - only valid if the
// next content group is a "*" element
return *content_group == [&CssPathSelector::Global];
},
};
let current_selector_matches = selector_group_matches(&content_group, &html_node_tree[cur_node_id]);
if direct_parent_has_to_match && !current_selector_matches {
// If the element was a ">" element and the current,
// direct parent does not match, return false
return false; // not executed (maybe this is the bug)
}
// Important: Set if the current selector has matched the element
last_selector_matched = current_selector_matches;
// Select if the next content group has to exactly match or if it can potentially be skipped
direct_parent_has_to_match = reason == DirectChildren;
current_node = node_hierarchy[cur_node_id].parent;
}
last_selector_matched
}
struct CssGroupIterator<'a> {
pub css_path: &'a Vec<CssPathSelector>,
pub current_idx: usize,
pub last_reason: CssGroupSplitReason,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum CssGroupSplitReason {
Children,
DirectChildren,
}
impl<'a> CssGroupIterator<'a> {
pub fn new(css_path: &'a Vec<CssPathSelector>) -> Self {
let initial_len = css_path.len();
Self {
css_path,
current_idx: initial_len,
last_reason: CssGroupSplitReason::Children,
}
}
}
impl<'a> Iterator for CssGroupIterator<'a> {
type Item = (CssContentGroup<'a>, CssGroupSplitReason);
fn next(&mut self) -> Option<(CssContentGroup<'a>, CssGroupSplitReason)> {
use self::CssPathSelector::*;
let mut new_idx = self.current_idx;
if new_idx == 0 {
return None;
}
let mut current_path = Vec::new();
while new_idx != 0 {
match self.css_path.get(new_idx - 1)? {
Children => {
self.last_reason = CssGroupSplitReason::Children;
break;
},
DirectChildren => {
self.last_reason = CssGroupSplitReason::DirectChildren;
break;
},
other => current_path.push(other),
}
new_idx -= 1;
}
current_path.reverse();
if new_idx == 0 {
if current_path.is_empty() {
None
} else {
// Last element of path
self.current_idx = 0;
Some((current_path, self.last_reason))
}
} else {
// skip the "Children | DirectChildren" element itself
self.current_idx = new_idx - 1;
Some((current_path, self.last_reason))
}
}
}
#[test]
fn test_css_group_iterator() {
use self::CssPathSelector::*;
use azul_css::NodeTypePath;
// ".hello > #id_text.new_class div.content"
// -> ["div.content", "#id_text.new_class", ".hello"]
let selectors = vec![
Class("hello".into()),
DirectChildren,
Id("id_test".into()),
Class("new_class".into()),
Children,
Type(NodeTypePath::Div),
Class("content".into()),
];
let mut it = CssGroupIterator::new(&selectors);
assert_eq!(it.next(), Some((vec![
&Type(NodeTypePath::Div),
&Class("content".into()),
], CssGroupSplitReason::Children)));
assert_eq!(it.next(), Some((vec![
&Id("id_test".into()),
&Class("new_class".into()),
], CssGroupSplitReason::DirectChildren)));
assert_eq!(it.next(), Some((vec![
&Class("hello".into()),
], CssGroupSplitReason::DirectChildren))); // technically not correct
assert_eq!(it.next(), None);
// Test single class
let selectors_2 = vec![
Class("content".into()),
];
let mut it = CssGroupIterator::new(&selectors_2);
assert_eq!(it.next(), Some((vec![
&Class("content".into()),
], CssGroupSplitReason::Children)));
assert_eq!(it.next(), None);
}
fn construct_html_cascade_tree<'a, T: Layout>(
input: &'a NodeDataContainer<NodeData<T>>,
node_hierarchy: &NodeHierarchy,
node_depths_sorted: &[(usize, NodeId)])
-> NodeDataContainer<HtmlCascadeInfo<'a, T>>
{
let mut nodes = (0..node_hierarchy.len()).map(|_| HtmlCascadeInfo {
node_data: &input[NodeId::new(0)],
index_in_parent: 0,
is_last_child: false,
is_hovered_over: false,
is_active: false,
is_focused: false,
}).collect::<Vec<_>>();
for (_depth, parent_id) in node_depths_sorted {
// Note: starts at 1 instead of 0
let index_in_parent = parent_id.preceding_siblings(node_hierarchy).count();
let parent_html_matcher = HtmlCascadeInfo {
node_data: &input[*parent_id],
index_in_parent: index_in_parent, // necessary for nth-child
is_last_child: node_hierarchy[*parent_id].next_sibling.is_none(), // Necessary for :last selectors
is_hovered_over: false, // TODO
is_active: false, // TODO
is_focused: false, // TODO
};
nodes[parent_id.index()] = parent_html_matcher;
for (child_idx, child_id) in parent_id.children(node_hierarchy).enumerate() {
let child_html_matcher = HtmlCascadeInfo {
node_data: &input[child_id],
index_in_parent: child_idx + 1, // necessary for nth-child
is_last_child: node_hierarchy[child_id].next_sibling.is_none(),
is_hovered_over: false, // TODO
is_active: false, // TODO
is_focused: false, // TODO
};
nodes[child_id.index()] = child_html_matcher;
}
}
NodeDataContainer { internal: nodes }
}
/// Matches a single groupt of items, panics on Children or DirectChildren selectors
///
/// The intent is to "split" the CSS path into groups by selectors, then store and cache
/// whether the direct or any parent has matched the path correctly
fn selector_group_matches<'a, T: Layout>(selectors: &[&CssPathSelector], html_node: &HtmlCascadeInfo<'a, T>) -> bool {
use self::CssPathSelector::*;
for selector in selectors {
match selector {
Global => { },
Type(t) => {
if html_node.node_data.node_type.get_path() != *t {
return false;
}
},
Class(c) => {
if !html_node.node_data.classes.contains(c) {
return false;
}
},
Id(id) => {
if !html_node.node_data.ids.contains(id) {
return false;
}
},
PseudoSelector(CssPathPseudoSelector::First) => {
// Notice: index_in_parent is 1-indexed
if html_node.index_in_parent != 1 { return false; }
},
PseudoSelector(CssPathPseudoSelector::Last) => {
// Notice: index_in_parent is 1-indexed
if !html_node.is_last_child { return false; }
},
PseudoSelector(CssPathPseudoSelector::NthChild(x)) => {
if html_node.index_in_parent != *x { return false; }
},
PseudoSelector(CssPathPseudoSelector::Hover) => {
if !html_node.is_hovered_over { return false; }
},
PseudoSelector(CssPathPseudoSelector::Active) => {
if !html_node.is_active { return false; }
},
PseudoSelector(CssPathPseudoSelector::Focus) => {
if !html_node.is_focused { return false; }
},
DirectChildren | Children => {
panic!("Unreachable: DirectChildren or Children in CSS path!");
},
}
}
true
}
pub(crate) fn match_dom_selectors<T: Layout>(
ui_state: &UiState<T>,
style: &Css)
-> UiDescription<T>
{
use ui_solver::get_non_leaf_nodes_sorted_by_depth;
use std::collections::BTreeMap;
let root = ui_state.dom.root;
let arena_borrow = &*ui_state.dom.arena.borrow();
let non_leaf_nodes = get_non_leaf_nodes_sorted_by_depth(&arena_borrow.node_layout);
let mut styled_nodes = BTreeMap::<NodeId, StyledNode>::new();
let html_tree = construct_html_cascade_tree(&arena_borrow.node_data, &arena_borrow.node_layout, &non_leaf_nodes);
for (_depth, parent_id) in non_leaf_nodes {
let mut parent_rules = styled_nodes.get(&parent_id).cloned().unwrap_or_default();
// Iterate through all style rules, test if they match
// This is technically O(n ^ 2), however, there are usually not that many style blocks,
// so the cost of this should be insignificant.
for applying_rule in style.rules.iter().filter(|rule| matches_html_element(&rule.path, parent_id, &arena_borrow.node_layout, &html_tree)) {
parent_rules.style_constraints.extend(applying_rule.declarations.clone());
}
let inheritable_rules: Vec<CssDeclaration> = parent_rules.style_constraints.iter().filter(|prop| prop.is_inheritable()).cloned().collect();
// For children: inherit from parents - filter children that themselves are not parents!
for child_id in parent_id.children(&arena_borrow.node_layout) {
let child_node = &arena_borrow.node_layout[child_id];
match child_node.first_child {
None => {
// Style children that themselves aren't parents
let mut child_rules = inheritable_rules.clone();
// Iterate through all style rules, test if they match
// This is technically O(n ^ 2), however, there are usually not that many style blocks,
// so the cost of this should be insignificant.
for applying_rule in style.rules.iter().filter(|rule| matches_html_element(&rule.path, child_id, &arena_borrow.node_layout, &html_tree)) {
child_rules.extend(applying_rule.declarations.clone());
}
styled_nodes.insert(child_id, StyledNode { style_constraints: child_rules });
},
Some(_) => {
// For all children that themselves are parents, simply copy the inheritable rules
styled_nodes.insert(child_id, StyledNode { style_constraints: inheritable_rules.clone() });
},
}
}
styled_nodes.insert(parent_id, parent_rules);
}
UiDescription {
// Note: this clone is necessary, otherwise,
// we wouldn't be able to update the UiState
//
// WARNING: The UIState can modify the `arena` with its copy of the Rc !
// Be careful about appending things to the arena, since that could modify
// the UiDescription without you knowing!
ui_descr_arena: ui_state.dom.arena.clone(),
ui_descr_root: root,
styled_nodes: styled_nodes,
default_style_of_node: StyledNode::default(),
dynamic_style_overrides: ui_state.dynamic_style_overrides.clone(),
}
}
/// Sort the style rules by their weight, so that the rules are applied in the correct order.
/// Should always be called when a new style is loaded from an external source.
pub(crate) fn sort_by_specificity(mut style: Css) -> Css {
style.rules.sort_by(|a, b| get_specificity(&a.path).cmp(&get_specificity(&b.path)));
style
}
/// Returns specificity of the given css path. Further information can be found on
/// [the w3 website](http://www.w3.org/TR/selectors/#specificity).
fn get_specificity(path: &CssPath) -> (usize, usize, usize) {
let id_count = path.selectors.iter().filter(|x| if let CssPathSelector::Id(_) = x { true } else { false }).count();
let class_count = path.selectors.iter().filter(|x| if let CssPathSelector::Class(_) = x { true } else { false }).count();
let div_count = path.selectors.iter().filter(|x| if let CssPathSelector::Type(_) = x { true } else { false }).count();
(id_count, class_count, div_count)
}
#[test]
fn test_specificity() {
use self::CssPathSelector::*;
use azul_css::NodeTypePath;
assert_eq!(get_specificity(&CssPath { selectors: vec![Id("hello".into())] }), (1, 0, 0));
assert_eq!(get_specificity(&CssPath { selectors: vec![Class("hello".into())] }), (0, 1, 0));
assert_eq!(get_specificity(&CssPath { selectors: vec![Type(NodeTypePath::Div)] }), (0, 0, 1));
assert_eq!(get_specificity(&CssPath { selectors: vec![Id("hello".into()), Type(NodeTypePath::Div)] }), (1, 0, 1));
}
// Assert that order of the style items is correct (in order of CSS path specificity, lowest-to-highest)
#[test]
fn test_specificity_sort() {
use azul_css::*;
use self::CssPathSelector::*;
use azul_css::NodeTypePath::*;
let input_style = Css {
rules: vec![
// Rules are sorted from lowest-specificity to highest specificity
CssRuleBlock { path: CssPath { selectors: vec![Global] }, declarations: Vec::new() },
CssRuleBlock { path: CssPath { selectors: vec![Global, Type(Div), Class("my_class".into()), Id("my_id".into())] }, declarations: Vec::new() },
CssRuleBlock { path: CssPath { selectors: vec![Global, Type(Div), Id("my_id".into())] }, declarations: Vec::new() },
CssRuleBlock { path: CssPath { selectors: vec![Global, Id("my_id".into())] }, declarations: Vec::new() },
CssRuleBlock { path: CssPath { selectors: vec![Type(Div), Class("my_class".into()), Class("specific".into()), Id("my_id".into())] }, declarations: Vec::new() },
],
};
let sorted_style = sort_by_specificity(input_style);
let expected_style = Css {
rules: vec![
// Rules are sorted from lowest-specificity to highest specificity
CssRuleBlock { path: CssPath { selectors: vec![Global] }, declarations: Vec::new() },
CssRuleBlock { path: CssPath { selectors: vec![Global, Id("my_id".into())] }, declarations: Vec::new() },
CssRuleBlock { path: CssPath { selectors: vec![Global, Type(Div), Id("my_id".into())] }, declarations: Vec::new() },
CssRuleBlock { path: CssPath { selectors: vec![Global, Type(Div), Class("my_class".into()), Id("my_id".into())] }, declarations: Vec::new() },
CssRuleBlock { path: CssPath { selectors: vec![Type(Div), Class("my_class".into()), Class("specific".into()), Id("my_id".into())] }, declarations: Vec::new() },
],
};
assert_eq!(sorted_style, expected_style);
}
|
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::time::Instant;
const INPUT: &str = include_str!("../input.txt");
fn part1() -> u64 {
let mut numbers: Vec<u64> = INPUT.lines().map(|line| line.parse().unwrap()).collect();
numbers.sort_unstable();
let mut prev = 0;
let mut counts = [0; 2];
for adapter in numbers {
let diff = usize::try_from(adapter - prev).unwrap();
let index = diff % 3;
if index <= 1 {
counts[index] += 1;
}
prev = adapter;
}
(counts[0] + 1) * counts[1]
}
fn part2() -> u64 {
let mut all_adapters: Vec<u64> = INPUT.lines().map(|line| line.parse().unwrap()).collect();
all_adapters.push(0);
all_adapters.sort_unstable();
let mut memo = VecDeque::with_capacity(3);
memo.push_back(1);
for i in 1..all_adapters.len() {
let last_3_iter = all_adapters.iter().skip(i.saturating_sub(3)).take(3);
let cur_adapter = all_adapters[i];
let ways = memo
.iter()
.zip(last_3_iter)
.fold(0, |acc, (memo_val, adapter)| {
if cur_adapter - adapter <= 3 {
acc + memo_val
} else {
acc
}
});
memo.push_back(ways);
if memo.len() > 3 {
memo.pop_front();
}
}
*memo.back().unwrap()
}
fn main() {
let start = Instant::now();
println!("part 1: {}", part1());
println!("part 1 took {}ms", (Instant::now() - start).as_millis());
let start = Instant::now();
println!("part 2: {}", part2());
println!("part 2 took {}ms", (Instant::now() - start).as_millis());
}
#[cfg(test)]
mod tests {
use super::{part1, part2};
#[test]
fn test_part1() {
assert_eq!(part1(), 1755);
}
#[test]
fn test_part2() {
assert_eq!(part2(), 4049565169664);
}
}
|
// Copyright 2019 Steven Bosnick
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms
use crate::{Arch, Error, Layout, LayoutStrategy, Result, PAGE_SIZE};
use goblin::elf::{header, program_header, Elf, ProgramHeader};
use itertools::Itertools;
/// An input ELF file that satisfies the necessary constraints for direct loading.
///
/// The constraints that the input ELF file must satisfy are:
/// * it must be an executable ELF file (not a shared library)
/// * it must contain neither a dynamic array nor an interpreter reference
#[derive(Debug)]
pub struct Input<'a> {
arch: Arch,
phdr: Vec<ProgramHeader>,
entry: u64,
input: &'a [u8],
}
impl<'a> Input<'a> {
/// Create a new `Input` from the given input bytes.
///
/// # Errors
/// `new()` can return the following errors:
/// * `Error::BadElf`: `input` is not an ELF file
/// * `Error::InvalidElf`: `input` does not satisfy the required constraints
pub fn new(input: &'a [u8]) -> Result<Self> {
let elf = Elf::parse(input)?;
let arch = Arch::new(&elf.header)?;
let entry = elf.header.e_entry;
verify(&elf)?;
Ok(Input {
arch,
input,
entry,
phdr: sort_loadable_headers(elf.program_headers).collect(),
})
}
/// Layout the output file using the given strategy for selecting the
/// starting physical address.
///
/// # Errors
/// `layout()` can return the following errors:
/// * `Error::InvalidElf`: `start` is `FromInput` and the input contains sparse
/// segments with large gaps between their physical addresses
pub fn layout(&'a self, start: LayoutStrategy) -> Result<Layout<'a>> {
if start == LayoutStrategy::FromInput {
verify_dense_segments(self.phdr.iter())?;
verify_first_segment_not_near_zero(self.phdr.iter())?;
}
Ok(Layout::new(
self.arch,
self.phdr.iter(),
self.input,
self.entry,
start,
))
}
}
fn sort_loadable_headers(
phdr: impl IntoIterator<Item = ProgramHeader>,
) -> impl Iterator<Item = ProgramHeader> {
phdr.into_iter()
.filter(|ph| ph.p_type == program_header::PT_LOAD)
.sorted_by_key(|ph| (ph.p_paddr, ph.p_vaddr))
}
fn verify(elf: &Elf) -> Result<()> {
use Error::InvalidElf;
let message = if elf.header.e_type != header::ET_EXEC {
Some("Elf file not an executable file.")
} else if elf.dynamic.is_some() {
Some("Elf file contains a dynamic array.")
} else if elf.interpreter.is_some() {
Some("Elf file contains an interpretor.")
} else {
None
};
message.map_or(Ok(()), |message| {
Err(InvalidElf {
message: message.to_owned(),
})
})
}
fn verify_dense_segments<'a>(phdr: impl Iterator<Item = &'a ProgramHeader>) -> Result<()> {
let max_segment_gap = phdr
.tuple_windows::<(_, _)>()
.map(|(ph1, ph2)| ph2.p_paddr - (ph1.p_paddr + ph1.p_memsz))
.max();
match max_segment_gap {
Some(max) if max as usize > PAGE_SIZE => {
let message = "ELF file segments are sparse with large gaps in their physical layout";
Err(Error::InvalidElf {
message: message.to_owned(),
})
}
_ => Ok(()),
}
}
fn verify_first_segment_not_near_zero<'a>(
phdr: impl Iterator<Item = &'a ProgramHeader>,
) -> Result<()> {
let min_paddr = phdr.map(|ph| ph.p_paddr).min();
match min_paddr {
Some(min) if (min as usize) < PAGE_SIZE => {
let message =
"ELF file's first segment physical address does not leave room for headers";
Err(Error::InvalidElf {
message: message.to_owned(),
})
}
_ => Ok(()),
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::Error;
use dynamic::Dyn;
use goblin::container::Ctx;
use goblin::elf::header::{self, Header};
use goblin::elf::program_header::{self, ProgramHeader};
use goblin::elf::r#dyn as dynamic;
use scroll::ctx::SizeWith;
use scroll::Pwrite;
use std::ffi::CString;
#[test]
fn new_input_on_bad_bytes_is_error() {
let input = [0xba, 0xdd, 0x00, 0xd8, 0xde, 0xad, 0xbe, 0xef];
let result = Input::new(&input);
assert_matches!(result, Err(Error::BadElf(_)));
}
#[test]
fn new_input_with_shared_library_is_error() {
let mut input = vec![0; 512];
let ctx = get_ctx();
let mut offset: usize = 0;
input
.gwrite(
Header {
e_type: header::ET_DYN,
e_phoff: Header::size(&ctx) as u64,
e_phnum: 1,
..Header::new(ctx)
},
&mut offset,
)
.unwrap();
input
.gwrite_with(
ProgramHeader {
p_offset: (Header::size(&ctx) + ProgramHeader::size(&ctx)) as u64,
p_vaddr: 0x1000,
p_filesz: 13,
p_memsz: 16,
..ProgramHeader::new()
},
&mut offset,
ctx,
)
.unwrap();
input
.gwrite(
CString::new("Hello World!").expect("Bad CString"),
&mut offset,
)
.unwrap();
let result = Input::new(&input);
assert_matches!(result, Err(Error::InvalidElf { message: _ }));
}
#[test]
fn new_input_with_dynamic_array_is_error() {
let hello = CString::new("Hello World!").expect("Bad CString");
let hello_len = hello.as_bytes_with_nul().len();
let mut input = vec![0; 512];
let ctx = get_ctx();
let mut offset: usize = 0;
write_header(&ctx, &mut input, &mut offset, 2);
input
.gwrite_with(
ProgramHeader {
p_offset: (Header::size(&ctx) + 2 * ProgramHeader::size(&ctx)) as u64,
p_vaddr: 0x1000,
p_filesz: 100,
p_memsz: 100,
..ProgramHeader::new()
},
&mut offset,
ctx,
)
.unwrap();
input
.gwrite_with(
ProgramHeader {
p_type: program_header::PT_DYNAMIC,
p_offset: (Header::size(&ctx) + 2 * ProgramHeader::size(&ctx) + hello_len)
as u64,
p_vaddr: 0x2000,
p_filesz: 2 * Dyn::size_with(&ctx) as u64,
p_memsz: 2 * Dyn::size_with(&ctx) as u64,
..ProgramHeader::new()
},
&mut offset,
ctx,
)
.unwrap();
input
.gwrite(
CString::new("Hello World!").expect("Bad CString"),
&mut offset,
)
.unwrap();
input
.gwrite_with(
Dyn {
d_tag: dynamic::DT_INIT,
d_val: 0x1000,
},
&mut offset,
ctx,
)
.unwrap();
input
.gwrite_with(
Dyn {
d_tag: dynamic::DT_NULL,
d_val: 0,
},
&mut offset,
ctx,
)
.unwrap();
let result = Input::new(&input);
assert_matches!(result, Err(Error::InvalidElf { message: _ }));
}
#[test]
fn new_input_with_interpretor_is_error() {
let hello = CString::new("Hello World!").expect("Bad CString");
let hello_len = hello.as_bytes_with_nul().len();
let mut input = vec![0; 512];
let ctx = get_ctx();
let mut offset: usize = 0;
write_header(&ctx, &mut input, &mut offset, 2);
input
.gwrite_with(
ProgramHeader {
p_type: program_header::PT_INTERP,
p_offset: (Header::size(&ctx) + 2 * ProgramHeader::size(&ctx)) as u64,
p_vaddr: 0x1000,
p_filesz: hello_len as u64,
p_memsz: hello_len as u64,
..ProgramHeader::new()
},
&mut offset,
ctx,
)
.unwrap();
input
.gwrite_with(
ProgramHeader {
p_offset: (Header::size(&ctx) + 2 * ProgramHeader::size(&ctx)) as u64,
p_vaddr: 0x1000,
p_filesz: 100,
p_memsz: 100,
..ProgramHeader::new()
},
&mut offset,
ctx,
)
.unwrap();
input.gwrite(hello, &mut offset).unwrap();
let result = Input::new(&input);
assert_matches!(result, Err(Error::InvalidElf { message: _ }));
}
#[test]
fn input_layout_with_from_input_start_and_sparse_segements_is_error() {
let hello = CString::new("Hello World!").expect("Bad CString");
let hello_len = hello.as_bytes_with_nul().len();
let mut buffer = vec![0; 4 * PAGE_SIZE];
let ctx = get_ctx();
let mut offset: usize = 0;
write_header(&ctx, &mut buffer, &mut offset, 2);
buffer
.gwrite_with(
ProgramHeader {
p_offset: (Header::size(&ctx) + 2 * ProgramHeader::size(&ctx)) as u64,
p_vaddr: 0x1000,
p_paddr: 0x4000,
p_filesz: hello_len as u64,
p_memsz: 100,
..ProgramHeader::new()
},
&mut offset,
ctx,
)
.unwrap();
buffer
.gwrite_with(
ProgramHeader {
p_offset: (Header::size(&ctx) + 2 * ProgramHeader::size(&ctx) + hello_len)
as u64,
p_vaddr: 0x1000 + 2 * PAGE_SIZE as u64,
p_paddr: 0x4000 + 2 * PAGE_SIZE as u64,
p_filesz: hello_len as u64,
p_memsz: 100,
..ProgramHeader::new()
},
&mut offset,
ctx,
)
.unwrap();
buffer.gwrite(hello.clone(), &mut offset).unwrap();
buffer.gwrite(hello, &mut offset).unwrap();
let input = Input::new(&buffer).expect("Invalid ELF file passed to Input::new()");
let result = input.layout(LayoutStrategy::FromInput);
assert_matches!(result, Err(Error::InvalidElf { message: _ }));
}
#[test]
fn input_layout_with_from_input_start_and_first_segment_near_zero_is_error() {
let hello = CString::new("Hello World!").expect("Bad CString");
let hello_len = hello.as_bytes_with_nul().len();
let mut buffer = vec![0; 4 * PAGE_SIZE];
let ctx = get_ctx();
let mut offset: usize = 0;
write_header(&ctx, &mut buffer, &mut offset, 2);
buffer
.gwrite_with(
ProgramHeader {
p_offset: (Header::size(&ctx) + ProgramHeader::size(&ctx)) as u64,
p_vaddr: 0x1000,
p_paddr: 0x0010,
p_filesz: hello_len as u64,
p_memsz: 100,
..ProgramHeader::new()
},
&mut offset,
ctx,
)
.unwrap();
buffer.gwrite(hello, &mut offset).unwrap();
let input = Input::new(&buffer).expect("Invalid ELF file passed to Input::new()");
let result = input.layout(LayoutStrategy::FromInput);
assert_matches!(result, Err(Error::InvalidElf { message: _ }));
}
fn get_ctx() -> Ctx {
use goblin::container::{Container, Endian};
Ctx::new(Container::Little, Endian::Little)
}
fn write_header(ctx: &Ctx, input: &mut [u8], offset: &mut usize, phnum: u16) {
input
.gwrite(
Header {
e_type: header::ET_EXEC,
e_phoff: Header::size(ctx) as u64,
e_phnum: phnum,
..Header::new(*ctx)
},
offset,
)
.unwrap();
}
}
|
use cocoa::base::id;
/// `MTLStructType` is part of the reflection API that allows Metal framework
/// code to query details of a struct that is passed as an argument of a Metal
/// shading language function. You do not allocate or initialize `MTLStructType`
/// objects. To obtain a `MTLStructType` object, you can query the
/// bufferStructType property of a `MTLArgument` object, or call the structType
/// method for a `MTLStructMember` object. To examine the details of the struct,
/// you can recursively drill down the members property of the `MTLStructType`
/// object, which contains details about struct members, each of which is
/// represented by a `MTLStructMember` object.
pub trait MTLStructType {
/// An array of objects that describe the fields in the struct. (read-only)
///
/// #Description
///
/// Each array element in `members` is a `MTLStructMember` object that
/// corresponds to one of the fields in the struct.
unsafe fn members(self) -> id;
/// Returns an object that represents the member of the struct with a given name.
///
/// #Description
///
/// An object that represents the named struct member. If `name` does not match
/// a member name, `nil` is returned.
unsafe fn memberByName(self, name: id) -> id;
}
impl MTLStructType for id {
unsafe fn members(self) -> id {
msg_send![self, members]
}
unsafe fn memberByName(self, name: id) -> id {
msg_send![self, memberByName:name]
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - CR1"]
pub cr1: CR1,
#[doc = "0x04 - CR2"]
pub cr2: CR2,
#[doc = "0x08 - OAR1"]
pub oar1: OAR1,
#[doc = "0x0c - OAR2"]
pub oar2: OAR2,
#[doc = "0x10 - DR"]
pub dr: DR,
#[doc = "0x14 - SR1"]
pub sr1: SR1,
#[doc = "0x18 - SR2"]
pub sr2: SR2,
#[doc = "0x1c - CCR"]
pub ccr: CCR,
#[doc = "0x20 - TRISE"]
pub trise: TRISE,
}
#[doc = "CR1 (rw) register accessor: CR1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr1`]
module"]
pub type CR1 = crate::Reg<cr1::CR1_SPEC>;
#[doc = "CR1"]
pub mod cr1;
#[doc = "CR2 (rw) register accessor: CR2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr2::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 [`cr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr2`]
module"]
pub type CR2 = crate::Reg<cr2::CR2_SPEC>;
#[doc = "CR2"]
pub mod cr2;
#[doc = "OAR1 (rw) register accessor: OAR1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`oar1::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 [`oar1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`oar1`]
module"]
pub type OAR1 = crate::Reg<oar1::OAR1_SPEC>;
#[doc = "OAR1"]
pub mod oar1;
#[doc = "OAR2 (rw) register accessor: OAR2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`oar2::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 [`oar2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`oar2`]
module"]
pub type OAR2 = crate::Reg<oar2::OAR2_SPEC>;
#[doc = "OAR2"]
pub mod oar2;
#[doc = "DR (rw) register accessor: DR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dr::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 [`dr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`dr`]
module"]
pub type DR = crate::Reg<dr::DR_SPEC>;
#[doc = "DR"]
pub mod dr;
#[doc = "SR1 (rw) register accessor: SR1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr1::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 [`sr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr1`]
module"]
pub type SR1 = crate::Reg<sr1::SR1_SPEC>;
#[doc = "SR1"]
pub mod sr1;
#[doc = "SR2 (r) register accessor: SR2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr2::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr2`]
module"]
pub type SR2 = crate::Reg<sr2::SR2_SPEC>;
#[doc = "SR2"]
pub mod sr2;
#[doc = "CCR (rw) register accessor: CCR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr::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 [`ccr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr`]
module"]
pub type CCR = crate::Reg<ccr::CCR_SPEC>;
#[doc = "CCR"]
pub mod ccr;
#[doc = "TRISE (rw) register accessor: TRISE\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`trise::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 [`trise::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`trise`]
module"]
pub type TRISE = crate::Reg<trise::TRISE_SPEC>;
#[doc = "TRISE"]
pub mod trise;
|
use std::env;
/// Sorts the values using merge sort.
fn msort(values: &[i64]) -> Vec<i64> {
let lc = values.len() / 2;
let lvec;
let rvec;
let (mut l, mut r) = values.split_at(lc);
if !(l.len() <= 1 && r.len() <= 1) {
lvec = msort(l);
rvec = msort(r);
l = &lvec[..];
r = &rvec[..];
}
let mut sorted: Vec<i64> = Vec::with_capacity(values.len());
let mut l_iter = l.into_iter().peekable();
let mut r_iter = r.into_iter().peekable();
while l_iter.peek().is_some() || r_iter.peek().is_some() {
if l_iter.peek().is_none() {
sorted.push(*r_iter.next().unwrap());
} else if r_iter.peek().is_none() {
sorted.push(*l_iter.next().unwrap());
} else if *l_iter.peek().unwrap() < *r_iter.peek().unwrap() {
sorted.push(*l_iter.next().unwrap());
} else {
sorted.push(*r_iter.next().unwrap());
}
}
sorted
}
fn main() {
let values: Vec<i64> =
env::args().skip(1).map(|x| x.parse::<i64>().unwrap()).collect();
let sorted = msort(&values);
for v in sorted {
print!("{} ", v);
}
print!("\n");
}
|
#[doc = "Reader of register RCC_TIMG2PRER"]
pub type R = crate::R<u32, super::RCC_TIMG2PRER>;
#[doc = "Writer for register RCC_TIMG2PRER"]
pub type W = crate::W<u32, super::RCC_TIMG2PRER>;
#[doc = "Register RCC_TIMG2PRER `reset()`'s with value 0x8000_0000"]
impl crate::ResetValue for super::RCC_TIMG2PRER {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x8000_0000
}
}
#[doc = "TIMG2PRE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIMG2PRE_A {
#[doc = "0: The Timers kernel clock is equal to\r\n mlhclk if APB2DIV is corresponding to a division\r\n by 1 or 2, else it is equal to 2 x Fpclk2\r\n (default after reset)"]
B_0X0 = 0,
#[doc = "1: The Timers kernel clock is equal to\r\n mlhclk if APB2DIV is corresponding to division by\r\n 1, 2 or 4, else it is equal to 4 x\r\n Fpclk2"]
B_0X1 = 1,
}
impl From<TIMG2PRE_A> for bool {
#[inline(always)]
fn from(variant: TIMG2PRE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TIMG2PRE`"]
pub type TIMG2PRE_R = crate::R<bool, TIMG2PRE_A>;
impl TIMG2PRE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIMG2PRE_A {
match self.bits {
false => TIMG2PRE_A::B_0X0,
true => TIMG2PRE_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == TIMG2PRE_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == TIMG2PRE_A::B_0X1
}
}
#[doc = "Write proxy for field `TIMG2PRE`"]
pub struct TIMG2PRE_W<'a> {
w: &'a mut W,
}
impl<'a> TIMG2PRE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TIMG2PRE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The Timers kernel clock is equal to mlhclk if APB2DIV is corresponding to a division by 1 or 2, else it is equal to 2 x Fpclk2 (default after reset)"]
#[inline(always)]
pub fn b_0x0(self) -> &'a mut W {
self.variant(TIMG2PRE_A::B_0X0)
}
#[doc = "The Timers kernel clock is equal to mlhclk if APB2DIV is corresponding to division by 1, 2 or 4, else it is equal to 4 x Fpclk2"]
#[inline(always)]
pub fn b_0x1(self) -> &'a mut W {
self.variant(TIMG2PRE_A::B_0X1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "TIMG2PRERDY\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TIMG2PRERDY_A {
#[doc = "0: The new division factor is not yet\r\n taken into account."]
B_0X0 = 0,
#[doc = "1: The new division factor is taken\r\n into account. (default after reset)"]
B_0X1 = 1,
}
impl From<TIMG2PRERDY_A> for bool {
#[inline(always)]
fn from(variant: TIMG2PRERDY_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TIMG2PRERDY`"]
pub type TIMG2PRERDY_R = crate::R<bool, TIMG2PRERDY_A>;
impl TIMG2PRERDY_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIMG2PRERDY_A {
match self.bits {
false => TIMG2PRERDY_A::B_0X0,
true => TIMG2PRERDY_A::B_0X1,
}
}
#[doc = "Checks if the value of the field is `B_0X0`"]
#[inline(always)]
pub fn is_b_0x0(&self) -> bool {
*self == TIMG2PRERDY_A::B_0X0
}
#[doc = "Checks if the value of the field is `B_0X1`"]
#[inline(always)]
pub fn is_b_0x1(&self) -> bool {
*self == TIMG2PRERDY_A::B_0X1
}
}
impl R {
#[doc = "Bit 0 - TIMG2PRE"]
#[inline(always)]
pub fn timg2pre(&self) -> TIMG2PRE_R {
TIMG2PRE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 31 - TIMG2PRERDY"]
#[inline(always)]
pub fn timg2prerdy(&self) -> TIMG2PRERDY_R {
TIMG2PRERDY_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIMG2PRE"]
#[inline(always)]
pub fn timg2pre(&mut self) -> TIMG2PRE_W {
TIMG2PRE_W { w: self }
}
}
|
use crate::input::device::{Device, DeviceType};
use crate::input::event_filter::{EventFilter, EventFilterManager};
use crate::input::events::{InputEvent, KeyboardEvent};
use crate::{config::ConfigManager, input::seat::SeatManager};
use log::debug;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::ops::Deref;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use wlroots_sys::*;
use xkbcommon::xkb;
#[cfg(not(test))]
use xkbcommon::xkb::ffi::xkb_state_ref;
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct RepeatRate(u32);
impl Default for RepeatRate {
fn default() -> Self {
RepeatRate(33)
}
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct RepeatDelay(u32);
impl Default for RepeatDelay {
fn default() -> Self {
RepeatDelay(500)
}
}
#[derive(Default, Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KeyboardConfig {
pub xkb_rules: String,
pub xkb_model: String,
pub xkb_layout: String,
pub xkb_variant: String,
pub xkb_options: Option<String>,
pub repeat_rate: RepeatRate,
pub repeat_delay: RepeatDelay,
}
pub struct Keyboard {
seat_manager: Rc<SeatManager>,
event_filter_manager: Rc<EventFilterManager>,
device: Rc<Device>,
keyboard: *mut wlr_keyboard,
xkb_state: RefCell<xkb::State>,
event_manager: RefCell<Option<Pin<Box<KeyboardEventManager>>>>,
}
impl Keyboard {
fn init(
config_manager: Rc<ConfigManager>,
seat_manager: Rc<SeatManager>,
event_filter_manager: Rc<EventFilterManager>,
device: Rc<Device>,
) -> Rc<Keyboard> {
debug!("Keyboard::init: {}", device.name());
let keyboard_ptr = match device.device_type() {
DeviceType::Keyboard(keyboard_ptr) => keyboard_ptr,
_ => panic!("Keyboard::init expects a keyboard device"),
};
let config = &config_manager.config().keyboard;
set_keymap_from_config(keyboard_ptr, config);
let keyboard = Rc::new(Keyboard {
seat_manager,
event_filter_manager,
device: device.clone(),
keyboard: keyboard_ptr,
xkb_state: RefCell::new(unsafe {
xkb::State::from_raw_ptr(xkb_state_ref((*keyboard_ptr).xkb_state))
}),
event_manager: RefCell::new(None),
});
let subscription =
config_manager
.on_config_changed()
.subscribe(listener!(keyboard => move |config| {
set_keymap_from_config(keyboard.raw_ptr(), &config.keyboard);
*keyboard.xkb_state.borrow_mut() = unsafe {
xkb::State::from_raw_ptr(xkb_state_ref((*keyboard_ptr).xkb_state))
};
}));
device.on_destroy.then(listener!(config_manager => move || {
config_manager.on_config_changed().unsubscribe(subscription);
}));
let mut event_manager = KeyboardEventManager::new(Rc::downgrade(&keyboard));
unsafe {
event_manager.modifiers(&mut (*keyboard_ptr).events.modifiers);
event_manager.key(&mut (*keyboard_ptr).events.key);
}
*keyboard.event_manager.borrow_mut() = Some(event_manager);
keyboard
}
pub fn raw_ptr(&self) -> *mut wlr_keyboard {
self.keyboard
}
pub fn device(&self) -> Rc<Device> {
self.device.clone()
}
pub fn xkb_state(&self) -> xkb::State {
self.xkb_state.borrow().clone()
}
}
fn set_keymap_from_config(keyboard_ptr: *mut wlr_keyboard, config: &KeyboardConfig) {
// We need to prepare an XKB keymap and assign it to the keyboard.
let context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
let keymap = xkb::Keymap::new_from_names(
&context,
&config.xkb_rules,
&config.xkb_model,
&config.xkb_layout,
&config.xkb_variant,
config.xkb_options.clone(),
xkb::KEYMAP_COMPILE_NO_FLAGS,
)
.expect("xkb::Keymap could not be created");
unsafe {
wlr_keyboard_set_keymap(keyboard_ptr, keymap.get_raw_ptr());
wlr_keyboard_set_repeat_info(
keyboard_ptr,
config.repeat_rate.0 as i32,
config.repeat_delay.0 as i32,
);
}
}
pub(crate) trait KeyboardEventHandler {
fn modifiers(&self);
fn key(&self, event: *const wlr_event_keyboard_key);
}
impl KeyboardEventHandler for Keyboard {
fn modifiers(&self) {
unsafe {
// A seat can only have one keyboard, but this is a limitation of the
// Wayland protocol - not wlroots. We assign all connected keyboards to the
// same seat. You can swap out the underlying wlr_keyboard like this and
// wlr_seat handles this transparently.
wlr_seat_set_keyboard(self.seat_manager.raw_seat(), self.device.raw_ptr());
// Send modifiers to the client.
wlr_seat_keyboard_notify_modifiers(
self.seat_manager.raw_seat(),
&mut (*self.keyboard).modifiers,
);
}
}
fn key(&self, event: *const wlr_event_keyboard_key) {
let event = unsafe { KeyboardEvent::from_ptr(self, event) };
let handled = self.event_filter_manager.handle_keyboard_event(&event);
if !handled {
unsafe {
// Otherwise, we pass it along to the client.
wlr_seat_set_keyboard(self.seat_manager.raw_seat(), self.device.raw_ptr());
wlr_seat_keyboard_notify_key(
self.seat_manager.raw_seat(),
event.time_msec(),
event.libinput_keycode(),
event.raw_state(),
);
}
}
}
}
wayland_listener!(
KeyboardEventManager,
Weak<Keyboard>,
[
modifiers => modifiers_func: |this: &mut KeyboardEventManager, _data: *mut libc::c_void,| unsafe {
if let Some(handler) = this.data.upgrade() {
handler.modifiers();
}
};
key => key_func: |this: &mut KeyboardEventManager, data: *mut libc::c_void,| unsafe {
if let Some(handler) = this.data.upgrade() {
handler.key(data as _);
}
};
]
);
pub struct KeyboardManager {
config_manager: Rc<ConfigManager>,
seat_manager: Rc<SeatManager>,
event_filter_manager: Rc<EventFilterManager>,
keyboards: RefCell<Vec<Rc<Keyboard>>>,
}
impl KeyboardManager {
pub(crate) fn init(
config_manager: Rc<ConfigManager>,
seat_manager: Rc<SeatManager>,
event_filter_manager: Rc<EventFilterManager>,
) -> Rc<KeyboardManager> {
let keyboard_manager = Rc::new(KeyboardManager {
config_manager,
seat_manager: seat_manager.clone(),
event_filter_manager,
keyboards: RefCell::new(vec![]),
});
seat_manager
.on_new_device
.subscribe(listener!(keyboard_manager => move |device| {
if let DeviceType::Keyboard(_) = device.device_type() {
device.on_destroy.then(listener!(device, keyboard_manager => move || {
keyboard_manager
.keyboards
.borrow_mut()
.retain(|keyboard| keyboard.device.deref() != device.deref());
keyboard_manager
.seat_manager
.set_has_any_keyboard(keyboard_manager.has_keyboard());
}));
unsafe {
wlr_seat_set_keyboard(keyboard_manager.seat_manager.raw_seat(), device.raw_ptr());
}
let keyboard = Keyboard::init(
keyboard_manager.config_manager.clone(),
keyboard_manager.seat_manager.clone(),
keyboard_manager.event_filter_manager.clone(),
device.clone(),
);
keyboard_manager.keyboards.borrow_mut().push(keyboard);
keyboard_manager.seat_manager.set_has_any_keyboard(true);
}
}));
keyboard_manager
}
pub fn has_keyboard(&self) -> bool {
!self.keyboards.borrow().is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::*;
use std::ptr;
use std::rc::Rc;
#[test]
fn it_drops_and_cleans_up_on_destroy() {
let config_manager = Rc::new(ConfigManager::default());
let seat_manager = SeatManager::mock(ptr::null_mut(), ptr::null_mut());
let event_filter_manager = Rc::new(EventFilterManager::new());
let keyboard_manager = Rc::new(KeyboardManager::init(
config_manager,
seat_manager.clone(),
event_filter_manager,
));
let mut raw_keyboard = wlr_keyboard {
impl_: ptr::null(),
group: ptr::null_mut(),
keymap_string: ptr::null_mut(),
keymap_size: 0,
keymap: ptr::null_mut(),
xkb_state: ptr::null_mut(),
led_indexes: [0; 3],
mod_indexes: [0; 8],
keycodes: [0; 32],
num_keycodes: 0,
modifiers: wlr_keyboard_modifiers {
depressed: 0,
latched: 0,
locked: 0,
group: 0,
},
repeat_info: wlr_keyboard__bindgen_ty_1 { rate: 0, delay: 0 },
events: wlr_keyboard__bindgen_ty_2 {
key: new_wl_signal(),
modifiers: new_wl_signal(),
keymap: new_wl_signal(),
repeat_info: new_wl_signal(),
destroy: new_wl_signal(),
},
data: ptr::null_mut(),
};
let mut device = wlr_input_device {
impl_: ptr::null(),
type_: wlr_input_device_type_WLR_INPUT_DEVICE_KEYBOARD,
vendor: 0,
product: 0,
name: ptr::null_mut(),
width_mm: 0.0,
height_mm: 0.0,
output_name: ptr::null_mut(),
__bindgen_anon_1: wlr_input_device__bindgen_ty_1 {
keyboard: &mut raw_keyboard,
},
events: wlr_input_device__bindgen_ty_2 {
destroy: new_wl_signal(),
},
data: ptr::null_mut(),
link: new_wl_list(),
};
let key_signal = WlSignal::from_ptr(&mut raw_keyboard.events.key);
let modifiers_signal = WlSignal::from_ptr(&mut raw_keyboard.events.modifiers);
let keymap_signal = WlSignal::from_ptr(&mut raw_keyboard.events.keymap);
let repeat_info_signal = WlSignal::from_ptr(&mut raw_keyboard.events.repeat_info);
let destroy_signal = WlSignal::from_ptr(&mut device.events.destroy);
let device = Device::init(&mut device);
let weak_device = Rc::downgrade(&device);
seat_manager.on_new_device.fire(device);
let keyboard = keyboard_manager.keyboards.borrow().first().unwrap().clone();
let weak_keyboard = Rc::downgrade(&keyboard);
drop(keyboard);
assert!(weak_device.upgrade().is_some());
assert!(weak_keyboard.upgrade().is_some());
assert!(key_signal.listener_count() == 1);
assert!(modifiers_signal.listener_count() == 1);
assert!(destroy_signal.listener_count() == 1);
assert!(keyboard_manager.has_keyboard());
destroy_signal.emit();
assert!(key_signal.listener_count() == 0);
assert!(modifiers_signal.listener_count() == 0);
assert!(keymap_signal.listener_count() == 0);
assert!(repeat_info_signal.listener_count() == 0);
assert!(destroy_signal.listener_count() == 0);
assert!(!keyboard_manager.has_keyboard());
assert!(weak_keyboard.upgrade().is_none());
assert!(weak_device.upgrade().is_none());
}
}
#[cfg(test)]
use xkbcommon::xkb::ffi::{xkb_keymap, xkb_state};
#[cfg(test)]
unsafe fn wlr_seat_set_keyboard(_: *mut wlr_seat, _: *mut wlr_input_device) {}
#[cfg(test)]
unsafe fn wlr_keyboard_set_keymap(_: *mut wlr_keyboard, _: *mut xkb_keymap) {}
#[cfg(test)]
unsafe fn wlr_keyboard_set_repeat_info(_: *mut wlr_keyboard, _: i32, _: i32) {}
#[cfg(test)]
unsafe fn xkb_state_ref(ptr: *mut xkb_state) -> *mut xkb_state {
ptr
}
|
pub(in crate) mod properties_;
pub(in crate) mod ref_;
pub(in crate) mod type_;
#[cfg(test)]
use crate::types::keyword_type::KeywordType;
use crate::types::{
draft_version::DraftVersion, schema::Schema, schema_error::SchemaError, scope_builder::ScopeBuilder, validator::Validator, validator_error_iterator::ValidationErrorIterator,
};
use json_trait_rs::JsonType;
use std::{ops::Deref, sync::Arc};
use url::Url;
#[derive(Debug)]
pub(in crate) enum DraftValidator {
Ref(ref_::Ref),
Properties(properties_::Properties),
Type(type_::Type),
}
impl DraftValidator {
pub(in crate) fn validation_errors<T: 'static + JsonType>(&self, path: &str, value: &T) -> ValidationErrorIterator {
match self {
Self::Ref(validator) => validator.validation_errors(path, value),
Self::Properties(validator) => validator.validation_errors(path, value),
Self::Type(validator) => validator.validation_errors(path, value),
}
}
pub(in crate) fn is_valid<T: 'static + JsonType>(&self, path: &str, value: &T) -> bool {
self.validation_errors(path, value).next().is_none()
}
#[cfg(test)]
pub(in crate) fn keyword_type(&self) -> KeywordType {
match self {
Self::Ref(validator) => validator.keyword_type(),
Self::Properties(validator) => validator.keyword_type(),
Self::Type(validator) => validator.keyword_type(),
}
}
}
pub(in crate) fn compile_draft_validators<T: 'static + JsonType>(scope_builder: &mut ScopeBuilder<T>, schema: &Schema) -> Result<Vec<DraftValidator>, SchemaError> {
let mut validators: Vec<DraftValidator> = Vec::new();
match scope_builder.draft_version {
DraftVersion::Draft4 => {
if let Some(validator) = type_::Type::compile(scope_builder, schema)? {
validators.push(DraftValidator::Type(validator));
}
if let Some(validator) = properties_::Properties::compile(scope_builder, schema)? {
validators.push(DraftValidator::Properties(validator));
}
if let Some(validator) = ref_::Ref::compile(scope_builder, schema)? {
validators.push(DraftValidator::Ref(validator));
}
}
};
validators.shrink_to_fit();
Ok(validators)
}
|
#[doc = "Register `SSCR` reader"]
pub type R = crate::R<SSCR_SPEC>;
#[doc = "Register `SSCR` writer"]
pub type W = crate::W<SSCR_SPEC>;
#[doc = "Field `VSH` reader - Vertical Synchronization Height (in units of horizontal scan line)"]
pub type VSH_R = crate::FieldReader<u16>;
#[doc = "Field `VSH` writer - Vertical Synchronization Height (in units of horizontal scan line)"]
pub type VSH_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 11, O, u16>;
#[doc = "Field `HSW` reader - Horizontal Synchronization Width (in units of pixel clock period)"]
pub type HSW_R = crate::FieldReader<u16>;
#[doc = "Field `HSW` writer - Horizontal Synchronization Width (in units of pixel clock period)"]
pub type HSW_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 12, O, u16>;
impl R {
#[doc = "Bits 0:10 - Vertical Synchronization Height (in units of horizontal scan line)"]
#[inline(always)]
pub fn vsh(&self) -> VSH_R {
VSH_R::new((self.bits & 0x07ff) as u16)
}
#[doc = "Bits 16:27 - Horizontal Synchronization Width (in units of pixel clock period)"]
#[inline(always)]
pub fn hsw(&self) -> HSW_R {
HSW_R::new(((self.bits >> 16) & 0x0fff) as u16)
}
}
impl W {
#[doc = "Bits 0:10 - Vertical Synchronization Height (in units of horizontal scan line)"]
#[inline(always)]
#[must_use]
pub fn vsh(&mut self) -> VSH_W<SSCR_SPEC, 0> {
VSH_W::new(self)
}
#[doc = "Bits 16:27 - Horizontal Synchronization Width (in units of pixel clock period)"]
#[inline(always)]
#[must_use]
pub fn hsw(&mut self) -> HSW_W<SSCR_SPEC, 16> {
HSW_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 = "Synchronization Size Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sscr::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 [`sscr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SSCR_SPEC;
impl crate::RegisterSpec for SSCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`sscr::R`](R) reader structure"]
impl crate::Readable for SSCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`sscr::W`](W) writer structure"]
impl crate::Writable for SSCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SSCR to value 0"]
impl crate::Resettable for SSCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use super::{shared::mask_32::DepthVector32, shared::vector_128::DelimiterClassifierImpl128, *};
use crate::{
classification::mask::m32,
classification::{quotes::QuoteClassifiedBlock, ResumeClassifierBlockState},
debug,
input::{error::InputError, InputBlock},
FallibleIterator,
};
use std::marker::PhantomData;
const SIZE: usize = 32;
shared::depth_classifier!(
Ssse3VectorIterator32,
DelimiterClassifierImpl128,
DepthVector32,
32,
u32
);
#[inline]
fn new_vector<'a, B: InputBlock<'a, SIZE>>(
bytes: QuoteClassifiedBlock<B, u32, SIZE>,
classifier: &DelimiterClassifierImpl128,
) -> DepthVector32<'a, B> {
new_vector_from(bytes, classifier, 0)
}
#[inline]
fn new_vector_from<'a, B: InputBlock<'a, SIZE>>(
bytes: QuoteClassifiedBlock<B, u32, SIZE>,
classifier: &DelimiterClassifierImpl128,
idx: usize,
) -> DepthVector32<'a, B> {
// SAFETY: target_feature invariant
unsafe { new_sse2(bytes, classifier, idx) }
}
#[target_feature(enable = "sse2")]
#[inline]
unsafe fn new_sse2<'a, B: InputBlock<'a, SIZE>>(
bytes: QuoteClassifiedBlock<B, u32, SIZE>,
classifier: &DelimiterClassifierImpl128,
start_idx: usize,
) -> DepthVector32<'a, B> {
let idx_mask = 0xFFFF_FFFF_u32 << start_idx;
let (block1, block2) = bytes.block.halves();
let (opening_mask1, closing_mask1) = classifier.get_opening_and_closing_masks(block1);
let (opening_mask2, closing_mask2) = classifier.get_opening_and_closing_masks(block2);
let combined_opening_mask = m32::combine_16(opening_mask1, opening_mask2);
let combined_closing_mask = m32::combine_16(closing_mask1, closing_mask2);
let opening_mask = combined_opening_mask & (!bytes.within_quotes_mask) & idx_mask;
let closing_mask = combined_closing_mask & (!bytes.within_quotes_mask) & idx_mask;
DepthVector32 {
quote_classified: bytes,
opening_mask,
closing_mask,
opening_count: opening_mask.count_ones(),
depth: 0,
idx: 0,
phantom: PhantomData,
}
}
|
fn main() {
let a = 4.6;
let mut _b: f32 = 3.91e5;
println!("{}", _b);
_b = a;
println!("{} {}", a, _b);
}
|
//! Subcommands for the application.
//!
//! Each subcommand is implemented in it's own submodule.
//! See the nested submodules for more information on
//! specific commands.
use crate::prelude::*;
mod apply;
mod list;
mod read;
/// Returns currently supported subcommands.
pub fn subcommands<'a, 'b>() -> Vec<App<'a, 'b>> {
vec![
apply::subcommand(),
list::subcommand(),
read::subcommand(),
]
}
/// Calls the subexec for the matched subcommand.
pub fn subexec(subcmd: (&str, Option<&ArgMatches>)) -> Failure {
match subcmd {
("apply", Some(m)) => apply::exec(m),
("list", Some(m)) => list::exec(m),
("read", Some(m)) => read::exec(m),
_ => Err("no matching command found".into()),
}
}
|
#![deny(
anonymous_parameters,
bad_style,
missing_copy_implementations,
missing_debug_implementations,
// missing_docs, // TODO: add missing_docs to list of deny
unused_extern_crates,
unused_import_braces,
unused_results,
unused_qualifications,
)]
extern crate reqwest;
extern crate serde_json;
extern crate serde_yaml;
extern crate url;
use std::cell;
use std::fs;
use std::io;
use std::io::prelude::Read;
use std::path;
use std::time::Duration;
enum_with_automatic_from_trait_implementation!(
derive(Clone, Copy, Debug),
UrlError,
ParseError(url::ParseError),
SyntaxViolation(url::SyntaxViolation)
);
enum_with_automatic_from_trait_implementation!(
derive(Debug),
LoaderError,
IOError(io::Error),
InvalidURL(UrlError),
FetchURLFailed(reqwest::Error),
JSONError(serde_json::Error),
YAMLError(serde_yaml::Error)
);
from_error_to_enum_variant!(url::ParseError, LoaderError, InvalidURL, |error| {
UrlError::ParseError(error)
});
from_error_to_enum_variant!(url::SyntaxViolation, LoaderError, InvalidURL, |error| {
UrlError::SyntaxViolation(error)
});
#[derive(Clone, Copy, Debug)]
pub enum Format {
JSON,
YAML,
}
pub trait Loader {
fn load_from_string(&self, content: String) -> Result<serde_json::Value, LoaderError>;
fn load_from_path(&self, path: &str) -> Result<serde_json::Value, LoaderError> {
let mut content = String::new();
let _ = fs::File::open(&path::Path::new(path))?.read_to_string(&mut content)?;
self.load_from_string(content)
}
fn load_from_url(&self, url: &str) -> Result<serde_json::Value, LoaderError> {
self.load_from_url_with_timeout(url, 30_000)
}
fn load_from_url_with_timeout(
&self,
url: &str,
timeout_ms: u64,
) -> Result<serde_json::Value, LoaderError> {
let violation = cell::Cell::new(None);
let url = url::Url::options()
.syntax_violation_callback(Some(&|v| violation.set(Some(v))))
.parse(url)?;
if let Some(violation) = violation.into_inner() {
Err(violation)?
}
if url.scheme() == "file" {
// Using unwrap as we do assume that the url is valid
self.load_from_path(url.to_file_path().unwrap().to_str().unwrap())
} else {
let mut client_builder = reqwest::Client::builder();
let client = client_builder
.gzip(true)
.timeout(Duration::from_millis(timeout_ms))
.build()?;
self.load_from_string(client.get(url.as_ref()).send()?.text()?)
}
}
}
struct JSONLoader;
struct YAMLLoader;
impl Format {
fn get_loader(self) -> Box<Loader> {
match self {
Format::YAML => Box::new(YAMLLoader),
Format::JSON => Box::new(JSONLoader),
}
}
}
impl Loader for JSONLoader {
fn load_from_string(&self, content: String) -> Result<serde_json::Value, LoaderError> {
match serde_json::from_str(&content) {
Ok(value) => Ok(value),
Err(serde_error) => Err(serde_error)?,
}
}
}
impl Loader for YAMLLoader {
fn load_from_string(&self, content: String) -> Result<serde_json::Value, LoaderError> {
match serde_yaml::from_str(&content) {
Ok(value) => Ok(value),
Err(serde_error) => Err(serde_error)?,
}
}
}
pub fn load_from_string(
content: String,
format: Option<Format>,
) -> Result<serde_json::Value, LoaderError> {
match format {
None => Format::YAML, // TODO: make it smarter?
Some(format) => format,
}.get_loader()
.load_from_string(content)
}
pub fn load_from_path(
path: &str,
format: Option<Format>,
) -> Result<serde_json::Value, LoaderError> {
match format {
None => Format::YAML, // TODO: make it smarter?
Some(format) => format,
}.get_loader()
.load_from_path(path)
}
pub fn load_from_url(url: &str, format: Option<Format>) -> Result<serde_json::Value, LoaderError> {
match format {
None => Format::YAML, // TODO: make it smarter?
Some(format) => format,
}.get_loader()
.load_from_url(url)
}
pub fn load_from_url_with_timeout(
url: &str,
timeout_ms: u64,
format: Option<Format>,
) -> Result<serde_json::Value, LoaderError> {
match format {
None => Format::YAML, // TODO: make it smarter?
Some(format) => format,
}.get_loader()
.load_from_url_with_timeout(url, timeout_ms)
}
|
#[doc = "Register `PLL1DIVR` reader"]
pub type R = crate::R<PLL1DIVR_SPEC>;
#[doc = "Register `PLL1DIVR` writer"]
pub type W = crate::W<PLL1DIVR_SPEC>;
#[doc = "Field `DIVN1` reader - multiplication factor for PLL1 VCO Set and reset by software to control the multiplication factor of the VCO. These bits can be written only when the PLL is disabled (PLL1ON = PLL1RDY = 0). ..........: not used ... ... Others: wrong configurations The software must set correctly these bits to insure that the VCO output frequency is between its valid frequency range, that is: 128 to 560Â MHz if PLL1VCOSEL = 0 150 to 420Â MHz if PLL1VCOSEL = 1 VCO output frequency = Fref1_ck x DIVN1, when fractional value 0 has been loaded into FRACN1, with: DIVN1 between 8 and 420 The input frequency Fref1_ck must be between 1 and 16Â MHz."]
pub type DIVN1_R = crate::FieldReader<u16>;
#[doc = "Field `DIVN1` writer - multiplication factor for PLL1 VCO Set and reset by software to control the multiplication factor of the VCO. These bits can be written only when the PLL is disabled (PLL1ON = PLL1RDY = 0). ..........: not used ... ... Others: wrong configurations The software must set correctly these bits to insure that the VCO output frequency is between its valid frequency range, that is: 128 to 560Â MHz if PLL1VCOSEL = 0 150 to 420Â MHz if PLL1VCOSEL = 1 VCO output frequency = Fref1_ck x DIVN1, when fractional value 0 has been loaded into FRACN1, with: DIVN1 between 8 and 420 The input frequency Fref1_ck must be between 1 and 16Â MHz."]
pub type DIVN1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 9, O, u16>;
#[doc = "Field `DIVP1` reader - PLL1 DIVP division factor Set and reset by software to control the frequency of the pll1_p_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). Note that odd division factors are not allowed. ..."]
pub type DIVP1_R = crate::FieldReader<DIVP1_A>;
#[doc = "PLL1 DIVP division factor Set and reset by software to control the frequency of the pll1_p_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). Note that odd division factors are not allowed. ...\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum DIVP1_A {
#[doc = "0: pll_p_ck = vco_ck"]
Div1 = 0,
#[doc = "1: pll_p_ck = vco_ck / 2"]
Div2 = 1,
#[doc = "3: pll_p_ck = vco_ck / 4"]
Div4 = 3,
#[doc = "5: pll_p_ck = vco_ck / 6"]
Div6 = 5,
#[doc = "7: pll_p_ck = vco_ck / 8"]
Div8 = 7,
#[doc = "9: pll_p_ck = vco_ck / 10"]
Div10 = 9,
#[doc = "11: pll_p_ck = vco_ck / 12"]
Div12 = 11,
#[doc = "13: pll_p_ck = vco_ck / 14"]
Div14 = 13,
#[doc = "15: pll_p_ck = vco_ck / 16"]
Div16 = 15,
#[doc = "17: pll_p_ck = vco_ck / 18"]
Div18 = 17,
#[doc = "19: pll_p_ck = vco_ck / 20"]
Div20 = 19,
#[doc = "21: pll_p_ck = vco_ck / 22"]
Div22 = 21,
#[doc = "23: pll_p_ck = vco_ck / 24"]
Div24 = 23,
#[doc = "25: pll_p_ck = vco_ck / 26"]
Div26 = 25,
#[doc = "27: pll_p_ck = vco_ck / 28"]
Div28 = 27,
#[doc = "29: pll_p_ck = vco_ck / 30"]
Div30 = 29,
#[doc = "31: pll_p_ck = vco_ck / 32"]
Div32 = 31,
#[doc = "33: pll_p_ck = vco_ck / 34"]
Div34 = 33,
#[doc = "35: pll_p_ck = vco_ck / 36"]
Div36 = 35,
#[doc = "37: pll_p_ck = vco_ck / 38"]
Div38 = 37,
#[doc = "39: pll_p_ck = vco_ck / 40"]
Div40 = 39,
#[doc = "41: pll_p_ck = vco_ck / 42"]
Div42 = 41,
#[doc = "43: pll_p_ck = vco_ck / 44"]
Div44 = 43,
#[doc = "45: pll_p_ck = vco_ck / 46"]
Div46 = 45,
#[doc = "47: pll_p_ck = vco_ck / 48"]
Div48 = 47,
#[doc = "49: pll_p_ck = vco_ck / 50"]
Div50 = 49,
#[doc = "51: pll_p_ck = vco_ck / 52"]
Div52 = 51,
#[doc = "53: pll_p_ck = vco_ck / 54"]
Div54 = 53,
#[doc = "55: pll_p_ck = vco_ck / 56"]
Div56 = 55,
#[doc = "57: pll_p_ck = vco_ck / 58"]
Div58 = 57,
#[doc = "59: pll_p_ck = vco_ck / 60"]
Div60 = 59,
#[doc = "61: pll_p_ck = vco_ck / 62"]
Div62 = 61,
#[doc = "63: pll_p_ck = vco_ck / 64"]
Div64 = 63,
#[doc = "65: pll_p_ck = vco_ck / 66"]
Div66 = 65,
#[doc = "67: pll_p_ck = vco_ck / 68"]
Div68 = 67,
#[doc = "69: pll_p_ck = vco_ck / 70"]
Div70 = 69,
#[doc = "71: pll_p_ck = vco_ck / 72"]
Div72 = 71,
#[doc = "73: pll_p_ck = vco_ck / 74"]
Div74 = 73,
#[doc = "75: pll_p_ck = vco_ck / 76"]
Div76 = 75,
#[doc = "77: pll_p_ck = vco_ck / 78"]
Div78 = 77,
#[doc = "79: pll_p_ck = vco_ck / 80"]
Div80 = 79,
#[doc = "81: pll_p_ck = vco_ck / 82"]
Div82 = 81,
#[doc = "83: pll_p_ck = vco_ck / 84"]
Div84 = 83,
#[doc = "85: pll_p_ck = vco_ck / 86"]
Div86 = 85,
#[doc = "87: pll_p_ck = vco_ck / 88"]
Div88 = 87,
#[doc = "89: pll_p_ck = vco_ck / 90"]
Div90 = 89,
#[doc = "91: pll_p_ck = vco_ck / 92"]
Div92 = 91,
#[doc = "93: pll_p_ck = vco_ck / 94"]
Div94 = 93,
#[doc = "95: pll_p_ck = vco_ck / 96"]
Div96 = 95,
#[doc = "97: pll_p_ck = vco_ck / 98"]
Div98 = 97,
#[doc = "99: pll_p_ck = vco_ck / 100"]
Div100 = 99,
#[doc = "101: pll_p_ck = vco_ck / 102"]
Div102 = 101,
#[doc = "103: pll_p_ck = vco_ck / 104"]
Div104 = 103,
#[doc = "105: pll_p_ck = vco_ck / 106"]
Div106 = 105,
#[doc = "107: pll_p_ck = vco_ck / 108"]
Div108 = 107,
#[doc = "109: pll_p_ck = vco_ck / 110"]
Div110 = 109,
#[doc = "111: pll_p_ck = vco_ck / 112"]
Div112 = 111,
#[doc = "113: pll_p_ck = vco_ck / 114"]
Div114 = 113,
#[doc = "115: pll_p_ck = vco_ck / 116"]
Div116 = 115,
#[doc = "117: pll_p_ck = vco_ck / 118"]
Div118 = 117,
#[doc = "119: pll_p_ck = vco_ck / 120"]
Div120 = 119,
#[doc = "121: pll_p_ck = vco_ck / 122"]
Div122 = 121,
#[doc = "123: pll_p_ck = vco_ck / 124"]
Div124 = 123,
#[doc = "125: pll_p_ck = vco_ck / 126"]
Div126 = 125,
#[doc = "127: pll_p_ck = vco_ck / 128"]
Div128 = 127,
}
impl From<DIVP1_A> for u8 {
#[inline(always)]
fn from(variant: DIVP1_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for DIVP1_A {
type Ux = u8;
}
impl DIVP1_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<DIVP1_A> {
match self.bits {
0 => Some(DIVP1_A::Div1),
1 => Some(DIVP1_A::Div2),
3 => Some(DIVP1_A::Div4),
5 => Some(DIVP1_A::Div6),
7 => Some(DIVP1_A::Div8),
9 => Some(DIVP1_A::Div10),
11 => Some(DIVP1_A::Div12),
13 => Some(DIVP1_A::Div14),
15 => Some(DIVP1_A::Div16),
17 => Some(DIVP1_A::Div18),
19 => Some(DIVP1_A::Div20),
21 => Some(DIVP1_A::Div22),
23 => Some(DIVP1_A::Div24),
25 => Some(DIVP1_A::Div26),
27 => Some(DIVP1_A::Div28),
29 => Some(DIVP1_A::Div30),
31 => Some(DIVP1_A::Div32),
33 => Some(DIVP1_A::Div34),
35 => Some(DIVP1_A::Div36),
37 => Some(DIVP1_A::Div38),
39 => Some(DIVP1_A::Div40),
41 => Some(DIVP1_A::Div42),
43 => Some(DIVP1_A::Div44),
45 => Some(DIVP1_A::Div46),
47 => Some(DIVP1_A::Div48),
49 => Some(DIVP1_A::Div50),
51 => Some(DIVP1_A::Div52),
53 => Some(DIVP1_A::Div54),
55 => Some(DIVP1_A::Div56),
57 => Some(DIVP1_A::Div58),
59 => Some(DIVP1_A::Div60),
61 => Some(DIVP1_A::Div62),
63 => Some(DIVP1_A::Div64),
65 => Some(DIVP1_A::Div66),
67 => Some(DIVP1_A::Div68),
69 => Some(DIVP1_A::Div70),
71 => Some(DIVP1_A::Div72),
73 => Some(DIVP1_A::Div74),
75 => Some(DIVP1_A::Div76),
77 => Some(DIVP1_A::Div78),
79 => Some(DIVP1_A::Div80),
81 => Some(DIVP1_A::Div82),
83 => Some(DIVP1_A::Div84),
85 => Some(DIVP1_A::Div86),
87 => Some(DIVP1_A::Div88),
89 => Some(DIVP1_A::Div90),
91 => Some(DIVP1_A::Div92),
93 => Some(DIVP1_A::Div94),
95 => Some(DIVP1_A::Div96),
97 => Some(DIVP1_A::Div98),
99 => Some(DIVP1_A::Div100),
101 => Some(DIVP1_A::Div102),
103 => Some(DIVP1_A::Div104),
105 => Some(DIVP1_A::Div106),
107 => Some(DIVP1_A::Div108),
109 => Some(DIVP1_A::Div110),
111 => Some(DIVP1_A::Div112),
113 => Some(DIVP1_A::Div114),
115 => Some(DIVP1_A::Div116),
117 => Some(DIVP1_A::Div118),
119 => Some(DIVP1_A::Div120),
121 => Some(DIVP1_A::Div122),
123 => Some(DIVP1_A::Div124),
125 => Some(DIVP1_A::Div126),
127 => Some(DIVP1_A::Div128),
_ => None,
}
}
#[doc = "pll_p_ck = vco_ck"]
#[inline(always)]
pub fn is_div1(&self) -> bool {
*self == DIVP1_A::Div1
}
#[doc = "pll_p_ck = vco_ck / 2"]
#[inline(always)]
pub fn is_div2(&self) -> bool {
*self == DIVP1_A::Div2
}
#[doc = "pll_p_ck = vco_ck / 4"]
#[inline(always)]
pub fn is_div4(&self) -> bool {
*self == DIVP1_A::Div4
}
#[doc = "pll_p_ck = vco_ck / 6"]
#[inline(always)]
pub fn is_div6(&self) -> bool {
*self == DIVP1_A::Div6
}
#[doc = "pll_p_ck = vco_ck / 8"]
#[inline(always)]
pub fn is_div8(&self) -> bool {
*self == DIVP1_A::Div8
}
#[doc = "pll_p_ck = vco_ck / 10"]
#[inline(always)]
pub fn is_div10(&self) -> bool {
*self == DIVP1_A::Div10
}
#[doc = "pll_p_ck = vco_ck / 12"]
#[inline(always)]
pub fn is_div12(&self) -> bool {
*self == DIVP1_A::Div12
}
#[doc = "pll_p_ck = vco_ck / 14"]
#[inline(always)]
pub fn is_div14(&self) -> bool {
*self == DIVP1_A::Div14
}
#[doc = "pll_p_ck = vco_ck / 16"]
#[inline(always)]
pub fn is_div16(&self) -> bool {
*self == DIVP1_A::Div16
}
#[doc = "pll_p_ck = vco_ck / 18"]
#[inline(always)]
pub fn is_div18(&self) -> bool {
*self == DIVP1_A::Div18
}
#[doc = "pll_p_ck = vco_ck / 20"]
#[inline(always)]
pub fn is_div20(&self) -> bool {
*self == DIVP1_A::Div20
}
#[doc = "pll_p_ck = vco_ck / 22"]
#[inline(always)]
pub fn is_div22(&self) -> bool {
*self == DIVP1_A::Div22
}
#[doc = "pll_p_ck = vco_ck / 24"]
#[inline(always)]
pub fn is_div24(&self) -> bool {
*self == DIVP1_A::Div24
}
#[doc = "pll_p_ck = vco_ck / 26"]
#[inline(always)]
pub fn is_div26(&self) -> bool {
*self == DIVP1_A::Div26
}
#[doc = "pll_p_ck = vco_ck / 28"]
#[inline(always)]
pub fn is_div28(&self) -> bool {
*self == DIVP1_A::Div28
}
#[doc = "pll_p_ck = vco_ck / 30"]
#[inline(always)]
pub fn is_div30(&self) -> bool {
*self == DIVP1_A::Div30
}
#[doc = "pll_p_ck = vco_ck / 32"]
#[inline(always)]
pub fn is_div32(&self) -> bool {
*self == DIVP1_A::Div32
}
#[doc = "pll_p_ck = vco_ck / 34"]
#[inline(always)]
pub fn is_div34(&self) -> bool {
*self == DIVP1_A::Div34
}
#[doc = "pll_p_ck = vco_ck / 36"]
#[inline(always)]
pub fn is_div36(&self) -> bool {
*self == DIVP1_A::Div36
}
#[doc = "pll_p_ck = vco_ck / 38"]
#[inline(always)]
pub fn is_div38(&self) -> bool {
*self == DIVP1_A::Div38
}
#[doc = "pll_p_ck = vco_ck / 40"]
#[inline(always)]
pub fn is_div40(&self) -> bool {
*self == DIVP1_A::Div40
}
#[doc = "pll_p_ck = vco_ck / 42"]
#[inline(always)]
pub fn is_div42(&self) -> bool {
*self == DIVP1_A::Div42
}
#[doc = "pll_p_ck = vco_ck / 44"]
#[inline(always)]
pub fn is_div44(&self) -> bool {
*self == DIVP1_A::Div44
}
#[doc = "pll_p_ck = vco_ck / 46"]
#[inline(always)]
pub fn is_div46(&self) -> bool {
*self == DIVP1_A::Div46
}
#[doc = "pll_p_ck = vco_ck / 48"]
#[inline(always)]
pub fn is_div48(&self) -> bool {
*self == DIVP1_A::Div48
}
#[doc = "pll_p_ck = vco_ck / 50"]
#[inline(always)]
pub fn is_div50(&self) -> bool {
*self == DIVP1_A::Div50
}
#[doc = "pll_p_ck = vco_ck / 52"]
#[inline(always)]
pub fn is_div52(&self) -> bool {
*self == DIVP1_A::Div52
}
#[doc = "pll_p_ck = vco_ck / 54"]
#[inline(always)]
pub fn is_div54(&self) -> bool {
*self == DIVP1_A::Div54
}
#[doc = "pll_p_ck = vco_ck / 56"]
#[inline(always)]
pub fn is_div56(&self) -> bool {
*self == DIVP1_A::Div56
}
#[doc = "pll_p_ck = vco_ck / 58"]
#[inline(always)]
pub fn is_div58(&self) -> bool {
*self == DIVP1_A::Div58
}
#[doc = "pll_p_ck = vco_ck / 60"]
#[inline(always)]
pub fn is_div60(&self) -> bool {
*self == DIVP1_A::Div60
}
#[doc = "pll_p_ck = vco_ck / 62"]
#[inline(always)]
pub fn is_div62(&self) -> bool {
*self == DIVP1_A::Div62
}
#[doc = "pll_p_ck = vco_ck / 64"]
#[inline(always)]
pub fn is_div64(&self) -> bool {
*self == DIVP1_A::Div64
}
#[doc = "pll_p_ck = vco_ck / 66"]
#[inline(always)]
pub fn is_div66(&self) -> bool {
*self == DIVP1_A::Div66
}
#[doc = "pll_p_ck = vco_ck / 68"]
#[inline(always)]
pub fn is_div68(&self) -> bool {
*self == DIVP1_A::Div68
}
#[doc = "pll_p_ck = vco_ck / 70"]
#[inline(always)]
pub fn is_div70(&self) -> bool {
*self == DIVP1_A::Div70
}
#[doc = "pll_p_ck = vco_ck / 72"]
#[inline(always)]
pub fn is_div72(&self) -> bool {
*self == DIVP1_A::Div72
}
#[doc = "pll_p_ck = vco_ck / 74"]
#[inline(always)]
pub fn is_div74(&self) -> bool {
*self == DIVP1_A::Div74
}
#[doc = "pll_p_ck = vco_ck / 76"]
#[inline(always)]
pub fn is_div76(&self) -> bool {
*self == DIVP1_A::Div76
}
#[doc = "pll_p_ck = vco_ck / 78"]
#[inline(always)]
pub fn is_div78(&self) -> bool {
*self == DIVP1_A::Div78
}
#[doc = "pll_p_ck = vco_ck / 80"]
#[inline(always)]
pub fn is_div80(&self) -> bool {
*self == DIVP1_A::Div80
}
#[doc = "pll_p_ck = vco_ck / 82"]
#[inline(always)]
pub fn is_div82(&self) -> bool {
*self == DIVP1_A::Div82
}
#[doc = "pll_p_ck = vco_ck / 84"]
#[inline(always)]
pub fn is_div84(&self) -> bool {
*self == DIVP1_A::Div84
}
#[doc = "pll_p_ck = vco_ck / 86"]
#[inline(always)]
pub fn is_div86(&self) -> bool {
*self == DIVP1_A::Div86
}
#[doc = "pll_p_ck = vco_ck / 88"]
#[inline(always)]
pub fn is_div88(&self) -> bool {
*self == DIVP1_A::Div88
}
#[doc = "pll_p_ck = vco_ck / 90"]
#[inline(always)]
pub fn is_div90(&self) -> bool {
*self == DIVP1_A::Div90
}
#[doc = "pll_p_ck = vco_ck / 92"]
#[inline(always)]
pub fn is_div92(&self) -> bool {
*self == DIVP1_A::Div92
}
#[doc = "pll_p_ck = vco_ck / 94"]
#[inline(always)]
pub fn is_div94(&self) -> bool {
*self == DIVP1_A::Div94
}
#[doc = "pll_p_ck = vco_ck / 96"]
#[inline(always)]
pub fn is_div96(&self) -> bool {
*self == DIVP1_A::Div96
}
#[doc = "pll_p_ck = vco_ck / 98"]
#[inline(always)]
pub fn is_div98(&self) -> bool {
*self == DIVP1_A::Div98
}
#[doc = "pll_p_ck = vco_ck / 100"]
#[inline(always)]
pub fn is_div100(&self) -> bool {
*self == DIVP1_A::Div100
}
#[doc = "pll_p_ck = vco_ck / 102"]
#[inline(always)]
pub fn is_div102(&self) -> bool {
*self == DIVP1_A::Div102
}
#[doc = "pll_p_ck = vco_ck / 104"]
#[inline(always)]
pub fn is_div104(&self) -> bool {
*self == DIVP1_A::Div104
}
#[doc = "pll_p_ck = vco_ck / 106"]
#[inline(always)]
pub fn is_div106(&self) -> bool {
*self == DIVP1_A::Div106
}
#[doc = "pll_p_ck = vco_ck / 108"]
#[inline(always)]
pub fn is_div108(&self) -> bool {
*self == DIVP1_A::Div108
}
#[doc = "pll_p_ck = vco_ck / 110"]
#[inline(always)]
pub fn is_div110(&self) -> bool {
*self == DIVP1_A::Div110
}
#[doc = "pll_p_ck = vco_ck / 112"]
#[inline(always)]
pub fn is_div112(&self) -> bool {
*self == DIVP1_A::Div112
}
#[doc = "pll_p_ck = vco_ck / 114"]
#[inline(always)]
pub fn is_div114(&self) -> bool {
*self == DIVP1_A::Div114
}
#[doc = "pll_p_ck = vco_ck / 116"]
#[inline(always)]
pub fn is_div116(&self) -> bool {
*self == DIVP1_A::Div116
}
#[doc = "pll_p_ck = vco_ck / 118"]
#[inline(always)]
pub fn is_div118(&self) -> bool {
*self == DIVP1_A::Div118
}
#[doc = "pll_p_ck = vco_ck / 120"]
#[inline(always)]
pub fn is_div120(&self) -> bool {
*self == DIVP1_A::Div120
}
#[doc = "pll_p_ck = vco_ck / 122"]
#[inline(always)]
pub fn is_div122(&self) -> bool {
*self == DIVP1_A::Div122
}
#[doc = "pll_p_ck = vco_ck / 124"]
#[inline(always)]
pub fn is_div124(&self) -> bool {
*self == DIVP1_A::Div124
}
#[doc = "pll_p_ck = vco_ck / 126"]
#[inline(always)]
pub fn is_div126(&self) -> bool {
*self == DIVP1_A::Div126
}
#[doc = "pll_p_ck = vco_ck / 128"]
#[inline(always)]
pub fn is_div128(&self) -> bool {
*self == DIVP1_A::Div128
}
}
#[doc = "Field `DIVP1` writer - PLL1 DIVP division factor Set and reset by software to control the frequency of the pll1_p_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). Note that odd division factors are not allowed. ..."]
pub type DIVP1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O, DIVP1_A>;
impl<'a, REG, const O: u8> DIVP1_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "pll_p_ck = vco_ck"]
#[inline(always)]
pub fn div1(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div1)
}
#[doc = "pll_p_ck = vco_ck / 2"]
#[inline(always)]
pub fn div2(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div2)
}
#[doc = "pll_p_ck = vco_ck / 4"]
#[inline(always)]
pub fn div4(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div4)
}
#[doc = "pll_p_ck = vco_ck / 6"]
#[inline(always)]
pub fn div6(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div6)
}
#[doc = "pll_p_ck = vco_ck / 8"]
#[inline(always)]
pub fn div8(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div8)
}
#[doc = "pll_p_ck = vco_ck / 10"]
#[inline(always)]
pub fn div10(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div10)
}
#[doc = "pll_p_ck = vco_ck / 12"]
#[inline(always)]
pub fn div12(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div12)
}
#[doc = "pll_p_ck = vco_ck / 14"]
#[inline(always)]
pub fn div14(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div14)
}
#[doc = "pll_p_ck = vco_ck / 16"]
#[inline(always)]
pub fn div16(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div16)
}
#[doc = "pll_p_ck = vco_ck / 18"]
#[inline(always)]
pub fn div18(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div18)
}
#[doc = "pll_p_ck = vco_ck / 20"]
#[inline(always)]
pub fn div20(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div20)
}
#[doc = "pll_p_ck = vco_ck / 22"]
#[inline(always)]
pub fn div22(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div22)
}
#[doc = "pll_p_ck = vco_ck / 24"]
#[inline(always)]
pub fn div24(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div24)
}
#[doc = "pll_p_ck = vco_ck / 26"]
#[inline(always)]
pub fn div26(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div26)
}
#[doc = "pll_p_ck = vco_ck / 28"]
#[inline(always)]
pub fn div28(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div28)
}
#[doc = "pll_p_ck = vco_ck / 30"]
#[inline(always)]
pub fn div30(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div30)
}
#[doc = "pll_p_ck = vco_ck / 32"]
#[inline(always)]
pub fn div32(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div32)
}
#[doc = "pll_p_ck = vco_ck / 34"]
#[inline(always)]
pub fn div34(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div34)
}
#[doc = "pll_p_ck = vco_ck / 36"]
#[inline(always)]
pub fn div36(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div36)
}
#[doc = "pll_p_ck = vco_ck / 38"]
#[inline(always)]
pub fn div38(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div38)
}
#[doc = "pll_p_ck = vco_ck / 40"]
#[inline(always)]
pub fn div40(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div40)
}
#[doc = "pll_p_ck = vco_ck / 42"]
#[inline(always)]
pub fn div42(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div42)
}
#[doc = "pll_p_ck = vco_ck / 44"]
#[inline(always)]
pub fn div44(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div44)
}
#[doc = "pll_p_ck = vco_ck / 46"]
#[inline(always)]
pub fn div46(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div46)
}
#[doc = "pll_p_ck = vco_ck / 48"]
#[inline(always)]
pub fn div48(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div48)
}
#[doc = "pll_p_ck = vco_ck / 50"]
#[inline(always)]
pub fn div50(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div50)
}
#[doc = "pll_p_ck = vco_ck / 52"]
#[inline(always)]
pub fn div52(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div52)
}
#[doc = "pll_p_ck = vco_ck / 54"]
#[inline(always)]
pub fn div54(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div54)
}
#[doc = "pll_p_ck = vco_ck / 56"]
#[inline(always)]
pub fn div56(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div56)
}
#[doc = "pll_p_ck = vco_ck / 58"]
#[inline(always)]
pub fn div58(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div58)
}
#[doc = "pll_p_ck = vco_ck / 60"]
#[inline(always)]
pub fn div60(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div60)
}
#[doc = "pll_p_ck = vco_ck / 62"]
#[inline(always)]
pub fn div62(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div62)
}
#[doc = "pll_p_ck = vco_ck / 64"]
#[inline(always)]
pub fn div64(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div64)
}
#[doc = "pll_p_ck = vco_ck / 66"]
#[inline(always)]
pub fn div66(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div66)
}
#[doc = "pll_p_ck = vco_ck / 68"]
#[inline(always)]
pub fn div68(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div68)
}
#[doc = "pll_p_ck = vco_ck / 70"]
#[inline(always)]
pub fn div70(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div70)
}
#[doc = "pll_p_ck = vco_ck / 72"]
#[inline(always)]
pub fn div72(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div72)
}
#[doc = "pll_p_ck = vco_ck / 74"]
#[inline(always)]
pub fn div74(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div74)
}
#[doc = "pll_p_ck = vco_ck / 76"]
#[inline(always)]
pub fn div76(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div76)
}
#[doc = "pll_p_ck = vco_ck / 78"]
#[inline(always)]
pub fn div78(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div78)
}
#[doc = "pll_p_ck = vco_ck / 80"]
#[inline(always)]
pub fn div80(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div80)
}
#[doc = "pll_p_ck = vco_ck / 82"]
#[inline(always)]
pub fn div82(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div82)
}
#[doc = "pll_p_ck = vco_ck / 84"]
#[inline(always)]
pub fn div84(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div84)
}
#[doc = "pll_p_ck = vco_ck / 86"]
#[inline(always)]
pub fn div86(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div86)
}
#[doc = "pll_p_ck = vco_ck / 88"]
#[inline(always)]
pub fn div88(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div88)
}
#[doc = "pll_p_ck = vco_ck / 90"]
#[inline(always)]
pub fn div90(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div90)
}
#[doc = "pll_p_ck = vco_ck / 92"]
#[inline(always)]
pub fn div92(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div92)
}
#[doc = "pll_p_ck = vco_ck / 94"]
#[inline(always)]
pub fn div94(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div94)
}
#[doc = "pll_p_ck = vco_ck / 96"]
#[inline(always)]
pub fn div96(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div96)
}
#[doc = "pll_p_ck = vco_ck / 98"]
#[inline(always)]
pub fn div98(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div98)
}
#[doc = "pll_p_ck = vco_ck / 100"]
#[inline(always)]
pub fn div100(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div100)
}
#[doc = "pll_p_ck = vco_ck / 102"]
#[inline(always)]
pub fn div102(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div102)
}
#[doc = "pll_p_ck = vco_ck / 104"]
#[inline(always)]
pub fn div104(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div104)
}
#[doc = "pll_p_ck = vco_ck / 106"]
#[inline(always)]
pub fn div106(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div106)
}
#[doc = "pll_p_ck = vco_ck / 108"]
#[inline(always)]
pub fn div108(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div108)
}
#[doc = "pll_p_ck = vco_ck / 110"]
#[inline(always)]
pub fn div110(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div110)
}
#[doc = "pll_p_ck = vco_ck / 112"]
#[inline(always)]
pub fn div112(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div112)
}
#[doc = "pll_p_ck = vco_ck / 114"]
#[inline(always)]
pub fn div114(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div114)
}
#[doc = "pll_p_ck = vco_ck / 116"]
#[inline(always)]
pub fn div116(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div116)
}
#[doc = "pll_p_ck = vco_ck / 118"]
#[inline(always)]
pub fn div118(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div118)
}
#[doc = "pll_p_ck = vco_ck / 120"]
#[inline(always)]
pub fn div120(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div120)
}
#[doc = "pll_p_ck = vco_ck / 122"]
#[inline(always)]
pub fn div122(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div122)
}
#[doc = "pll_p_ck = vco_ck / 124"]
#[inline(always)]
pub fn div124(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div124)
}
#[doc = "pll_p_ck = vco_ck / 126"]
#[inline(always)]
pub fn div126(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div126)
}
#[doc = "pll_p_ck = vco_ck / 128"]
#[inline(always)]
pub fn div128(self) -> &'a mut crate::W<REG> {
self.variant(DIVP1_A::Div128)
}
}
#[doc = "Field `DIVQ1` reader - PLL1 DIVQ division factor Set and reset by software to control the frequency of the pll1_q_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). ..."]
pub type DIVQ1_R = crate::FieldReader;
#[doc = "Field `DIVQ1` writer - PLL1 DIVQ division factor Set and reset by software to control the frequency of the pll1_q_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). ..."]
pub type DIVQ1_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 7, O>;
#[doc = "Field `DIVR1` reader - PLL1 DIVR division factor Set and reset by software to control the frequency of the pll1_r_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). ..."]
pub type DIVR1_R = crate::FieldReader;
#[doc = "Field `DIVR1` writer - PLL1 DIVR division factor Set and reset by software to control the frequency of the pll1_r_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). ..."]
pub type DIVR1_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 7, O>;
impl R {
#[doc = "Bits 0:8 - multiplication factor for PLL1 VCO Set and reset by software to control the multiplication factor of the VCO. These bits can be written only when the PLL is disabled (PLL1ON = PLL1RDY = 0). ..........: not used ... ... Others: wrong configurations The software must set correctly these bits to insure that the VCO output frequency is between its valid frequency range, that is: 128 to 560Â MHz if PLL1VCOSEL = 0 150 to 420Â MHz if PLL1VCOSEL = 1 VCO output frequency = Fref1_ck x DIVN1, when fractional value 0 has been loaded into FRACN1, with: DIVN1 between 8 and 420 The input frequency Fref1_ck must be between 1 and 16Â MHz."]
#[inline(always)]
pub fn divn1(&self) -> DIVN1_R {
DIVN1_R::new((self.bits & 0x01ff) as u16)
}
#[doc = "Bits 9:15 - PLL1 DIVP division factor Set and reset by software to control the frequency of the pll1_p_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). Note that odd division factors are not allowed. ..."]
#[inline(always)]
pub fn divp1(&self) -> DIVP1_R {
DIVP1_R::new(((self.bits >> 9) & 0x7f) as u8)
}
#[doc = "Bits 16:22 - PLL1 DIVQ division factor Set and reset by software to control the frequency of the pll1_q_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). ..."]
#[inline(always)]
pub fn divq1(&self) -> DIVQ1_R {
DIVQ1_R::new(((self.bits >> 16) & 0x7f) as u8)
}
#[doc = "Bits 24:30 - PLL1 DIVR division factor Set and reset by software to control the frequency of the pll1_r_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). ..."]
#[inline(always)]
pub fn divr1(&self) -> DIVR1_R {
DIVR1_R::new(((self.bits >> 24) & 0x7f) as u8)
}
}
impl W {
#[doc = "Bits 0:8 - multiplication factor for PLL1 VCO Set and reset by software to control the multiplication factor of the VCO. These bits can be written only when the PLL is disabled (PLL1ON = PLL1RDY = 0). ..........: not used ... ... Others: wrong configurations The software must set correctly these bits to insure that the VCO output frequency is between its valid frequency range, that is: 128 to 560Â MHz if PLL1VCOSEL = 0 150 to 420Â MHz if PLL1VCOSEL = 1 VCO output frequency = Fref1_ck x DIVN1, when fractional value 0 has been loaded into FRACN1, with: DIVN1 between 8 and 420 The input frequency Fref1_ck must be between 1 and 16Â MHz."]
#[inline(always)]
#[must_use]
pub fn divn1(&mut self) -> DIVN1_W<PLL1DIVR_SPEC, 0> {
DIVN1_W::new(self)
}
#[doc = "Bits 9:15 - PLL1 DIVP division factor Set and reset by software to control the frequency of the pll1_p_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). Note that odd division factors are not allowed. ..."]
#[inline(always)]
#[must_use]
pub fn divp1(&mut self) -> DIVP1_W<PLL1DIVR_SPEC, 9> {
DIVP1_W::new(self)
}
#[doc = "Bits 16:22 - PLL1 DIVQ division factor Set and reset by software to control the frequency of the pll1_q_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). ..."]
#[inline(always)]
#[must_use]
pub fn divq1(&mut self) -> DIVQ1_W<PLL1DIVR_SPEC, 16> {
DIVQ1_W::new(self)
}
#[doc = "Bits 24:30 - PLL1 DIVR division factor Set and reset by software to control the frequency of the pll1_r_ck clock. These bits can be written only when the PLL1 is disabled (PLL1ON = 0 and PLL1RDY = 0). ..."]
#[inline(always)]
#[must_use]
pub fn divr1(&mut self) -> DIVR1_W<PLL1DIVR_SPEC, 24> {
DIVR1_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 = "\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pll1divr::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 [`pll1divr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PLL1DIVR_SPEC;
impl crate::RegisterSpec for PLL1DIVR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pll1divr::R`](R) reader structure"]
impl crate::Readable for PLL1DIVR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`pll1divr::W`](W) writer structure"]
impl crate::Writable for PLL1DIVR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PLL1DIVR to value 0x0101_0280"]
impl crate::Resettable for PLL1DIVR_SPEC {
const RESET_VALUE: Self::Ux = 0x0101_0280;
}
|
fn main(){
let a = vec![1,1,2];
for var in &a {
println!("{}", var);
}
} |
use std::{collections::HashSet, sync::Arc};
use apllodb_shared_components::{ApllodbError, ApllodbResult, Schema, SchemaIndex, SqlValue};
use apllodb_sql_parser::apllodb_ast;
use apllodb_storage_engine_interface::{ColumnName, Row, TableName};
use crate::{
ast_translator::AstTranslator,
attribute::attribute_name::AttributeName,
correlation::{
aliased_correlation_name::AliasedCorrelationName, correlation_name::CorrelationName,
},
field::{aliased_field_name::AliasedFieldName, field_name::FieldName},
records::{record::Record, record_schema::RecordSchema, Records},
};
#[derive(Clone, Debug, new)]
pub(crate) struct InsertCommandAnalyzer {
command: apllodb_ast::InsertCommand,
}
impl InsertCommandAnalyzer {
pub(super) fn table_name_to_insert(&self) -> ApllodbResult<TableName> {
AstTranslator::table_name(self.command.table_name.clone())
}
fn column_names_to_insert(&self) -> ApllodbResult<Vec<ColumnName>> {
let ast_column_names = self.command.column_names.clone().into_vec();
ast_column_names
.into_iter()
.map(AstTranslator::column_name)
.collect()
}
fn naive_afn_to_insert(&self) -> ApllodbResult<HashSet<AliasedFieldName>> {
self.column_names_to_insert()?
.into_iter()
.map(|cn| {
let attr_name = AttributeName::ColumnNameVariant(cn);
let corr_name = CorrelationName::TableNameVariant(self.table_name_to_insert()?);
let aliased_corr_name = AliasedCorrelationName::new(corr_name, None);
let field_name = FieldName::new(aliased_corr_name, attr_name);
let aliased_field_name = AliasedFieldName::new(field_name, None);
Ok(aliased_field_name)
})
.collect()
}
fn schema_to_insert(&self) -> ApllodbResult<RecordSchema> {
Ok(RecordSchema::from(self.naive_afn_to_insert()?))
}
/// InsertNode takes its input as Records.
/// Here creates Records from VALUES.
pub(super) fn records_to_insert(&self) -> ApllodbResult<Records> {
let schema = Arc::new(self.schema_to_insert()?);
let records: Vec<Record> = self
.command
.values
.clone()
.into_vec()
.into_iter()
.map(|insert_value| {
let ast_expressions = insert_value.expressions.as_vec();
if schema.len() != ast_expressions.len() {
ApllodbError::feature_not_supported(
"VALUES expressions and column names must have same length currently",
);
}
// prepare enough length vec first.
let mut constant_values: Vec<SqlValue> = vec![];
for _ in 0..schema.len() {
constant_values.push(SqlValue::Null);
}
// insert SqlValue from VALUES following column names order.
for (cn, ast_expr) in self
.command
.column_names
.as_vec()
.iter()
.zip(ast_expressions)
{
let expr = AstTranslator::expression_in_non_select(
ast_expr.clone(),
vec![self.table_name_to_insert()?],
)?;
let sql_value = expr.to_sql_value_for_expr_without_index()?;
let (pos, _) = schema.index(&SchemaIndex::from(cn.0 .0.as_str()))?;
constant_values[pos.to_usize()] = sql_value;
}
let row = Row::new(constant_values);
Ok(Record::new(schema.clone(), row))
})
.collect::<ApllodbResult<_>>()?;
Ok(Records::new(schema, records))
}
}
|
// 标准库<stdlib.h>内置的abs函数
extern "C" {
#[link_name = "abs"]
fn abs_in_rust(input: i32) -> i32;
}
fn main() {
unsafe {
println!("abs(-1) is {}", abs_in_rust(-1));
}
}
|
//! Structs intended to be used as table indices.
//!
pub mod entity_id;
use crate::empty_key;
use crate::geometry::Axial;
use serde::{Deserialize, Serialize};
use std::ops::Add;
pub use entity_id::EntityId;
#[derive(
Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Copy, Hash, Serialize, Deserialize,
)]
pub struct EntityTime(pub EntityId, pub u64);
#[derive(
Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Copy, Hash, Serialize, Deserialize,
)]
pub struct IntentId(pub u32);
#[derive(Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Copy, Serialize, Deserialize)]
pub struct ScriptId(pub uuid::Uuid);
#[derive(
Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Copy, Hash, Serialize, Deserialize,
)]
pub struct UserId(pub uuid::Uuid);
#[derive(
Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Copy, Hash, Serialize, Deserialize,
)]
pub struct WorldPosition {
pub room: Axial,
#[serde(rename = "roomPos")]
pub pos: Axial,
}
/// Newtype wrapper around Axial point for positions that are inside a room.
#[derive(
Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Copy, Hash, Serialize, Deserialize,
)]
pub struct RoomPosition(pub Axial);
/// Newtype wrapper around Axial point for room ids.
#[derive(
Debug, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Copy, Hash, Serialize, Deserialize,
)]
pub struct Room(pub Axial);
impl Room {
pub fn as_array(self) -> [i32; 2] {
self.0.as_array()
}
pub fn new(x: i32, y: i32) -> Self {
Self(Axial::new(x, y))
}
pub fn dist(self, Room(other): Self) -> u32 {
self.0.dist(other)
}
}
impl Add for Room {
type Output = Self;
fn add(self, Room(b): Self) -> Self {
Self(self.0.add(b))
}
}
unsafe impl Send for Room {}
unsafe impl Send for UserId {}
unsafe impl Send for EntityId {}
unsafe impl Send for ScriptId {}
// Identify config tables
empty_key!(ConfigKey);
// Storage key for unindexed tables.
empty_key!(EmptyKey);
|
//! Support for the Orbital Screenshooter Protocol
use crate::wayland_sys::server::wl_display as wl_server_display;
use wlroots_sys::{wl_display, wlr_screenshooter, wlr_screenshooter_create, wlr_screenshooter_destroy};
#[derive(Debug)]
pub struct Screenshooter {
screenshooter: *mut wlr_screenshooter
}
impl Screenshooter {
pub(crate) unsafe fn new(display: *mut wl_server_display) -> Option<Self> {
let screenshooter_raw = wlr_screenshooter_create(display as *mut wl_display);
if !screenshooter_raw.is_null() {
Some(Screenshooter {
screenshooter: screenshooter_raw
})
} else {
None
}
}
}
impl Drop for Screenshooter {
fn drop(&mut self) {
unsafe { wlr_screenshooter_destroy(self.screenshooter) }
}
}
|
#[doc = "Reader of register PWR_WKUPFR"]
pub type R = crate::R<u32, super::PWR_WKUPFR>;
#[doc = "Reader of field `WKUPF1`"]
pub type WKUPF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `WKUPF2`"]
pub type WKUPF2_R = crate::R<bool, bool>;
#[doc = "Reader of field `WKUPF3`"]
pub type WKUPF3_R = crate::R<bool, bool>;
#[doc = "Reader of field `WKUPF4`"]
pub type WKUPF4_R = crate::R<bool, bool>;
#[doc = "Reader of field `WKUPF5`"]
pub type WKUPF5_R = crate::R<bool, bool>;
#[doc = "Reader of field `WKUPF6`"]
pub type WKUPF6_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - WKUPF1"]
#[inline(always)]
pub fn wkupf1(&self) -> WKUPF1_R {
WKUPF1_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - WKUPF2"]
#[inline(always)]
pub fn wkupf2(&self) -> WKUPF2_R {
WKUPF2_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - WKUPF3"]
#[inline(always)]
pub fn wkupf3(&self) -> WKUPF3_R {
WKUPF3_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - WKUPF4"]
#[inline(always)]
pub fn wkupf4(&self) -> WKUPF4_R {
WKUPF4_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - WKUPF5"]
#[inline(always)]
pub fn wkupf5(&self) -> WKUPF5_R {
WKUPF5_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - WKUPF6"]
#[inline(always)]
pub fn wkupf6(&self) -> WKUPF6_R {
WKUPF6_R::new(((self.bits >> 5) & 0x01) != 0)
}
}
|
/*
--- Day 7: Amplification Circuit ---
*/
use intcode_vm;
use std::io::{self, BufRead};
#[aoc_generator(day7)]
pub fn input_generator(input: &str) -> Vec<i64> {
// let input = "3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0"; // 43210 (4,3,2,1,0)
// let input = "3,23,3,24,1002,24,10,24,1002,23,-1,23, 101,5,23,23,1,24,23,23,4,23,99,0,0"; // 54321 (0,1,2,3,4)
// let input = "3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0"; // 65210 (1,0,4,3,2)
// let input = "3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5";
let memory: Vec<i64> = input
.split_terminator(",")
.map(|x| x.trim().parse::<i64>().expect("Expected integer"))
.collect();
return memory;
}
pub fn run_program(memory: &Vec<i64>, permutations: Vec<i64>, loopback_mode: bool) -> i64 {
// Create 5 VM instances
let mut machines: Vec<intcode_vm::VM> = Vec::new();
let num_machines: usize = 5;
// Enable logging for the VM
intcode_vm::enable_logging();
// Create each VM
for _i in 0..num_machines {
machines.push(intcode_vm::VM::from_memory(memory));
}
// Create a vector containing all permutations of the input
let perms = permute::permute(permutations);
// println!("Total # permutations: {}", perms.len());
// Track the largest permutation index
// let mut largest_perm_index = 0;
let mut largest_perm_value = 0;
// For each permutation, run each vm in sequence and log the result
for (_, perm) in perms.iter().enumerate() {
// Log the current perm
// println!("Current perm: {:?}", perm);
// Reset the memory in the VM between runs,
let mut vm_output = 0;
let mut first_run = true;
for (i, vm) in machines.iter_mut().enumerate() {
vm.reset(memory);
vm.input.push(*perm.get(i).expect("Invalid index"));
}
// Set the first VM's 2nd input instruction to 0
machines[0].input.push(0);
let mut status = intcode_vm::Status::Halt;
loop {
for i in 0..num_machines {
// println!("vm_index: {}", i);
let vm = &mut machines[i];
if first_run {
if i > 0 {
// println!("VM #{} (first run) - Pushing input {}", i, vm_output);
vm.input.push(vm_output);
}
} else {
// println!("VM #{} - Pushing input {}", i, vm_output);
vm.input.push(vm_output);
}
loop {
status = vm.run_intcode();
match status {
intcode_vm::Status::WaitForInput => {
println!("VM #{} - Waiting for input...", i);
let stdin = io::stdin();
let input = stdin
.lock()
.lines()
.next()
.unwrap()
.unwrap()
.parse::<i64>()
.expect("Expected integer");
vm.input.push(input);
vm.process_input();
}
intcode_vm::Status::NewOutput => {
vm_output = vm.output.remove(0);
// println!("VM #{} - Output: {}", i, vm_output);
break;
}
intcode_vm::Status::Halt => {
// println!("VM #{} - Has finshed", i);
break;
}
}
}
}
if loopback_mode {
first_run = false;
if status == intcode_vm::Status::Halt {
break;
}
} else {
break;
}
}
if vm_output > largest_perm_value {
largest_perm_value = vm_output;
// largest_perm_index = p;
}
}
// println!(
// "Largest permutation: #{} {:?}",
// largest_perm_value, perms[largest_perm_index]
// );
return largest_perm_value;
}
#[aoc(day7, part1)]
pub fn solve_part1(memory: &Vec<i64>) -> i64 {
return run_program(memory, vec![0, 1, 2, 3, 4], false);
}
#[aoc(day7, part2)]
pub fn solve_part2(memory: &Vec<i64>) -> i64 {
return run_program(memory, vec![5, 6, 7, 8, 9], true);
}
|
use std::collections::{HashMap,HashSet};
pub type AttrMap = HashMap<String, String>;
//Node
#[allow(dead_code)]
pub struct Node {
// child nodes
children : Vec<Node>,
//node type
node_type: NodeType,
}
//Node Type
pub enum NodeType {
Text(String),
Element(ElementData),
Comment(String),
CData(String),
}
#[allow(dead_code)]
pub struct ElementData {
tag_name: String,
attributes: AttrMap,
}
//create a text node
pub fn text(data: String) -> Node {
Node {
children: Vec::new(), node_type: NodeType::Text(data)
}
}
#[test]
fn text_node_test() {
let mut d = String::new();
d.push_str("my text node");
let txt_node = text(d);
match txt_node.node_type {
NodeType::Comment(_) => panic!("It is not comment"),
NodeType::Text(data) => println!("data {}", data),
_ => panic!("Must have data"),
}
//assert!(txt_node.node_type == NodeType::Text)
}
//create a comment node
pub fn comment(data: String) -> Node {
Node {
children: Vec::new(), node_type: NodeType::Comment(data)
}
}
#[test]
fn comment_node_test() {
let mut d = String::new();
d.push_str("my comment node");
let comment_node = comment(d);
match comment_node.node_type {
NodeType::Comment(_) => println!("It is a comment"),
NodeType::Text(_) => panic!("Shouldn't be text node"),
_ => panic!("Must have data"),
}
//assert!(txt_node.node_type == NodeType::Text)
}
//create a comment node
pub fn cdata(data: String) -> Node {
Node {
children: Vec::new(), node_type: NodeType::CData(data)
}
}
#[test]
fn cdata_node_test() {
let mut d = String::new();
d.push_str("my cdata node");
let cdata_node = cdata(d);
match cdata_node.node_type {
NodeType::CData(_) => println!("It is a cdata"),
NodeType::Text(_) => panic!("Shouldn't be text node"),
_ => panic!("Must have data"),
}
//assert!(txt_node.node_type == NodeType::Text)
}
//create a element
#[allow(dead_code)]
pub fn elem(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {
Node {
children: children,
node_type: NodeType::Element(ElementData {
tag_name: name,
attributes: attrs,
})
}
}
#[test]
fn elem_node_test() {
let mut attrs = HashMap::new();
attrs.insert(String::from_str("id"), String::from_str("value"));
let mut nodes = Vec::new();
nodes.push(text(String::from_str("text_node")));
nodes.push(comment(String::from_str("comment_node")));
let elem_node = elem(String::from_str("element"), attrs, nodes);
match elem_node.node_type {
NodeType::CData(_) => panic!("It is a cdata"),
NodeType::Text(_) => panic!("Shouldn't be text node"),
NodeType::Element(data) => {
println!("{}", data.to_str());
assert!(data.tag_name == String::from_str("element"));
assert!(*data.id().unwrap() == String::from_str("value"));
},
_ => panic!("Must have data"),
}
//assert!(txt_node.node_type == NodeType::Text)
}
impl ElementData {
#[allow(dead_code)]
#[warn(deprecated)]
pub fn get_attribute(&self, key: &str) -> Option<&String> {
self.attributes.get(key)
}
#[allow(dead_code)]
pub fn id(&self) -> Option<&String> {
self.get_attribute("id")
}
#[allow(dead_code)]
pub fn classes(&self) -> HashSet<&str> {
match self.get_attribute("class") {
Some(classlist) => classlist.as_slice().split(' ').collect(),
None => HashSet::new()
}
}
pub fn to_str(&self) -> String {
let mut s = String::new();
s.push_str("<");
s = s + self.tag_name;
s.push_str(" ");
for (attr, value) in self.attributes.iter() {
s = s + format!("{}=\"{}\"", attr ,value);
}
s.push_str(" >");
return s;
}
} |
use crate::server::network::{
decode::*,
stream::*
};
use std::fmt::Debug;
#[derive(Clone, Eq, PartialEq, Debug)]
/// Represents an incoming or outgoing packet on the network.
/// This is somewhat of an intermitinte format for data.
pub enum Packet {
/// Asks the server for a usid | packet id `0` | ()
PingUSID(),
/// Responds for request of usid with one | packet id `1` | (usid)
PongUSID(usize),
/// Pings the server | packet id `2` | (usid)
PingServer(usize),
/// Server pongs back | packet id `3` | (usid)
PongServer(usize),
/// Pings a client | packet id `4` | (server accociated location)
PingClient(usize),
/// Client pongs back | packet id `5` | (usid, server accociated location)
PongClient(usize, usize),
/// Client sends the robot it is watching | packet id `6` | (usid, robot number)
G2020RobotSelected(usize, usize),
/// Server sends client scouter information | packet id `7` | ([length], Vec<team number, amount> where len = [length])
/// DEPRECIATED, TO BE REMOVED
_G2020ScoutersWaiting(usize, Vec<(usize, usize)>),
/// Server tells scouters to begin scouting | packet id `8` | ()
/// DEPRECIATED, TO BE REMOVED
_G2020InitateScouting(),
/// Client sends server request for the scouters that are waiting | packet id `9` | ()
G2020RequestWaiting(),
/// Client sends server request for current running match id | packet id `a`/10 | ()
G2020RequestRunningGameID(),
/// Server responds with the current running match id | packet id `b`/11 | (id)
G2020RunningGameID(usize),
/// Client sends server request to leave queue | packet id `c`/12 | (usid)
G2020LeaveQueue(usize),
/// Client sends server number of preloaded power cells | packet id `d`/13 | (robot, match, cells)
G2020PreloadedCells(usize, usize, usize),
/// Client sends server an autonoumous shot data | packet id `e`/14 | (robot, match, is_high, did_miss, position)
G2020AutoShot(usize, usize, bool, bool, usize),
/// Client sends server the state of the line cross checkbox | packet id `f`/15 | (robot, match, is_checked)
G2020AutoLine(usize, usize, bool),
/// Client sends server teleop shot data | packet id `g`/16 | (robot, match, is_high, did_miss, position)
G2020TeleShot(usize, usize, bool, bool, usize),
/// Client tells server that position control happened | packet id `h`/17 | (robot, match)
G2020PositionControl(usize, usize),
/// Client tells server that rotation control happened | packet id `i`/18 | (robot, match)
G2020RotationControl(usize, usize),
/// Client tells server that climbing was attempted | packet id `j`/19 | (robot, match, reposition, balenced, success)
G2020AttemptedClimb(usize, usize, bool, bool, bool),
/// Client tells server end game questions | packet id `k`/20 | (robot, match, ctrl_pannel, fouls, can_def, was_defed, was_red, can_def_prof, was_defed_prof)
G2020EndGameQuestions(usize, usize, bool, bool, bool, bool, bool, usize, usize),
/// Client tells server it wants data | packet id `l`/21 | (type, id)
/// type = 0: id = team
/// type = 1: id = match
/// type = 2: all (id irrelevant)
G2020RequestData(usize, usize),
/// Server sends back data | packet id `m`/22 | (len, json)
G2020ReturnData(usize, String),
/// Client reuqests admin access | packet id `n`/23 | (password)
ARequestAccess(usize),
/// Server denies access | packet id `o`/24 | ()
ADenyAccess(),
/// Server allows access | packet id `p`/25 | (token)
AGrantAccess(String),
/// Client sends admin command | packet id `q`/26 | (token, command, data)
/// command = 1: clear data full (no data)
/// command = 2: set password (password)
/// command = 3: clear team (team number)
/// command = 4: clear match (match number)
ACommand(String, usize, usize)
}
impl Packet {
/// Translates raw text into a stream and then into packets
pub fn get_packets_from_raw(raw: &str) -> Vec<Packet> {
return Packet::get_packets_from_stream(stream_from_raw(raw));
}
/// Translates a stream into packets.
pub fn get_packets_from_stream(stream: Stream) -> Vec<Packet> {
return stream.packets.clone();
}
/// Returns the usid inside the packet, if any
pub fn get_usid(self) -> Option<usize> {
match self {
Packet::G2020RobotSelected(a, _) => return Some(a),
Packet::PingServer(a) => return Some(a),
Packet::PongClient(a, _) => return Some(a),
Packet::PongServer(a) => return Some(a),
Packet::PongUSID(a) => return Some(a),
Packet::G2020LeaveQueue(a) => return Some(a),
_ => { return None }
}
}
}
|
pub mod fees;
pub mod network;
|
use std::hash;
use super::prelude::*;
#[derive(Debug, Clone, Eq)]
pub struct StringLit {
pub value: String,
}
impl Display for StringLit {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.value)
}
}
impl hash::Hash for StringLit {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
impl PartialEq for StringLit {
fn eq(&self, other: &Self) -> bool {
self.value.eq(&other.value)
}
}
|
use tree;
fn main() {
let test = tree::new();
}
|
#[doc = "Register `DCR1` reader"]
pub type R = crate::R<DCR1_SPEC>;
#[doc = "Register `DCR1` writer"]
pub type W = crate::W<DCR1_SPEC>;
#[doc = "Field `CKMODE` reader - Mode 0 / mode 3"]
pub type CKMODE_R = crate::BitReader<CKMODE_A>;
#[doc = "Mode 0 / mode 3\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CKMODE_A {
#[doc = "0: CLK must stay low while NCS is high (chip-select released). This is referred to as Mode 0"]
Mode0 = 0,
#[doc = "1: CLK must stay high while NCS is high (chip-select released). This is referred to as Mode 3"]
Mode3 = 1,
}
impl From<CKMODE_A> for bool {
#[inline(always)]
fn from(variant: CKMODE_A) -> Self {
variant as u8 != 0
}
}
impl CKMODE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CKMODE_A {
match self.bits {
false => CKMODE_A::Mode0,
true => CKMODE_A::Mode3,
}
}
#[doc = "CLK must stay low while NCS is high (chip-select released). This is referred to as Mode 0"]
#[inline(always)]
pub fn is_mode0(&self) -> bool {
*self == CKMODE_A::Mode0
}
#[doc = "CLK must stay high while NCS is high (chip-select released). This is referred to as Mode 3"]
#[inline(always)]
pub fn is_mode3(&self) -> bool {
*self == CKMODE_A::Mode3
}
}
#[doc = "Field `CKMODE` writer - Mode 0 / mode 3"]
pub type CKMODE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CKMODE_A>;
impl<'a, REG, const O: u8> CKMODE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "CLK must stay low while NCS is high (chip-select released). This is referred to as Mode 0"]
#[inline(always)]
pub fn mode0(self) -> &'a mut crate::W<REG> {
self.variant(CKMODE_A::Mode0)
}
#[doc = "CLK must stay high while NCS is high (chip-select released). This is referred to as Mode 3"]
#[inline(always)]
pub fn mode3(self) -> &'a mut crate::W<REG> {
self.variant(CKMODE_A::Mode3)
}
}
#[doc = "Field `FRCK` reader - Free running clock"]
pub type FRCK_R = crate::BitReader<FRCK_A>;
#[doc = "Free running clock\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FRCK_A {
#[doc = "0: CLK is not free running"]
Disabled = 0,
#[doc = "1: CLK is free running (always provided)"]
Enabled = 1,
}
impl From<FRCK_A> for bool {
#[inline(always)]
fn from(variant: FRCK_A) -> Self {
variant as u8 != 0
}
}
impl FRCK_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FRCK_A {
match self.bits {
false => FRCK_A::Disabled,
true => FRCK_A::Enabled,
}
}
#[doc = "CLK is not free running"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == FRCK_A::Disabled
}
#[doc = "CLK is free running (always provided)"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == FRCK_A::Enabled
}
}
#[doc = "Field `FRCK` writer - Free running clock"]
pub type FRCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FRCK_A>;
impl<'a, REG, const O: u8> FRCK_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "CLK is not free running"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(FRCK_A::Disabled)
}
#[doc = "CLK is free running (always provided)"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(FRCK_A::Enabled)
}
}
#[doc = "Field `DLYBYP` reader - Delay block bypass"]
pub type DLYBYP_R = crate::BitReader<DLYBYP_A>;
#[doc = "Delay block bypass\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DLYBYP_A {
#[doc = "0: The internal sampling clock (called feedback clock) or the DQS data strobe external signal is delayed by the delay block (for more details on this block, refer to the dedicated section of the reference manual as it is not part of the OCTOSPI peripheral)"]
DelayBlockEnabled = 0,
#[doc = "1: The delay block is bypassed, so the internal sampling clock or the DQS data strobe external signal is not affected by the delay block. The delay is shorter than when the delay block is not bypassed, even with the delay value set to minimum value in delay block"]
DelayBlockBypassed = 1,
}
impl From<DLYBYP_A> for bool {
#[inline(always)]
fn from(variant: DLYBYP_A) -> Self {
variant as u8 != 0
}
}
impl DLYBYP_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DLYBYP_A {
match self.bits {
false => DLYBYP_A::DelayBlockEnabled,
true => DLYBYP_A::DelayBlockBypassed,
}
}
#[doc = "The internal sampling clock (called feedback clock) or the DQS data strobe external signal is delayed by the delay block (for more details on this block, refer to the dedicated section of the reference manual as it is not part of the OCTOSPI peripheral)"]
#[inline(always)]
pub fn is_delay_block_enabled(&self) -> bool {
*self == DLYBYP_A::DelayBlockEnabled
}
#[doc = "The delay block is bypassed, so the internal sampling clock or the DQS data strobe external signal is not affected by the delay block. The delay is shorter than when the delay block is not bypassed, even with the delay value set to minimum value in delay block"]
#[inline(always)]
pub fn is_delay_block_bypassed(&self) -> bool {
*self == DLYBYP_A::DelayBlockBypassed
}
}
#[doc = "Field `DLYBYP` writer - Delay block bypass"]
pub type DLYBYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DLYBYP_A>;
impl<'a, REG, const O: u8> DLYBYP_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "The internal sampling clock (called feedback clock) or the DQS data strobe external signal is delayed by the delay block (for more details on this block, refer to the dedicated section of the reference manual as it is not part of the OCTOSPI peripheral)"]
#[inline(always)]
pub fn delay_block_enabled(self) -> &'a mut crate::W<REG> {
self.variant(DLYBYP_A::DelayBlockEnabled)
}
#[doc = "The delay block is bypassed, so the internal sampling clock or the DQS data strobe external signal is not affected by the delay block. The delay is shorter than when the delay block is not bypassed, even with the delay value set to minimum value in delay block"]
#[inline(always)]
pub fn delay_block_bypassed(self) -> &'a mut crate::W<REG> {
self.variant(DLYBYP_A::DelayBlockBypassed)
}
}
#[doc = "Field `CSHT` reader - Chip-select high time"]
pub type CSHT_R = crate::FieldReader;
#[doc = "Field `CSHT` writer - Chip-select high time"]
pub type CSHT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
#[doc = "Field `DEVSIZE` reader - Device size"]
pub type DEVSIZE_R = crate::FieldReader;
#[doc = "Field `DEVSIZE` writer - Device size"]
pub type DEVSIZE_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 5, O>;
#[doc = "Field `MTYP` reader - Memory type"]
pub type MTYP_R = crate::FieldReader<MTYP_A>;
#[doc = "Memory type\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum MTYP_A {
#[doc = "0: Micron mode, D0/D1 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes"]
MicronMode = 0,
#[doc = "1: Macronix mode, D1/D0 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes"]
MacronixMode = 1,
#[doc = "2: Standard Mode"]
StandardMode = 2,
#[doc = "3: Macronix RAM mode, D1/D0 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes with dedicated address mapping"]
MacronixRamMode = 3,
#[doc = "4: HyperBus memory mode, the protocol follows the HyperBus specification. 8-data-bit DTR mode must be selected"]
HyperBusMemoryMode = 4,
#[doc = "5: HyperBus register mode, addressing register space. The memory-mapped accesses in this mode must be non-cacheable, or Indirect read/write modes must be used"]
HyperBusMode = 5,
}
impl From<MTYP_A> for u8 {
#[inline(always)]
fn from(variant: MTYP_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for MTYP_A {
type Ux = u8;
}
impl MTYP_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<MTYP_A> {
match self.bits {
0 => Some(MTYP_A::MicronMode),
1 => Some(MTYP_A::MacronixMode),
2 => Some(MTYP_A::StandardMode),
3 => Some(MTYP_A::MacronixRamMode),
4 => Some(MTYP_A::HyperBusMemoryMode),
5 => Some(MTYP_A::HyperBusMode),
_ => None,
}
}
#[doc = "Micron mode, D0/D1 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes"]
#[inline(always)]
pub fn is_micron_mode(&self) -> bool {
*self == MTYP_A::MicronMode
}
#[doc = "Macronix mode, D1/D0 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes"]
#[inline(always)]
pub fn is_macronix_mode(&self) -> bool {
*self == MTYP_A::MacronixMode
}
#[doc = "Standard Mode"]
#[inline(always)]
pub fn is_standard_mode(&self) -> bool {
*self == MTYP_A::StandardMode
}
#[doc = "Macronix RAM mode, D1/D0 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes with dedicated address mapping"]
#[inline(always)]
pub fn is_macronix_ram_mode(&self) -> bool {
*self == MTYP_A::MacronixRamMode
}
#[doc = "HyperBus memory mode, the protocol follows the HyperBus specification. 8-data-bit DTR mode must be selected"]
#[inline(always)]
pub fn is_hyper_bus_memory_mode(&self) -> bool {
*self == MTYP_A::HyperBusMemoryMode
}
#[doc = "HyperBus register mode, addressing register space. The memory-mapped accesses in this mode must be non-cacheable, or Indirect read/write modes must be used"]
#[inline(always)]
pub fn is_hyper_bus_mode(&self) -> bool {
*self == MTYP_A::HyperBusMode
}
}
#[doc = "Field `MTYP` writer - Memory type"]
pub type MTYP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O, MTYP_A>;
impl<'a, REG, const O: u8> MTYP_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Micron mode, D0/D1 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes"]
#[inline(always)]
pub fn micron_mode(self) -> &'a mut crate::W<REG> {
self.variant(MTYP_A::MicronMode)
}
#[doc = "Macronix mode, D1/D0 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes"]
#[inline(always)]
pub fn macronix_mode(self) -> &'a mut crate::W<REG> {
self.variant(MTYP_A::MacronixMode)
}
#[doc = "Standard Mode"]
#[inline(always)]
pub fn standard_mode(self) -> &'a mut crate::W<REG> {
self.variant(MTYP_A::StandardMode)
}
#[doc = "Macronix RAM mode, D1/D0 ordering in DTR 8-data-bit mode. Regular-command protocol in Single-, Dual-, Quad- and Octal-SPI modes with dedicated address mapping"]
#[inline(always)]
pub fn macronix_ram_mode(self) -> &'a mut crate::W<REG> {
self.variant(MTYP_A::MacronixRamMode)
}
#[doc = "HyperBus memory mode, the protocol follows the HyperBus specification. 8-data-bit DTR mode must be selected"]
#[inline(always)]
pub fn hyper_bus_memory_mode(self) -> &'a mut crate::W<REG> {
self.variant(MTYP_A::HyperBusMemoryMode)
}
#[doc = "HyperBus register mode, addressing register space. The memory-mapped accesses in this mode must be non-cacheable, or Indirect read/write modes must be used"]
#[inline(always)]
pub fn hyper_bus_mode(self) -> &'a mut crate::W<REG> {
self.variant(MTYP_A::HyperBusMode)
}
}
impl R {
#[doc = "Bit 0 - Mode 0 / mode 3"]
#[inline(always)]
pub fn ckmode(&self) -> CKMODE_R {
CKMODE_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Free running clock"]
#[inline(always)]
pub fn frck(&self) -> FRCK_R {
FRCK_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 3 - Delay block bypass"]
#[inline(always)]
pub fn dlybyp(&self) -> DLYBYP_R {
DLYBYP_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bits 8:10 - Chip-select high time"]
#[inline(always)]
pub fn csht(&self) -> CSHT_R {
CSHT_R::new(((self.bits >> 8) & 7) as u8)
}
#[doc = "Bits 16:20 - Device size"]
#[inline(always)]
pub fn devsize(&self) -> DEVSIZE_R {
DEVSIZE_R::new(((self.bits >> 16) & 0x1f) as u8)
}
#[doc = "Bits 24:26 - Memory type"]
#[inline(always)]
pub fn mtyp(&self) -> MTYP_R {
MTYP_R::new(((self.bits >> 24) & 7) as u8)
}
}
impl W {
#[doc = "Bit 0 - Mode 0 / mode 3"]
#[inline(always)]
#[must_use]
pub fn ckmode(&mut self) -> CKMODE_W<DCR1_SPEC, 0> {
CKMODE_W::new(self)
}
#[doc = "Bit 1 - Free running clock"]
#[inline(always)]
#[must_use]
pub fn frck(&mut self) -> FRCK_W<DCR1_SPEC, 1> {
FRCK_W::new(self)
}
#[doc = "Bit 3 - Delay block bypass"]
#[inline(always)]
#[must_use]
pub fn dlybyp(&mut self) -> DLYBYP_W<DCR1_SPEC, 3> {
DLYBYP_W::new(self)
}
#[doc = "Bits 8:10 - Chip-select high time"]
#[inline(always)]
#[must_use]
pub fn csht(&mut self) -> CSHT_W<DCR1_SPEC, 8> {
CSHT_W::new(self)
}
#[doc = "Bits 16:20 - Device size"]
#[inline(always)]
#[must_use]
pub fn devsize(&mut self) -> DEVSIZE_W<DCR1_SPEC, 16> {
DEVSIZE_W::new(self)
}
#[doc = "Bits 24:26 - Memory type"]
#[inline(always)]
#[must_use]
pub fn mtyp(&mut self) -> MTYP_W<DCR1_SPEC, 24> {
MTYP_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 = "device configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dcr1::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 [`dcr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DCR1_SPEC;
impl crate::RegisterSpec for DCR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dcr1::R`](R) reader structure"]
impl crate::Readable for DCR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dcr1::W`](W) writer structure"]
impl crate::Writable for DCR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DCR1 to value 0"]
impl crate::Resettable for DCR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use quote::quote_spanned;
use super::{
FlowProperties, FlowPropertyVal, OperatorCategory, OperatorConstraints, OperatorWriteOutput,
WriteContextArgs, RANGE_0, RANGE_1,
};
use crate::graph::{OpInstGenerics, OperatorInstance};
/// > 0 input streams, 1 output stream
///
/// > Arguments: An [`AsRef`](https://doc.rust-lang.org/std/convert/trait.AsRef.html)`<`[`Path`](https://doc.rust-lang.org/nightly/std/path/struct.Path.html)`>`
/// for a file to read as json. This will emit the parsed value one time.
///
/// `source_json` may take one generic type argument, the type of the value to be parsed, which must implement [`Deserialize`](https://docs.rs/serde/latest/serde/de/trait.Deserialize.html).
///
/// ```hydroflow
/// source_json("example.json") -> for_each(|json: hydroflow::serde_json::Value| println!("{:#?}", json));
/// ```
pub const SOURCE_JSON: OperatorConstraints = OperatorConstraints {
name: "source_json",
categories: &[OperatorCategory::Source],
hard_range_inn: RANGE_0,
soft_range_inn: RANGE_0,
hard_range_out: RANGE_1,
soft_range_out: RANGE_1,
num_args: 1,
persistence_args: RANGE_0,
type_args: &(0..=1),
is_external_input: true,
ports_inn: None,
ports_out: None,
properties: FlowProperties {
deterministic: FlowPropertyVal::Yes,
monotonic: FlowPropertyVal::Yes,
inconsistency_tainted: false,
},
input_delaytype_fn: |_| None,
write_fn: |wc @ &WriteContextArgs {
root,
op_span,
ident,
op_inst:
OperatorInstance {
generics: OpInstGenerics { type_args, .. },
arguments,
..
},
..
},
_| {
let generic_type = type_args.get(0).map(|ty| quote_spanned!(op_span=> : #ty));
let ident_jsonread = wc.make_ident("jsonread");
let write_prologue = quote_spanned! {op_span=>
// Note that reading the entire file to memory is (probably still) faster than using a
// reader: https://github.com/serde-rs/json/issues/160
let mut #ident_jsonread = {
let string = ::std::fs::read_to_string(#arguments).unwrap();
let value #generic_type = #root::serde_json::from_str(&*string).unwrap();
::std::iter::once(value)
};
};
let write_iterator = quote_spanned! {op_span=>
let #ident = #ident_jsonread.by_ref();
};
Ok(OperatorWriteOutput {
write_prologue,
write_iterator,
..Default::default()
})
},
};
|
extern crate dirs;
extern crate tar;
extern crate flate2;
extern crate cargo_toml_builder;
use std::path::Path;
use std::process::{Command, ExitStatus, Stdio};
use std::{env, fs, io};
use std::fs::File;
use std::io::Write;
use crate::builders::{ProjectBuilder, Application};
use crate::{set_deployment_vars, k8s_deploy, Emojis};
pub struct JavaBuilder;
impl ProjectBuilder for JavaBuilder {
fn is_dependencies_ok(&self) -> bool {
let java_result = Command::new("which")
.arg("java")
.stdout(Stdio::null())
.status().is_ok();
if java_result {
Command::new("which")
.arg("mvn")
.stdout(Stdio::null())
.status()
.is_ok()
} else {
false
}
}
fn pre_compile(&self, app: &Application) {
env::set_current_dir(&app.work_dir);
// Find and replace occurrences of {docker-image} and {tag} in deployment.yml
set_deployment_vars(&app);
// Find and replace occurrences of {application-name}, {application-version} in pom.xml
JavaBuilder::set_pom_vars(&app);
}
fn compile(&self, app: &Application) {
env::set_current_dir(&app.work_dir);
println!("{} Downloading and install dependencies...", Emojis::default().floppy_disk());
println!("{} Compiling project...", Emojis::default().coffee());
let install_status = JavaBuilder::install();
if install_status.is_ok() {
println!("{} Image created successfully!", Emojis::default().frame_picture())
};
}
fn build(self, app: Application) {
println!("{} Building Project...", Emojis::default().worker());
self.compile(&app);
}
fn push(self, app: Application) {
env::set_current_dir(&app.work_dir);
println!("{} Push container image...", Emojis::default().rocket());
let push_status = JavaBuilder::push(&app);
if push_status.is_ok() {
println!("{} Pushed!", Emojis::default().moon());
};
}
fn deploy(self, app: Application) {
k8s_deploy(&app)
}
}
impl JavaBuilder {
fn set_pom_vars(app: &&Application) {
let pom_path = Path::new(&app.work_dir).join("pom.xml");
let pom_template_content = fs::read_to_string(pom_path.clone()).unwrap();
let name = format!("<artifactId>{}</artifactId>", app.name);
let pom_name = pom_template_content.replace("<artifactId>{application-name}</artifactId>", name.as_ref());
let version = format!("<version>{}</version>", app.tag);
let repo_name = format!("<repo.name>{}</repo.name>", app.registry);
let tag_version = format!("<tag.version>{}</tag.version>", app.tag);
let repo = pom_name.replace("<repo.name>{repo}</repo.name>", repo_name.as_ref());
let tag = repo.replace("<tag.version>{tag}</tag.version>", tag_version.as_ref());
let pom_content = tag.replace("<version>{tag}</version>", version.as_ref());
let mut pom_file = File::create(pom_path).unwrap();
pom_file.write_all(pom_content.as_ref());
}
fn install() -> io::Result<ExitStatus> {
//TODO: Rewrite pom.xml with tag specified
let install_status = Command::new("mvn")
.arg("install")
.status();
install_status
}
fn push(app: &Application) -> io::Result<ExitStatus> {
//TODO: Rewrite deployment.yml with tag specified
let push_status = Command::new("mvn")
.arg("jib:build")
.arg(format!("-Djib.to.auth.username={}", &app.registry_user))
.arg(format!("-Djib.to.auth.password={}", &app.registry_pass))
.status();
push_status
}
} |
mod helpers;
use jsonprima;
// Invalid JSON tokens.
test!(test_1, "q", vec![("E106", 0, 1)]);
test!(test_2, " q", vec![("E106", 2, 3)]);
|
const WAVEFORM: [u16; 32] = [
15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
];
#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct Triangle {
pub sample: u16,
pub enabled: bool,
timer: u16,
timer_period: u16,
waveform_counter: usize,
pub length_counter: u8,
length_counter_halt: bool, // (this bit is also the linear counter's control flag)
linear_counter: u8,
counter_reload_value: u8,
linear_counter_reload: bool,
}
impl Triangle {
pub fn new() -> Self {
Triangle {
sample: 0,
enabled: false,
timer: 0,
timer_period: 0,
waveform_counter: 0,
length_counter: 0,
length_counter_halt: false,
linear_counter: 0,
counter_reload_value: 0,
linear_counter_reload: false,
}
}
pub fn clock(&mut self) {
if self.timer == 0 {
self.timer = self.timer_period;
// The sequencer is clocked by the timer as long as both the linear counter and the length counter are nonzero.
if self.linear_counter != 0 && self.length_counter != 0 {
self.waveform_counter = (self.waveform_counter + 1) % 32;
}
} else {
self.timer -= 1;
}
self.sample = WAVEFORM[self.waveform_counter];
}
pub fn clock_linear_counter(&mut self) {
// When the frame counter generates a linear counter clock, the following actions occur in order:
// If the linear counter reload flag is set, the linear counter is reloaded with the counter reload value,
if self.linear_counter_reload {
self.linear_counter = self.counter_reload_value;
} else if self.linear_counter != 0 { // otherwise if the linear counter is non-zero, it is decremented.
self.linear_counter -= 1;
}
// If the control flag is clear, the linear counter reload flag is cleared.
if !self.length_counter_halt {
self.linear_counter_reload = false;
}
}
pub fn clock_length_counter(&mut self) {
if !(self.length_counter == 0 || self.length_counter_halt) {
self.length_counter -= 1;
}
}
// $4008
pub fn write_counter(&mut self, value: u8) {
self.length_counter_halt = value >> 7 != 0;
self.counter_reload_value = (value << 1) >> 1;
}
// $400A
pub fn write_timer_low(&mut self, value: u8) {
self.timer_period &= 0b00000111_00000000;
self.timer_period |= value as u16;
}
// $400B
pub fn write_timer_high(&mut self, value: u8) {
if self.enabled {
self.length_counter = super::LENGTH_COUNTER_TABLE[value as usize >> 3];
}
self.timer_period &= 0b00000000_11111111;
let timer_high = value & 0b0000_0111;
self.timer_period |= (timer_high as u16) << 8;
self.linear_counter_reload = true;
}
}
|
/**
* Day 6 - Custom Customs
*/
use std::fmt;
// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------
struct Group {
/** Keep list of anyone 'yes' questions */
any: [bool; 26],
/** Keep list of everyone 'yes' questions */
all: [bool; 26],
}
// ---------------------------------------------------------------------------
// Implementations
// ---------------------------------------------------------------------------
impl Group {
fn line_to_array(line: &str) -> [bool;26] {
let mut res: [bool; 26] = [false; 26];
let a = 'a' as usize;
for l in line.chars().filter(|c| c.is_ascii_lowercase()) {
let index = l as usize - a;
res[index] = true;
}
res
}
/** Parse "Anyone said yes" */
fn parse(input: &String) -> Group {
let mut res = Group{any: [false; 26], all: [true; 26]};
for line in input.lines() {
for (i, x) in Group::line_to_array(line).iter().enumerate() {
if *x == true {
res.any[i] = true;
} else {
res.all[i] = false;
}
}
}
println!("Group {} -> {} {}", input, res.nb_any(), res.nb_all());
res
}
fn nb_any(&self) -> usize {
self.any.iter().filter(|c| **c==true).count()
}
fn nb_all(&self) -> usize {
self.all.iter().filter(|c| **c==true).count()
}
}
// ---------------------------------------------------------------------------
// Input builder
// ---------------------------------------------------------------------------
fn empty_line(input: &str) -> bool {
input.trim().is_empty()
}
#[aoc_generator(day6)]
fn input_gen(input: &str) -> Vec<Group> {
let mut groups = Vec::new();
let mut entry = String::new();
for line in input.lines() {
// empty line -> end of group
if empty_line(line) {
groups.push(Group::parse(&entry));
entry.clear();
} else {
entry.push_str(line);
entry.push('\n');
}
}
// Don't forget last entry
groups.push(Group::parse(&entry));
groups
}
// ---------------------------------------------------------------------------
// Solvers
// ---------------------------------------------------------------------------
#[aoc(day6, part1)]
fn part1(groups: &[Group]) -> usize {
groups.iter().fold(0, |acc, x| acc + x.nb_any())
}
#[aoc(day6, part2)]
fn part2(groups: &[Group]) -> usize {
groups.iter().fold(0, |acc, x| acc + x.nb_all())
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
static SAMPLE: &'static str = "abc
a
b
c
ab
ac
a
a
a
a
b";
#[test]
fn check_sample() {
let groups = input_gen(SAMPLE);
assert_eq!(groups.len(), 5);
assert_eq!(groups[0].nb_any(), 3);
assert_eq!(groups[1].nb_any(), 3);
assert_eq!(groups[2].nb_any(), 3);
assert_eq!(groups[3].nb_any(), 1);
assert_eq!(groups[4].nb_any(), 1);
assert_eq!(groups[0].nb_all(), 3);
assert_eq!(groups[1].nb_all(), 0);
assert_eq!(groups[2].nb_all(), 1);
assert_eq!(groups[3].nb_all(), 1);
assert_eq!(groups[4].nb_all(), 1);
}
}
|
#![allow(dead_code)]
#[track_caller]
pub(crate) fn init() {
let _ = env_logger::builder().is_test(true).try_init();
}
|
bitflags! {
pub struct EventFlags: u64 {
const FLAG_TIMEOUT = 0b000000000001;
const FLAG_READ = 0b000000000010;
const FLAG_WRITE = 0b000000000100;
const FLAG_PERSIST = 0b000000001000;
const FLAG_ERROR = 0b000000010000;
const FLAG_ACCEPT = 0b000000100000;
const FLAG_ENDED = 0b000001000000;
const FLAG_READ_PERSIST = 0b000010000000;
const FLAG_WRITE_PERSIST = 0b000100000000;
}
}
|
use std::{fs, io};
use anyhow::Result;
use serde_json::json;
use super::{write_response, Message};
use icon::prepend_filer_icon;
fn into_string(entry: std::fs::DirEntry, enable_icon: bool) -> String {
let path = entry.path();
let path_str = if path.is_dir() {
format!(
"{}/",
path.file_name().and_then(std::ffi::OsStr::to_str).unwrap()
)
} else {
path.file_name()
.and_then(std::ffi::OsStr::to_str)
.map(Into::into)
.unwrap()
};
if enable_icon {
prepend_filer_icon(&entry.path(), &path_str)
} else {
path_str
}
}
fn read_dir_entries(dir: &str, enable_icon: bool) -> Result<Vec<String>> {
let mut entries = fs::read_dir(dir)?
.map(|res| res.map(|x| into_string(x, enable_icon)))
.collect::<Result<Vec<_>, io::Error>>()?;
entries.sort();
Ok(entries)
}
pub(super) fn handle_message(msg: Message) {
if let Some(dir) = msg.params.get("cwd").and_then(|x| x.as_str()) {
let enable_icon = msg
.params
.get("enable_icon")
.and_then(|x| x.as_bool())
.unwrap_or(false);
let result = match read_dir_entries(&dir, enable_icon) {
Ok(entries) => {
let result = json!({
"entries": entries,
"dir": dir,
"total": entries.len(),
});
json!({ "result": result, "id": msg.id })
}
Err(err) => {
let error = json!({"message": format!("{}", err), "dir": dir});
json!({ "error": error, "id": msg.id })
}
};
write_response(result);
}
}
#[test]
fn test_dir() {
let entries = read_dir_entries("/.DocumentRevisions-V100/", true).unwrap();
println!("entry: {:?}", entries);
}
|
//! IPFS node implementation
//#![deny(missing_docs)]
#![feature(try_trait)]
#[macro_use] extern crate failure;
#[macro_use] extern crate log;
pub use libp2p::PeerId;
use std::marker::PhantomData;
use std::path::PathBuf;
use futures::channel::mpsc::{channel, Sender, Receiver};
use std::future::Future;
pub mod bitswap;
pub mod block;
mod config;
pub mod error;
pub mod ipld;
pub mod ipns;
pub mod p2p;
pub mod path;
pub mod repo;
pub mod unixfs;
pub use self::block::{Block, Cid};
use self::config::ConfigFile;
pub use self::error::Error;
use self::ipld::IpldDag;
pub use self::ipld::Ipld;
use self::ipns::Ipns;
pub use self::p2p::SwarmTypes;
use self::p2p::{create_swarm, SwarmOptions, TSwarm};
pub use self::path::IpfsPath;
pub use self::repo::RepoTypes;
use self::repo::{create_repo, RepoOptions, Repo, RepoEvent};
use self::unixfs::File;
static IPFS_LOG: &str = "info";
static IPFS_PATH: &str = ".rust-ipfs";
static XDG_APP_NAME: &str = "rust-ipfs";
static CONFIG_FILE: &str = "config.json";
/// All types can be changed at compile time by implementing
/// `IpfsTypes`.
pub trait IpfsTypes: SwarmTypes + RepoTypes {}
impl<T: RepoTypes> SwarmTypes for T {
type TStrategy = bitswap::strategy::AltruisticStrategy<Self>;
}
impl<T: SwarmTypes + RepoTypes> IpfsTypes for T {}
/// Default IPFS types.
#[derive(Clone)]
pub struct Types;
impl RepoTypes for Types {
type TBlockStore = repo::fs::FsBlockStore;
#[cfg(feature = "rocksdb")]
type TDataStore = repo::fs::RocksDataStore;
#[cfg(not(feature = "rocksdb"))]
type TDataStore = repo::mem::MemDataStore;
}
/// Testing IPFS types
#[derive(Clone)]
pub struct TestTypes;
impl RepoTypes for TestTypes {
type TBlockStore = repo::mem::MemBlockStore;
type TDataStore = repo::mem::MemDataStore;
}
/// Ipfs options
#[derive(Clone, Debug)]
pub struct IpfsOptions<Types: IpfsTypes> {
_marker: PhantomData<Types>,
/// The ipfs log level that should be passed to env_logger.
pub ipfs_log: String,
/// The path of the ipfs repo.
pub ipfs_path: PathBuf,
/// The ipfs config.
pub config: ConfigFile,
}
impl Default for IpfsOptions<Types> {
/// Create `IpfsOptions` from environment.
fn default() -> Self {
let ipfs_log = std::env::var("IPFS_LOG").unwrap_or(IPFS_LOG.into());
let ipfs_path = std::env::var("IPFS_PATH").unwrap_or_else(|_| {
let mut ipfs_path = std::env::var("HOME").unwrap_or("".into());
ipfs_path.push_str("/");
ipfs_path.push_str(IPFS_PATH);
ipfs_path
}).into();
let xdg_dirs = xdg::BaseDirectories::with_prefix(XDG_APP_NAME).unwrap();
let path = xdg_dirs.place_config_file(CONFIG_FILE).unwrap();
let config = ConfigFile::new(path);
IpfsOptions {
_marker: PhantomData,
ipfs_log,
ipfs_path,
config
}
}
}
impl Default for IpfsOptions<TestTypes> {
/// Creates `IpfsOptions` for testing without reading or writing to the
/// file system.
fn default() -> Self {
let ipfs_log = std::env::var("IPFS_LOG").unwrap_or(IPFS_LOG.into());
let ipfs_path = std::env::var("IPFS_PATH").unwrap_or(IPFS_PATH.into()).into();
let config = std::env::var("IPFS_TEST_CONFIG").map(|s| ConfigFile::new(s)).unwrap_or_else(|_| ConfigFile::default());
IpfsOptions {
_marker: PhantomData,
ipfs_log,
ipfs_path,
config,
}
}
}
/// Ipfs struct creates a new IPFS node and is the main entry point
/// for interacting with IPFS.
pub struct Ipfs<Types: IpfsTypes> {
repo: Repo<Types>,
dag: IpldDag<Types>,
ipns: Ipns<Types>,
exit_events: Vec<Sender<IpfsEvent>>,
}
enum IpfsEvent {
Exit,
}
/// Configured Ipfs instace or value which can be only initialized.
pub struct UninitializedIpfs<Types: IpfsTypes> {
repo: Repo<Types>,
dag: IpldDag<Types>,
ipns: Ipns<Types>,
moved_on_init: Option<(Receiver<RepoEvent>, TSwarm<Types>)>,
exit_events: Vec<Sender<IpfsEvent>>,
}
impl<Types: IpfsTypes> UninitializedIpfs<Types> {
pub fn new(options: IpfsOptions<Types>) -> Self {
let repo_options = RepoOptions::<Types>::from(&options);
let (repo, repo_events) = create_repo(repo_options);
let swarm_options = SwarmOptions::<Types>::from(&options);
let swarm = create_swarm(swarm_options, repo.clone());
let dag = IpldDag::new(repo.clone());
let ipns = Ipns::new(repo.clone());
UninitializedIpfs {
repo,
dag,
ipns,
moved_on_init: Some((repo_events, swarm)),
exit_events: Vec::default(),
}
}
/// Initialize the ipfs repo.
pub async fn start(mut self) -> Result<(Ipfs<Types>, impl std::future::Future<Output = ()>), Error> {
use futures::compat::Stream01CompatExt;
let (repo_events, swarm) = self.moved_on_init
.take()
.expect("Cant see how this should happen");
self.repo.init().await?;
self.repo.init().await?;
let (sender, receiver) = channel::<IpfsEvent>(1);
self.exit_events.push(sender);
let fut = IpfsFuture {
repo_events,
exit_events: receiver,
swarm: swarm.compat(),
};
let UninitializedIpfs { repo, dag, ipns, exit_events, .. } = self;
Ok((Ipfs {
repo,
dag,
ipns,
exit_events
}, fut))
}
}
impl<Types: IpfsTypes> Ipfs<Types> {
/// Creates a new ipfs node.
pub fn new(options: IpfsOptions<Types>) -> UninitializedIpfs<Types> {
UninitializedIpfs::new(options)
}
/// Puts a block into the ipfs repo.
pub async fn put_block(&mut self, block: Block) -> Result<Cid, Error> {
Ok(self.repo.put_block(block).await?)
}
/// Retrives a block from the ipfs repo.
pub async fn get_block(&mut self, cid: &Cid) -> Result<Block, Error> {
Ok(self.repo.get_block(cid).await?)
}
/// Remove block from the ipfs repo.
pub async fn remove_block(&mut self, cid: &Cid) -> Result<(), Error> {
Ok(self.repo.remove_block(cid).await?)
}
/// Puts an ipld dag node into the ipfs repo.
pub async fn put_dag(&self, ipld: Ipld) -> Result<IpfsPath, Error> {
Ok(self.dag.put(ipld, cid::Codec::DagCBOR).await?)
}
/// Gets an ipld dag node from the ipfs repo.
pub async fn get_dag(&self, path: IpfsPath) -> Result<Ipld, Error> {
Ok(self.dag.get(path).await?)
}
/// Adds a file into the ipfs repo.
pub async fn add(&self, path: PathBuf) -> Result<IpfsPath, Error> {
let dag = self.dag.clone();
let file = File::new(path).await?;
let path = file.put_unixfs_v1(&dag).await?;
Ok(path)
}
/// Gets a file from the ipfs repo.
pub async fn get(&self, path: IpfsPath) -> Result<File, Error> {
Ok(File::get_unixfs_v1(&self.dag, path).await?)
}
/// Resolves a ipns path to an ipld path.
pub async fn resolve_ipns(&self, path: &IpfsPath) -> Result<IpfsPath, Error> {
Ok(self.ipns.resolve(path).await?)
}
/// Publishes an ipld path.
pub async fn publish_ipns(&self, key: &PeerId, path: &IpfsPath) -> Result<IpfsPath, Error> {
Ok(self.ipns.publish(key, path).await?)
}
/// Cancel an ipns path.
pub async fn cancel_ipns(&self, key: &PeerId) -> Result<(), Error> {
self.ipns.cancel(key).await?;
Ok(())
}
/// Exit daemon.
pub fn exit_daemon(mut self) {
for mut s in self.exit_events.drain(..) {
let _ = s.try_send(IpfsEvent::Exit);
}
}
}
pub struct IpfsFuture<Types: SwarmTypes> {
swarm: futures::compat::Compat01As03<TSwarm<Types>>,
repo_events: Receiver<RepoEvent>,
exit_events: Receiver<IpfsEvent>,
}
use std::pin::Pin;
use std::task::{Poll, Context};
impl<Types: SwarmTypes> Future for IpfsFuture<Types> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
use futures::Stream;
loop {
// FIXME: this can probably be rewritten as a async { loop { select! { ... } } } once
// libp2p uses std::future ... I couldn't figure out way to wrap it as compat,
// box it and fuse it to for it to be used with futures::select!
{
let pin = Pin::new(&mut self.exit_events);
if let Poll::Ready(Some(IpfsEvent::Exit)) = pin.poll_next(ctx) {
return Poll::Ready(());
}
}
{
loop {
let pin = Pin::new(&mut self.repo_events);
match pin.poll_next(ctx) {
Poll::Ready(Some(RepoEvent::WantBlock(cid))) =>
self.swarm.get_mut().want_block(cid),
Poll::Ready(Some(RepoEvent::ProvideBlock(cid))) =>
self.swarm.get_mut().provide_block(cid),
Poll::Ready(Some(RepoEvent::UnprovideBlock(cid))) =>
self.swarm.get_mut().stop_providing_block(&cid),
Poll::Ready(None) => panic!("other side closed the repo_events?"),
Poll::Pending => break,
}
}
}
{
let poll = Pin::new(&mut self.swarm).poll_next(ctx);
match poll {
Poll::Ready(Some(_)) => {},
Poll::Ready(None) => { return Poll::Ready(()); },
Poll::Pending => { return Poll::Pending; }
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::future::{FutureExt, TryFutureExt};
/// Testing helper for std::future::Futures until we can upgrade tokio
pub(crate) fn async_test<O, F>(future: F) -> O
where O: 'static + Send,
F: std::future::Future<Output = O> + 'static + Send
{
let (tx, rx) = std::sync::mpsc::channel();
tokio::run(async move {
let tx = tx;
let awaited = future.await;
tx.send(awaited).unwrap();
}.unit_error().boxed().compat());
rx.recv().unwrap()
}
#[test]
fn test_put_and_get_block() {
async_test(async move {
let options = IpfsOptions::<TestTypes>::default();
let block = Block::from("hello block\n");
let ipfs = Ipfs::new(options);
let (mut ipfs, fut) = ipfs.start().await.unwrap();
tokio::spawn(fut.unit_error().boxed().compat());
let cid: Cid = ipfs.put_block(block.clone()).await.unwrap();
let new_block = ipfs.get_block(&cid).await.unwrap();
assert_eq!(block, new_block);
ipfs.exit_daemon();
});
}
#[test]
fn test_put_and_get_dag() {
let options = IpfsOptions::<TestTypes>::default();
async_test(async move {
let (ipfs, fut) = Ipfs::new(options).start().await.unwrap();
tokio::spawn(fut.unit_error().boxed().compat());
let data: Ipld = vec![-1, -2, -3].into();
let cid = ipfs.put_dag(data.clone()).await.unwrap();
let new_data = ipfs.get_dag(cid.into()).await.unwrap();
assert_eq!(data, new_data);
ipfs.exit_daemon();
});
}
}
|
#[doc = "Register `MMC_RX_INTERRUPT` reader"]
pub type R = crate::R<MMC_RX_INTERRUPT_SPEC>;
#[doc = "Register `MMC_RX_INTERRUPT` writer"]
pub type W = crate::W<MMC_RX_INTERRUPT_SPEC>;
#[doc = "Field `RXCRCERPIS` reader - MMC Receive CRC Error Packet Counter Interrupt Status This bit is set when the Rx CRC error packets register (ETH_RX_CRC_ERROR_PACKETS) counter reaches half of the maximum value or the maximum value.\n\nThe field is **cleared** (set to zero) following a read operation."]
pub type RXCRCERPIS_R = crate::BitReader;
#[doc = "Field `RXCRCERPIS` writer - MMC Receive CRC Error Packet Counter Interrupt Status This bit is set when the Rx CRC error packets register (ETH_RX_CRC_ERROR_PACKETS) counter reaches half of the maximum value or the maximum value."]
pub type RXCRCERPIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RXALGNERPIS` reader - MMC Receive Alignment Error Packet Counter Interrupt Status This bit is set when the Rx alignment error packets register (ETH_RX_ALIGNMENT_ERROR_PACKETS) counter reaches half of the maximum value or the maximum value.\n\nThe field is **cleared** (set to zero) following a read operation."]
pub type RXALGNERPIS_R = crate::BitReader;
#[doc = "Field `RXALGNERPIS` writer - MMC Receive Alignment Error Packet Counter Interrupt Status This bit is set when the Rx alignment error packets register (ETH_RX_ALIGNMENT_ERROR_PACKETS) counter reaches half of the maximum value or the maximum value."]
pub type RXALGNERPIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RXUCGPIS` reader - MMC Receive Unicast Good Packet Counter Interrupt Status This bit is set when the Rx unicast packets good register (ETH_RX_UNICAST_PACKETS_GOOD) counter reaches half of the maximum value or the maximum value.\n\nThe field is **cleared** (set to zero) following a read operation."]
pub type RXUCGPIS_R = crate::BitReader;
#[doc = "Field `RXUCGPIS` writer - MMC Receive Unicast Good Packet Counter Interrupt Status This bit is set when the Rx unicast packets good register (ETH_RX_UNICAST_PACKETS_GOOD) counter reaches half of the maximum value or the maximum value."]
pub type RXUCGPIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RXLPIUSCIS` reader - MMC Receive LPI microsecond counter interrupt status This bit is set when the Rx LPI microsecond counter register (ETH_RX_LPI_USEC_CNTR) counter reaches half of the maximum value or the maximum value.\n\nThe field is **cleared** (set to zero) following a read operation."]
pub type RXLPIUSCIS_R = crate::BitReader;
#[doc = "Field `RXLPIUSCIS` writer - MMC Receive LPI microsecond counter interrupt status This bit is set when the Rx LPI microsecond counter register (ETH_RX_LPI_USEC_CNTR) counter reaches half of the maximum value or the maximum value."]
pub type RXLPIUSCIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RXLPITRCIS` reader - MMC Receive LPI transition counter interrupt status This bit is set when the Rx LPI transition counter register (ETH_RX_LPI_TRAN_CNTR) counter reaches half of the maximum value or the maximum value.\n\nThe field is **cleared** (set to zero) following a read operation."]
pub type RXLPITRCIS_R = crate::BitReader;
#[doc = "Field `RXLPITRCIS` writer - MMC Receive LPI transition counter interrupt status This bit is set when the Rx LPI transition counter register (ETH_RX_LPI_TRAN_CNTR) counter reaches half of the maximum value or the maximum value."]
pub type RXLPITRCIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 5 - MMC Receive CRC Error Packet Counter Interrupt Status This bit is set when the Rx CRC error packets register (ETH_RX_CRC_ERROR_PACKETS) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
pub fn rxcrcerpis(&self) -> RXCRCERPIS_R {
RXCRCERPIS_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - MMC Receive Alignment Error Packet Counter Interrupt Status This bit is set when the Rx alignment error packets register (ETH_RX_ALIGNMENT_ERROR_PACKETS) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
pub fn rxalgnerpis(&self) -> RXALGNERPIS_R {
RXALGNERPIS_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 17 - MMC Receive Unicast Good Packet Counter Interrupt Status This bit is set when the Rx unicast packets good register (ETH_RX_UNICAST_PACKETS_GOOD) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
pub fn rxucgpis(&self) -> RXUCGPIS_R {
RXUCGPIS_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 26 - MMC Receive LPI microsecond counter interrupt status This bit is set when the Rx LPI microsecond counter register (ETH_RX_LPI_USEC_CNTR) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
pub fn rxlpiuscis(&self) -> RXLPIUSCIS_R {
RXLPIUSCIS_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - MMC Receive LPI transition counter interrupt status This bit is set when the Rx LPI transition counter register (ETH_RX_LPI_TRAN_CNTR) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
pub fn rxlpitrcis(&self) -> RXLPITRCIS_R {
RXLPITRCIS_R::new(((self.bits >> 27) & 1) != 0)
}
}
impl W {
#[doc = "Bit 5 - MMC Receive CRC Error Packet Counter Interrupt Status This bit is set when the Rx CRC error packets register (ETH_RX_CRC_ERROR_PACKETS) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
#[must_use]
pub fn rxcrcerpis(&mut self) -> RXCRCERPIS_W<MMC_RX_INTERRUPT_SPEC, 5> {
RXCRCERPIS_W::new(self)
}
#[doc = "Bit 6 - MMC Receive Alignment Error Packet Counter Interrupt Status This bit is set when the Rx alignment error packets register (ETH_RX_ALIGNMENT_ERROR_PACKETS) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
#[must_use]
pub fn rxalgnerpis(&mut self) -> RXALGNERPIS_W<MMC_RX_INTERRUPT_SPEC, 6> {
RXALGNERPIS_W::new(self)
}
#[doc = "Bit 17 - MMC Receive Unicast Good Packet Counter Interrupt Status This bit is set when the Rx unicast packets good register (ETH_RX_UNICAST_PACKETS_GOOD) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
#[must_use]
pub fn rxucgpis(&mut self) -> RXUCGPIS_W<MMC_RX_INTERRUPT_SPEC, 17> {
RXUCGPIS_W::new(self)
}
#[doc = "Bit 26 - MMC Receive LPI microsecond counter interrupt status This bit is set when the Rx LPI microsecond counter register (ETH_RX_LPI_USEC_CNTR) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
#[must_use]
pub fn rxlpiuscis(&mut self) -> RXLPIUSCIS_W<MMC_RX_INTERRUPT_SPEC, 26> {
RXLPIUSCIS_W::new(self)
}
#[doc = "Bit 27 - MMC Receive LPI transition counter interrupt status This bit is set when the Rx LPI transition counter register (ETH_RX_LPI_TRAN_CNTR) counter reaches half of the maximum value or the maximum value."]
#[inline(always)]
#[must_use]
pub fn rxlpitrcis(&mut self) -> RXLPITRCIS_W<MMC_RX_INTERRUPT_SPEC, 27> {
RXLPITRCIS_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 = "MMC Rx interrupt register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmc_rx_interrupt::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 [`mmc_rx_interrupt::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct MMC_RX_INTERRUPT_SPEC;
impl crate::RegisterSpec for MMC_RX_INTERRUPT_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`mmc_rx_interrupt::R`](R) reader structure"]
impl crate::Readable for MMC_RX_INTERRUPT_SPEC {}
#[doc = "`write(|w| ..)` method takes [`mmc_rx_interrupt::W`](W) writer structure"]
impl crate::Writable for MMC_RX_INTERRUPT_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets MMC_RX_INTERRUPT to value 0"]
impl crate::Resettable for MMC_RX_INTERRUPT_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
/**
* cargo new ep1
* cd C:\Users\むずでょ\OneDrive\ドキュメント\practice-rust\concurrency\ep1
* cargo build --example channel-2
* cargo run --example channel-2
*
* [メッセージ受け渡しを使ってスレッド間でデータを転送する](https://doc.rust-jp.rs/book/second-edition/ch16-02-message-passing.html)
*/
use std::thread;
use std::sync::mpsc;
fn main() {
let (childEnter, childExit) = mpsc::channel();
let (mainEnter, mainExit) = mpsc::channel();
let childHandle = thread::spawn(move || {
let mut childBall = 1;
childEnter.send(childBall).unwrap();
childBall = mainExit.recv().unwrap();
println!("Child | Expected: 11, Got: {}.", childBall);
childBall += 100;
childEnter.send(childBall).unwrap();
childBall = mainExit.recv().unwrap();
println!("Child | Expected: 1111, Got: {}, Finished.", childBall);
});
let mut mainBall = childExit.recv().unwrap();
println!("Main | Expected: 1, Got: {}.", mainBall);
mainBall += 10;
mainEnter.send(mainBall).unwrap();
mainBall = childExit.recv().unwrap();
println!("Main | Expected: 111, Got: {}.", mainBall);
mainBall += 1000;
mainEnter.send(mainBall).unwrap();
childHandle.join().unwrap();
println!("Main | Finished.");
} |
// chapter 2 "using variables and types"
fn main() {
let outer = 42;
{
// this prints the inner variable
// but it cannot be reached
// outside the block:
let inner = 3.14;
println!("inner variable: {}", inner);
// this prints the outer variable
// defined outside the block:
println!("outer variable: {}", outer);
// this shadows the outer variable
// defined outside the block:
let outer = 99;
println!("not so outer variable: {}", outer);
}
println!("outer variable: {}", outer);
}
// output should be:
/*
inner block variable: 3.14
outer block variable: 42
not so outer block variable: 99
outer variable: 42
*/
// end of output
|
#![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
extern crate serde_derive;
extern crate uuid;
use uuid::Uuid;
use rand::thread_rng;
use rand::seq::SliceRandom;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use serde_json;
use serde_json::json;
mod boards;
use boards::BOARDS;
#[derive(Clone)]
struct Game {
name: String,
state: String,
players: Vec<Player>
}
impl Game {
fn update_digit(&mut self, icol: u8, irow: u8, digit: u8) {
let index: usize = (irow * 9 + icol) as usize;
self.state = self.state[..index].to_string() + &digit.to_string() + &self.state[(index+1)..].to_string();
}
fn increase_score(&mut self, id: &str) -> Result<()> {
let player: &mut Player = &mut self.players.iter_mut().find(|p| p.id == id).expect(format!("Player {} not found", &id).as_str());
player.score = player.score + 1;
Ok(())
}
fn add_player(&mut self, player: Player) {
println!("Adding {}", &player.name);
self.players.push(player);
}
fn player_exists(&self, id: &str) -> bool {
self.players.iter().position(|p| p.id == id) != None
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
struct Player {
name: String,
id: String,
score: u32,
}
type ID = String;
type MessageMap = Arc<Mutex<HashMap<ID, Game>>>;
use ws::listen;
use ws::{Error, Handler, Handshake, CloseCode, Sender, Result, Message};
use env_logger;
const GAME_ID: &str = "abcde";
struct Server {
out: Sender,
player_id: String,
games: MessageMap,
outputs: Arc<Mutex<Vec<Sender>>>,
}
use serde_derive::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct SendDigitMessage {
icol: u8,
irow: u8,
digit: u8
}
impl Handler for Server {
fn on_open(&mut self, _: Handshake) -> Result<()> {
// Add new output to outputs
self.outputs.lock().unwrap().push(self.out.clone());
let mut hashmap = self.games.lock().unwrap();
if !hashmap.contains_key(GAME_ID) {
println!("found key! {}", GAME_ID);
let mut rng = thread_rng();
let game = Game {
name: GAME_ID.to_string(),
state: BOARDS.choose(&mut rng).unwrap().to_string(),
players: Vec::new()
};
hashmap.insert(GAME_ID.to_string(), game.clone());
}
let game = hashmap.get(GAME_ID).unwrap();
println!("new connection: {}. New player ID: {}", self.out.connection_id(), &self.player_id);
self.out.send(Message::text(json!({
"state": &game.state,
"gameName": &game.name
}).to_string()))?;
self.update_players(&game)?;
Ok(())
}
fn on_message(&mut self, msg: Message) -> Result<()> {
println!("Client says {}", msg);
if let Message::Text(txt) = msg.clone() {
let v: serde_json::Value = serde_json::from_str(&txt).unwrap();
if &v["type"] == "send_digit" {
let data: SendDigitMessage = serde_json::from_str(&txt).unwrap();
let mut hashmap = self.games.lock().unwrap();
let game = hashmap.get_mut(GAME_ID).unwrap();
if !game.player_exists(&self.player_id) {
// player_id is not initialized yet
return Ok(());
}
game.update_digit(data.icol, data.irow, data.digit);
game.increase_score(&self.player_id);
self.send_everyone(Message::text(json!({
"state": &game.state,
"gameName": &game.name
}).to_string()));
self.update_players(&game)?
} else if &v["type"] == "connect" {
let mut hashmap = self.games.lock().unwrap();
let game = hashmap.get_mut(GAME_ID).unwrap();
let name: String = String::from(v["name"].as_str().unwrap());
game.add_player(Player {
name: name.clone(),
id: self.player_id.clone(),
score: 0,
});
self.out.send(Message::text(json!({
"type": "welcome",
"playerId": self.player_id.clone(),
"name": name.clone()
}).to_string()))?;
self.update_players(&game)?;
}
}
Ok(())
}
fn on_close(&mut self, code: CloseCode, reason: &str) {
match code {
CloseCode::Normal => println!("The client is done with the connection."),
CloseCode::Away => println!("The client is leaving the site."),
CloseCode::Abnormal => println!(
"Closing handshake failed! Unable to obtain closing status from client."),
_ => println!("The client encountered an error: {}", reason),
}
}
fn on_error(&mut self, err: Error) {
println!("The server encountered an error: {:?}", err);
}
}
impl Server {
fn send_everyone(&self, msg: Message) -> Result<()> {
for out in self.outputs.lock().unwrap().iter() {
out.send(msg.clone())?;
}
Ok(())
}
fn update_players(&self, game: &Game) -> Result<()> {
let response = json!({
"type": "update_players",
"players": &game.players
});
self.send_everyone(Message::text(response.to_string()))?;
Ok(())
}
}
fn main() {
env_logger::init();
let map: MessageMap = Arc::new(Mutex::new(HashMap::<ID, Game>::new()));
let output_counter = Arc::new(Mutex::new(Vec::new()));
listen("127.0.0.1:3012", |out| { Server { outputs: output_counter.clone(), out: out, games: map.clone(), player_id: Uuid::new_v4().to_string() } }).unwrap()
} |
use super::Data;
macro_rules! outer {
() => ("
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
<meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">
<title>Index of {dir}</title>
<style>
body {{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
line-height: 1.5;
font-size: 62.5%;
}}
table {{
width: 80%;
font-size: 1.2rem;
border-collapse: collapse;
margin: 32px auto 0 auto;
}}
table thead td {{
font-weight: 700;
border-bottom: 2px solid #757575;
}}
table tbody td {{
padding: 8px 4px;
}}
table tbody .filetype {{
text-transform: capitalize;
}}
</style>
</head>
<body>
<table>
<thead>
<tr>
<td>Filename</td>
<td>Filetype</td>
</tr>
</thead>
<tbody>
{data}
</tbody>
</table>
</body>
</html>
");
}
macro_rules! inner {
() => ("
<tr>
<td>
<a href=\"{name}\">{name}</a>
</td>
<td class=\"filetype\">
{type}
</td>
</tr>
");
}
pub fn generate(data: Data) -> String {
let mut table_data = String::new();
for file in data.files {
table_data.push_str(&format!(inner!(), name=file.file_name, type=file.file_type));
}
format!(outer!(), dir=data.dir, data=table_data)
}
|
use std::io::{self,stdin, stdout, Read, Write};
#[allow(dead_code)]
pub fn pause() {
let mut stdout = stdout();
stdout.write(b"Press Enter to continue...").unwrap();
stdout.flush().unwrap();
stdin().read(&mut [0]).unwrap();
}
#[allow(dead_code)]
pub fn get_input() -> String {
let mut buffer = String::new();
let stdin = io::stdin();
stdin.read_line(&mut buffer).unwrap();
return buffer;
}
#[allow(dead_code)]
pub fn remove_whitespace(s: &mut String) {
s.retain(|c| !c.is_whitespace());
}
|
extern crate advent_support;
extern crate regex;
extern crate lazy_static;
use lazy_static::lazy_static;
#[derive(Debug, Default)]
struct Passport {
byr: Option<i32>,
iyr: Option<i32>,
eyr: Option<i32>,
hgt: Option<String>,
hcl: Option<String>,
ecl: Option<String>,
pid: Option<String>,
cid: Option<i64>,
}
lazy_static! {
static ref HEIGHT_RE: regex::Regex = regex::Regex::new(r"^(\d+)(cm|in)$").unwrap();
static ref HAIR_RE: regex::Regex = regex::Regex::new(r"^#[0-9a-f]{6}$").unwrap();
static ref EYE_RE: regex::Regex = regex::Regex::new(r"^(amb|blu|brn|gry|grn|hzl|oth)$").unwrap();
static ref PID_RE: regex::Regex = regex::Regex::new(r"^[0-9]{9}$").unwrap();
}
fn add_to_passport(pass: &mut Passport, partial_desc: &String) {
let fields = partial_desc.split(" ");
for field in fields {
let kv: Vec<&str> = field.split(":").collect();
assert!(kv.len() == 2);
let val = kv[1];
match kv[0] {
"byr" => pass.byr = Some(val.parse().unwrap()),
"iyr" => pass.iyr = Some(val.parse().unwrap()),
"eyr" => pass.eyr = Some(val.parse().unwrap()),
"hgt" => pass.hgt = Some(String::from(val)),
"hcl" => pass.hcl = Some(String::from(val)),
"ecl" => pass.ecl = Some(String::from(val)),
"pid" => pass.pid = Some(String::from(val)),
"cid" => pass.cid = Some(val.parse().unwrap()),
_ => {
panic!("unsupported key: {}", kv[0])
}
}
}
}
fn parse_passports(lines: &Vec<String>) -> Vec<Passport> {
let mut result: Vec<Passport> = Vec::new();
let mut curr_pass = Passport{..Default::default()};
let mut was_modified = false;
for line in lines {
if line.len() > 0 {
add_to_passport(&mut curr_pass, line);
was_modified = true;
} else {
if was_modified {
result.push(curr_pass);
}
curr_pass = Passport{..Default::default()};
was_modified = false;
}
}
if was_modified {
result.push(curr_pass);
}
result
}
fn passport_valid(p: &Passport) -> bool {
p.byr.is_some() &&
p.iyr.is_some() &&
p.eyr.is_some() &&
p.hgt.is_some() &&
p.hcl.is_some() &&
p.ecl.is_some() &&
p.pid.is_some() &&
// p.cid.is_some() &&
true
}
// byr (Birth Year) - four digits; at least 1920 and at most 2002.
fn check_byr(p: &Passport) -> bool {
match p.byr {
Some(val) => val >= 1920 && val <= 2002,
None => false
}
}
// iyr (Issue Year) - four digits; at least 2010 and at most 2020.
fn check_iyr(p: &Passport) -> bool {
match p.iyr {
Some(val) => val >= 2010 && val <= 2020,
None => false
}
}
// eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
fn check_eyr(p: &Passport) -> bool {
match p.eyr {
Some(val) => val >= 2020 && val <= 2030,
None => false
}
}
// hgt (Height) - a number followed by either cm or in:
// If cm, the number must be at least 150 and at most 193.
// If in, the number must be at least 59 and at most 76.
fn check_hgt(p: &Passport) -> bool {
match &p.hgt {
Some(hgt) => match HEIGHT_RE.captures(&hgt) {
Some(m) => {
let number = m.get(1).unwrap().as_str().parse::<i32>().unwrap();
match m.get(2).unwrap().as_str() {
"cm" => number >= 150 && number <= 193,
"in" => number >= 59 && number <= 76,
_ => false
}
}
None => false
},
None => false
}
}
// hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
fn check_hcl(p: &Passport) -> bool {
match &p.hcl {
Some(hcl) => match HAIR_RE.captures(&hcl) {
Some(_) => true,
None => false
},
None => false
}
}
// ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
fn check_ecl(p: &Passport) -> bool {
match &p.ecl {
Some(ecl) => match EYE_RE.captures(&ecl) {
Some(_) => true,
None => false
},
None => false
}
}
// pid (Passport ID) - a nine-digit number, including leading zeroes.
fn check_pid(p: &Passport) -> bool {
match &p.pid {
Some(pid) => match PID_RE.captures(&pid) {
Some(_) => true,
None => false
},
None => false
}
}
// cid (Country ID) - ignored, missing or not.
fn check_cid(_: &Passport) -> bool {
true
}
fn passport_valid2(p: &Passport) -> bool {
check_byr(p) &&
check_iyr(p) &&
check_eyr(p) &&
check_hgt(p) &&
check_hcl(p) &&
check_ecl(p) &&
check_pid(p) &&
check_cid(p) &&
true
}
fn main() {
let lines = advent_support::lines_arg1();
// for line in &lines {
// println!("{}", line)
// }
let passports = parse_passports(&lines);
// for p in &passports {
// println!("{:?}", p)
// }
let valid = passports.iter().filter(|p| passport_valid(p)).count();
println!("part1 - valid passports: {}", valid);
let valid2 = passports.iter().filter(|p| passport_valid2(p)).count();
println!("part2 - valid passports: {}", valid2);
}
|
#[doc = "Register `RIR` reader"]
pub type R = crate::R<RIR_SPEC>;
#[doc = "Field `RTR` reader - RTR"]
pub type RTR_R = crate::BitReader;
#[doc = "Field `IDE` reader - IDE"]
pub type IDE_R = crate::BitReader;
#[doc = "Field `EXID` reader - EXID"]
pub type EXID_R = crate::FieldReader<u32>;
#[doc = "Field `STID` reader - STID"]
pub type STID_R = crate::FieldReader<u16>;
impl R {
#[doc = "Bit 1 - RTR"]
#[inline(always)]
pub fn rtr(&self) -> RTR_R {
RTR_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - IDE"]
#[inline(always)]
pub fn ide(&self) -> IDE_R {
IDE_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bits 3:20 - EXID"]
#[inline(always)]
pub fn exid(&self) -> EXID_R {
EXID_R::new((self.bits >> 3) & 0x0003_ffff)
}
#[doc = "Bits 21:31 - STID"]
#[inline(always)]
pub fn stid(&self) -> STID_R {
STID_R::new(((self.bits >> 21) & 0x07ff) as u16)
}
}
#[doc = "receive FIFO mailbox identifier register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rir::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RIR_SPEC;
impl crate::RegisterSpec for RIR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rir::R`](R) reader structure"]
impl crate::Readable for RIR_SPEC {}
#[doc = "`reset()` method sets RIR to value 0"]
impl crate::Resettable for RIR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[macro_use]
extern crate maplit;
use chrono::prelude::*;
use rusoto_core::Region;
use rusoto_dynamodb::{AttributeValue, DynamoDb, DynamoDbClient, QueryInput, ScanInput};
use serde::{Deserialize, Serialize};
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::env;
use uuid::Uuid;
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Schedule {
pub id: Option<Uuid>,
pub enabled: Option<bool>,
pub run_interval_minutes: u32,
pub apikey: String,
pub algorithm: String,
pub input: String,
pub username: Option<String>,
}
#[allow(dead_code)]
impl Schedule {
pub fn to_schedule(item: &HashMap<String, AttributeValue, RandomState>) -> Schedule {
Schedule {
id: item
.get("id")
.and_then(|x| x.s.as_ref())
.map(|x| Uuid::parse_str(&x).expect("error parsing id")),
enabled: item.get("enabled").and_then(|x| x.bool.to_owned()),
run_interval_minutes: item
.get("run_interval_minutes")
.and_then(|x| x.n.as_ref())
.map(|x| {
x.parse::<u32>()
.expect("error parsing run_interval_minutes")
})
.expect("missing required run_interval_minutes"),
apikey: item
.get("apikey")
.and_then(|x| x.s.to_owned())
.expect("missing required apikey"),
algorithm: item
.get("algorithm")
.and_then(|x| x.s.to_owned())
.expect("missing required algorithm"),
input: item
.get("input")
.and_then(|x| x.s.to_owned())
.expect("missing required input"),
username: item.get("username").and_then(|x| x.s.to_owned()),
}
}
pub fn from_schedule(schedule: Schedule) -> HashMap<String, AttributeValue> {
hashmap! {
String::from("username") => AttributeValue { s: schedule.username, ..Default::default() },
String::from("id") => AttributeValue { s: schedule.id.map(|uid| uid.to_string()), ..Default::default() },
String::from("enabled") => AttributeValue { bool: schedule.enabled, ..Default::default() },
String::from("run_interval_minutes") => AttributeValue { n: Some(schedule.run_interval_minutes.to_string()), ..Default::default() },
String::from("apikey") => AttributeValue { s: Some(schedule.apikey), ..Default::default() },
String::from("algorithm") => AttributeValue { s: Some(schedule.algorithm), ..Default::default() },
String::from("input") => AttributeValue { s: Some(schedule.input), ..Default::default() },
}
}
pub fn get_schedules_to_run() -> Vec<Schedule> {
let attribute_map = hashmap! {
String::from(":enabled") => AttributeValue { bool: Some(true), ..Default::default() }
};
let scan_input = ScanInput {
consistent_read: Some(true),
filter_expression: Some(String::from("enabled = :enabled")),
expression_attribute_values: Some(attribute_map),
table_name: env::var("USER_SCHEDULE_TABLE_NAME")
.expect("env variable USER_SCHEDULE_TABLE_NAME not found"),
..Default::default()
};
let client = DynamoDbClient::new(Region::UsEast1);
let minutes = Local::now().minute();
match client.scan(scan_input).sync() {
Ok(output) => match output.items {
None => vec![],
Some(items) => items
.iter()
.map(Schedule::to_schedule)
.filter(|x| minutes % x.run_interval_minutes == 0)
.collect(),
},
Err(error) => {
println!("{}", error.to_string());
vec![]
}
}
}
pub fn get_schedules_by_username(username: String) -> Vec<Schedule> {
let attribute_map = hashmap! {
String::from(":username") => AttributeValue { s: Some(username), ..Default::default() }
};
let query_input = QueryInput {
consistent_read: Some(true),
key_condition_expression: Some(String::from("username = :username")),
expression_attribute_values: Some(attribute_map),
table_name: env::var("USER_SCHEDULE_TABLE_NAME")
.expect("env variable USER_SCHEDULE_TABLE_NAME not found"),
..Default::default()
};
let client = DynamoDbClient::new(Region::UsEast1);
match client.query(query_input).sync() {
Ok(output) => match output.items {
None => vec![],
Some(items) => items.iter().map(Schedule::to_schedule).collect(),
},
Err(error) => {
println!("{}", error.to_string());
vec![]
}
}
}
}
|
use std::io;
use std::io::BufRead;
pub fn fuel_for_module(mass: u64) -> u64 {
(mass / 3).saturating_sub(2)
}
pub fn fuel_for_module_recursive(mass: u64) -> u64 {
let mut total = 0;
let mut cur = mass;
while cur > 0 {
cur = fuel_for_module(cur);
total += cur;
}
total
}
pub fn parse_file(f: Box<dyn io::BufRead>) -> Vec<u64> {
f.lines()
.map(|l| u64::from_str_radix(&l.unwrap(), 10).unwrap())
.collect()
}
pub fn total_fuel(v: &[u64], op: &dyn Fn(u64) -> u64) -> u64 {
v.iter().map(|mass| op(*mass)).sum()
}
#[cfg(test)]
mod tests {
use super::{fuel_for_module, fuel_for_module_recursive, parse_file, total_fuel};
use std::io::Cursor;
#[test]
fn known_values() {
assert_eq!(fuel_for_module(12), 2);
assert_eq!(fuel_for_module(14), 2);
assert_eq!(fuel_for_module(1969), 654);
assert_eq!(fuel_for_module(100756), 33583);
}
#[test]
fn known_values_recursive() {
assert_eq!(fuel_for_module_recursive(12), 2);
assert_eq!(fuel_for_module_recursive(14), 2);
assert_eq!(fuel_for_module_recursive(1969), 966);
assert_eq!(fuel_for_module_recursive(100756), 50346);
}
#[test]
fn total_value() {
let input = b"12\n14\n1969\n100756\n";
assert_eq!(
total_fuel(&parse_file(Box::new(Cursor::new(input))), &fuel_for_module),
2 + 2 + 654 + 33583
);
}
}
|
#[derive(Debug, Clone, Copy)]
pub enum ErrorKind {
InvalidArgument,
PluginFailure,
Bug,
VerificationError,
NotImplementedError,
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::fmt::Display for NmstateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.kind, self.msg)
}
}
#[derive(Debug)]
pub struct NmstateError {
kind: ErrorKind,
msg: String,
}
impl NmstateError {
pub fn new(kind: ErrorKind, msg: String) -> Self {
Self { kind, msg }
}
pub fn kind(&self) -> ErrorKind {
self.kind
}
pub fn msg(&self) -> &str {
self.msg.as_str()
}
}
impl From<serde_json::Error> for NmstateError {
fn from(e: serde_json::Error) -> Self {
NmstateError::new(ErrorKind::Bug, format!("serde_json::Error: {}", e))
}
}
|
use super::Context;
use std::sync::Arc;
mod health;
use uuid::Uuid;
use warp::Filter;
pub struct Api;
pub struct Token(pub String);
#[derive(Debug)]
pub enum TokenParseError {
Type,
}
impl std::str::FromStr for Token {
type Err = TokenParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.starts_with("Bearer ") {
let s = &s[7..];
Ok(Token(s.to_string()))
} else {
Err(TokenParseError::Type)
}
}
}
impl Api {
pub async fn serve(ctx: Context, addr: impl Into<std::net::SocketAddr> + 'static) {
let ctx = Arc::new(ctx);
let ctx = warp::any().map(move || ctx.clone());
let validate_token = ctx
.clone()
.and(warp::header::<Token>("Authorization"))
.map(|ctx: Arc<Context>, token: Token| ctx.tokens.validate_token(&token.0).unwrap());
let prefix = warp::path!("api" / ..);
let health = warp::path!("health").map(|| {
let status = health::HealthCheckResponse::ok();
warp::reply::json(&status)
});
let sessions_id = warp::path!("app" / String / "sessions" / Uuid)
.and(ctx.clone())
.and(validate_token.clone())
.and_then(
|app_id: String, session_id, ctx: Arc<Context>, tok| async move {
ctx.get_session(&app_id, session_id, tok)
.await
.map(|s| warp::reply::json(&s))
.map_err(|e| warp::reject::custom(e))
},
);
let session_field = warp::path!("app" / String / "sessions" / Uuid / String)
.and(ctx.clone())
.and(validate_token.clone())
.and_then(
|app_id: String, session_id, field: String, ctx: Arc<Context>, tok| async move {
ctx.get_session_field(&app_id, session_id, field.as_ref(), tok)
.await
.map(|s| warp::reply::json(&s))
.map_err(|e| warp::reject::custom(e))
},
);
let replace_session = warp::put()
.and(warp::path!("app" / String / "sessions" / Uuid))
.and(ctx.clone())
.and(validate_token.clone())
.and(warp::body::json::<serde_json::Value>())
.and_then(
|app_id: String, session_id, ctx: Arc<Context>, tok, body| async move {
ctx.replace_session(&app_id, session_id, body, tok)
.await
.map(|s| warp::reply::json(&s))
.map_err(|e| warp::reject::custom(e))
},
);
let add_session = warp::post()
.and(warp::path!("app" / String / "sessions"))
.and(ctx.clone())
.and(validate_token.clone())
.and(warp::body::json::<serde_json::Value>())
.and_then(|app_id: String, ctx: Arc<Context>, tok, body| async move {
ctx.new_session(&app_id, body, tok)
.await
.map(|s| warp::reply::json(&s))
.map_err(|e| warp::reject::custom(e))
});
let api = prefix
.and(warp::path!("v1" / ..))
.and(
health
.or(session_field)
.or(sessions_id)
.or(replace_session)
.or(add_session),
)
.recover(super::error::handle_error);
warp::serve(api).run(addr).await;
}
}
|
//! Types used by [`crate::Transport`].
use super::history;
use crate::data::channel;
use crate::data::object::Object;
use crate::data::pam;
use crate::data::presence;
use crate::data::pubsub;
use crate::data::timetoken::Timetoken;
use crate::data::uuid::UUID;
use std::{collections::HashMap, marker::PhantomData};
/// A request to publish a message to a channel.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Publish {
/// A channel name to publish the message to.
pub channel: channel::Name,
/// The body of the message.
pub payload: Object,
/// Additional information associated with the message.
pub meta: Option<Object>,
}
/// Subscribe to messages on channels and/or channel groups.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Subscribe {
/// The destinations to subscribe to.
pub to: Vec<pubsub::SubscribeTo>,
/// A timetoken to use.
/// tt: 0 (zero) for the initial subscribe, or a valid timetoken if
/// resuming / continuing / fast-forwarding from a previous subscribe flow.
/// tr: Region as returned from the initial call with tt=0.
pub timetoken: Timetoken,
/// The heartbeat value to send to the PubNub network.
pub heartbeat: Option<presence::HeartbeatValue>,
}
/// Set state for a user for channels and/or channel groups.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetState {
/// The channel names to set state for.
pub channels: Vec<channel::Name>,
/// The channel group names to set state for.
pub channel_groups: Vec<channel::Name>,
/// The User UUID to set state for.
pub uuid: UUID,
/// State to set.
pub state: Object,
}
/// Get state for a user for channels and/or channel groups.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GetState {
/// The channel names to get the state for.
pub channels: Vec<channel::Name>,
/// The channel group names to get state for.
pub channel_groups: Vec<channel::Name>,
/// The User UUID to get state for.
pub uuid: UUID,
}
/// Retrieve UUID and State Information for subscribed devices on a specific
/// channel.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HereNow<TRespondWith>
where
TRespondWith: presence::respond_with::RespondWith,
{
/// The channel names to get the state for.
pub channels: Vec<channel::Name>,
/// The channel group names to get state for.
pub channel_groups: Vec<channel::Name>,
/// Type that specializes the response type.
pub respond_with: PhantomData<TRespondWith>,
}
/// Retrieve UUID and State Information for subscribed devices on a all
/// channels.
#[allow(missing_copy_implementations)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GlobalHereNow<TRespondWith>
where
TRespondWith: presence::respond_with::RespondWith,
{
/// Type that specializes the response type.
pub respond_with: PhantomData<TRespondWith>,
}
/// Get list of channels user is present in.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WhereNow {
/// The User UUID to get list of channels for.
pub uuid: UUID,
}
/// Announce a heartbeat.
#[allow(missing_copy_implementations)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Heartbeat {
/// The presence timeout period. If `None`, the default value is used.
pub heartbeat: Option<presence::HeartbeatValue>,
/// The subscription destinations to announce heartbeat for.
pub to: Vec<pubsub::SubscribeTo>,
/// The User UUID to announce subscribtion for.
pub uuid: UUID,
/// State to set for channels and channel groups.
pub state: Object,
}
/// PAMv3 Grant.
pub type Grant = pam::GrantBody;
/// Fetch history.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GetHistory {
/// The channel names to get the history for.
pub channels: Vec<channel::Name>,
/// The batch history is limited to 500 channels and only the last 25
/// messages per channel.
pub max: Option<usize>,
/// Direction of time traversal. Default is false, which means timeline is
/// traversed newest to oldest.
pub reverse: Option<bool>,
/// If provided, lets you select a "start date", in Timetoken format.
/// If not provided, it will default to current time.
/// Page through results by providing a start OR end time token.
/// Retrieve a slice of the time line by providing both a start AND end time
/// token.
/// Start is "exclusive" - that is, the first item returned will be
/// the one immediately after the start Timetoken value.
pub start: Option<history::Timetoken>,
/// If provided, lets you select an "end date", in Timetoken format.
/// If not provided, it will provide up to the number of messages defined
/// in the "max" parameter. Page through results by providing a start OR end
/// time token. Retrieve a slice of the time line by providing both a start
/// AND end time token.
/// End is "exclusive" - that is, if a message is associated exactly with
/// the end Timetoken, it will be included in the result.
pub end: Option<history::Timetoken>,
/// Whether to request metadata to be populated in the returned items or
/// not.
pub include_metadata: Option<bool>,
}
/// Delete from history.
///
/// Delete API is asynchronously processed. Getting a successful response
/// implies the Delete request has been received and will be processed soon.
///
/// After the delete has been processed, a webhook is called if the subkey
/// specifies one. If multiple (say N) channels are given in the request
/// a single 200 is returned but N webhook calls will be made.
///
/// There is a setting to accept delete from history requests for a key, which
/// you must enable by checking the `Enable Delete-From-History` checkbox in the
/// key settings for your key in the Administration Portal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeleteHistory {
/// The channel names to detete history at.
pub channels: Vec<channel::Name>,
/// Start time is not inclusive, as in message with timestamp start will not
/// be deleted.
pub start: Option<history::Timetoken>,
/// End time is inclusive, as in message with timestamp end will be deleted.
pub end: Option<history::Timetoken>,
}
/// Get message counts over a time period.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MessageCountsWithTimetoken {
/// The channel names to get message counts at.
pub channels: Vec<channel::Name>,
/// A single timetoken to cover all channels.
/// Must be greater than zero.
pub timetoken: history::Timetoken,
}
/// Get message counts over a time period per channel.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MessageCountsWithChannelTimetokens {
/// A list of channels with timetokens to get message counts at.
/// Timetoken value must be non-zero.
pub channels: HashMap<channel::Name, history::Timetoken>,
}
|
#![deny(missing_docs)]
use nix::sys::select::*;
use nix::sys::time::{TimeVal, TimeValLike};
use nix::unistd::getpid;
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixDatagram;
use std;
use super::Result;
const BUF_SIZE: usize = 10_240;
const PATH_DEFAULT_CLIENT: &str = "/tmp";
const PATH_DEFAULT_SERVER: &str = "/var/run/wpa_supplicant/wlan0";
/// Error type used for some library functions
#[derive(Debug, Fail, PartialEq)]
enum WpaError {
#[fail(display = "Failed to execute the specified command")]
Failure,
}
/// Builder object used to construct a `WpaCtrl` session
#[derive(Default)]
pub struct WpaCtrlBuilder {
cli_path: Option<PathBuf>,
ctrl_path: Option<PathBuf>,
}
impl WpaCtrlBuilder {
/// A path-like object for this application's UNIX domain socket
///
/// # Examples
///
/// ```
/// use wpactrl::WpaCtrl;
/// let wpa = WpaCtrl::new()
/// .cli_path("/tmp")
/// .open()
/// .unwrap();
/// ```
pub fn cli_path<I, P>(mut self, cli_path: I) -> Self
where I: Into<Option<P>>, P: AsRef<Path> + Sized, PathBuf: From<P> {
self.cli_path = cli_path.into().map(PathBuf::from);
self
}
/// A path-like object for the wpasupplicant / hostap UNIX domain sockets
///
/// # Examples
///
/// ```
/// use wpactrl::WpaCtrl;
/// let wpa = WpaCtrl::new()
/// .ctrl_path("/var/run/wpa_supplicant/wlan0")
/// .open()
/// .unwrap();
/// ```
pub fn ctrl_path<I, P>(mut self, ctrl_path: I) -> Self
where I: Into<Option<P>>, P: AsRef<Path> + Sized, PathBuf: From<P> {
self.ctrl_path = ctrl_path.into().map(PathBuf::from);
self
}
/// Open a control interface to wpasupplicant.
///
/// # Examples
///
/// ```
/// use wpactrl::WpaCtrl;
/// let wpa = WpaCtrl::new().open().unwrap();
/// ```
pub fn open(self) -> Result<WpaCtrl> {
let mut counter = 0;
loop {
counter += 1;
let bind_filename = format!("wpa_ctrl_{}-{}", getpid(), counter);
let bind_filepath = self.cli_path.as_ref().map(|p|p.as_path()).unwrap_or_else(||Path::new(PATH_DEFAULT_CLIENT)).join(bind_filename);
match UnixDatagram::bind(&bind_filepath) {
Ok(socket) => {
socket.connect(self.ctrl_path.unwrap_or_else(||PATH_DEFAULT_SERVER.into()))?;
socket.set_nonblocking(true)?;
return Ok(WpaCtrl(WpaCtrlInternal {
buffer: [0; BUF_SIZE],
handle: socket,
filepath: bind_filepath,
}))
},
Err(ref e) if counter < 2 && e.kind() == std::io::ErrorKind::AddrInUse => {
std::fs::remove_file(bind_filepath)?;
continue;
},
Err(e) => Err(e)?,
};
}
}
}
struct WpaCtrlInternal {
buffer: [u8; BUF_SIZE],
handle: UnixDatagram,
filepath: PathBuf,
}
impl WpaCtrlInternal {
/// Check if any messages are available
pub fn pending(&mut self) -> Result<bool> {
let mut fd_set = FdSet::new();
let raw_fd = self.handle.as_raw_fd();
fd_set.insert(raw_fd);
select(raw_fd+1, Some(&mut fd_set), None, None, Some(&mut TimeVal::seconds(0)))?;
Ok(fd_set.contains(raw_fd))
}
/// Receive a message
pub fn recv(&mut self) -> Result<Option<String>> {
if self.pending()? {
let buf_len = self.handle.recv(&mut self.buffer)?;
std::str::from_utf8(&self.buffer[0..buf_len]).map(|s|Some(s.to_owned())).map_err(|e|e.into())
} else {
Ok(None)
}
}
/// Send a command to wpasupplicant / hostapd.
fn request<F: FnMut(&str)>(&mut self, cmd: &str, mut cb: F) -> Result<String> {
self.handle.send(cmd.as_bytes())?;
loop {
let mut fd_set = FdSet::new();
fd_set.insert(self.handle.as_raw_fd());
select(self.handle.as_raw_fd()+1, Some(&mut fd_set), None, None, Some(&mut TimeVal::seconds(10)))?;
match self.handle.recv(&mut self.buffer) {
Ok(len) => {
let s = std::str::from_utf8(&self.buffer[0..len])?;
if s.starts_with('<') {
cb(s)
} else {
return Ok(s.to_owned());
}
},
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) => return Err(e.into()),
}
}
}
}
impl Drop for WpaCtrlInternal {
fn drop(&mut self) {
if let Err(e) = std::fs::remove_file(&self.filepath) {
warn!("Unable to unlink {:?}", e);
}
}
}
/// A connection to wpasupplicant / hostap
pub struct WpaCtrl(WpaCtrlInternal);
impl WpaCtrl {
/// Creates a builder for a wpasupplicant / hostap connection
///
/// # Examples
///
/// ```
/// let wpa = wpactrl::WpaCtrl::new().open().unwrap();
/// ```
pub fn new() -> WpaCtrlBuilder {
WpaCtrlBuilder::default()
}
/// Register as an event monitor for control interface messages
///
/// # Examples
///
/// ```
/// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap();
/// let wpa_attached = wpa.attach().unwrap();
/// ```
pub fn attach(mut self) -> Result<WpaCtrlAttached> {
// FIXME: None closure would be better
if self.0.request("ATTACH", |_: &str|())? != "OK\n" {
Err(WpaError::Failure.into())
} else {
Ok(WpaCtrlAttached(self.0, VecDeque::new()))
}
}
/// Send a command to wpa_supplicant/hostapd.
///
/// Commands are generally identical to those used in wpa_cli,
/// except all uppercase (eg LIST_NETWORKS, SCAN, etc)
///
/// # Examples
///
/// ```
/// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap();
/// assert_eq!(wpa.request("PING").unwrap(), "PONG\n");
/// ```
pub fn request(&mut self, cmd: &str) -> Result<String> {
self.0.request(cmd, |_: &str|())
}
}
/// A connection to wpasupplicant / hostap that receives status messages
pub struct WpaCtrlAttached(WpaCtrlInternal, VecDeque<String>);
impl WpaCtrlAttached {
/// Stop listening for and discard any remaining control interface messages
///
/// # Examples
///
/// ```
/// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap().attach().unwrap();
/// wpa.detach().unwrap();
/// ```
pub fn detach(mut self) -> Result<WpaCtrl> {
if self.0.request("DETACH", |_: &str|())? != "OK\n" {
Err(WpaError::Failure.into())
} else {
Ok(WpaCtrl(self.0))
}
}
/// Receive the next control interface message.
///
/// Note that multiple control interface messages can be pending;
/// call this function repeatedly until it returns None to get all of them.
///
/// # Examples
///
/// ```
/// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap().attach().unwrap();
/// assert_eq!(wpa.recv().unwrap(), None);
/// ```
pub fn recv(&mut self) -> Result<Option<String>> {
if let Some(s) = self.1.pop_back() {
Ok(Some(s))
} else {
self.0.recv()
}
}
/// Send a command to wpa_supplicant/hostapd.
///
/// Commands are generally identical to those used in wpa_cli,
/// except all uppercase (eg LIST_NETWORKS, SCAN, etc)
///
/// Control interface messages will be buffered as the command
/// runs, and will be returned on the next call to recv.
///
/// # Examples
///
/// ```
/// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap();
/// assert_eq!(wpa.request("PING").unwrap(), "PONG\n");
/// ```
pub fn request(&mut self, cmd: &str) -> Result<String> {
let mut messages = VecDeque::new();
let r = self.0.request(cmd, |s: &str|{
messages.push_front(s.into())
});
self.1.extend(messages);
r
}
}
#[cfg(test)]
mod test {
use super::*;
fn wpa_ctrl() -> WpaCtrl {
WpaCtrl::new().open().unwrap()
}
#[test]
fn attach() {
wpa_ctrl().attach().unwrap().detach().unwrap().attach().unwrap().detach().unwrap();
}
#[test]
fn detach() {
let wpa = wpa_ctrl().attach().unwrap();
wpa.detach().unwrap();
}
#[test]
fn new() {
wpa_ctrl();
}
#[test]
fn request() {
let mut wpa = wpa_ctrl();
assert_eq!(wpa.request("PING").unwrap(), "PONG\n");
let mut wpa_attached = wpa.attach().unwrap();
// FIXME: This may not trigger the callback
assert_eq!(wpa_attached.request("PING").unwrap(), "PONG\n");
}
#[test]
fn recv() {
let mut wpa = wpa_ctrl().attach().unwrap();
assert_eq!(wpa.recv().unwrap(), None);
assert_eq!(wpa.request("SCAN").unwrap(), "OK\n");
loop {
match wpa.recv().unwrap() {
Some(s) => {
assert_eq!(&s[3..], "CTRL-EVENT-SCAN-STARTED ");
break;
}
None => std::thread::sleep(std::time::Duration::from_millis(10)),
}
}
wpa.detach().unwrap();
}
}
|
use core::fmt;
use core::iter::{FromIterator, IntoIterator};
use core::mem::{self, ManuallyDrop};
use core::ptr;
use core::sync::atomic::Ordering::{self, Acquire, Relaxed, Release};
#[cfg(feature = "examples-debug")]
use core::sync::atomic::AtomicUsize;
cfg_if::cfg_if! {
if #[cfg(feature = "std")] {
use std::sync::Arc;
} else {
use alloc::sync::Arc;
}
}
use crate::conquer_pointer::MarkedPtr;
use crate::{Maybe, ReclaimRef, ReclaimThreadState};
type Atomic<T, R> = crate::Atomic<T, R, 0>;
type Owned<T, R> = crate::Owned<T, R, 0>;
/********** global node drop counter (debug) ******************************************************/
#[cfg(feature = "examples-debug")]
pub static NODE_DROP_COUNTER: AtomicUsize = AtomicUsize::new(0);
////////////////////////////////////////////////////////////////////////////////////////////////////
// ArcStack
////////////////////////////////////////////////////////////////////////////////////////////////////
/// An [`Arc`] based version of Treiber's lock-free stack.
pub struct ArcStack<T, R: ReclaimRef<Node<T, R>>> {
inner: Arc<Stack<T, R>>,
thread_state: ManuallyDrop<R::ThreadState>,
}
/*********** impl Send ****************************************************************************/
unsafe impl<T, R: ReclaimRef<Node<T, R>>> Send for ArcStack<T, R> {}
/*********** impl Clone ***************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>>> Clone for ArcStack<T, R> {
#[inline]
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
thread_state: ManuallyDrop::new(unsafe {
self.inner.reclaimer.build_thread_state_unchecked()
}),
}
}
}
/*********** impl inherent ************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>> + Default> ArcStack<T, R> {
#[inline]
pub fn new() -> Self {
Self::with_reclaimer(Default::default())
}
}
impl<T, R: ReclaimRef<Node<T, R>>> ArcStack<T, R> {
#[inline]
pub fn with_reclaimer(reclaimer: R) -> Self {
let inner = Arc::new(Stack::<_, R>::with_reclaimer(reclaimer));
let thread_state = unsafe { inner.reclaimer.build_thread_state_unchecked() };
Self { inner, thread_state: ManuallyDrop::new(thread_state) }
}
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
#[inline]
pub fn push(&self, elem: T) {
unsafe { self.inner.push(elem, &self.thread_state) }
}
#[inline]
pub fn pop(&self) -> Option<T> {
unsafe { self.inner.pop_unchecked(&self.thread_state) }
}
#[inline]
pub fn try_unwrap(self) -> Result<Stack<T, R>, Self> {
// circumvents the restrictions on moving out of types implementing Drop.
let (inner, mut thread_state) = unsafe {
let inner = ptr::read(&self.inner);
let thread_state = ptr::read(&self.thread_state);
mem::forget(self);
(inner, thread_state)
};
Arc::try_unwrap(inner)
.map(|stack| {
unsafe { ManuallyDrop::drop(&mut thread_state) };
stack
})
.map_err(|inner| Self { inner, thread_state })
}
}
/********** impl Debug ****************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>> + Default> fmt::Debug for ArcStack<T, R> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ArcStack {{ ... }}")
}
}
/********** impl Default **************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>> + Default> Default for ArcStack<T, R> {
#[inline]
fn default() -> Self {
Self::new()
}
}
/********** impl Drop *****************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>>> Drop for ArcStack<T, R> {
#[inline]
fn drop(&mut self) {
// SAFETY: Drop Local state before the `Arc`, because it may hold a pointer into it.
unsafe { ManuallyDrop::drop(&mut self.thread_state) };
}
}
/********** impl From (Stack) *********************************************************************/
impl<T, R: ReclaimRef<Node<T, R>>> From<Stack<T, R>> for ArcStack<T, R> {
#[inline]
fn from(stack: Stack<T, R>) -> Self {
let inner = Arc::new(stack);
let thread_state =
ManuallyDrop::new(unsafe { inner.reclaimer.build_thread_state_unchecked() });
Self { inner, thread_state }
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// StackRef
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A thread-local reference to a [`Stack`].
pub struct StackRef<'s, T, R: ReclaimRef<Node<T, R>>> {
stack: &'s Stack<T, R>,
thread_state: R::ThreadState,
}
/********** impl inherent *************************************************************************/
impl<'s, T, R: ReclaimRef<Node<T, R>>> StackRef<'s, T, R> {
/// Creates a new [`StackRef`] from the given `stack` reference.
#[inline]
pub fn new(stack: &'s Stack<T, R>) -> Self {
Self { stack, thread_state: unsafe { stack.reclaimer.build_thread_state_unchecked() } }
}
}
impl<'s, T, R: ReclaimRef<Node<T, R>>> StackRef<'s, T, R> {
/// Returns `true` if the stack is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.stack.is_empty()
}
/// Pushes `elem` to the top of the stack.
#[inline]
pub fn push(&self, elem: T) {
unsafe { self.stack.push(elem, &self.thread_state) };
}
/// Pops the element from the top of the stack or returns [`None`] if the
/// stack is empty.
#[inline]
pub fn pop(&self) -> Option<T> {
unsafe { self.stack.pop_unchecked(&self.thread_state) }
}
}
/********** impl Debug ****************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>>> fmt::Debug for StackRef<'_, T, R> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "StackRef {{ ... }}")
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Stack
////////////////////////////////////////////////////////////////////////////////////////////////////
pub struct Stack<T, R: ReclaimRef<Node<T, R>>> {
head: Atomic<Node<T, R>, R::Reclaim>,
reclaimer: R,
}
/********** impl inherent *************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>> + Default> Stack<T, R> {
#[inline]
pub fn new() -> Self {
Self::with_reclaimer(Default::default())
}
}
impl<T, R: ReclaimRef<Node<T, R>>> Stack<T, R> {
const RELEASE_CAS: (Ordering, Ordering) = (Release, Relaxed);
#[inline]
pub fn with_reclaimer(reclaimer: R) -> Self {
Self { head: Atomic::null(), reclaimer }
}
#[inline]
pub fn as_ref(&self) -> StackRef<T, R> {
StackRef::new(self)
}
#[inline]
pub fn is_empty(&self) -> bool {
self.head.load_unprotected(Ordering::Relaxed).is_null()
}
#[inline]
pub unsafe fn push(&self, elem: T, thread_state: &R::ThreadState) {
let mut node = thread_state.alloc_owned(Node::new(elem));
loop {
let head = self.head.load_unprotected(Acquire);
// safety: The store only becomes visible if the subsequent CAS succeeds, in which case
// the head could not have changed and has therefore not been retired by any other thread
node.next.store(head.assume_storable(), Relaxed);
match self.head.compare_exchange_weak(head, node, Self::RELEASE_CAS) {
Ok(_) => return,
Err(err) => node = err.input,
}
}
}
#[inline]
pub unsafe fn pop_unchecked(&self, thread_state: &R::ThreadState) -> Option<T> {
let mut guard = thread_state.build_guard();
while let Maybe::Some(shared) = self.head.load(&mut guard, Acquire).shared() {
// safety: `next` can be safely used as store argument for the subsequent CAS, since it
// will only be actually stored if it succeeds, in which case the node could not have
// been popped and retired/reclaimed in between.
let next = shared.as_ref().next.load_unprotected(Relaxed).assume_storable();
if let Ok(unlinked) = self.head.compare_exchange_weak(shared, next, Self::RELEASE_CAS) {
let elem = unlinked.take(|node| &node.elem);
thread_state.retire_record(unlinked.into_retired());
return Some(elem);
}
}
None
}
}
/********** impl Default **************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>> + Default> Default for Stack<T, R> {
#[inline]
fn default() -> Self {
Self::new()
}
}
/********** impl Drop *****************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>>> Drop for Stack<T, R> {
#[inline]
fn drop(&mut self) {
unsafe {
let mut curr = self.head.take();
while let Some(mut node) = curr {
ManuallyDrop::drop(&mut node.elem);
curr = node.next.take();
}
}
}
}
/********** impl IntoIterator *********************************************************************/
impl<T, R: ReclaimRef<Node<T, R>>> IntoIterator for Stack<T, R> {
type Item = T;
type IntoIter = IntoIter<T, R>;
#[inline]
fn into_iter(mut self) -> Self::IntoIter {
IntoIter { curr: unsafe { self.head.take() } }
}
}
/********** impl FromIterator *********************************************************************/
impl<T, R: ReclaimRef<Node<T, R>> + Default> FromIterator<T> for Stack<T, R> {
#[inline]
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let reclaimer = R::default();
let head = Atomic::null();
let mut prev = MarkedPtr::null();
for elem in iter.into_iter() {
let node = reclaimer.alloc_owned(Node::new(elem));
unsafe { node.next.as_raw() }.store(prev, Ordering::Relaxed);
prev = Owned::as_marked_ptr(&node);
head.store(node, Ordering::Relaxed);
}
Self { head, reclaimer }
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IntoIter
////////////////////////////////////////////////////////////////////////////////////////////////////
pub struct IntoIter<T, R: ReclaimRef<Node<T, R>>> {
curr: Option<Owned<Node<T, R>, R::Reclaim>>,
}
/********** impl Iterator *************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>>> Iterator for IntoIter<T, R> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.curr.take().map(|mut node| unsafe {
let elem = ptr::read(&*node.elem);
self.curr = node.next.take();
elem
})
}
}
/********** impl Drop *****************************************************************************/
impl<T, R: ReclaimRef<Node<T, R>>> Drop for IntoIter<T, R> {
#[inline]
fn drop(&mut self) {
while let Some(_) = self.next() {}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Node
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A node type for storing a [`Stack`]'s individual elements.
pub struct Node<T, R: ReclaimRef<Self>> {
/// The node's element, which is only ever dropped as part of a node when a
/// non-empty [`Stack`] itself is dropped.
elem: ManuallyDrop<T>,
/// The node's next pointer.
next: Atomic<Self, R::Reclaim>,
}
/********** impl inherent *************************************************************************/
impl<T, R: ReclaimRef<Self>> Node<T, R> {
#[inline]
fn new(elem: T) -> Self {
Self { elem: ManuallyDrop::new(elem), next: Atomic::default() }
}
}
/********** impl Drop *****************************************************************************/
#[cfg(feature = "examples-debug")]
impl<T, R: ReclaimRef<Self>> Drop for Node<T, R> {
#[inline]
fn drop(&mut self) {
NODE_DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
}
}
|
#[doc = "Reader of register DIV"]
pub type R = crate::R<u32, super::DIV>;
#[doc = "Writer for register DIV"]
pub type W = crate::W<u32, super::DIV>;
#[doc = "Register DIV `reset()`'s with value 0"]
impl crate::ResetValue for super::DIV {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "set to 0xaa0 + div where\\n div = 0 divides by 32\\n div = 1-31 divides by div\\n any other value sets div=0 and therefore divides by 32\\n this register resets to div=16\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u16)]
pub enum DIV_A {
#[doc = "2720: `101010100000`"]
PASS = 2720,
}
impl From<DIV_A> for u16 {
#[inline(always)]
fn from(variant: DIV_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `DIV`"]
pub type DIV_R = crate::R<u16, DIV_A>;
impl DIV_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u16, DIV_A> {
use crate::Variant::*;
match self.bits {
2720 => Val(DIV_A::PASS),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PASS`"]
#[inline(always)]
pub fn is_pass(&self) -> bool {
*self == DIV_A::PASS
}
}
#[doc = "Write proxy for field `DIV`"]
pub struct DIV_W<'a> {
w: &'a mut W,
}
impl<'a> DIV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIV_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "`101010100000`"]
#[inline(always)]
pub fn pass(self) -> &'a mut W {
self.variant(DIV_A::PASS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0fff) | ((value as u32) & 0x0fff);
self.w
}
}
impl R {
#[doc = "Bits 0:11 - set to 0xaa0 + div where\\n div = 0 divides by 32\\n div = 1-31 divides by div\\n any other value sets div=0 and therefore divides by 32\\n this register resets to div=16"]
#[inline(always)]
pub fn div(&self) -> DIV_R {
DIV_R::new((self.bits & 0x0fff) as u16)
}
}
impl W {
#[doc = "Bits 0:11 - set to 0xaa0 + div where\\n div = 0 divides by 32\\n div = 1-31 divides by div\\n any other value sets div=0 and therefore divides by 32\\n this register resets to div=16"]
#[inline(always)]
pub fn div(&mut self) -> DIV_W {
DIV_W { w: self }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.