text stringlengths 8 4.13M |
|---|
use crate::api;
use crate::component::{Panel, PanelBlock, PanelHeading};
use serde::{Deserialize, Serialize};
use yew::format::Json;
use yew::prelude::*;
use yew::services::fetch::FetchTask;
use yew_router::prelude::*;
const ANSWER_SUGGESTIONS: [&str; 7] = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
#[derive(Serialize, Deserialize, Debug)]
struct State {
title: String,
choices: Vec<String>,
loading: bool,
}
pub enum Msg {
UpdateTitle(String),
UpdateChoice(usize, String),
Submit,
PostSuccess(api::CreatePollResponse),
PostFailed,
}
pub struct CreatePoll {
link: ComponentLink<Self>,
state: State,
router: RouteAgentDispatcher<()>,
tasks: Vec<FetchTask>,
}
impl Component for CreatePoll {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
state: State {
title: "".into(),
choices: vec!["".into(); 3],
loading: false,
},
router: RouteAgentDispatcher::new(),
tasks: Vec::new(),
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::UpdateTitle(value) => {
self.state.title = value;
true
}
Msg::UpdateChoice(i, value) => {
self.state.choices[i] = value;
if i == self.state.choices.len() - 1 {
self.state.choices.push("".to_owned());
}
true
}
Msg::Submit => {
self.state.loading = true;
let task = api::create_poll(
&self.state.title,
&self.state.choices,
&self.link,
|response| {
if let (meta, Json(Ok(body))) = response.into_parts() {
if meta.status.is_success() {
return Msg::PostSuccess(body);
}
}
Msg::PostFailed
},
);
self.tasks.push(task);
true
}
Msg::PostSuccess(response) => {
self.router
.send(yew_router::agent::RouteRequest::ChangeRoute(
yew_router::route::Route::from(crate::AppRoute::Poll(response.poll)),
));
false
}
Msg::PostFailed => false,
}
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
let valid_choices = self.state.choices.iter().filter(|s| s.len() > 0).count();
let can_submit = self.state.title.len() > 0 && valid_choices >= 2;
let button_class = if self.state.loading {
"button is-primary is-loading"
} else {
"button is-primary"
};
html! (
<Panel>
<PanelHeading>
<div class="level">
<div class="level-left">
<div class="level-item">
{"Create a Dot Poll"}
</div>
</div>
</div>
</PanelHeading>
<PanelBlock>
<form class="control">
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label">{"Title"}</label>
</div>
<div class="field-body">
<div class="field">
<div class="control">
<input class="input" type="text"
placeholder="Which day of the week should we select?..."
value=&self.state.title oninput=self.link.callback(|e:
InputData| Msg::UpdateTitle(e.value)) />
</div>
</div>
</div>
</div>
{ for self.state.choices.iter().enumerate().map(|(i, _)| self.view_answer(i)) }
<div class="field is-grouped is-grouped-right">
<p class="control">
<a class={button_class} onclick=self.link.callback(|_| Msg::Submit)
disabled={!can_submit}>
{"Create Poll"}
</a>
</p>
</div>
</form>
</PanelBlock>
</Panel>
)
}
}
impl CreatePoll {
fn view_answer(&self, i: usize) -> Html {
let placeholder = if i < ANSWER_SUGGESTIONS.len() {
ANSWER_SUGGESTIONS[i]
} else {
""
};
html! {
<div class="field is-horizontal">
<div class="field-label is-normal">
<label class="label">{if i == 0 { "Choices" } else { "" }}</label>
</div>
<div class="field-body">
<div class="field has-addons">
<p class="control is-expanded">
<input class="input" type="text" placeholder={placeholder} value=&self.state.choices[i]
oninput=self.link.callback(move |e: InputData| Msg::UpdateChoice(i, e.value)) />
</p>
</div>
</div>
</div>
}
}
}
|
#[doc = "Reader of register PP"]
pub type R = crate::R<u32, super::PP>;
#[doc = "Count Size\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum SIZE_A {
#[doc = "0: Timer A and Timer B counters are 16 bits each with an 8-bit prescale counter"]
_16 = 0,
#[doc = "1: Timer A and Timer B counters are 32 bits each with a 16-bit prescale counter"]
_32 = 1,
}
impl From<SIZE_A> for u8 {
#[inline(always)]
fn from(variant: SIZE_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `SIZE`"]
pub type SIZE_R = crate::R<u8, SIZE_A>;
impl SIZE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, SIZE_A> {
use crate::Variant::*;
match self.bits {
0 => Val(SIZE_A::_16),
1 => Val(SIZE_A::_32),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `_16`"]
#[inline(always)]
pub fn is_16(&self) -> bool {
*self == SIZE_A::_16
}
#[doc = "Checks if the value of the field is `_32`"]
#[inline(always)]
pub fn is_32(&self) -> bool {
*self == SIZE_A::_32
}
}
#[doc = "Reader of field `CHAIN`"]
pub type CHAIN_R = crate::R<bool, bool>;
#[doc = "Reader of field `SYNCCNT`"]
pub type SYNCCNT_R = crate::R<bool, bool>;
#[doc = "Reader of field `ALTCLK`"]
pub type ALTCLK_R = crate::R<bool, bool>;
impl R {
#[doc = "Bits 0:3 - Count Size"]
#[inline(always)]
pub fn size(&self) -> SIZE_R {
SIZE_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bit 4 - Chain with Other Timers"]
#[inline(always)]
pub fn chain(&self) -> CHAIN_R {
CHAIN_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Synchronize Start"]
#[inline(always)]
pub fn synccnt(&self) -> SYNCCNT_R {
SYNCCNT_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Alternate Clock Source"]
#[inline(always)]
pub fn altclk(&self) -> ALTCLK_R {
ALTCLK_R::new(((self.bits >> 6) & 0x01) != 0)
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod lru;
use std::borrow::Borrow;
use std::hash::BuildHasher;
use std::hash::Hash;
use crate::Meter;
/// A trait for a cache.
pub trait Cache<K, V, S, M>
where
K: Eq + Hash,
S: BuildHasher,
M: Meter<K, V>,
{
/// Creates an empty cache that can hold at most `capacity` as measured by `meter` with the
/// given hash builder.
fn with_meter_and_hasher(cap: u64, meter: M, hash_builder: S) -> Self;
/// Returns a reference to the value corresponding to the given key in the cache, if
/// any.
fn get<'a, Q>(&'a mut self, k: &Q) -> Option<&'a V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized;
/// Returns a mutable reference to the value corresponding to the given key in the cache, if
/// any.
fn get_mut<'a, Q>(&'a mut self, k: &Q) -> Option<&'a mut V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized;
/// Returns a reference to the value corresponding to the key in the cache or `None` if it is
/// not present in the cache. Unlike `get`, `peek` does not update the Cache state so the key's
/// position will be unchanged.
fn peek<'a, Q>(&'a self, k: &Q) -> Option<&'a V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized;
/// Returns a mutable reference to the value corresponding to the key in the cache or `None`
/// if it is not present in the cache. Unlike `get_mut`, `peek_mut` does not update the Cache
/// state so the key's position will be unchanged.
fn peek_mut<'a, Q>(&'a mut self, k: &Q) -> Option<&'a mut V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized;
/// Returns the value corresponding to the item by policy or `None` if the
/// cache is empty. Like `peek`, `peek_by_policy` does not update the Cache state so the item's
/// position will be unchanged.
// TODO: change to fn peek_by_policy<'a>(&self) -> Option<(&'a K, &'a V)>;
fn peek_by_policy(&self) -> Option<(&K, &V)>;
/// Inserts a key-value pair into the cache. If the key already existed, the old value is
/// returned.
fn put(&mut self, k: K, v: V) -> Option<V>;
/// Removes the given key from the cache and returns its corresponding value.
fn pop<Q>(&mut self, k: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized;
/// Removes and returns the key-value pair as a tuple by policy (Lru, Lfu, etc.).
fn pop_by_policy(&mut self) -> Option<(K, V)>;
/// Checks if the map contains the given key.
fn contains<Q>(&self, k: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized;
/// Returns the number of key-value pairs in the cache.
fn len(&self) -> usize;
/// Returns `true` if the cache contains no key-value pairs.
fn is_empty(&self) -> bool;
/// Returns the maximum size of the key-value pairs the cache can hold, as measured by the
/// `Meter` used by the cache.
fn capacity(&self) -> u64;
/// Sets the size of the key-value pairs the cache can hold, as measured by the `Meter` used by
/// the cache.
fn set_capacity(&mut self, cap: u64);
/// Returns the size of all the key-value pairs in the cache, as measured by the `Meter` used
/// by the cache.
fn size(&self) -> u64;
/// Removes all key-value pairs from the cache.
fn clear(&mut self);
}
|
pub mod convert_libc_char_test;
pub mod convert_i32_test;
pub mod convert_string_test;
pub mod convert_str_test;
|
#[path = "with_empty_list_options/with_arity_zero.rs"]
mod with_arity_zero;
test_stdout!(
without_arity_zero_returns_pid_to_parent_and_child_process_exits_badarity,
"badarity\n"
);
|
//! Information about frame timing.
//!
//! By default the engine will run at 60 fps (giving a delta of 16.667 ms), but it will change
//! its fixed framerate if necessary. For example, if the game fails to meet 60 fps, the engine
//! will throttle down to 30 fps (with a delta of 33.333 ms) until it can return to 60 fps. The
//! time delta doesn't represent the exact amount of time it took to complete the last frame,
//! rather it gives the current locked framerate for the game. Therefore, game code can be
//! written with the assumption of a fixed time step (i.e. the delta will be the same
//! frame-to-frame) even if the exact time step may occaisonally change in practice.
use std::time::Duration;
/// Returns the exact time between frames.
///
/// See module documentation for more information about frame timing.
pub fn delta() -> Duration {
Duration::new(1, 0) / 60
}
/// Returns the current time between frames in seconds.
///
/// See module documentation for more information about frame timing.
pub fn delta_f32() -> f32 {
1.0 / 60.0
}
|
pub struct {{ AppName }}Config {
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_{{ app_name }}_config() {
}
}
|
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000000007;
fn alphabet2idx(c: char) -> usize {
if c.is_ascii_lowercase() {
c as u8 as usize - 'a' as u8 as usize
} else if c.is_ascii_uppercase() {
c as u8 as usize - 'A' as u8 as usize
} else {
panic!("wtf")
}
}
fn main() {
let (h, w, n): (usize, usize, usize) = parse_line().unwrap();
let mut pp: Vec<(usize, usize, usize)> = vec![];
for i in 1..=n {
let ab: (usize, usize) = parse_line().unwrap();
pp.push((i, ab.0, ab.1));
}
let mut ans: Vec<(usize, usize)> = vec![(0, 0); n + 1];
pp.sort_by(|a, b| a.1.cmp(&b.1));
let mut tatenow = 0;
let mut tatecount = 0;
for p in pp.iter() {
if tatecount != p.1 {
tatenow += 1;
ans[p.0].0 = tatenow;
tatecount = p.1;
} else {
ans[p.0].0 = tatenow;
}
}
pp.sort_by(|a, b| a.2.cmp(&b.2));
let mut yokonow = 0;
let mut yokocount = 0;
for p in pp.iter() {
if yokocount != p.2 {
yokonow += 1;
ans[p.0].1 = yokonow;
yokocount = p.2;
} else {
ans[p.0].1 = yokonow;
}
}
for a in ans.iter().skip(1) {
println!("{} {}", a.0, a.1);
}
}
|
use ethers::prelude::ContractError;
use std::result::Result;
pub mod escalator;
pub mod liquidations;
pub mod sentinel;
pub mod vaults;
pub type EthersResult<T, M> = Result<T, ContractError<M>>;
|
//! This is an implementation of Single Decree Paxos, an algorithm that ensures a cluster of
//! servers never disagrees on a value.
//!
//! # The Algorithm
//!
//! The Paxos algorithm is comprised of two phases. These are best understood in reverse order.
//!
//! ## Phase 2
//!
//! Phase 2 involves broadcasting a proposal (or a sequence of proposals in the case of
//! Multipaxos). If a quorum accepts a proposal, it is considered "decided" by the cluster even if
//! the leader does not observe that decision, e.g. due to message loss.
//!
//! ## Phase 1
//!
//! Phase 1 solves the more complex problem of leadership handoff by introducing a notion of
//! leadership "terms" and a technique for ensuring new terms are consistent with earlier terms.
//!
//! 1. Each term has a distinct leader. Before proposing values during its term, the
//! leader broadcasts a message that closes previous terms. Once a quorum replies, the leader
//! knows that previous leaders are unable to reach new (and possibly contradictory) decisions.
//! 2. The leader also needs to learn the proposal that was decided by previous terms (or sequence
//! of proposals for Multipaxos), so in their replies, the servers indicate their previously
//! accepted proposals.
//! 3. The leader cannot be guaranteed to know if a proposal was decided unless it talks with every
//! server, which undermines the availability of the system, so Paxos leverages a clever trick:
//! the leader drives the most recent accepted proposal to a quorum (and for Multipaxos it does
//! this for each index in the sequence of proposals). It only needs to look at the most recent
//! proposal because any previous leader would have done the same prior to sending its new
//! proposals.
//! 4. Many optimizations are possible. For example, the leader can skip driving consensus on a
//! previous proposal if the Phase 1 quorum already agrees or the leader observes auxiliary
//! state from which it can infer agreement. The latter optimizations are particularly important
//! for Multipaxos.
//!
//! ## Leadership Terms
//!
//! It is safe to start a new term at any time.
//!
//! In Multipaxos, a term is typically maintained until the leader times out (as observed by a
//! peer), allowing that leader to propose a sequence of values while (1) avoiding contention
//! and (2) only paying the cost of a single message round trip for each proposal.
//!
//! In contrast, with Single Decree Paxos, a term is typically coupled to the life of a client
//! request, so each client request gets a new term. This can result in contention if many values
//! are proposed in parallel, but the following implementation follows this approach to match how
//! the algorithm is typically described.
use serde::{Deserialize, Serialize};
use stateright::actor::register::{RegisterActor, RegisterMsg, RegisterMsg::*};
use stateright::actor::{majority, model_peers, Actor, ActorModel, Id, Network, Out};
use stateright::report::WriteReporter;
use stateright::semantics::register::Register;
use stateright::semantics::LinearizabilityTester;
use stateright::util::{HashableHashMap, HashableHashSet};
use stateright::{Checker, Expectation, Model};
use std::borrow::Cow;
type Round = u32;
type Ballot = (Round, Id);
type Proposal = (RequestId, Id, Value);
type RequestId = u64;
type Value = char;
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
enum PaxosMsg {
Prepare {
ballot: Ballot,
},
Prepared {
ballot: Ballot,
last_accepted: Option<(Ballot, Proposal)>,
},
Accept {
ballot: Ballot,
proposal: Proposal,
},
Accepted {
ballot: Ballot,
},
Decided {
ballot: Ballot,
proposal: Proposal,
},
}
use PaxosMsg::*;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct PaxosState {
// shared state
ballot: Ballot,
// leader state
proposal: Option<Proposal>,
prepares: HashableHashMap<Id, Option<(Ballot, Proposal)>>,
accepts: HashableHashSet<Id>,
// acceptor state
accepted: Option<(Ballot, Proposal)>,
is_decided: bool,
}
#[derive(Clone)]
struct PaxosActor {
peer_ids: Vec<Id>,
}
impl Actor for PaxosActor {
type Msg = RegisterMsg<RequestId, Value, PaxosMsg>;
type State = PaxosState;
type Timer = ();
fn on_start(&self, _id: Id, _o: &mut Out<Self>) -> Self::State {
PaxosState {
// shared state
ballot: (0, Id::from(0)),
// leader state
proposal: None,
prepares: Default::default(),
accepts: Default::default(),
// acceptor state
accepted: None,
is_decided: false,
}
}
fn on_msg(
&self,
id: Id,
state: &mut Cow<Self::State>,
src: Id,
msg: Self::Msg,
o: &mut Out<Self>,
) {
if state.is_decided {
if let Get(request_id) = msg {
// While it's tempting to `o.send(src, GetOk(request_id, None))` for undecided,
// we don't know if a value was decided elsewhere and the delivery is pending. Our
// solution is to not reply in this case, but a more useful choice might be
// to broadcast to the other actors and let them reply to the originator, or query
// the other actors and reply based on that.
let (_b, (_req_id, _src, value)) =
state.accepted.expect("decided but lacks accepted state");
o.send(src, GetOk(request_id, value));
};
return;
}
match msg {
Put(request_id, value) if state.proposal.is_none() => {
let mut state = state.to_mut();
state.proposal = Some((request_id, src, value));
state.prepares = Default::default();
state.accepts = Default::default();
// Simulate `Prepare` self-send.
state.ballot = (state.ballot.0 + 1, id);
// Simulate `Prepared` self-send.
state.prepares.insert(id, state.accepted);
o.broadcast(
&self.peer_ids,
&Internal(Prepare {
ballot: state.ballot,
}),
);
}
Internal(Prepare { ballot }) if state.ballot < ballot => {
state.to_mut().ballot = ballot;
o.send(
src,
Internal(Prepared {
ballot,
last_accepted: state.accepted,
}),
);
}
Internal(Prepared {
ballot,
last_accepted,
}) if ballot == state.ballot => {
let mut state = state.to_mut();
state.prepares.insert(src, last_accepted);
if state.prepares.len() == majority(self.peer_ids.len() + 1) {
// This stage is best understood as "leadership handoff," in which this term's
// leader needs to ensure it does not contradict a decision (a quorum of
// accepts) from a previous term. Here's how:
//
// 1. To start this term, the leader first "locked" the older terms from
// additional accepts via the `Prepare` messages.
// 2. If the servers reached a decision in a previous term, then the observed
// prepare quorum is guaranteed to contain that accepted proposal, and we
// have to favor that one.
// 3. We only have to drive the proposal accepted by the most recent term
// because the leaders of the previous terms would have done the same before
// asking their peers to accept proposals (so any proposals accepted by
// earlier terms either match the most recently accepted proposal or are
// guaranteed to have never reached quorum and so are safe to ignore).
// 4. If no proposals were previously accepted, the leader is safe to proceed
// with the one from the client.
let proposal = state
.prepares
.values()
.max()
.unwrap()
.map(|(_b, p)| p)
.unwrap_or_else(|| state.proposal.expect("proposal expected")); // See `Put` case above.
state.proposal = Some(proposal);
// Simulate `Accept` self-send.
state.accepted = Some((ballot, proposal));
// Simulate `Accepted` self-send.
state.accepts.insert(id);
o.broadcast(&self.peer_ids, &Internal(Accept { ballot, proposal }));
}
}
Internal(Accept { ballot, proposal }) if state.ballot <= ballot => {
let mut state = state.to_mut();
state.ballot = ballot;
state.accepted = Some((ballot, proposal));
o.send(src, Internal(Accepted { ballot }));
}
Internal(Accepted { ballot }) if ballot == state.ballot => {
let mut state = state.to_mut();
state.accepts.insert(src);
if state.accepts.len() == majority(self.peer_ids.len() + 1) {
state.is_decided = true;
let proposal = state.proposal.expect("proposal expected"); // See `Put` case above.
o.broadcast(&self.peer_ids, &Internal(Decided { ballot, proposal }));
let (request_id, requester_id, _) = proposal;
o.send(requester_id, PutOk(request_id));
}
}
Internal(Decided { ballot, proposal }) => {
let mut state = state.to_mut();
state.ballot = ballot;
state.accepted = Some((ballot, proposal));
state.is_decided = true;
}
_ => {}
}
}
}
#[derive(Clone)]
struct PaxosModelCfg {
client_count: usize,
server_count: usize,
network: Network<<PaxosActor as Actor>::Msg>,
}
impl PaxosModelCfg {
fn into_model(
self,
) -> ActorModel<RegisterActor<PaxosActor>, Self, LinearizabilityTester<Id, Register<Value>>>
{
ActorModel::new(
self.clone(),
LinearizabilityTester::new(Register(Value::default())),
)
.actors((0..self.server_count).map(|i| {
RegisterActor::Server(PaxosActor {
peer_ids: model_peers(i, self.server_count),
})
}))
.actors((0..self.client_count).map(|_| RegisterActor::Client {
put_count: 1,
server_count: self.server_count,
}))
.init_network(self.network)
.property(Expectation::Always, "linearizable", |_, state| {
state.history.serialized_history().is_some()
})
.property(Expectation::Sometimes, "value chosen", |_, state| {
for env in state.network.iter_deliverable() {
if let RegisterMsg::GetOk(_req_id, value) = env.msg {
if *value != Value::default() {
return true;
}
}
}
false
})
.record_msg_in(RegisterMsg::record_returns)
.record_msg_out(RegisterMsg::record_invocations)
}
}
#[cfg(test)]
#[test]
fn can_model_paxos() {
use stateright::actor::ActorModelAction::Deliver;
// BFS
let checker = PaxosModelCfg {
client_count: 2,
server_count: 3,
network: Network::new_unordered_nonduplicating([]),
}
.into_model()
.checker()
.spawn_bfs()
.join();
checker.assert_properties();
#[rustfmt::skip]
checker.assert_discovery("value chosen", vec![
Deliver { src: 4.into(), dst: 1.into(), msg: Put(4, 'B') },
Deliver { src: 1.into(), dst: 0.into(), msg: Internal(Prepare { ballot: (1, 1.into()) }) },
Deliver { src: 0.into(), dst: 1.into(), msg: Internal(Prepared { ballot: (1, 1.into()), last_accepted: None }) },
Deliver { src: 1.into(), dst: 2.into(), msg: Internal(Accept { ballot: (1, 1.into()), proposal: (4, 4.into(), 'B') }) },
Deliver { src: 2.into(), dst: 1.into(), msg: Internal(Accepted { ballot: (1, 1.into()) }) },
Deliver { src: 1.into(), dst: 4.into(), msg: PutOk(4) },
Deliver { src: 1.into(), dst: 2.into(), msg: Internal(Decided { ballot: (1, 1.into()), proposal: (4, 4.into(), 'B') }) },
Deliver { src: 4.into(), dst: 2.into(), msg: Get(8) }
]);
assert_eq!(checker.unique_state_count(), 16_668);
// DFS
let checker = PaxosModelCfg {
client_count: 2,
server_count: 3,
network: Network::new_unordered_nonduplicating([]),
}
.into_model()
.checker()
.spawn_dfs()
.join();
checker.assert_properties();
#[rustfmt::skip]
checker.assert_discovery("value chosen", vec![
Deliver { src: 4.into(), dst: 1.into(), msg: Put(4, 'B') },
Deliver { src: 1.into(), dst: 0.into(), msg: Internal(Prepare { ballot: (1, 1.into()) }) },
Deliver { src: 0.into(), dst: 1.into(), msg: Internal(Prepared { ballot: (1, 1.into()), last_accepted: None }) },
Deliver { src: 1.into(), dst: 2.into(), msg: Internal(Accept { ballot: (1, 1.into()), proposal: (4, 4.into(), 'B') }) },
Deliver { src: 2.into(), dst: 1.into(), msg: Internal(Accepted { ballot: (1, 1.into()) }) },
Deliver { src: 1.into(), dst: 4.into(), msg: PutOk(4) },
Deliver { src: 1.into(), dst: 2.into(), msg: Internal(Decided { ballot: (1, 1.into()), proposal: (4, 4.into(), 'B') }) },
Deliver { src: 4.into(), dst: 2.into(), msg: Get(8) }
]);
assert_eq!(checker.unique_state_count(), 16_668);
}
fn main() -> Result<(), pico_args::Error> {
use stateright::actor::spawn;
use std::net::{Ipv4Addr, SocketAddrV4};
env_logger::init_from_env(env_logger::Env::default().default_filter_or("info")); // `RUST_LOG=${LEVEL}` env variable to override
let mut args = pico_args::Arguments::from_env();
match args.subcommand()?.as_deref() {
Some("check") => {
let client_count = args.opt_free_from_str()?.unwrap_or(2);
let network = args
.opt_free_from_str()?
.unwrap_or(Network::new_unordered_nonduplicating([]));
println!(
"Model checking Single Decree Paxos with {} clients.",
client_count
);
PaxosModelCfg {
client_count,
server_count: 3,
network,
}
.into_model()
.checker()
.threads(num_cpus::get())
.spawn_dfs()
.report(&mut WriteReporter::new(&mut std::io::stdout()));
}
Some("explore") => {
let client_count = args.opt_free_from_str()?.unwrap_or(2);
let address = args
.opt_free_from_str()?
.unwrap_or("localhost:3000".to_string());
let network = args
.opt_free_from_str()?
.unwrap_or(Network::new_unordered_nonduplicating([]));
println!(
"Exploring state space for Single Decree Paxos with {} clients on {}.",
client_count, address
);
PaxosModelCfg {
client_count,
server_count: 3,
network,
}
.into_model()
.checker()
.threads(num_cpus::get())
.serve(address);
}
Some("spawn") => {
let port = 3000;
println!(" A set of servers that implement Single Decree Paxos.");
println!(" You can monitor and interact using tcpdump and netcat.");
println!(" Use `tcpdump -D` if you see error `lo0: No such device exists`.");
println!("Examples:");
println!("$ sudo tcpdump -i lo0 -s 0 -nnX");
println!("$ nc -u localhost {}", port);
println!(
"{}",
serde_json::to_string(&RegisterMsg::Put::<RequestId, Value, ()>(1, 'X')).unwrap()
);
println!(
"{}",
serde_json::to_string(&RegisterMsg::Get::<RequestId, Value, ()>(2)).unwrap()
);
println!();
// WARNING: Omits `ordered_reliable_link` to keep the message
// protocol simple for `nc`.
let id0 = Id::from(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port));
let id1 = Id::from(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port + 1));
let id2 = Id::from(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port + 2));
spawn(
serde_json::to_vec,
|bytes| serde_json::from_slice(bytes),
vec![
(
id0,
PaxosActor {
peer_ids: vec![id1, id2],
},
),
(
id1,
PaxosActor {
peer_ids: vec![id0, id2],
},
),
(
id2,
PaxosActor {
peer_ids: vec![id0, id1],
},
),
],
)
.unwrap();
}
_ => {
println!("USAGE:");
println!(" ./paxos check [CLIENT_COUNT] [NETWORK]");
println!(" ./paxos explore [CLIENT_COUNT] [ADDRESS] [NETWORK]");
println!(" ./paxos spawn");
println!(
"NETWORK: {}",
Network::<<PaxosActor as Actor>::Msg>::names().join(" | ")
);
}
}
Ok(())
}
|
use std::collections::HashMap;
use std::fmt;
use crate::ast::{Script, Expr};
#[derive(Debug)]
pub enum CombineError {
DuplicateDecl(String),
NoSuchDecl(String),
Recursion(String),
}
#[derive(Clone, Debug)]
pub struct Program {
pub order: Vec<String>,
pub funcs: HashMap<String, Func>,
}
#[derive(Clone, Debug)]
pub struct Func {
pub args: Vec<(String, Expr)>,
pub ret: Expr,
pub body: Expr,
pub prelude: bool,
}
enum Visited {
Visiting,
Visited,
}
pub fn combine(prelude_script: &Script, main_script: &Script) -> Result<Program, CombineError> {
let mut funcs = HashMap::new();
for ((name, decl), prelude) in prelude_script.decls.iter().map(|d|(d,true)).chain(main_script.decls.iter().map(|d|(d,false))) {
if funcs.contains_key(name) {
return Err(CombineError::DuplicateDecl(name.clone()));
}
funcs.insert(name.clone(), Func {
args: decl.args.clone(),
ret: decl.ret.clone(),
body: decl.body.clone(),
prelude
});
}
let prelude_order:Vec<_> = prelude_script.decls.iter().map(|d|d.0.clone()).collect();
let mut visits = HashMap::new();
for name in &prelude_order {
visits.insert(name.clone(), Visited::Visited);
}
let mut program = Program {
order: prelude_order,
funcs,
};
for (name,_) in &main_script.decls {
visit_for_ordering(&mut program, name, &mut visits)?;
}
Ok(program)
}
fn visit_for_ordering(program: &mut Program, name: &str, visits: &mut HashMap<String,Visited>) -> Result<(), CombineError> {
if let Some(v) = visits.get(name) {
match v {
Visited::Visited => Ok(()),
Visited::Visiting => Err(CombineError::Recursion(name.to_owned())),
}
} else {
visits.insert(name.to_owned(), Visited::Visiting);
for dep in &get_dependencies(program, name)? {
visit_for_ordering(program, dep, visits)?;
}
visits.insert(name.to_owned(), Visited::Visited);
program.order.push(name.to_owned());
Ok(())
}
}
fn get_dependencies(program: &Program, name: &str) -> Result<Vec<String>, CombineError> {
if let Some(func) = program.funcs.get(name) {
let mut result = vec![];
for arg in &func.args {
add_dependencies(&arg.1, &mut result);
}
add_dependencies(&func.ret, &mut result);
add_dependencies(&func.body, &mut result);
Ok(result)
} else {
Err(CombineError::NoSuchDecl(name.to_owned()))
}
}
fn add_dependencies(expr: &Expr, result: &mut Vec<String>) {
match expr {
Expr::Int(_) => {}
Expr::Var(x) => {
if !result.contains(x) {
result.push(x.clone());
}
}
Expr::Call(f,xs) => {
if !result.contains(f) {
result.push(f.clone());
}
for x in xs {
add_dependencies(x, result);
}
}
Expr::Array(xs) => {
for x in xs {
add_dependencies(x, result);
}
}
}
}
impl fmt::Display for CombineError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Combine error {:?}", self)
}
}
impl std::error::Error for CombineError {}
|
//! Based on 'Go concurrency is not parallelism'
//! www.soroushjp.com/2015/02/07/go-concurrency-is-not-parallelism-real-world-lessons-with-monte-carlo-simulations/
#![feature(test)]
extern crate test;
extern crate num_cpus;
extern crate rand;
use std::thread;
use rand::distributions::{IndependentSample, Range};
// The number of samples to take to estimate Pi.
pub static DEFAULT_NUMBER_OF_SAMPLES: usize = 1_000_000;
// Estimate Pi by taking random samples.
pub fn pi(samples: usize) -> f64
{
let mut inside_circle = 0;
let mut rng = rand::thread_rng();
let range = Range::new(-1.0, 1.0);
for _ in (0..samples)
{
let x: f64 = range.ind_sample(&mut rng);
let y: f64 = range.ind_sample(&mut rng);
if x*x + y*y <= 1.0
{
inside_circle += 1;
}
}
4.0 * (inside_circle as f64) / (samples as f64)
}
// Estimate Pi in parallel!
pub fn parallel_pi(samples: usize, num_threads: usize) -> f64
{
let samples_per_thread = samples / num_threads;
let guards: Vec<_> = (0..num_threads).map(|_| {
thread::spawn(move || { pi(samples_per_thread) })
}).collect();
let sum = guards.into_iter()
.fold(0.0, |sum, g| g.join().unwrap() + sum);
sum / (num_threads as f64)
}
fn main()
{
let iterations = DEFAULT_NUMBER_OF_SAMPLES;
let num_threads = num_cpus::get();
let pi_estimate = parallel_pi(iterations, num_threads);
println!("Pi after {} iterations using {} threads: {}",
iterations, num_threads, pi_estimate);
}
#[cfg(test)]
mod tests
{
extern crate num_cpus;
use super::*;
use test::Bencher;
// The number of threads to spawn
static DEFAULT_NUMER_OF_THREADS: usize = 2;
#[test]
fn test_calculate_pi()
{
let expected_pi = 3.1415;
let delta = 0.01;
let estimate = pi(DEFAULT_NUMBER_OF_SAMPLES);
assert!((estimate - expected_pi).abs() <= delta);
}
#[test]
fn test_parallel_calculate_pi()
{
let expected_pi = 3.1415;
let delta = 0.01;
let estimate = parallel_pi(DEFAULT_NUMBER_OF_SAMPLES,
DEFAULT_NUMER_OF_THREADS);
assert!((estimate - expected_pi).abs() <= delta);
}
#[bench]
fn bench_calculate_pi(b: &mut Bencher)
{
b.iter(|| {
pi(DEFAULT_NUMBER_OF_SAMPLES)
})
}
#[bench]
fn bench_calculate_parallel_pi(b: &mut Bencher)
{
b.iter(|| {
parallel_pi(DEFAULT_NUMBER_OF_SAMPLES,
num_cpus::get());
})
}
}
|
use std::boxed::Box;
use std::rc::Rc;
pub mod graphics;
use graphics::{Graphic, GraphicContext};
mod pdf;
use pdf::{Dict, Name, ObjRef, Object, PDFData};
pub struct PDF {
pages: Vec<Page>,
writer: pdf::PDFWrite,
catalog: Rc<ObjRef<Dict>>,
outlines: Rc<ObjRef<Dict>>,
pages_obj: Rc<ObjRef<Dict>>,
}
impl PDF {
/// Creates a new PDF file with the given output writer
pub fn new(out: Box<dyn std::io::Write>) -> Self {
let mut writer = pdf::PDFWrite::new(out);
let outlines = ObjRef::new(
0,
Dict::from_vec(vec![("Type", Name::new("Outlines")), ("Count", Rc::new(0))]),
);
writer.add_object(outlines.clone());
let pages_obj = ObjRef::new(0, Dict::from_vec(vec![("Type", Name::new("Pages"))]));
writer.add_object(pages_obj.clone());
Self {
pages: vec![],
catalog: writer.create_root(Dict::from_vec(vec![
("Type", Name::new("Catalog")),
("Outlines", outlines.clone()),
("Pages", pages_obj.clone()),
])),
outlines,
pages_obj,
writer,
}
}
/// Creates a new PDF file, using the file as a writer to write to
pub fn from_file(file: std::fs::File) -> Self {
Self::new(Box::new(file))
}
/// Adds a page to the PDF
///
/// The page is consumed, and may (or may not)
/// be written to the output right away.
pub fn add_page(&mut self, page: Page) {
self.pages.push(page);
}
/// Completes the writing process
///
/// TODO: this may be added to a drop implementation
pub fn write(mut self) -> std::io::Result<()> {
let (pg_obj, tmp) = (&mut self.pages_obj, &mut self.writer);
let p: Vec<Rc<dyn Object>> = self
.pages
.into_iter()
.map(|p| tmp.add_object(p.render(pg_obj.clone())))
.collect();
self.pages_obj.add_entry("Count", Rc::new(p.len()));
self.pages_obj.add_entry("Kids", Rc::new(p));
self.writer.write()
}
}
pub struct Page {
// elements: Vec<Box<dyn Graphic>>,
graphics: GraphicContext,
}
impl Page {
pub fn new() -> Self {
Self {
// elements: vec![],
graphics: GraphicContext::new(),
}
}
pub fn add(&mut self, g: Rc<impl Graphic>) {
self.graphics.render(g);
}
fn render(self, parent: Rc<dyn PDFData>) -> Rc<dyn Object> {
let (streams, resources) = self.graphics.compile();
if streams.len() == 1 {
ObjRef::new(
0,
Dict::from_vec(vec![
("Type", Name::new("Page")),
("Parent", parent),
(
"MediaBox",
graphics::Rect::new(0f64, 0f64, 612f64, 792f64).as_data(),
),
("Contents", streams[0].clone()),
("Resources", resources),
]),
)
} else {
ObjRef::new(
0,
Dict::from_vec(vec![
("Type", Name::new("Page")),
("Parent", parent),
(
"MediaBox",
graphics::Rect::new(0f64, 0f64, 612f64, 792f64).as_data(),
),
("Contents", Rc::new(streams.clone())),
("Resources", resources),
]),
)
}
}
}
|
// some convenience macros
#[macro_export]
macro_rules! clone_all {
($($i:ident),+) => {
$(let $i = $i.clone();)+
}
}
#[macro_export]
macro_rules! clone_mut {
($($i:ident),+) => {
$(let mut $i = $i.clone();)+
}
}
|
#[allow(unused_imports)]
use proconio::{
input, fastout,
};
fn solve(n: usize, p: Vec<Vec<f64>>) -> String {
for i in 0..(n - 2) {
for j in (i + 1)..(n - 1) {
for k in (j + 1)..n {
if check_straight(&p[i], &p[j], &p[k]) {
return "Yes".to_string();
}
}
}
}
"No".to_string()
}
fn check_straight(p1: &Vec<f64>, p2: &Vec<f64>, p3: &Vec<f64>) -> bool {
let vec_x: Vec<f64> = vec![p1[0] - p2[0], p1[1] - p2[1]];
let vec_y: Vec<f64> = vec![p2[0] - p3[0], p2[1] - p3[1]];
if vec_x[0] / vec_y[0] == vec_x[1] / vec_y[1] {
return true;
} else {
return false;
}
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
input! {
n: usize, p: [[f64; 2]; n],
}
println!("{}", solve(n, p));
Ok(())
}
fn main() {
match run() {
Err(err) => panic!("{}", err),
_ => (),
};
}
|
//!
//! Traits for generics
//!
use crate::internal::Generics;
use crate::Generic;
/// Provides methods to add generics to elements.
pub trait GenericExt {
/// Add a single generic.
fn add_generic(&mut self, generic: Generic) -> &mut Self;
/// Add multiple generics at once.
fn add_generics<'a>(&mut self, generics: impl IntoIterator<Item = &'a Generic>) -> &mut Self;
}
impl<T: Generics> GenericExt for T {
/// Add a single generic.
fn add_generic(&mut self, generic: Generic) -> &mut Self {
self.generics_mut().push(generic);
self
}
/// Add multiple generics at once.
fn add_generics<'a>(&mut self, generics: impl IntoIterator<Item = &'a Generic>) -> &mut Self {
self.generics_mut()
.extend(generics.into_iter().map(ToOwned::to_owned));
self
}
}
|
use std::collections::HashMap;
// External uses
use futures::{FutureExt, TryFutureExt};
use jsonrpc_core::Error;
use jsonrpc_derive::rpc;
// Workspace uses
use models::node::{
tx::{TxEthSignature, TxHash},
Address, FranklinTx, Token, TokenLike, TxFeeTypes,
};
// use storage::{
// chain::{
// block::records::BlockDetails, operations::records::StoredExecutedPriorityOperation,
// operations_ext::records::TxReceiptResponse,
// },
// ConnectionPool, StorageProcessor,
// };
// Local uses
use crate::fee_ticker::{BatchFee, Fee};
use bigdecimal::BigDecimal;
use super::{types::*, RpcApp};
use std::time::Instant;
pub type FutureResp<T> = Box<dyn futures01::Future<Item = T, Error = Error> + Send>;
#[rpc]
pub trait Rpc {
#[rpc(name = "account_info", returns = "AccountInfoResp")]
fn account_info(&self, addr: Address) -> FutureResp<AccountInfoResp>;
#[rpc(name = "ethop_info", returns = "ETHOpInfoResp")]
fn ethop_info(&self, serial_id: u32) -> FutureResp<ETHOpInfoResp>;
#[rpc(name = "tx_info", returns = "ETHOpInfoResp")]
fn tx_info(&self, hash: TxHash) -> FutureResp<TransactionInfoResp>;
#[rpc(name = "tx_submit", returns = "TxHash")]
fn tx_submit(
&self,
tx: Box<FranklinTx>,
signature: Box<Option<TxEthSignature>>,
fast_processing: Option<bool>,
) -> FutureResp<TxHash>;
#[rpc(name = "submit_txs_batch", returns = "Vec<TxHash>")]
fn submit_txs_batch(&self, txs: Vec<TxWithSignature>) -> FutureResp<Vec<TxHash>>;
#[rpc(name = "contract_address", returns = "ContractAddressResp")]
fn contract_address(&self) -> FutureResp<ContractAddressResp>;
/// "ETH" | #ERC20_ADDRESS => {Token}
#[rpc(name = "tokens", returns = "Token")]
fn tokens(&self) -> FutureResp<HashMap<String, Token>>;
#[rpc(name = "get_tx_fee", returns = "Fee")]
fn get_tx_fee(
&self,
tx_type: TxFeeTypes,
address: Address,
token_like: TokenLike,
) -> FutureResp<Fee>;
#[rpc(name = "get_txs_batch_fee_in_wei", returns = "BatchFee")]
fn get_txs_batch_fee_in_wei(
&self,
tx_types: Vec<TxFeeTypes>,
addresses: Vec<Address>,
token_like: TokenLike,
) -> FutureResp<BatchFee>;
#[rpc(name = "get_token_price", returns = "BigDecimal")]
fn get_token_price(&self, token_like: TokenLike) -> FutureResp<BigDecimal>;
#[rpc(name = "get_confirmations_for_eth_op_amount", returns = "u64")]
fn get_confirmations_for_eth_op_amount(&self) -> FutureResp<u64>;
}
impl Rpc for RpcApp {
fn account_info(&self, addr: Address) -> FutureResp<AccountInfoResp> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle.spawn(self_._impl_account_info(addr)).await.unwrap()
};
Box::new(resp.boxed().compat())
}
fn ethop_info(&self, serial_id: u32) -> FutureResp<ETHOpInfoResp> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle
.spawn(self_._impl_ethop_info(serial_id))
.await
.unwrap()
};
Box::new(resp.boxed().compat())
}
fn tx_info(&self, hash: TxHash) -> FutureResp<TransactionInfoResp> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle.spawn(self_._impl_tx_info(hash)).await.unwrap()
};
Box::new(resp.boxed().compat())
}
fn tx_submit(
&self,
tx: Box<FranklinTx>,
signature: Box<Option<TxEthSignature>>,
fast_processing: Option<bool>,
) -> FutureResp<TxHash> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle
.spawn(self_._impl_tx_submit(tx, signature, fast_processing))
.await
.unwrap()
};
Box::new(resp.boxed().compat())
}
fn submit_txs_batch(&self, txs: Vec<TxWithSignature>) -> FutureResp<Vec<TxHash>> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle
.spawn(self_._impl_submit_txs_batch(txs))
.await
.unwrap()
};
Box::new(resp.boxed().compat())
}
fn contract_address(&self) -> FutureResp<ContractAddressResp> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle.spawn(self_._impl_contract_address()).await.unwrap()
};
Box::new(resp.boxed().compat())
}
fn tokens(&self) -> FutureResp<HashMap<String, Token>> {
let timer = Instant::now();
let self_ = self.clone();
log::trace!("Clone timer: {} ms", timer.elapsed().as_millis());
let resp = async move {
let timer = Instant::now();
let handle = self_.tokio_runtime.clone();
let res = handle.spawn(self_._impl_tokens()).await.unwrap();
log::trace!("Token impl timer: {} ms", timer.elapsed().as_millis());
res
};
Box::new(resp.boxed().compat())
}
fn get_tx_fee(
&self,
tx_type: TxFeeTypes,
address: Address,
token_like: TokenLike,
) -> FutureResp<Fee> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle
.spawn(self_._impl_get_tx_fee(tx_type, address, token_like))
.await
.unwrap()
};
Box::new(resp.boxed().compat())
}
fn get_txs_batch_fee_in_wei(
&self,
tx_types: Vec<TxFeeTypes>,
addresses: Vec<Address>,
token_like: TokenLike,
) -> FutureResp<BatchFee> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle
.spawn(self_._impl_get_txs_batch_fee_in_wei(tx_types, addresses, token_like))
.await
.unwrap()
};
Box::new(resp.boxed().compat())
}
fn get_token_price(&self, token_like: TokenLike) -> FutureResp<BigDecimal> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle
.spawn(self_._impl_get_token_price(token_like))
.await
.unwrap()
};
Box::new(resp.boxed().compat())
}
fn get_confirmations_for_eth_op_amount(&self) -> FutureResp<u64> {
let self_ = self.clone();
let resp = async move {
let handle = self_.tokio_runtime.clone();
handle
.spawn(self_._impl_get_confirmations_for_eth_op_amount())
.await
.unwrap()
};
Box::new(resp.boxed().compat())
}
}
|
use ptgui::prelude::*;
use raylib::prelude::*;
fn main() {
let (mut rl_handler, rl_thread) = raylib::init()
.size(1280, 720)
.title("Dropdown Test")
.build();
rl_handler.set_target_fps(60);
let mut g_handler = GuiHandler::<()>::new(Colour::WHITE);
g_handler
.add_slider(69, 420, 69.0)
.set_components_fix_widths(true)
.add_dropdown("Test")
.get_dropdowns_mut()
.unwrap()
.get_mut(0)
.unwrap()
.add_slider(0, 100, 50.0);
while !rl_handler.window_should_close() {
let mut draw_handler = g_handler.draw(&mut rl_handler, &rl_thread).unwrap();
draw_handler.draw_fps(0, 0);
}
}
|
//! Quadrature encoder interface
/// Quadrature encoder interface
///
/// # Examples
///
/// You can use this interface to measure the speed of a motor
///
/// ```
/// extern crate embedded_hal as hal;
/// #[macro_use(block)]
/// extern crate nb;
///
/// use hal::prelude::*;
///
/// fn main() {
/// let mut qei: Qei1 = {
/// // ..
/// # Qei1
/// };
/// let mut timer: Timer6 = {
/// // ..
/// # Timer6
/// };
///
///
/// let before = qei.try_count().unwrap();
/// timer.try_start(1.s()).unwrap();
/// block!(timer.try_wait());
/// let after = qei.try_count().unwrap();
///
/// let speed = after.wrapping_sub(before);
/// println!("Speed: {} pulses per second", speed);
/// }
///
/// # use core::convert::Infallible;
/// # struct Seconds(u32);
/// # trait U32Ext { fn s(self) -> Seconds; }
/// # impl U32Ext for u32 { fn s(self) -> Seconds { Seconds(self) } }
/// # struct Qei1;
/// # impl hal::qei::Qei for Qei1 {
/// # type Error = Infallible;
/// # type Count = u16;
/// # fn try_count(&self) -> Result<u16, Self::Error> { Ok(0) }
/// # fn try_direction(&self) -> Result<::hal::qei::Direction, Self::Error> { unimplemented!() }
/// # }
/// # struct Timer6;
/// # impl hal::timer::CountDown for Timer6 {
/// # type Error = Infallible;
/// # type Time = Seconds;
/// # fn try_start<T>(&mut self, _: T) -> Result<(), Infallible> where T: Into<Seconds> { Ok(()) }
/// # fn try_wait(&mut self) -> ::nb::Result<(), Infallible> { Ok(()) }
/// # }
/// ```
// unproven reason: needs to be re-evaluated in the new singletons world. At the very least this needs a
// reference implementation
pub trait Qei {
/// Enumeration of `Qei` errors
type Error;
/// The type of the value returned by `count`
type Count;
/// Returns the current pulse count of the encoder
fn try_count(&self) -> Result<Self::Count, Self::Error>;
/// Returns the count direction
fn try_direction(&self) -> Result<Direction, Self::Error>;
}
/// Count direction
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Direction {
/// 3, 2, 1
Downcounting,
/// 1, 2, 3
Upcounting,
}
|
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn nextafterf(x: f32, y: f32) -> f32 {
if x.is_nan() || y.is_nan() {
return x + y;
}
let mut ux_i = x.to_bits();
let uy_i = y.to_bits();
if ux_i == uy_i {
return y;
}
let ax = ux_i & 0x7fff_ffff_u32;
let ay = uy_i & 0x7fff_ffff_u32;
if ax == 0 {
if ay == 0 {
return y;
}
ux_i = (uy_i & 0x8000_0000_u32) | 1;
} else if ax > ay || ((ux_i ^ uy_i) & 0x8000_0000_u32) != 0 {
ux_i -= 1;
} else {
ux_i += 1;
}
let e = ux_i.wrapping_shr(0x7f80_0000_u32);
// raise overflow if ux_f is infinite and x is finite
if e == 0x7f80_0000_u32 {
force_eval!(x + x);
}
let ux_f = f32::from_bits(ux_i);
// raise underflow if ux_f is subnormal or zero
if e == 0 {
force_eval!(x * x + ux_f * ux_f);
}
ux_f
}
|
use std::{io, fs};
use std::fs::File;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::default::Default;
use std::io::Write;
use liquid::{Renderable, LiquidOptions, Context, Value};
use markdown;
use liquid;
#[derive(Debug)]
pub struct Document {
pub name: String,
pub attributes: HashMap<String, String>,
pub content: String,
markdown: bool,
}
impl Document {
pub fn new(name: String,
attributes: HashMap<String, String>,
content: String,
markdown: bool)
-> Document {
Document {
name: name,
attributes: attributes,
content: content,
markdown: markdown,
}
}
pub fn get_attributes(&self) -> HashMap<String, Value> {
let mut data = HashMap::new();
for key in self.attributes.keys() {
if let Some(val) = self.attributes.get(key) {
data.insert(key.to_owned(), Value::Str(val.clone()));
}
}
data
}
pub fn as_html(&self, post_data: &Vec<Value>) -> Result<String, String> {
let mut options: LiquidOptions = Default::default();
let template = try!(liquid::parse(&self.content, &mut options));
// TODO: pass in documents as template data if as_html is called on Index Document..
let mut data = Context::with_values(self.get_attributes());
data.set_val("posts", Value::Array(post_data.clone()));
Ok(template.render(&mut data).unwrap_or(String::new()))
}
pub fn create_file(&self,
dest: &Path,
layouts: &HashMap<String, String>,
post_data: &Vec<Value>)
-> io::Result<()> {
// construct target path
let mut file_path_buf = PathBuf::new();
file_path_buf.push(dest);
file_path_buf.push(&self.name);
file_path_buf.set_extension("html");
let file_path = file_path_buf.as_path();
let layout_path = self.attributes.get(&"@extends".to_owned()).expect(&format!("No @extends line creating {:?}", self.name));
let layout = layouts.get(layout_path).expect(&format!("No layout path {:?} creating {:?}", layout_path, self.name));
// create target directories if any exist
match file_path.parent() {
Some(ref parents) => try!(fs::create_dir_all(parents)),
None => (),
};
let mut file = try!(File::create(&file_path));
let mut data = Context::new();
// TODO: improve error handling for liquid errors
let mut html = match self.as_html(post_data) {
Ok(x) => x,
Err(e) => {
println!("Warning, liquid failed: {}", e);
String::new()
}
};
if self.markdown {
html = markdown::to_html(&html);
}
data.set_val("content", Value::Str(html));
// Insert the attributes into the layout template
for key in self.attributes.keys() {
if let Some(val) = self.attributes.get(key) {
data.set_val(key, Value::Str(val.clone()));
}
}
let mut options: LiquidOptions = Default::default();
// TODO: improve error handling for liquid errors
let template = match liquid::parse(&layout, &mut options) {
Ok(x) => x,
Err(e) => {
panic!("Warning, liquid failed: {}", e);
}
};
let res = template.render(&mut data).unwrap_or(String::new());
println!("Created {}", file_path.display());
file.write_all(&res.into_bytes())
}
}
|
use std::io;
use std::path::Path;
use std::process::{Command, Stdio};
use rayon::prelude::*;
#[derive(Debug, Deserialize, Eq, Hash)]
pub struct Repo {
pub name: String,
pub html_url: String,
pub ssh_url: String,
pub namespace: String,
pub branch: String,
}
impl Repo {
pub fn get_url(&self) -> &str {
&self.html_url
}
pub fn get_ssh_url(&self) -> &str {
&self.ssh_url
}
}
impl PartialEq for Repo {
fn eq(&self, other: &Repo) -> bool {
&self.name == &other.name
}
}
#[derive(Debug, Fail)]
pub enum GitError {
#[fail(display = "unable to spawn command: {}", why)]
CommandSpawn { why: io::Error },
#[fail(display = "returned an exit status of {}", status)]
Failed { status: i32 }
}
fn git_cmd(args: &[&str], name: &str) -> Result<String, (String, GitError)> {
match Command::new("git").args(args).stdout(Stdio::null()).status() {
Ok(status) => if status.success() {
Ok(name.to_owned())
} else {
Err((name.to_owned(), GitError::Failed { status: status.code().unwrap_or(1) }))
},
Err(why) => Err((name.to_owned(), GitError::CommandSpawn { why }))
}
}
fn parallel_process<M, E, N>(repos: Vec<Repo>, flags: u8, namespace: &str, message: M, exists: E, new: N)
where M: Sync + Send + Fn(&Repo),
E: Sync + Send + Fn(&Repo, &str) -> Result<String, (String, GitError)>,
N: Sync + Send + Fn(&Repo, &str) -> Result<String, (String, GitError)>,
{
let results = repos
.par_iter()
.filter(|repo| namespace == "" || repo.namespace == namespace)
.inspect(|repo| message(repo))
.map(|repo| {
let url = if flags & 0b01 != 0 { repo.get_ssh_url() } else { repo.get_url() };
if Path::new(&repo.name).exists() {
exists(repo, url)
} else {
new(repo, url)
}
})
.collect::<Vec<Result<String, (String, GitError)>>>();
for result in results {
match result {
Ok(repo) => println!("successfully cloned {}", repo),
Err((repo, why)) => println!("failed to clone {}: {}", repo, why)
}
}
}
pub trait GitAction {
fn get_repos(&self) -> Vec<Repo>;
fn list(&self, namespace: &str) {
let repos = self.get_repos();
let repos = repos.iter()
.filter(|repo| namespace == "" || repo.namespace == namespace);
for repo in repos {
println!("{}: {}", repo.name, repo.ssh_url);
}
}
fn clone(&self, flags: u8, namespace: &str) {
parallel_process(
self.get_repos(),
flags,
namespace,
// Message to print before processing repo
|repo| println!("cloning {} from {}", repo.name, repo.get_url()),
// If repo already exists, do this
|repo, _url| Ok(repo.name.clone()),
// Else, do this
|repo, url| git_cmd(&["clone", "--recursive", url, &repo.name], &repo.name)
)
}
fn pull(&self, flags: u8, namespace: &str) {
parallel_process(
self.get_repos(),
flags,
namespace,
|repo| println!("pulling {} from {}", repo.name, repo.get_url()),
|repo, _url| {
git_cmd(&["-C", &repo.name, "pull"], &repo.name)
.and_then(|_| git_cmd(&["-C", &repo.name, "submodule", "sync", "--recursive"], &repo.name))
.and_then(|_| git_cmd(&["-C", &repo.name, "submodule", "update", "--init"], &repo.name))
},
|repo, url| git_cmd(&["clone", "--recursive", url, &repo.name], &repo.name)
)
}
fn checkout(&self, flags: u8, namespace: &str) {
parallel_process(
self.get_repos(),
flags,
namespace,
|repo| println!("checking out {} from {}", repo.name, repo.get_url()),
|repo, _url| {
git_cmd(&["-C", &repo.name, "fetch", "origin"], &repo.name)
.and_then(|_| git_cmd(&["-C", &repo.name, "checkout", "-B", &repo.branch, &format!("origin/{}", repo.branch)], &repo.name))
.and_then(|_| git_cmd(&["-C", &repo.name, "submodule", "sync", "--recursive"], &repo.name))
.and_then(|_| git_cmd(&["-C", &repo.name, "submodule", "update", "--init", "--recursive"], &repo.name))
},
|repo, url| git_cmd(&["clone", "--recursive", url, &repo.name], &repo.name)
)
}
fn mirror_pull(&self, flags: u8, namespace: &str) {
parallel_process(
self.get_repos(),
flags,
namespace,
|repo| println!("pulling mirror {} from {}", repo.name, repo.get_url()),
|repo, _url| git_cmd(&["-C", &repo.name, "remote", "update", "--prune"], &repo.name),
|repo, url| git_cmd(&["clone", "--mirror", url, &repo.name], &repo.name)
)
}
fn mirror_push(&self, flags: u8, namespace: &str) {
parallel_process(
self.get_repos(),
flags,
namespace,
|repo| println!("pushing mirror {} from {}", repo.name, repo.get_url()),
|repo, url| git_cmd(&["-C", &repo.name, "push", "--mirror", url], &repo.name),
|repo, url| git_cmd(&["-C", &repo.name, "push", "--mirror", url], &repo.name)
)
}
}
|
use crate::entry::context_switch::CURRENT_CONTEXT;
use crate::prelude::*;
pub fn do_arch_prctl(code: ArchPrctlCode, addr: *mut usize) -> Result<()> {
debug!("do_arch_prctl: code: {:?}, addr: {:?}", code, addr);
match code {
ArchPrctlCode::ARCH_SET_FS => {
CURRENT_CONTEXT.with(|context| {
context.borrow_mut().fs_base = addr as _;
});
}
ArchPrctlCode::ARCH_GET_FS => unsafe {
CURRENT_CONTEXT.with(|context| {
*addr = context.borrow_mut().fs_base as _;
});
},
ArchPrctlCode::ARCH_SET_GS | ArchPrctlCode::ARCH_GET_GS => {
return_errno!(EINVAL, "GS cannot be accessed from the user space");
}
}
Ok(())
}
#[allow(non_camel_case_types)]
#[derive(Debug)]
pub enum ArchPrctlCode {
ARCH_SET_GS = 0x1001,
ARCH_SET_FS = 0x1002,
ARCH_GET_FS = 0x1003,
ARCH_GET_GS = 0x1004,
}
impl ArchPrctlCode {
pub fn from_u32(bits: u32) -> Result<ArchPrctlCode> {
match bits {
0x1001 => Ok(ArchPrctlCode::ARCH_SET_GS),
0x1002 => Ok(ArchPrctlCode::ARCH_SET_FS),
0x1003 => Ok(ArchPrctlCode::ARCH_GET_FS),
0x1004 => Ok(ArchPrctlCode::ARCH_GET_GS),
_ => return_errno!(EINVAL, "Unknown code for arch_prctl"),
}
}
}
|
//! Default runtime
//!
//! By default, hyper includes the [tokio](https://tokio.rs) runtime. To ease
//! using it, several types are re-exported here.
//!
//! The inclusion of a default runtime can be disabled by turning off hyper's
//! `runtime` Cargo feature.
pub use futures::{Future, Stream};
pub use futures::future::{lazy, poll_fn};
use tokio;
use self::inner::Spawn;
/// Spawns a future on the default executor.
///
/// # Panics
///
/// This function will panic if the default executor is not set.
///
/// # Note
///
/// The `Spawn` return type is not currently meant for anything other than
/// to reserve adding new trait implementations to it later. It can be
/// ignored for now.
pub fn spawn<F>(f: F) -> Spawn
where
F: Future<Item=(), Error=()> + Send + 'static,
{
tokio::spawn(f);
Spawn {
_inner: (),
}
}
/// Start the Tokio runtime using the supplied future to bootstrap execution.
///
/// # Example
///
/// See the [server documentation](::server) for an example of its usage.
pub fn run<F>(f: F)
where
F: Future<Item=(), Error=()> + Send + 'static
{
tokio::run(f);
}
// Make the `Spawn` type an unnameable, so we can add
// methods or trait impls to it later without a breaking change.
mod inner {
#[allow(missing_debug_implementations)]
pub struct Spawn {
pub(super) _inner: (),
}
}
|
#[doc = "Reader of register MAPR2"]
pub type R = crate::R<u32, super::MAPR2>;
#[doc = "Writer for register MAPR2"]
pub type W = crate::W<u32, super::MAPR2>;
#[doc = "Register MAPR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::MAPR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TIM15_REMAP`"]
pub type TIM15_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM15_REMAP`"]
pub struct TIM15_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIM15_REMAP_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 `TIM16_REMAP`"]
pub type TIM16_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM16_REMAP`"]
pub struct TIM16_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIM16_REMAP_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 `TIM17_REMAP`"]
pub type TIM17_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM17_REMAP`"]
pub struct TIM17_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIM17_REMAP_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 `TIM13_REMAP`"]
pub type TIM13_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM13_REMAP`"]
pub struct TIM13_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIM13_REMAP_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 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `TIM14_REMAP`"]
pub type TIM14_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM14_REMAP`"]
pub struct TIM14_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIM14_REMAP_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `FSMC_NADV`"]
pub type FSMC_NADV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FSMC_NADV`"]
pub struct FSMC_NADV_W<'a> {
w: &'a mut W,
}
impl<'a> FSMC_NADV_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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `CEC_REMAP`"]
pub type CEC_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CEC_REMAP`"]
pub struct CEC_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> CEC_REMAP_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 `TIM1_DMA_REMAP`"]
pub type TIM1_DMA_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM1_DMA_REMAP`"]
pub struct TIM1_DMA_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIM1_DMA_REMAP_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 `TIM67_DAC_DMA_REMAP`"]
pub type TIM67_DAC_DMA_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM67_DAC_DMA_REMAP`"]
pub struct TIM67_DAC_DMA_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIM67_DAC_DMA_REMAP_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 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `TIM12_REMAP`"]
pub type TIM12_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM12_REMAP`"]
pub struct TIM12_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> TIM12_REMAP_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 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `MISC_REMAP`"]
pub type MISC_REMAP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MISC_REMAP`"]
pub struct MISC_REMAP_W<'a> {
w: &'a mut W,
}
impl<'a> MISC_REMAP_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 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
impl R {
#[doc = "Bit 0 - TIM15 remapping"]
#[inline(always)]
pub fn tim15_remap(&self) -> TIM15_REMAP_R {
TIM15_REMAP_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - TIM16 remapping"]
#[inline(always)]
pub fn tim16_remap(&self) -> TIM16_REMAP_R {
TIM16_REMAP_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - TIM17 remapping"]
#[inline(always)]
pub fn tim17_remap(&self) -> TIM17_REMAP_R {
TIM17_REMAP_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 8 - TIM13 remapping"]
#[inline(always)]
pub fn tim13_remap(&self) -> TIM13_REMAP_R {
TIM13_REMAP_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - TIM14 remapping"]
#[inline(always)]
pub fn tim14_remap(&self) -> TIM14_REMAP_R {
TIM14_REMAP_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - NADV connect/disconnect"]
#[inline(always)]
pub fn fsmc_nadv(&self) -> FSMC_NADV_R {
FSMC_NADV_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 3 - CEC remapping"]
#[inline(always)]
pub fn cec_remap(&self) -> CEC_REMAP_R {
CEC_REMAP_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - TIM1 DMA remapping"]
#[inline(always)]
pub fn tim1_dma_remap(&self) -> TIM1_DMA_REMAP_R {
TIM1_DMA_REMAP_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 11 - TIM67_DAC DMA remapping"]
#[inline(always)]
pub fn tim67_dac_dma_remap(&self) -> TIM67_DAC_DMA_REMAP_R {
TIM67_DAC_DMA_REMAP_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - TIM12 remapping"]
#[inline(always)]
pub fn tim12_remap(&self) -> TIM12_REMAP_R {
TIM12_REMAP_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Miscellaneous features remapping"]
#[inline(always)]
pub fn misc_remap(&self) -> MISC_REMAP_R {
MISC_REMAP_R::new(((self.bits >> 13) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM15 remapping"]
#[inline(always)]
pub fn tim15_remap(&mut self) -> TIM15_REMAP_W {
TIM15_REMAP_W { w: self }
}
#[doc = "Bit 1 - TIM16 remapping"]
#[inline(always)]
pub fn tim16_remap(&mut self) -> TIM16_REMAP_W {
TIM16_REMAP_W { w: self }
}
#[doc = "Bit 2 - TIM17 remapping"]
#[inline(always)]
pub fn tim17_remap(&mut self) -> TIM17_REMAP_W {
TIM17_REMAP_W { w: self }
}
#[doc = "Bit 8 - TIM13 remapping"]
#[inline(always)]
pub fn tim13_remap(&mut self) -> TIM13_REMAP_W {
TIM13_REMAP_W { w: self }
}
#[doc = "Bit 9 - TIM14 remapping"]
#[inline(always)]
pub fn tim14_remap(&mut self) -> TIM14_REMAP_W {
TIM14_REMAP_W { w: self }
}
#[doc = "Bit 10 - NADV connect/disconnect"]
#[inline(always)]
pub fn fsmc_nadv(&mut self) -> FSMC_NADV_W {
FSMC_NADV_W { w: self }
}
#[doc = "Bit 3 - CEC remapping"]
#[inline(always)]
pub fn cec_remap(&mut self) -> CEC_REMAP_W {
CEC_REMAP_W { w: self }
}
#[doc = "Bit 4 - TIM1 DMA remapping"]
#[inline(always)]
pub fn tim1_dma_remap(&mut self) -> TIM1_DMA_REMAP_W {
TIM1_DMA_REMAP_W { w: self }
}
#[doc = "Bit 11 - TIM67_DAC DMA remapping"]
#[inline(always)]
pub fn tim67_dac_dma_remap(&mut self) -> TIM67_DAC_DMA_REMAP_W {
TIM67_DAC_DMA_REMAP_W { w: self }
}
#[doc = "Bit 12 - TIM12 remapping"]
#[inline(always)]
pub fn tim12_remap(&mut self) -> TIM12_REMAP_W {
TIM12_REMAP_W { w: self }
}
#[doc = "Bit 13 - Miscellaneous features remapping"]
#[inline(always)]
pub fn misc_remap(&mut self) -> MISC_REMAP_W {
MISC_REMAP_W { w: self }
}
}
|
extern crate imap;
extern crate mailparse;
extern crate native_tls;
extern crate notify_rust;
extern crate rayon;
extern crate systray;
extern crate toml;
extern crate xdg;
extern crate openssl;
use native_tls::{TlsConnector, TlsConnectorBuilder, TlsStream};
use native_tls::backend::openssl::TlsConnectorBuilderExt;
use openssl::ssl;
use openssl::x509::X509;
use imap::client::Client;
use rayon::prelude::*;
use std::process::Command;
use std::io::prelude::*;
use std::net::TcpStream;
use std::time::Duration;
use std::sync::mpsc;
use std::fs::File;
use std::thread;
#[derive(Clone)]
struct Account {
name: String,
server: (String, u16),
sni_domain: String,
server_cert_data: Option<Vec<u8>>,
username: String,
password: String, // TODO: this should not stay in memory
}
struct Connection<T: Read + Write> {
account: Account,
socket: Client<T>,
}
impl Account {
pub fn connect(&self) -> Result<Connection<TlsStream<TcpStream>>, imap::error::Error> {
let tls = match self.server_cert_data {
Some(ref pem_data) => {
let cert = X509::from_pem(pem_data).unwrap();
let mut ssl_cb = ssl::SslConnectorBuilder::new(ssl::SslMethod::tls()).unwrap();
// the certificate needs to be injected directly into the store, there's no API for loading in-memory certs
ssl_cb.builder_mut().cert_store_mut().add_cert(cert).expect("Failed to add cert");
TlsConnectorBuilder::from_openssl(ssl_cb)
}
None => TlsConnector::builder()?
}.build()?;
let mut conn = Client::connect((&*self.server.0, self.server.1))?;
if !conn.capability()?.iter().any(|c| c == "STARTTLS") {
panic!("STARTTLS not in capabilities");
}
let mut conn = conn.secure(&self.sni_domain, tls).unwrap();
conn.login(&self.username, &self.password)?;
if !conn.capability()?.iter().any(|c| c == "IDLE") {
panic!("IDLE not in capabilities");
}
try!(conn.select("INBOX"));
Ok(Connection {
account: self.clone(),
socket: conn,
})
}
}
impl<T: Read + Write + imap::client::SetReadTimeout> Connection<T> {
pub fn handle(mut self, account: usize, mut tx: mpsc::Sender<(usize, usize)>) {
loop {
if let Err(_) = self.check(account, &mut tx) {
// the connection has failed for some reason
// try to log out (we probably can't)
self.socket.logout().is_err();
break;
}
}
// try to reconnect
let mut wait = 1;
for _ in 0..5 {
println!(
"connection to {} lost; trying to reconnect...",
self.account.name
);
match self.account.connect() {
Ok(c) => {
println!("{} connection reestablished", self.account.name);
return c.handle(account, tx);
}
Err(imap::error::Error::Io(_)) => {
thread::sleep(Duration::from_secs(wait));
}
Err(_) => break,
}
wait *= 2;
}
}
fn check(
&mut self,
account: usize,
tx: &mut mpsc::Sender<(usize, usize)>,
) -> Result<(), imap::error::Error> {
// Keep track of all the e-mails we have already notified about
let mut last_notified = 0;
loop {
// check current state of inbox
let mut unseen = self.socket
.run_command_and_read_response("UID SEARCH UNSEEN 1:*")?;
// remove last line of response (OK Completed)
unseen.pop();
let mut num_unseen = 0;
let mut uids = Vec::new();
let unseen = unseen.join(" ");
let unseen = unseen.split_whitespace().skip(2);
for uid in unseen.take_while(|&e| e != "" && e != "Completed") {
if let Ok(uid) = usize::from_str_radix(uid, 10) {
if uid > last_notified {
last_notified = uid;
uids.push(format!("{}", uid));
}
num_unseen += 1;
}
}
let mut subjects = Vec::new();
if !uids.is_empty() {
let mut finish = |message: &[u8]| -> bool {
match mailparse::parse_headers(message) {
Ok((headers, _)) => {
use mailparse::MailHeaderMap;
match headers.get_first_value("Subject") {
Ok(Some(subject)) => {
subjects.push(subject);
return true;
}
Ok(None) => {
subjects.push(String::from("<no subject>"));
return true;
}
Err(e) => {
println!("failed to get message subject: {:?}", e);
}
}
}
Err(e) => println!("failed to parse headers of message: {:?}", e),
}
false
};
let lines = self.socket.uid_fetch(&uids.join(","), "RFC822.HEADER")?;
let mut message = Vec::new();
for line in &lines {
if line.starts_with("* ") {
if !message.is_empty() {
finish(&message[..]);
message.clear();
}
continue;
}
message.extend(line.as_bytes());
}
finish(&message[..]);
}
if !subjects.is_empty() {
use notify_rust::{Notification, NotificationHint};
let title = format!(
"@{} has new mail ({} unseen)",
self.account.name,
num_unseen
);
let notification = format!("> {}", subjects.join("\n> "));
println!("! {}", title);
println!("{}", notification);
Notification::new()
.summary(&title)
.body(¬ification)
.icon("notification-message-email")
.hint(NotificationHint::Category("email".to_owned()))
.timeout(-1)
.show()
.expect("failed to launch notify-send");
}
tx.send((account, num_unseen)).unwrap();
// IDLE until we see changes
self.socket.idle()?.wait_keepalive()?;
}
}
}
fn main() {
// Load the user's config
let xdg = match xdg::BaseDirectories::new() {
Ok(xdg) => xdg,
Err(e) => {
println!("Could not find configuration file buzz.toml: {}", e);
return;
}
};
let config = match xdg.find_config_file("buzz.toml") {
Some(config) => config,
None => {
println!("Could not find configuration file buzz.toml");
return;
}
};
let config = {
let mut f = match File::open(config) {
Ok(f) => f,
Err(e) => {
println!("Could not open configuration file buzz.toml: {}", e);
return;
}
};
let mut s = String::new();
if let Err(e) = f.read_to_string(&mut s) {
println!("Could not read configuration file buzz.toml: {}", e);
return;
}
match s.parse::<toml::Value>() {
Ok(t) => t,
Err(e) => {
println!("Could not parse configuration file buzz.toml: {}", e);
return;
}
}
};
// Figure out what accounts we have to deal with
let accounts: Vec<_> = match config.as_table() {
Some(t) => t.iter()
.filter_map(|(name, v)| match v.as_table() {
None => {
println!("Configuration for account {} is broken: not a table", name);
None
}
Some(t) => {
let pwcmd = match t.get("pwcmd").and_then(|p| p.as_str()) {
None => return None,
Some(pwcmd) => pwcmd,
};
let password = Command::new("sh")
.arg("-c")
.arg(pwcmd)
.output()
.map(|output| {
if !output.status.success() {
panic!("Command failed: {}", pwcmd)
}
let s = String::from_utf8(output.stdout).expect("Password is not utf-8");
s.trim_right_matches('\n').to_owned()
})
.map_err(|e| panic!("Failed to launch password command for {}: {}", name, e))
.unwrap();
let pem_data = t.get("server_cert")
.map(|v| v.as_str().expect("Server cert must be a string"))
.map(|path| {
let mut f = File::open(path).expect(&format!("Could not open {}", path));
let mut pem = Vec::new();
f.read_to_end(&mut pem).expect(&format!("Failed to read {}", path));
pem
});
if let &Some(ref p) = &pem_data {
X509::from_pem(p).expect(&format!("Cert in {} is not PEM", name)); // X509 is not Send, and therefore can't be used later on while connecting
}
let server_name = t["server"].as_str().unwrap();
Some(Account {
name: name.as_str().to_owned(),
server: (
server_name.to_owned(),
t["port"].as_integer().unwrap() as u16,
),
sni_domain: match t.get("sni_domain") {
Some(data) => data.as_str().unwrap().to_owned(),
None => server_name.to_owned(),
},
server_cert_data: pem_data,
username: t["username"].as_str().unwrap().to_owned(),
password: password,
})
}
})
.collect(),
None => {
println!("Could not parse configuration file buzz.toml: not a table");
return;
}
};
if accounts.is_empty() {
println!("No accounts in config; exiting...");
return;
}
// Create a new application
let mut app = match systray::Application::new() {
Ok(app) => app,
Err(e) => {
println!("Could not create gtk application: {}", e);
return;
}
};
if let Err(e) = app.set_icon_from_file(&"/usr/share/icons/Faenza/stock/24/stock_disconnect.png"
.to_string())
{
println!("Could not set application icon: {}", e);
}
if let Err(e) = app.add_menu_item(&"Quit".to_string(), |window| {
window.quit();
}) {
println!("Could not add application Quit menu option: {}", e);
}
// TODO: w.set_tooltip(&"Whatever".to_string());
// TODO: app.wait_for_message();
let accounts: Vec<_> = accounts
.par_iter()
.filter_map(|account| {
let mut wait = 1;
for _ in 0..5 {
match account.connect() {
Ok(c) => return Some(c),
Err(imap::error::Error::Io(e)) => {
println!(
"Failed to connect account {}: {}; retrying in {}s",
account.name,
e,
wait
);
thread::sleep(Duration::from_secs(wait));
}
Err(e) => {
println!("{} host produced bad IMAP tunnel: {}", account.name, e);
break;
}
}
wait *= 2;
}
None
})
.collect();
if accounts.is_empty() {
println!("No accounts in config worked; exiting...");
return;
}
// We have now connected
app.set_icon_from_file(&"/usr/share/icons/Faenza/stock/24/stock_connect.png"
.to_string())
.ok();
let (tx, rx) = mpsc::channel();
let mut unseen: Vec<_> = accounts.iter().map(|_| 0).collect();
for (i, conn) in accounts.into_iter().enumerate() {
let tx = tx.clone();
thread::spawn(move || {
conn.handle(i, tx);
});
}
for (i, num_unseen) in rx {
unseen[i] = num_unseen;
if unseen.iter().sum::<usize>() == 0 {
app.set_icon_from_file(&"/usr/share/icons/oxygen/base/32x32/status/mail-unread.png"
.to_string())
.unwrap();
} else {
app.set_icon_from_file(
&"/usr/share/icons/oxygen/base/32x32/status/mail-unread-new.png".to_string(),
).unwrap();
}
}
}
|
#[cfg(feature = "ssl")]
extern crate openssl;
#[cfg(feature = "ssl")]
mod ssl;
mod tcp;
pub mod mock;
pub use tcp::{
NetworkOptions,
NetworkListener,
NetworkStream,
NetworkWriter,
NetworkReader
};
#[cfg(feature = "ssl")]
pub use ssl::{
SslContext,
SslStream,
SslError
};
#[cfg(not(feature = "ssl"))]
pub mod ssl {
use mock::MockStream;
use std::net::TcpStream;
use std::io;
use std::error::Error;
use std::path::Path;
pub type SslStream = MockStream;
pub type SslError = Error + 'static;
#[derive(Debug, Clone, Default)]
pub struct SslContext;
impl SslContext {
pub fn new(_: SslContext) -> Self {
panic!("ssl disabled");
}
pub fn with_cert_and_key<C, K, E>(_: C, _: K) -> Result<SslContext, E>
where C: AsRef<Path>, K: AsRef<Path>, E: Error + 'static {
panic!("ssl disabled");
}
pub fn accept(&self, _: TcpStream) -> Result<SslStream, io::Error> {
panic!("ssl disabled");
}
pub fn connect(&self, _: TcpStream) -> Result<SslStream, io::Error> {
panic!("ssl disabled");
}
}
}
|
use int::{Int, LargeInt};
macro_rules! ashl {
($intrinsic:ident: $ty:ty) => {
/// Returns `a << b`, requires `b < $ty::bits()`
#[cfg_attr(not(test), no_mangle)]
#[cfg_attr(all(not(test), not(target_arch = "arm")), no_mangle)]
#[cfg_attr(all(not(test), target_arch = "arm"), inline(always))]
pub extern "C" fn $intrinsic(a: $ty, b: u32) -> $ty {
let half_bits = <$ty>::bits() / 2;
if b & half_bits != 0 {
<$ty>::from_parts(0, a.low() << (b - half_bits))
} else if b == 0 {
a
} else {
<$ty>::from_parts(a.low() << b, (a.high() << b) | (a.low() >> (half_bits - b)))
}
}
}
}
macro_rules! ashr {
($intrinsic:ident: $ty:ty) => {
/// Returns arithmetic `a >> b`, requires `b < $ty::bits()`
#[cfg_attr(not(test), no_mangle)]
#[cfg_attr(all(not(test), not(target_arch = "arm")), no_mangle)]
#[cfg_attr(all(not(test), target_arch = "arm"), inline(always))]
pub extern "C" fn $intrinsic(a: $ty, b: u32) -> $ty {
let half_bits = <$ty>::bits() / 2;
if b & half_bits != 0 {
<$ty>::from_parts((a.high() >> (b - half_bits)) as <$ty as LargeInt>::LowHalf,
a.high() >> (half_bits - 1))
} else if b == 0 {
a
} else {
let high_unsigned = a.high() as <$ty as LargeInt>::LowHalf;
<$ty>::from_parts((high_unsigned << (half_bits - b)) | (a.low() >> b),
a.high() >> b)
}
}
}
}
macro_rules! lshr {
($intrinsic:ident: $ty:ty) => {
/// Returns logical `a >> b`, requires `b < $ty::bits()`
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn $intrinsic(a: $ty, b: u32) -> $ty {
let half_bits = <$ty>::bits() / 2;
if b & half_bits != 0 {
<$ty>::from_parts(a.high() >> (b - half_bits), 0)
} else if b == 0 {
a
} else {
<$ty>::from_parts((a.high() << (half_bits - b)) | (a.low() >> b), a.high() >> b)
}
}
}
}
#[cfg(not(all(feature = "c", target_arch = "x86")))]
ashl!(__ashldi3: u64);
ashl!(__ashlti3: u128);
#[cfg(not(all(feature = "c", target_arch = "x86")))]
ashr!(__ashrdi3: i64);
ashr!(__ashrti3: i128);
#[cfg(not(all(feature = "c", target_arch = "x86")))]
lshr!(__lshrdi3: u64);
lshr!(__lshrti3: u128);
|
use rayon::prelude::*;
fn main() {
let starting_number = 0;
let until = 99_999_999;
run_single_threaded(starting_number, until);
run_multi_threaded(starting_number, until);
}
fn run_single_threaded(starting_number: u128, until: u128) {
let instant = std::time::Instant::now();
let max = (starting_number..=until).into_iter().map(count_steps).max().unwrap_or(0);
println!(
"Single threaded ->\tmax: {}\ttime: {}ms",
max,
instant.elapsed().as_millis()
);
}
fn run_multi_threaded(starting_number: u128, until: u128) {
let instant = std::time::Instant::now();
let max = (starting_number..=until)
.into_par_iter()
.map(count_steps)
.max()
.unwrap_or(0);
println!(
"Multi threaded ->\tmax: {}\ttime: {}ms",
max,
instant.elapsed().as_millis()
);
}
fn count_steps(starting_number: u128) -> u16 {
let mut value = starting_number;
let mut count: u16 = 0;
while value > 1 {
if value % 2 == 0 {
value /= 2;
} else {
value = value * 3 + 1;
}
count += 1;
}
count
}
|
#![feature(test)]
use benchtest::benchtest;
use itertools::Itertools;
use std::collections::HashMap;
const INPUT: &str = include_str!("data/day3.txt");
#[derive(Hash, Eq, PartialEq, Copy, Clone, Debug, Default)]
struct Position {
x: i32,
y: i32,
}
fn puzzle_a(input: &str) -> i32 {
let (first, second) = input.trim().lines().collect_tuple().unwrap();
let (first_path, second_path) = (wire_path(first), wire_path(second));
first_path
.keys()
.filter(|&&pos| pos != Position::default())
.filter_map(|pos| second_path.get(pos).map(|_| pos.x.abs() + pos.y.abs()))
.min()
.unwrap()
}
fn puzzle_b(input: &str) -> u32 {
let (first, second) = input.trim().lines().collect_tuple().unwrap();
let (first_path, second_path) = (wire_path(first), wire_path(second));
first_path
.iter()
.filter_map(|(pos, s1)| second_path.get(&pos).map(|s2| s1 + s2))
.min()
.unwrap()
}
fn wire_path(instructions: &str) -> HashMap<Position, u32> {
let mut path = HashMap::new();
let mut pos = Position::default();
let mut step = 0;
fn trace(
schematic: &mut HashMap<Position, u32>,
amt: i32,
pos: &mut Position,
step: &mut u32,
mut inc: impl FnMut(&mut Position),
) {
for _ in 0..amt {
inc(pos);
*step += 1;
schematic.entry(*pos).or_insert(*step);
}
}
for code in instructions.split(",") {
let direction = code.get(0..1).unwrap();
let amt = code.get(1..).unwrap().parse::<i32>().unwrap();
match direction {
"R" => trace(&mut path, amt, &mut pos, &mut step, |p| p.x += 1),
"L" => trace(&mut path, amt, &mut pos, &mut step, |p| p.x -= 1),
"U" => trace(&mut path, amt, &mut pos, &mut step, |p| p.y += 1),
"D" => trace(&mut path, amt, &mut pos, &mut step, |p| p.y -= 1),
_ => unreachable!(),
};
}
path
}
fn main() {
println!("{}", puzzle_a(INPUT));
println!("{}", puzzle_b(INPUT));
}
benchtest! {
puzzle_a_test: puzzle_a(INPUT) => 221,
puzzle_b_test: puzzle_b(INPUT) => 18542
}
|
use rocket::Route;
use rocket_contrib::json::Json;
use crate::api::model::Client;
use crate::api::service::client_service;
use crate::common::http::ResponseWrapper;
#[get("/")]
fn list() -> ResponseWrapper<Vec<Client>> {
client_service::list()
}
#[get("/<id>")]
fn get(id: i32) -> ResponseWrapper<Client> {
client_service::get(id)
}
#[post("/", data = "<client>")]
fn create(client: Json<Client>) -> ResponseWrapper<Client> {
client_service::create(client.into_inner())
}
#[put("/", data = "<client>")]
fn update(client: Json<Client>) -> ResponseWrapper<Client> {
client_service::update(client.into_inner())
}
#[delete("/<id>")]
fn delete(id: i32) -> ResponseWrapper<bool> {
client_service::delete(id)
}
pub fn routes() -> Vec<Route> {
routes![list, get, create, update, delete]
} |
mod cli;
use {{ artifact_id }}::{get_greeting};
use log::{debug, info};
fn main() {
let matches = cli::app().get_matches();
cli::configure(&matches);
debug!("Initializing...");
if let Some(_) = matches.subcommand_matches("greet") {
info!("{}", get_greeting());
}
}
|
use nix::sys::epoll::{epoll_create1, epoll_ctl, epoll_wait, EpollCreateFlags, EpollOp, EpollEvent, EpollFlags};
use std::mem::MaybeUninit;
use nix::unistd::read;
use nix::Error;
fn main() {
real_main().unwrap();
}
fn real_main() -> Result<usize, Error>{
let efd = epoll_create1(EpollCreateFlags::EPOLL_CLOEXEC)?;
let fd = 0;
let mut event_watch = EpollEvent::new(EpollFlags::EPOLLIN, fd);
epoll_ctl(efd, EpollOp::EpollCtlAdd, fd as i32, Some(&mut event_watch))?;
let mut events_active:[EpollEvent;1] = unsafe { MaybeUninit::uninit().assume_init() };
let epoll_n = epoll_wait(efd, &mut events_active, -1)?;
for i in 0..epoll_n {
let eve = events_active[i];
let fd = eve.data();
let mut buffer = [0u8;128];
let nread = read(fd as i32, &mut buffer)?;
println!("{}", unsafe { String::from_raw_parts(buffer.as_mut_ptr(), nread, nread) });
}
return Result::Ok(0);
} |
#[macro_use]
extern crate log;
extern crate env_logger;
pub mod lexical;
pub mod syntax;
pub mod semantic;
pub mod codegen;
|
use std::thread;
use rand::Rng;
fn get_two_nums() {
// there is an a/sync version of this function example at
// https://rust-lang.github.io/async-book/01_getting_started/02_why_async.html
// but it is not 'real'
let thread_one = thread::spawn(|| {
let mut rng = rand::thread_rng();
println!("Integer: {}", rng.gen_range(0, 10));
});
let thread_two = thread::spawn(|| {
let mut rng = rand::thread_rng();
println!("Float: {}", rng.gen_range(0.0, 10.0))
});
thread_one.join().expect("thread one panicked");
thread_two.join().expect("thread two panicked");
}
fn main() {
get_two_nums();
}
|
use std::collections::HashSet;
use std::io::BufRead;
fn main() {
let args: Vec<_> = std::env::args().collect();
let file = std::fs::File::open(&args[1]).unwrap();
let mut lines = std::io::BufReader::new(file)
.lines()
.map(|line| line.unwrap());
let mut groups = Vec::new();
loop {
let group_lines = lines
.by_ref()
.take_while(|line| line.len() != 0)
.collect::<Vec<_>>();
if group_lines.len() != 0 {
groups.push(group_lines);
} else {
break;
}
}
println!(
"Solution of part 1 is {}",
groups
.iter()
.map(|lines| lines
.iter()
.flat_map(|line| line.chars())
.collect::<std::collections::HashSet<_>>()
.len())
.sum::<usize>()
);
println!(
"Solution of part 2 is {}",
groups
.iter()
.map(|lines| {
lines
.iter()
.fold(HashSet::new(), |set, line| {
let line_set = line.chars().collect::<std::collections::HashSet<_>>();
set.intersection(&line_set).cloned().collect()
})
.len()
})
.sum::<usize>()
);
}
|
pub const PIECE_SIZE_IN_BYTES: u64 = 8;
pub const PIECE_SIZE_IN_BITS: u64 = 64;
|
use crate::context::RpcContext;
use crate::websocket::types::{BlockHeader, SubscriptionBroadcaster};
use jsonrpsee::core::error::SubscriptionClosed;
use jsonrpsee::types::error::SubscriptionEmptyError;
use jsonrpsee::SubscriptionSink;
use tokio_stream::wrappers::BroadcastStream;
pub fn subscribe_new_heads(
_context: RpcContext,
mut sink: SubscriptionSink,
ws_new_heads_tx: &SubscriptionBroadcaster<BlockHeader>,
) -> Result<(), SubscriptionEmptyError> {
let ws_new_heads_tx = BroadcastStream::new(ws_new_heads_tx.0.subscribe());
tokio::spawn(async move {
match sink.pipe_from_try_stream(ws_new_heads_tx).await {
SubscriptionClosed::Success => {
sink.close(SubscriptionClosed::Success);
}
SubscriptionClosed::RemotePeerAborted => {
tracing::trace!("WS: newHeads subscription peer aborted");
}
SubscriptionClosed::Failed(error) => {
tracing::trace!("WS: newHeads subscription failed {error:?}");
sink.close(error);
}
};
});
Ok(())
}
|
//! Type wrappers and convenience functions for 3D collision detection
pub use collision::algorithm::minkowski::GJK3;
pub use collision::primitive::{ConvexPolyhedron, Cuboid, Particle3, Sphere};
pub use core::collide3d::*;
pub use core::{CollisionMode, CollisionStrategy};
use cgmath::Point3;
use collision::dbvt::{DynamicBoundingVolumeTree, TreeValueWrapped};
use collision::primitive::Primitive3;
use collision::Aabb3;
use specs::prelude::Entity;
use collide::{BasicCollisionSystem, SpatialCollisionSystem, SpatialSortingSystem};
use core::ContactEvent;
/// Contact event for 2D
///
/// ### Type parameters:
///
/// - `S`: Scalar type (f32 or f64)
pub type ContactEvent3<S> = ContactEvent<Entity, Point3<S>>;
/// ECS collision system for 3D, see
/// [`BasicCollisionSystem`](../collide/ecs/struct.BasicCollisionSystem.html) for more information.
///
/// ### Type parameters:
///
/// - `S`: Scalar type (f32 or f64)
/// - `T`: Transform
/// - `Y`: Collider type, see `Collider` for more information
pub type BasicCollisionSystem3<S, T, Y = ()> =
BasicCollisionSystem<Primitive3<S>, T, TreeValueWrapped<Entity, Aabb3<S>>, Aabb3<S>, Y>;
/// Spatial sorting system for 3D, see
/// [`SpatialSortingSystem`](../collide/ecs/struct.SpatialSortingSystem.html) for more information.
///
/// ### Type parameters:
///
/// - `S`: Scalar type (f32 or f64)
/// - `T`: Transform
/// - `Y`: Collider type, see `Collider` for more information
pub type SpatialSortingSystem3<S, T, Y = ()> =
SpatialSortingSystem<Primitive3<S>, T, TreeValueWrapped<Entity, Aabb3<S>>, Aabb3<S>, Y>;
/// Spatial collision system for 3D, see
/// [`SpatialCollisionSystem`](../collide/ecs/struct.SpatialCollisionSystem.html) for more
/// information.
///
/// ### Type parameters:
///
/// - `S`: Scalar type (f32 or f64)
/// - `T`: Transform
/// - `Y`: Collider type, see `Collider` for more information
pub type SpatialCollisionSystem3<S, T, Y = ()> = SpatialCollisionSystem<
Primitive3<S>,
T,
(usize, TreeValueWrapped<Entity, Aabb3<S>>),
Aabb3<S>,
Y,
>;
/// Dynamic bounding volume tree for 3D
///
/// ### Type parameters:
///
/// - `S`: Scalar type (f32 or f64)
pub type DynamicBoundingVolumeTree3<S> =
DynamicBoundingVolumeTree<TreeValueWrapped<Entity, Aabb3<S>>>;
|
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
fn main() {
let (a, b, k): (u64, u64, u64) = parse_line().unwrap();
let n = (a + b) as usize;
let mut ans = "".to_string();
let mut left_a = a;
let mut left_b = b;
let mut now_rank = 0;
for _ in 0..a + b {
// dbg!(left_a, left_b);
if left_a == 0 {
ans.push('b');
left_b -= 1;
continue;
}
if left_b == 0 {
ans.push('a');
left_a -= 1;
continue;
}
// aを選択したときの自由度
let mut tmp_a = nCr(left_a + left_b - 1, left_a - 1) as u64;
if tmp_a == 0 {
tmp_a += 1;
}
let tmp_b = nCr(left_a + left_b - 1, left_a) as u64;
let m = max(tmp_a, tmp_b);
// dbg!(tmp_a, tmp_b, now_rank);
if now_rank + tmp_a >= k {
ans.push('a');
left_a -= 1;
} else {
ans.push('b');
left_b -= 1;
now_rank += tmp_a;
}
}
println!("{}", ans);
}
/// 極力u64を超えないようにnCrを計算する
fn nCr(n: u64, r: u64) -> u128 {
if n < r {
panic!("cant n < r, {}C{}", n, r);
}
if r == 0 {
return 0;
}
let mut ans: u128 = 1;
if r > n - r {
let mut bunbo = (1..=n - r).rev().collect::<Vec<u64>>();
for i in r + 1..=n {
ans *= i as u128;
if let Some(last) = bunbo.get(bunbo.len() - 1) {
if ans % *last as u128 == 0 {
ans /= *last as u128;
bunbo.pop();
}
}
}
} else {
let mut bunbo = (1..=r).rev().collect::<Vec<u64>>();
for i in n - r + 1..=n {
ans *= i as u128;
if let Some(last) = bunbo.get(bunbo.len() - 1) {
if ans % *last as u128 == 0 {
ans /= *last as u128;
bunbo.pop();
}
}
}
}
return ans;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_nCr() {
assert_eq!(nCr(5, 2), 10);
assert_eq!(nCr(5, 3), 10);
assert_eq!(nCr(1, 1), 1);
assert_eq!(nCr(5, 1), 5);
assert_eq!(nCr(5, 0), 0);
assert_eq!(nCr(2_u64 * 100000, 2), 19999900000);
}
}
|
extern crate capnp;
#[macro_use]
extern crate capnp_rpc;
extern crate native_tls;
extern crate tokio;
extern crate tokio_tls;
extern crate helloworld;
use std::env;
use std::fs::read;
use std::io::{BufWriter, Error as IOError, ErrorKind as IOErrorKind};
use std::net::SocketAddr;
use capnp::capability::Promise;
use capnp_rpc::RpcSystem;
use capnp_rpc::rpc_twoparty_capnp::Side;
use capnp_rpc::twoparty::VatNetwork;
use native_tls::{Certificate, TlsConnector as NativeConnector};
use tokio::io::AsyncRead;
use tokio::net::TcpStream;
use tokio::prelude::Future;
use tokio::runtime::current_thread;
use tokio_tls::TlsConnector as TokioConnector;
use helloworld::Client;
fn main () {
let args: Vec<String> = env::args().collect();
let addr = args[1].parse::<SocketAddr>().unwrap();
let cert = read(&args[2]).unwrap();
let cert = Certificate::from_pem(cert.as_slice()).unwrap();
let connector = NativeConnector::builder()
.add_root_certificate(cert)
.build().unwrap();
let connector = TokioConnector::from(connector);
// Connect to server
let mut runtime = current_thread::Runtime::new().unwrap();
let stream = runtime.block_on(TcpStream::connect(&addr).and_then(|stream| {
stream.set_nodelay(true).unwrap();
connector.connect("localhost", stream)
.map_err(|e| IOError::new(IOErrorKind::Other, e))
})).unwrap();
// Boilerplate
let (reader, writer) = stream.split();
let writer = BufWriter::new(writer);
let network = VatNetwork::new(
reader,
writer,
Side::Client,
Default::default()
);
let mut rpc_system = RpcSystem::new(Box::new(network), None);
let client: Client = rpc_system.bootstrap(Side::Server);
runtime.spawn(rpc_system.map_err(|e| eprintln!("{:?}", e)));
// Prepare request
let mut request = client.say_hello_request();
request.get().init_request().set_name("World");
// Send request and wait for response
println!("Sending request...");
runtime.block_on(request.send().promise.and_then(|response| {
let reply = pry!(pry!(response.get()).get_reply());
let message = pry!(reply.get_message());
println!("Got reply: \"{}\"", message);
Promise::ok(())
})).unwrap();
}
|
/*
A simple example testing full search.
*/
use max_tree::prelude::*;
type Map = Vec<Vec<u8>>;
type Pos = [usize; 2];
fn main() {
let ref mut map: Map = vec![
vec![0, 0, 1],
vec![0, 0, 0],
vec![0, 0, 0]
];
let start: Pos = [0, 2];
let max_depth = 4;
let eps_depth = 0.00001;
let mut ai = Ai {
actions: actions,
execute: execute,
utility: utility,
undo: undo,
settings: AiSettings::new(max_depth, eps_depth),
analysis: AiAnalysis::new(),
};
let mut root = Node::root(start);
ai.full(&mut root, 0, map);
let mut node = &root;
loop {
println!("{:?}", node.data);
if let Some(i) = node.optimal() {
node = &node.children[i].1;
} else {
break;
}
}
}
fn undo(_: &Pos, _: &mut Map) {}
fn utility(pos: &Pos, map: &Map) -> f64 {
map[pos[1]][pos[0]] as f64
}
fn execute(pos: &Pos, action: &Action, map: &mut Map) -> Result<[usize; 2], ()> {
Ok(match *action {
Action::Left => {
if pos[0] <= 0 {return Err(())};
[pos[0] - 1, pos[1]]
}
Action::Right => {
if pos[0] + 1 >= map[0].len() {return Err(())};
[pos[0] + 1, pos[1]]
}
Action::Up => {
if pos[1] <= 0 {return Err(())};
[pos[0], pos[1] - 1]
}
Action::Down => {
if pos[1] + 1 >= map.len() {return Err(())};
[pos[0], pos[1] + 1]
}
})
}
fn actions(_: &Pos, _: &Map) -> Vec<Action> {
vec![Action::Left, Action::Right, Action::Up, Action::Down]
}
#[derive(Clone, Copy, Debug)]
pub enum Action {
Left,
Right,
Up,
Down,
}
|
use super::{TMessage, WMessage};
use futures_03::prelude::*;
use futures_03::ready;
use futures_03::stream::FusedStream;
use futures_03::task::{Context, Poll};
use std::io::Error;
use std::pin::Pin;
use tokio::io::{AsyncRead, AsyncWrite};
pub struct TcpFramed<T> {
io: T,
reading: Option<TMessage>,
writing: Option<WMessage>,
has_finished: bool,
}
impl<T> TcpFramed<T> {
pub fn new(io: T) -> Self {
TcpFramed {
io,
reading: None,
writing: None,
has_finished: false,
}
}
}
impl<T> Stream for TcpFramed<T>
where
T: AsyncRead + Unpin,
{
type Item = std::result::Result<TMessage, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let self_mut = self.get_mut();
loop {
//self.inner.poll()
if self_mut.reading.is_none() {
self_mut.reading = Some(TMessage::new());
}
let reading = &mut self_mut.reading;
let msg = reading.as_mut().unwrap();
// read from io
let mut io = &mut self_mut.io;
let pin_io = Pin::new(&mut io);
match ready!(pin_io.poll_read_buf(cx, msg)) {
Ok(n) => {
if n <= 0 {
self_mut.has_finished = true;
return Poll::Ready(None);
}
}
Err(e) => {
self_mut.has_finished = true;
return Poll::Ready(Some(Err(e)));
}
};
return Poll::Ready(Some(Ok(self_mut.reading.take().unwrap())));
}
}
}
impl<T> FusedStream for TcpFramed<T>
where
T: AsyncRead + Unpin,
{
fn is_terminated(&self) -> bool {
self.has_finished
}
}
impl<T> Sink<WMessage> for TcpFramed<T>
where
T: AsyncWrite + Unpin,
{
type Error = Error;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.writing.is_some() {
return self.poll_flush(cx);
}
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: WMessage) -> Result<(), Self::Error> {
let self_mut = self.get_mut();
self_mut.writing = Some(item);
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let self_mut = self.get_mut();
if self_mut.writing.is_some() {
let writing = self_mut.writing.as_mut().unwrap();
loop {
let mut io = &mut self_mut.io;
let pin_io = Pin::new(&mut io);
ready!(pin_io.poll_write_buf(cx, writing))?;
if writing.is_completed() {
self_mut.writing = None;
break;
}
}
}
let mut io = &mut self_mut.io;
let pin_io = Pin::new(&mut io);
// Try flushing the underlying IO
ready!(pin_io.poll_flush(cx))?;
return Poll::Ready(Ok(()));
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
ready!(self.poll_flush(cx))?;
Poll::Ready(Ok(()))
}
}
|
// 顶点坐标
#[derive(Copy, Clone)]
pub struct Position{
pub position: [f32; 3]
}
implement_vertex!(Position, position);
// 法线向量
#[derive(Copy, Clone)]
pub struct Normal{
pub normal: [f32; 3]
}
implement_vertex!(Normal, normal);
// 矩阵乘法
pub fn matrix_multi(first: &[[f32; 4]; 4], second: &[[f32; 4]; 4]) -> [[f32; 4]; 4] {
let mut a: [[f32; 4]; 4] = [[0.0; 4]; 4];
for i in 0..4 {
for k in 0..4 {
let r:f32 = first[i][k];
for j in 0..4 {
a[i][j] += r*second[k][j];
}
}
}
return a;
} |
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use serde::Deserialize;
use serde::Serialize;
use crate::SeqV;
/// `Change` describes a state change, including the states before and after a change.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, derive_more::From)]
pub struct Change<T, ID = u64>
where
ID: Clone + PartialEq,
T: Clone + PartialEq,
{
/// identity of the resource that is changed.
pub ident: Option<ID>,
pub prev: Option<SeqV<T>>,
pub result: Option<SeqV<T>>,
}
impl<T, ID> Change<T, ID>
where
ID: Clone + PartialEq + Debug,
T: Clone + PartialEq + Debug,
{
pub fn new(prev: Option<SeqV<T>>, result: Option<SeqV<T>>) -> Self {
Change {
ident: None,
prev,
result,
}
}
pub fn with_id(mut self, id: ID) -> Self {
self.ident = Some(id);
self
}
/// Maps `Option<SeqV<T>>` to `Option<U>` for `prev` and `result`.
pub fn map<F, U>(self, f: F) -> (Option<U>, Option<U>)
where F: Fn(SeqV<T>) -> U + Copy {
(self.prev.map(f), self.result.map(f))
}
/// Extract `prev` and `result`.
pub fn unpack(self) -> (Option<SeqV<T>>, Option<SeqV<T>>) {
(self.prev, self.result)
}
pub fn unwrap(self) -> (SeqV<T>, SeqV<T>) {
(self.prev.unwrap(), self.result.unwrap())
}
/// Extract `prev.seq` and `result.seq`.
pub fn unpack_seq(self) -> (Option<u64>, Option<u64>) {
self.map(|x| x.seq)
}
/// Extract `prev.data` and `result.data`.
pub fn unpack_data(self) -> (Option<T>, Option<T>) {
self.map(|x| x.data)
}
pub fn is_changed(&self) -> bool {
self.prev != self.result
}
/// Assumes it is a state change of an add operation and return Ok if the add operation succeed.
/// Otherwise it returns an error that is built by provided function.
pub fn added_or_else<F, E>(self, f: F) -> Result<SeqV<T>, E>
where F: FnOnce(SeqV<T>) -> E {
let (prev, result) = self.unpack();
if let Some(p) = prev {
return Err(f(p));
}
if let Some(res) = result {
return Ok(res);
}
unreachable!("impossible: both prev and result are None");
}
}
impl<T, ID> Display for Change<T, ID>
where
T: Debug + Clone + PartialEq,
ID: Debug + Clone + PartialEq,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "id: {:?}", self.ident)?;
write!(f, "prev: {:?}", self.prev)?;
write!(f, "result: {:?}", self.result)
}
}
|
use super::*;
pub struct DarkSkyComponentRegistry;
impl Plugin for DarkSkyComponentRegistry {
fn build(&self, app: &mut bevy::prelude::AppBuilder) {
app.register_component::<Player>();
}
}
#[derive(Properties, Default)]
struct Player {
pub health: f32,
}
|
use std::path::{ Path, PathBuf };
use std::cell::RefCell;
use std::rc::Rc;
use parser::{ Evaluator, Node };
use sensor::Sensor;
use util;
// Hwmon sensor
//
// An arbitrary (temperature) input of a hwmon device.
// While this can be used to monitor pretty much anything,
// it should only be used for temperature inputs as it will
// perform a conversion to actual degrees celsius.
pub struct HwmonSensor {
path : PathBuf,
value : Option<f64>,
}
impl HwmonSensor {
pub fn create(hwmon: &str, input: &str) -> Rc<RefCell<Box<Sensor>>> {
let base_path = format!("/sys/class/hwmon/{}/{}", hwmon, input);
let mut path_v = PathBuf::new();
path_v.push(Path::new(&base_path));
Rc::new(RefCell::new(Box::new(
HwmonSensor {
path : path_v,
value : None,
})))
}
fn pass_char(&self, c: char) -> bool {
match c {
'0'...'9' | '-' => true,
_ => false,
}
}
}
impl Sensor for HwmonSensor {
fn value(&self) -> f64 {
self.value.unwrap()
}
fn update(&mut self) -> Result<(), String> {
let raw_str = try!(util::read_text_file(&self.path));
let val_str = raw_str.chars()
.filter(|c| self.pass_char(*c))
.collect::<String>();
let raw_value = try!(val_str.parse::<f64>().map_err(|_| "Invalid number".to_string()));
self.value = Some(raw_value / 1000.0);
Ok(())
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
pub struct EvalHwmonSensor;
impl EvalHwmonSensor {
pub fn new() -> EvalHwmonSensor {
EvalHwmonSensor { }
}
}
impl Evaluator<Rc<RefCell<Box<Sensor>>>> for EvalHwmonSensor {
fn parse_nodes(&self, nodes: &[Node]) -> Result<Rc<RefCell<Box<Sensor>>>, String> {
Ok(HwmonSensor::create(
try!(util::get_text_node("hwmon-sensor", nodes, 0)),
try!(util::get_text_node("hwmon-sensor", nodes, 1))))
}
} |
use rand::{thread_rng, Rng};
const SYMBOLS: [char; 62] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'];
const BASE: u64 = 62;
pub fn random_token() -> String {
encode(10000000 + thread_rng().gen_range::<u64>(0, 1000000000))
}
// FIXME this can be made MUCH faster
pub fn encode(number: u64) -> String {
let rest = number % BASE;
let mut encoded_str = String::new();
encoded_str.push(SYMBOLS[rest as usize]);
if (number - rest) != 0 {
let newnumber = (number - rest) / BASE;
encoded_str = encode(newnumber) + &encoded_str;
}
encoded_str
}
// decodes a string
#[allow(dead_code)]
pub fn decode(input: &str) -> u64 {
let floatbase = BASE as f64;
let input_length = input.len() as i32;
let mut sum = 0;
for (index, current_char) in input.char_indices().rev() {
let pos_char = find_char_in_symbols(current_char).unwrap() as u64;
sum = sum + (pos_char * floatbase.powi(input_length - index as i32 - 1) as u64);
}
sum
}
#[allow(dead_code)]
fn find_char_in_symbols(c: char) -> Option<usize> {
for index in 0..BASE {
if SYMBOLS[index as usize] == c {
return Option::Some(index as usize);
}
}
Option::None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encode() {
assert_eq!(encode(1000000), String::from("4c92"));
}
#[test]
fn test_decode() {
assert_eq!(decode("4c92"), 1000000);
}
#[test]
fn test_encode_decode1() {
let number: u64 = 1234567890;
let encoded_val = encode(number);
assert_eq!(decode(&encoded_val), number);
}
#[test]
fn test_encode_decode2() {
let number: u64 = 9876543210;
let encoded_val = encode(number);
assert_eq!(decode(&encoded_val), number);
}
#[test]
fn test_encode_decode3() {
let number: u64 = 99889999998889;
let encoded_val = encode(number);
assert_eq!(decode(&encoded_val), number);
}
} |
use crate::prelude::*;
#[repr(C)]
#[derive(Debug)]
pub struct VkImageBlit {
pub srcSubresource: VkImageSubresourceLayers,
pub srcOffsets: [VkOffset3D; 2],
pub dstSubresource: VkImageSubresourceLayers,
pub dstOffsets: [VkOffset3D; 2],
}
|
use super::{Cache, LongLiveC, UStub, UdpServer};
use crate::config::TunCfg;
use crate::config::{LOCAL_SERVER, LOCAL_TPROXY_SERVER_PORT};
use crate::service::{SubServiceCtlCmd, TunMgrStub};
use bytes::BytesMut;
use failure::Error;
use log::{error, info};
use std::cell::RefCell;
use std::hash::{Hash, Hasher};
use std::net::SocketAddr;
use std::rc::Rc;
use tokio::sync::mpsc::UnboundedSender;
pub type LongLiveX = Rc<RefCell<UdpXMgr>>;
pub struct UdpXMgr {
tmstubs: Vec<TunMgrStub>,
ctl_tx: UnboundedSender<SubServiceCtlCmd>,
server: Rc<RefCell<super::UdpServer>>,
server6: Rc<RefCell<super::UdpServer>>,
cache: LongLiveC,
}
impl UdpXMgr {
pub fn new(
_cfg: &TunCfg,
tmstubs: Vec<TunMgrStub>,
ctl_tx: UnboundedSender<SubServiceCtlCmd>,
) -> LongLiveX {
info!("[UdpXMgr]new UdpXMgr");
Rc::new(RefCell::new(UdpXMgr {
tmstubs,
ctl_tx,
server: UdpServer::new(format!("{}:{}", LOCAL_SERVER, LOCAL_TPROXY_SERVER_PORT)),
server6: UdpServer::new(format!("[::1]:{}", LOCAL_TPROXY_SERVER_PORT)),
cache: Cache::new(),
}))
}
pub fn init(&self, s: LongLiveX) -> Result<(), Error> {
info!("[UdpXMgr]init UdpXMgr");
// set tx to each tm
for tm in self.tmstubs.iter() {
match tm
.ctl_tx
.send(SubServiceCtlCmd::SetUdpTx(self.ctl_tx.clone()))
{
Err(e) => {
error!("[UdpXMgr]init UdpXMgr error, send SetUpdTx failed:{}", e);
}
_ => {}
}
}
self.server.borrow_mut().start(s.clone())?;
self.server6.borrow_mut().start(s.clone())?;
Ok(())
}
pub fn stop(&mut self) {
self.tmstubs.clear();
{
let mut s = self.server.borrow_mut();
s.stop();
}
{
let mut s = self.server6.borrow_mut();
s.stop();
}
{
let mut s = self.cache.borrow_mut();
s.cleanup();
}
}
pub fn on_udp_server_closed(&mut self) {
// TODO: rebuild udp server
}
pub fn calc_hash_code(src_addr: SocketAddr, dst_addr: SocketAddr) -> usize {
let mut hasher = fnv::FnvHasher::default();
(src_addr, dst_addr).hash(&mut hasher);
hasher.finish() as usize
}
pub fn on_udp_msg_forward(&self, msg: BytesMut, src_addr: SocketAddr, dst_addr: SocketAddr) {
if self.tmstubs.len() < 1 {
error!("[UdpXMgr]no tm to handle udp forward");
return;
}
let hash_code = UdpXMgr::calc_hash_code(src_addr, dst_addr);
let tm_index = hash_code % self.tmstubs.len();
let tx = self.tmstubs[tm_index].ctl_tx.clone();
let cmd = SubServiceCtlCmd::UdpProxy((msg, src_addr, dst_addr, hash_code));
match tx.send(cmd) {
Err(e) => {
error!("[UdpXMgr] send UdpProxy to tm failed:{}", e);
}
_ => {}
}
}
pub fn on_udp_proxy_south(
&mut self,
lx: LongLiveX,
msg: bytes::Bytes,
src_addr: SocketAddr,
dst_addr: SocketAddr,
) {
let cache: &mut Cache = &mut self.cache.borrow_mut();
let mut stub = cache.get(&src_addr);
if stub.is_none() {
// build new stub
self.build_ustub(lx, cache, &src_addr);
stub = cache.get(&src_addr);
}
match stub {
Some(stub) => {
stub.on_udp_proxy_south(msg, dst_addr);
}
None => {
error!("[UdpXMgr] on_udp_proxy_south failed, no stub found");
}
}
}
fn build_ustub(&self, lx: LongLiveX, c: &mut Cache, src_addr: &SocketAddr) {
match UStub::new(src_addr, lx) {
Ok(ustub) => {
c.insert(self.cache.clone(), *src_addr, ustub);
}
Err(e) => {
error!("[UdpXMgr] build_ustub failed:{}", e);
}
}
}
pub fn on_ustub_closed(&mut self, src_addr: &SocketAddr) {
self.cache.borrow_mut().remove(src_addr);
}
}
|
/*!
```cargo
[dependencies]
slow-build = { version = "0.1.0", path = "slow-build" }
```
*/
fn main() {
println!("--output--");
println!("Ok");
}
|
#![cfg_attr(not(feature = "std"), no_std)]
use ink_env::Environment;
pub enum MintEngineEnvironment {}
impl Environment for MintEngineEnvironment {
const MAX_EVENT_TOPICS: usize = <ink_env::DefaultEnvironment as Environment>::MAX_EVENT_TOPICS;
type AccountId = <ink_env::DefaultEnvironment as Environment>::AccountId;
type Balance = <ink_env::DefaultEnvironment as Environment>::Balance;
type Hash = <ink_env::DefaultEnvironment as Environment>::Hash;
type Timestamp = <ink_env::DefaultEnvironment as Environment>::Timestamp;
type RentFraction = <ink_env::DefaultEnvironment as Environment>::RentFraction;
type BlockNumber = u32;
type ChainExtension = ink_env::NoChainExtension;
}
|
use serde::de::IntoDeserializer as _;
use crate::de::DatetimeDeserializer;
use crate::de::Error;
/// Deserialization implementation for TOML [values][crate::Value].
///
/// Can be creater either directly from TOML strings, using [`std::str::FromStr`],
/// or from parsed [values][crate::Value] using [`serde::de::IntoDeserializer::into_deserializer`].
///
/// # Example
///
/// ```
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Config {
/// title: String,
/// owner: Owner,
/// }
///
/// #[derive(Deserialize)]
/// struct Owner {
/// name: String,
/// }
///
/// let value = r#"{ title = 'TOML Example', owner = { name = 'Lisa' } }"#;
/// let deserializer = value.parse::<toml_edit::de::ValueDeserializer>().unwrap();
/// let config = Config::deserialize(deserializer).unwrap();
/// assert_eq!(config.title, "TOML Example");
/// assert_eq!(config.owner.name, "Lisa");
/// ```
pub struct ValueDeserializer {
input: crate::Item,
validate_struct_keys: bool,
}
impl ValueDeserializer {
pub(crate) fn new(input: crate::Item) -> Self {
Self {
input,
validate_struct_keys: false,
}
}
pub(crate) fn with_struct_key_validation(mut self) -> Self {
self.validate_struct_keys = true;
self
}
}
// Note: this is wrapped by `toml::de::ValueDeserializer` and any trait methods
// implemented here need to be wrapped there
impl<'de> serde::Deserializer<'de> for ValueDeserializer {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: serde::de::Visitor<'de>,
{
let span = self.input.span();
match self.input {
crate::Item::None => visitor.visit_none(),
crate::Item::Value(crate::Value::String(v)) => visitor.visit_string(v.into_value()),
crate::Item::Value(crate::Value::Integer(v)) => visitor.visit_i64(v.into_value()),
crate::Item::Value(crate::Value::Float(v)) => visitor.visit_f64(v.into_value()),
crate::Item::Value(crate::Value::Boolean(v)) => visitor.visit_bool(v.into_value()),
crate::Item::Value(crate::Value::Datetime(v)) => {
visitor.visit_map(DatetimeDeserializer::new(v.into_value()))
}
crate::Item::Value(crate::Value::Array(v)) => {
v.into_deserializer().deserialize_any(visitor)
}
crate::Item::Value(crate::Value::InlineTable(v)) => {
v.into_deserializer().deserialize_any(visitor)
}
crate::Item::Table(v) => v.into_deserializer().deserialize_any(visitor),
crate::Item::ArrayOfTables(v) => v.into_deserializer().deserialize_any(visitor),
}
.map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(span);
}
e
})
}
// `None` is interpreted as a missing field so be sure to implement `Some`
// as a present field.
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: serde::de::Visitor<'de>,
{
let span = self.input.span();
visitor.visit_some(self).map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(span);
}
e
})
}
fn deserialize_newtype_struct<V>(
self,
_name: &'static str,
visitor: V,
) -> Result<V::Value, Error>
where
V: serde::de::Visitor<'de>,
{
let span = self.input.span();
visitor
.visit_newtype_struct(self)
.map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(span);
}
e
})
}
fn deserialize_struct<V>(
self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: serde::de::Visitor<'de>,
{
if serde_spanned::__unstable::is_spanned(name, fields) {
if let Some(span) = self.input.span() {
return visitor.visit_map(super::SpannedDeserializer::new(self, span));
}
}
if name == toml_datetime::__unstable::NAME && fields == [toml_datetime::__unstable::FIELD] {
let span = self.input.span();
if let crate::Item::Value(crate::Value::Datetime(d)) = self.input {
return visitor
.visit_map(DatetimeDeserializer::new(d.into_value()))
.map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(span);
}
e
});
}
}
if self.validate_struct_keys {
let span = self.input.span();
match &self.input {
crate::Item::Table(values) => super::validate_struct_keys(&values.items, fields),
crate::Item::Value(crate::Value::InlineTable(values)) => {
super::validate_struct_keys(&values.items, fields)
}
_ => Ok(()),
}
.map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(span);
}
e
})?
}
self.deserialize_any(visitor)
}
// Called when the type to deserialize is an enum, as opposed to a field in the type.
fn deserialize_enum<V>(
self,
name: &'static str,
variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Error>
where
V: serde::de::Visitor<'de>,
{
let span = self.input.span();
match self.input {
crate::Item::Value(crate::Value::String(v)) => {
visitor.visit_enum(v.into_value().into_deserializer())
}
crate::Item::Value(crate::Value::InlineTable(v)) => {
if v.is_empty() {
Err(crate::de::Error::custom(
"wanted exactly 1 element, found 0 elements",
v.span(),
))
} else if v.len() != 1 {
Err(crate::de::Error::custom(
"wanted exactly 1 element, more than 1 element",
v.span(),
))
} else {
v.into_deserializer()
.deserialize_enum(name, variants, visitor)
}
}
crate::Item::Table(v) => v
.into_deserializer()
.deserialize_enum(name, variants, visitor),
e => Err(crate::de::Error::custom("wanted string or table", e.span())),
}
.map_err(|mut e: Self::Error| {
if e.span().is_none() {
e.set_span(span);
}
e
})
}
serde::forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq
bytes byte_buf map unit
ignored_any unit_struct tuple_struct tuple identifier
}
}
impl<'de> serde::de::IntoDeserializer<'de, crate::de::Error> for ValueDeserializer {
type Deserializer = Self;
fn into_deserializer(self) -> Self::Deserializer {
self
}
}
impl<'de> serde::de::IntoDeserializer<'de, crate::de::Error> for crate::Value {
type Deserializer = ValueDeserializer;
fn into_deserializer(self) -> Self::Deserializer {
ValueDeserializer::new(crate::Item::Value(self))
}
}
impl crate::Item {
pub(crate) fn into_deserializer(self) -> ValueDeserializer {
ValueDeserializer::new(self)
}
}
impl std::str::FromStr for ValueDeserializer {
type Err = Error;
/// Parses a value from a &str
fn from_str(s: &str) -> Result<Self, Self::Err> {
let v = crate::parser::parse_value(s).map_err(Error::from)?;
Ok(v.into_deserializer())
}
}
|
extern crate nalgebra;
extern crate jacobi;
extern crate pbr;
use std::io::Write;
use std::fs::File;
use std::f32;
use std::thread;
use pbr::ProgressBar;
use jacobi::{jacobi_iter, StencilElement};
use nalgebra::{DVector, Vector2};
pub fn write_ppm<W: Write>(w: &mut W,
c: &DVector<f32>,
width: usize, height: usize) {
write!(w, "P2\n{} {}\n255\n", width, height).unwrap();
let f = |v| -> u8 {(v * 255f32) as u8};
for i in 0..height {
for j in 0..width {
write!(w, "{} ",
f(c[j + 256*i])).unwrap();
}
write!(w, "\n").unwrap();
}
}
fn main() {
// 256x256 grid.
let size = 256*256;
let stencil = [
StencilElement{offset:1, value:1f32},
StencilElement{offset:256, value:1f32},
StencilElement{offset:-1, value:1f32},
StencilElement{offset:-256, value:1f32}
];
let indexer = |x: usize, y: usize| -> usize { x + 256*y };
let mut color_grid = DVector::<f32>::new_zeros(size);
let mut velocity_grid = DVector::<Vector2<f32>>::new_zeros(size);
let mut next_color_grid = DVector::<f32>::new_zeros(size);
let mut next_velocity_grid = DVector::<Vector2<f32>>::new_zeros(size);
let mut divergence = DVector::<f32>::new_zeros(size);
let mut pressure_grid = DVector::<f32>::new_zeros(size);
let mut next_pressure_grid = DVector::<f32>::new_zeros(size);
println!("Simulating 1000 frames.");
let mut progress_bar = ProgressBar::new(1000);
for frame in 0..1000 {
progress_bar.inc();
velocity_grid[indexer(127,0)] = Vector2::new(0.0f32, 3.0f32);
velocity_grid[indexer(128,0)] = Vector2::new(0.0f32, 3.0f32);
velocity_grid[indexer(126,0)] = Vector2::new(0.0f32, 3.0f32);
velocity_grid[indexer(129,0)] = Vector2::new(0.0f32, 3.0f32);
color_grid[indexer(127,0)] = 1f32;
color_grid[indexer(128,0)] = 1f32;
color_grid[indexer(126,0)] = 1f32;
color_grid[indexer(129,0)] = 1f32;
// 1. Advect color markers and velocity.
for x in 0..256 {
for y in 0..256 {
let delta = -velocity_grid[indexer(x, y)];
let sample_location = Vector2::new(x as f32, y as f32) + delta;
let sx = if sample_location.x < 0f32 { 0f32 }
else if sample_location.x > 255f32 { 255f32 }
else { sample_location.x };
let sy = if sample_location.y < 0f32 { 0f32 }
else if sample_location.y > 255f32 { 255f32 }
else { sample_location.y };
let x_floor = sx.floor();
let y_floor = sy.floor();
let x_ceil = sx.ceil();
let y_ceil = sy.ceil();
let x_frac = sx - x_floor;
let y_frac = sy - y_floor;
let f_indexer = |x, y| { indexer(x as usize, y as usize) };
let c_0 = color_grid[f_indexer(x_floor,y_floor)] * (1f32 - x_frac)
+ color_grid[f_indexer(x_ceil,y_floor)] * x_frac;
let c_1 = color_grid[f_indexer(x_floor,y_ceil)] * (1f32 - x_frac)
+ color_grid[f_indexer(x_ceil,y_ceil)] * x_frac;
let v_0 = velocity_grid[f_indexer(x_floor,y_floor)] * (1f32 - x_frac)
+ velocity_grid[f_indexer(x_ceil,y_floor)] * x_frac;
let v_1 = velocity_grid[f_indexer(x_floor,y_ceil)] * (1f32 - x_frac)
+ velocity_grid[f_indexer(x_ceil,y_ceil)] * x_frac;
next_color_grid[indexer(x, y)] = c_0 * (1f32 - y_frac) + c_1 * y_frac;
next_velocity_grid[indexer(x, y)] = v_0 * (1f32 - y_frac) + v_1 * y_frac;
}
}
std::mem::swap(&mut color_grid, &mut next_color_grid);
std::mem::swap(&mut velocity_grid, &mut next_velocity_grid);
// 2. Calculate divergence
for x in 0..256 {
for y in 0..256 {
let vx = match x {
0 => velocity_grid[indexer(x+1, y)].x,
255 => -velocity_grid[indexer(x-1, y)].x,
x => {
let px_0 = velocity_grid[indexer(x-1, y)].x;
let px_1 = velocity_grid[indexer(x+1, y)].x;
(px_1 - px_0) / 2f32
},
};
let vy = match y {
0 => velocity_grid[indexer(x, y+1)].y,
255 => -velocity_grid[indexer(x, y-1)].y,
y => {
let py_0 = velocity_grid[indexer(x, y-1)].y;
let py_1 = velocity_grid[indexer(x, y+1)].y;
(py_1 - py_0) / 2f32
},
};
divergence[indexer(x, y)] = vx + vy;
}
}
// 3. Approximate pressure jacobi iterations.
for _ in 0..50 {
jacobi_iter(-0.25f32, stencil.iter(),
&pressure_grid,
&mut next_pressure_grid,
&divergence);
std::mem::swap(&mut pressure_grid, &mut next_pressure_grid);
}
// 4. Apply pressure.
for x in 0..256 {
for y in 0..256 {
let vx = match x {
0 | 255 => 0.0f32,
x => {
let px_0 = pressure_grid[indexer(x-1, y)];
let px_1 = pressure_grid[indexer(x+1, y)];
(px_1 - px_0) / 2.0f32
},
};
let vy = match y {
0 | 255 => 0.0f32,
y => {
let py_0 = pressure_grid[indexer(x, y-1)];
let py_1 = pressure_grid[indexer(x, y+1)];
(py_1 - py_0) / 2.0f32
},
};
velocity_grid[indexer(x, y)] -= Vector2::new(vx, vy);
}
}
let buffer = color_grid.clone();
let frame = frame;
thread::spawn(move || {
let mut file = File::create(
&format!("images/fluid-frame{}.ppm", frame)).unwrap();
let _ = write_ppm(&mut file, &buffer, 256, 256);
});
}
}
|
#[doc = "Reader of register MIS"]
pub type R = crate::R<u32, super::MIS>;
#[doc = "Reader of field `CTSMIS`"]
pub type CTSMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `RXMIS`"]
pub type RXMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `TXMIS`"]
pub type TXMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `RTMIS`"]
pub type RTMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `FEMIS`"]
pub type FEMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `PEMIS`"]
pub type PEMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `BEMIS`"]
pub type BEMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `OEMIS`"]
pub type OEMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `_9BITMIS`"]
pub type _9BITMIS_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 1 - UART Clear to Send Modem Masked Interrupt Status"]
#[inline(always)]
pub fn ctsmis(&self) -> CTSMIS_R {
CTSMIS_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 4 - UART Receive Masked Interrupt Status"]
#[inline(always)]
pub fn rxmis(&self) -> RXMIS_R {
RXMIS_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - UART Transmit Masked Interrupt Status"]
#[inline(always)]
pub fn txmis(&self) -> TXMIS_R {
TXMIS_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - UART Receive Time-Out Masked Interrupt Status"]
#[inline(always)]
pub fn rtmis(&self) -> RTMIS_R {
RTMIS_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - UART Framing Error Masked Interrupt Status"]
#[inline(always)]
pub fn femis(&self) -> FEMIS_R {
FEMIS_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - UART Parity Error Masked Interrupt Status"]
#[inline(always)]
pub fn pemis(&self) -> PEMIS_R {
PEMIS_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - UART Break Error Masked Interrupt Status"]
#[inline(always)]
pub fn bemis(&self) -> BEMIS_R {
BEMIS_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - UART Overrun Error Masked Interrupt Status"]
#[inline(always)]
pub fn oemis(&self) -> OEMIS_R {
OEMIS_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 12 - 9-Bit Mode Masked Interrupt Status"]
#[inline(always)]
pub fn _9bitmis(&self) -> _9BITMIS_R {
_9BITMIS_R::new(((self.bits >> 12) & 0x01) != 0)
}
}
|
//! Assign a unique and immutable ID.
//!
//! Some types do not have a natural implementation for `PartialEq` or `Hash`.
//! In such cases, it can be convenient to assign an unique ID for each instance
//! of such types and use the ID to implement `PartialEq` or `Hash`.
//!
//! An ID have a length of 64-bit.
#![cfg_attr(not(any(test, doctest)), no_std)]
use core::sync::atomic::{AtomicU64, Ordering};
/// A unique id.
#[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
#[repr(transparent)]
pub struct ObjectId(u64);
impl ObjectId {
/// Create a new unique ID.
pub fn new() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
// Make sure that we can detect the overflow of id even in face of
// (extremely) concurrent addition on NEXT_ID.
assert!(id <= u64::max_value() / 2);
Self(id)
}
/// Return a special "null" ID.
///
/// Note that no ID created by `ObjectId::new()` will be equivalent to the
/// null ID.
pub const fn null() -> Self {
Self(0)
}
/// Get the ID value as `u64`.
pub const fn get(&self) -> u64 {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unique() {
let id0 = ObjectId::new();
let id1 = ObjectId::new();
assert!(id0 != id1);
assert!(id0.get() < id1.get());
}
#[test]
fn non_null() {
let id0 = ObjectId::new();
assert!(id0 != ObjectId::null());
}
}
|
//! TLS utilities.
//!
//! # Safety
//!
//! This file contains code that reads the raw phdr array pointed to by the
//! kernel-provided AUXV values.
#![allow(unsafe_code)]
use crate::backend::c;
use crate::backend::elf::*;
use crate::backend::param::auxv::exe_phdrs_slice;
use core::ptr::null;
/// For use with [`set_thread_area`].
///
/// [`set_thread_area`]: crate::runtime::set_thread_area
#[cfg(target_arch = "x86")]
pub type UserDesc = linux_raw_sys::general::user_desc;
pub(crate) fn startup_tls_info() -> StartupTlsInfo {
let mut base = null();
let mut tls_phdr = null();
let mut stack_size = 0;
let phdrs = exe_phdrs_slice();
// SAFETY: We assume the phdr array pointer and length the kernel provided
// to the process describe a valid phdr array.
unsafe {
for phdr in phdrs {
match phdr.p_type {
PT_PHDR => base = phdrs.as_ptr().cast::<u8>().sub(phdr.p_vaddr),
PT_TLS => tls_phdr = phdr,
PT_GNU_STACK => stack_size = phdr.p_memsz,
_ => {}
}
}
StartupTlsInfo {
addr: base.cast::<u8>().add((*tls_phdr).p_vaddr).cast(),
mem_size: (*tls_phdr).p_memsz,
file_size: (*tls_phdr).p_filesz,
align: (*tls_phdr).p_align,
stack_size,
}
}
}
/// The values returned from [`startup_tls_info`].
///
/// [`startup_tls_info`]: crate::runtime::startup_tls_info
pub struct StartupTlsInfo {
/// The base address of the TLS segment.
pub addr: *const c::c_void,
/// The size of the memory region.
pub mem_size: usize,
/// The size beyond which all memory is zero-initialized.
pub file_size: usize,
/// The required alignment for the TLS segment.
pub align: usize,
/// The requested minimum size for stacks.
pub stack_size: usize,
}
|
use core::cell::RefMut;
use hdk::{
self,
entry_definition::ValidatingEntryType,
error::ZomeApiResult,
holochain_core_types::{
cas::content::Address,
dna::entry_types::Sharing,
error::HolochainError,
json::JsonString,
entry::Entry,
},
};
use crate::cache::{self, Cache};
const SUBWIDGET_LINK_TAG: &str = "subwidgets";
/**
* This struct is what holochain uses for storing and validating a widget
*/
#[derive(Serialize, Deserialize, Debug, Clone, DefaultJson)]
pub struct WidgetEntry {
pub description: String
}
/**
* This function is used in define_zome! to register the widget entry
* Defines the validation and links for the entry
*/
pub fn def() -> ValidatingEntryType {
entry!(
name: "widget",
description: "Just your average widget",
sharing: Sharing::Public,
native_type: WidgetEntry,
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: |_message: WidgetEntry, _ctx: hdk::ValidationData| {
Ok(())
},
links: [
to!( // widgets can have subwidgets allowing infinite widget trees!
"widget",
tag: SUBWIDGET_LINK_TAG,
validation_package: || {
hdk::ValidationPackageDefinition::Entry
},
validation: |_base: Address, _target: Address, _ctx: hdk::ValidationData| {
Ok(())
}
)
]
)
}
pub fn get_widget(cache: RefMut<Cache>, widget_address: &Address) -> ZomeApiResult<WidgetEntry> {
cache::get_as_type(cache, widget_address)
}
pub fn get_subwidgets(cache: RefMut<Cache>, base_widget_address: &Address) -> ZomeApiResult<Vec<Address>> {
Ok(cache.get_links(base_widget_address, SUBWIDGET_LINK_TAG)?
.addresses()
.to_owned())
}
pub fn add_widget(mut cache: RefMut<Cache>, description: String) -> ZomeApiResult<Address> {
cache.commit_entry(&Entry::App(
"widget".into(),
WidgetEntry{description}.into()
))
}
pub fn add_subwidget(mut cache: RefMut<Cache>, base_address: &Address, target_address: &Address) -> ZomeApiResult<()> {
cache.link_entries(base_address, target_address, SUBWIDGET_LINK_TAG)
}
|
#![deny(warnings)]
#[macro_use]
extern crate stdweb;
extern crate gif;
use gif::{Repeat, SetParameter};
use std::cell::RefCell;
use stdweb::web::ArrayBuffer;
thread_local!{
static IMAGES: RefCell<Vec<Vec<u8>>> = RefCell::new(vec![]);
}
//添加一张图像数据rgba
fn add(data: Vec<u8>) -> i32 {
let mut count = -1;
IMAGES.with(|images| {
let mut images = images.borrow_mut();
images.push(data);
//js!(console.log(new Date(), "wasm: 图片添加完成"));
count = images.len() as i32;
});
count
}
fn count() -> i32 {
let mut count = -1;
IMAGES.with(|images| {
count = images.borrow().len() as i32;
});
count
}
fn clear() {
IMAGES.with(|images| {
images.borrow_mut().clear();
});
}
//生成gif
fn create(width: u16, height: u16, fps: u16) -> Vec<u8> {
let mut file = vec![];
IMAGES.with(|images| {
let mut images = images.borrow_mut();
{
let mut encoder = gif::Encoder::new(&mut file, width, height, &[]).unwrap();
encoder.set(Repeat::Infinite).unwrap();
let total = images.len() as i32;
let mut count = 0;
for image in &mut *images {
//js!(console.log(new Date(), "wasm: create count=", @{count}));
count += 1;
js!(worker.postMessage({what:"progress", arg0:@{count}, arg1:@{total}}));
let mut frame = gif::Frame::from_rgba(width, height, image);
frame.delay = 1000 / fps / 10; //设置帧率 10ms倍数
encoder.write_frame(&frame).unwrap();
//js!(console.log(new Date(), "wasm: create count=", @{count}, "帧添加完成."));
}
}
//let size = file.len() as i32;
//js!(console.log(new Date(), "wasm: create>10 文件大小:", @{size}));
});
file
}
#[allow(clippy::needless_pass_by_value)]
fn on_message(what: String, data: ArrayBuffer, width: u16, height: u16, fps: u16) {
let what = what.as_str();
match what {
"add" => {
let count = add(data.into());
js!{ worker.postMessage({what:"add", obj: @{count}}) }
}
"clear" => {
clear();
js!{ worker.postMessage({what:"clear"}) }
}
"create" => {
let img = create(width, height, fps);
js!{ worker.postMessage({what:"create", obj:@{img}}) }
}
"count" => {
let c = count();
js!{ worker.postMessage({what:"count", obj:@{c}}) }
}
_ => (),
}
}
fn main() {
stdweb::initialize();
let handle = |msg, data, width, height, fps| {
on_message(msg, data, width, height, fps);
};
js! {
var handle = @{handle};
worker.onMessage(function(msg){
console.log("线程收到消息:", msg);
handle(msg.what, msg.data, msg.width, msg.height, msg.fps);
});
console.log("线程准备完毕.");
worker.postMessage("init");
}
stdweb::event_loop();
}
|
use core::convert::TryInto;
use core::fmt;
use core::hash;
use core::str;
use anyhow::*;
use crate::erts::term::prelude::Boxed;
use super::prelude::{Binary, BinaryLiteral, HeapBin, IndexByte, MaybePartialByte, ProcBin};
/// A `BitString` that is guaranteed to always be a binary of aligned bytes
pub trait AlignedBinary: Binary {
/// Returns the underlying binary data as a byte slice
fn as_bytes(&self) -> &[u8];
/// Converts this binary to a `&str` slice.
///
/// This conversion does not move the string, it can be considered as
/// creating a new reference with a lifetime attached to that of `self`.
#[inline]
fn as_str<'a>(&'a self) -> &'a str {
assert!(
self.is_latin1() || self.is_utf8(),
"cannot convert a binary containing non-UTF-8/non-ASCII characters to &str"
);
unsafe { str::from_utf8_unchecked(self.as_bytes()) }
}
}
impl<T: ?Sized + AlignedBinary> AlignedBinary for Boxed<T> {
#[inline]
fn as_bytes(&self) -> &[u8] {
self.as_ref().as_bytes()
}
#[inline]
fn as_str(&self) -> &str {
self.as_ref().as_str()
}
}
impl<T: AlignedBinary> IndexByte for T {
default fn byte(&self, index: usize) -> u8 {
self.as_bytes()[index]
}
}
impl<A: AlignedBinary> MaybePartialByte for A {
#[inline]
default fn partial_byte_bit_len(&self) -> u8 {
0
}
#[inline]
default fn total_bit_len(&self) -> usize {
self.full_byte_len() * 8
}
#[inline]
default fn total_byte_len(&self) -> usize {
self.full_byte_len()
}
}
impl<A: AlignedBinary> MaybePartialByte for Boxed<A> {
#[inline]
fn partial_byte_bit_len(&self) -> u8 {
0
}
#[inline]
fn total_bit_len(&self) -> usize {
self.as_ref().full_byte_len() * 8
}
#[inline]
fn total_byte_len(&self) -> usize {
self.as_ref().full_byte_len()
}
}
macro_rules! impl_aligned_binary {
($t:ty) => {
impl fmt::Display for $t {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
display(self.as_bytes(), f)
}
}
impl hash::Hash for $t {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state)
}
}
impl Ord for $t {
/// > * Bitstrings are compared byte by byte, incomplete bytes are compared bit by bit.
/// > -- https://hexdocs.pm/elixir/operators.html#term-ordering
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.as_bytes().cmp(other.as_bytes())
}
}
impl PartialOrd for $t {
/// > * Bitstrings are compared byte by byte, incomplete bytes are compared bit by bit.
/// > -- https://hexdocs.pm/elixir/operators.html#term-ordering
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Eq for $t {}
impl PartialEq for $t {
/// > * Bitstrings are compared byte by byte, incomplete bytes are compared bit by bit.
/// > -- https://hexdocs.pm/elixir/operators.html#term-ordering
fn eq(&self, other: &$t) -> bool {
self.as_bytes().eq(other.as_bytes())
}
}
impl<T> PartialEq<T> for $t
where
T: ?Sized + AlignedBinary,
{
#[inline]
default fn eq(&self, other: &T) -> bool {
self.as_bytes().eq(other.as_bytes())
}
}
impl<T> PartialOrd<T> for $t
where
T: ?Sized + AlignedBinary,
{
#[inline]
default fn partial_cmp(&self, other: &T) -> Option<core::cmp::Ordering> {
self.as_bytes().partial_cmp(other.as_bytes())
}
}
impl TryInto<String> for &$t {
type Error = anyhow::Error;
fn try_into(self) -> Result<String, Self::Error> {
let s = str::from_utf8(self.as_bytes())
.with_context(|| format!("binary ({}) cannot be converted to String", self))?;
Ok(s.to_owned())
}
}
impl TryInto<String> for Boxed<$t> {
type Error = anyhow::Error;
fn try_into(self) -> Result<String, Self::Error> {
self.as_ref().try_into()
}
}
impl TryInto<Vec<u8>> for &$t {
type Error = anyhow::Error;
#[inline]
fn try_into(self) -> Result<Vec<u8>, Self::Error> {
Ok(self.as_bytes().to_vec())
}
}
impl TryInto<Vec<u8>> for Boxed<$t> {
type Error = anyhow::Error;
#[inline]
fn try_into(self) -> Result<Vec<u8>, Self::Error> {
self.as_ref().try_into()
}
}
};
}
impl_aligned_binary!(HeapBin);
impl_aligned_binary!(ProcBin);
impl_aligned_binary!(BinaryLiteral);
// We can't make this part of `impl_aligned_binary` because
// we can't implement TryInto directly for dynamically-sized types,
// only through references, so we implement them separately.
macro_rules! impl_aligned_try_into {
($t:ty) => {
impl TryInto<String> for $t {
type Error = anyhow::Error;
fn try_into(self) -> Result<String, Self::Error> {
let s = str::from_utf8(self.as_bytes())
.with_context(|| format!("binary ({}) cannot be converted to String", self))?;
Ok(s.to_owned())
}
}
impl TryInto<Vec<u8>> for $t {
type Error = anyhow::Error;
#[inline]
fn try_into(self) -> Result<Vec<u8>, Self::Error> {
Ok(self.as_bytes().to_vec())
}
}
};
}
impl_aligned_try_into!(ProcBin);
impl_aligned_try_into!(BinaryLiteral);
/// Displays a binary using Erlang-style formatting
pub(super) fn display(bytes: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("<<")?;
// Erlang restricts string formatting to only ascii.
if is_printable_ascii(bytes) {
write!(
f,
"\"{}\"",
str::from_utf8(bytes).unwrap().escape_default().to_string()
)?;
} else {
let mut iter = bytes.iter();
if let Some(byte) = iter.next() {
write!(f, "{}", byte)?;
for byte in iter {
write!(f, ",{}", byte)?;
}
}
}
f.write_str(">>")
}
// See https://github.com/erlang/otp/blob/dbf25321bdfdc3f4aae422b8ba2c0f31429eba61/erts/emulator/beam/erl_printf_term.c#L145-L149
fn is_printable_ascii(bytes: &[u8]) -> bool {
!bytes.iter().any(|byte| *byte < (' ' as u8) || *byte >= 127)
}
// Has to have explicit types to prevent E0119: conflicting implementations of trait
macro_rules! partial_eq_aligned_binary_aligned_binary {
($o:tt for $s:tt) => {
impl PartialEq<$o> for $s {
/// > * Bitstrings are compared byte by byte, incomplete bytes are compared bit by bit.
/// > -- https://hexdocs.pm/elixir/operators.html#term-ordering
fn eq(&self, other: &$o) -> bool {
self.as_bytes().eq(other.as_bytes())
}
}
};
}
// No (ProcBin for HeapBin) as we always reverse order to save space
partial_eq_aligned_binary_aligned_binary!(HeapBin for ProcBin);
partial_eq_aligned_binary_aligned_binary!(HeapBin for BinaryLiteral);
partial_eq_aligned_binary_aligned_binary!(ProcBin for BinaryLiteral);
|
#[doc = "Reader of register C1PR3"]
pub type R = crate::R<u32, super::C1PR3>;
#[doc = "Writer for register C1PR3"]
pub type W = crate::W<u32, super::C1PR3>;
#[doc = "Register C1PR3 `reset()`'s with value 0"]
impl crate::ResetValue for super::C1PR3 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Configurable event inputs x+64 Pending bit\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PR82_A {
#[doc = "0: No trigger request occurred"]
NOTPENDING = 0,
#[doc = "1: Selected trigger request occurred"]
PENDING = 1,
}
impl From<PR82_A> for bool {
#[inline(always)]
fn from(variant: PR82_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PR82`"]
pub type PR82_R = crate::R<bool, PR82_A>;
impl PR82_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PR82_A {
match self.bits {
false => PR82_A::NOTPENDING,
true => PR82_A::PENDING,
}
}
#[doc = "Checks if the value of the field is `NOTPENDING`"]
#[inline(always)]
pub fn is_not_pending(&self) -> bool {
*self == PR82_A::NOTPENDING
}
#[doc = "Checks if the value of the field is `PENDING`"]
#[inline(always)]
pub fn is_pending(&self) -> bool {
*self == PR82_A::PENDING
}
}
#[doc = "Configurable event inputs x+64 Pending bit\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PR82_AW {
#[doc = "1: Clears pending bit"]
CLEAR = 1,
}
impl From<PR82_AW> for bool {
#[inline(always)]
fn from(variant: PR82_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `PR82`"]
pub struct PR82_W<'a> {
w: &'a mut W,
}
impl<'a> PR82_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PR82_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears pending bit"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(PR82_AW::CLEAR)
}
#[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 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Configurable event inputs x+64 Pending bit"]
pub type PR84_A = PR82_A;
#[doc = "Reader of field `PR84`"]
pub type PR84_R = crate::R<bool, PR82_A>;
#[doc = "Configurable event inputs x+64 Pending bit"]
pub type PR84_AW = PR82_AW;
#[doc = "Write proxy for field `PR84`"]
pub struct PR84_W<'a> {
w: &'a mut W,
}
impl<'a> PR84_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PR84_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears pending bit"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(PR82_AW::CLEAR)
}
#[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 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Configurable event inputs x+64 Pending bit"]
pub type PR85_A = PR82_A;
#[doc = "Reader of field `PR85`"]
pub type PR85_R = crate::R<bool, PR82_A>;
#[doc = "Configurable event inputs x+64 Pending bit"]
pub type PR85_AW = PR82_AW;
#[doc = "Write proxy for field `PR85`"]
pub struct PR85_W<'a> {
w: &'a mut W,
}
impl<'a> PR85_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PR85_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears pending bit"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(PR82_AW::CLEAR)
}
#[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 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Configurable event inputs x+64 Pending bit"]
pub type PR86_A = PR82_A;
#[doc = "Reader of field `PR86`"]
pub type PR86_R = crate::R<bool, PR82_A>;
#[doc = "Configurable event inputs x+64 Pending bit"]
pub type PR86_AW = PR82_AW;
#[doc = "Write proxy for field `PR86`"]
pub struct PR86_W<'a> {
w: &'a mut W,
}
impl<'a> PR86_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PR86_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Clears pending bit"]
#[inline(always)]
pub fn clear(self) -> &'a mut W {
self.variant(PR82_AW::CLEAR)
}
#[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 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
impl R {
#[doc = "Bit 18 - Configurable event inputs x+64 Pending bit"]
#[inline(always)]
pub fn pr82(&self) -> PR82_R {
PR82_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 20 - Configurable event inputs x+64 Pending bit"]
#[inline(always)]
pub fn pr84(&self) -> PR84_R {
PR84_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - Configurable event inputs x+64 Pending bit"]
#[inline(always)]
pub fn pr85(&self) -> PR85_R {
PR85_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - Configurable event inputs x+64 Pending bit"]
#[inline(always)]
pub fn pr86(&self) -> PR86_R {
PR86_R::new(((self.bits >> 22) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 18 - Configurable event inputs x+64 Pending bit"]
#[inline(always)]
pub fn pr82(&mut self) -> PR82_W {
PR82_W { w: self }
}
#[doc = "Bit 20 - Configurable event inputs x+64 Pending bit"]
#[inline(always)]
pub fn pr84(&mut self) -> PR84_W {
PR84_W { w: self }
}
#[doc = "Bit 21 - Configurable event inputs x+64 Pending bit"]
#[inline(always)]
pub fn pr85(&mut self) -> PR85_W {
PR85_W { w: self }
}
#[doc = "Bit 22 - Configurable event inputs x+64 Pending bit"]
#[inline(always)]
pub fn pr86(&mut self) -> PR86_W {
PR86_W { w: self }
}
}
|
use std::pin::Pin;
use juniper::graphql_subscription;
type Stream<'a, I> = Pin<Box<dyn futures::Stream<Item = I> + Send + 'a>>;
struct Obj;
#[graphql_subscription]
impl Obj {
async fn id(&self, __num: i32) -> Stream<'static, &'static str> {
Box::pin(stream::once(future::ready("funA")))
}
}
fn main() {}
|
#[doc = "Reader of register SWIER2"]
pub type R = crate::R<u32, super::SWIER2>;
#[doc = "Writer for register SWIER2"]
pub type W = crate::W<u32, super::SWIER2>;
#[doc = "Register SWIER2 `reset()`'s with value 0"]
impl crate::ResetValue for super::SWIER2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Software interrupt on line 35\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SWI35_A {
#[doc = "1: Generates an interrupt request"]
PEND = 1,
}
impl From<SWI35_A> for bool {
#[inline(always)]
fn from(variant: SWI35_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SWI35`"]
pub type SWI35_R = crate::R<bool, SWI35_A>;
impl SWI35_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, SWI35_A> {
use crate::Variant::*;
match self.bits {
true => Val(SWI35_A::PEND),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PEND`"]
#[inline(always)]
pub fn is_pend(&self) -> bool {
*self == SWI35_A::PEND
}
}
#[doc = "Write proxy for field `SWI35`"]
pub struct SWI35_W<'a> {
w: &'a mut W,
}
impl<'a> SWI35_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SWI35_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Generates an interrupt request"]
#[inline(always)]
pub fn pend(self) -> &'a mut W {
self.variant(SWI35_A::PEND)
}
#[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 = "Software interrupt on line 36"]
pub type SWI36_A = SWI35_A;
#[doc = "Reader of field `SWI36`"]
pub type SWI36_R = crate::R<bool, SWI35_A>;
#[doc = "Write proxy for field `SWI36`"]
pub struct SWI36_W<'a> {
w: &'a mut W,
}
impl<'a> SWI36_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SWI36_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Generates an interrupt request"]
#[inline(always)]
pub fn pend(self) -> &'a mut W {
self.variant(SWI35_A::PEND)
}
#[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 = "Software interrupt on line 37"]
pub type SWI37_A = SWI35_A;
#[doc = "Reader of field `SWI37`"]
pub type SWI37_R = crate::R<bool, SWI35_A>;
#[doc = "Write proxy for field `SWI37`"]
pub struct SWI37_W<'a> {
w: &'a mut W,
}
impl<'a> SWI37_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SWI37_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Generates an interrupt request"]
#[inline(always)]
pub fn pend(self) -> &'a mut W {
self.variant(SWI35_A::PEND)
}
#[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 = "Software interrupt on line 38"]
pub type SWI38_A = SWI35_A;
#[doc = "Reader of field `SWI38`"]
pub type SWI38_R = crate::R<bool, SWI35_A>;
#[doc = "Write proxy for field `SWI38`"]
pub struct SWI38_W<'a> {
w: &'a mut W,
}
impl<'a> SWI38_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SWI38_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Generates an interrupt request"]
#[inline(always)]
pub fn pend(self) -> &'a mut W {
self.variant(SWI35_A::PEND)
}
#[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
}
}
impl R {
#[doc = "Bit 3 - Software interrupt on line 35"]
#[inline(always)]
pub fn swi35(&self) -> SWI35_R {
SWI35_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Software interrupt on line 36"]
#[inline(always)]
pub fn swi36(&self) -> SWI36_R {
SWI36_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Software interrupt on line 37"]
#[inline(always)]
pub fn swi37(&self) -> SWI37_R {
SWI37_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Software interrupt on line 38"]
#[inline(always)]
pub fn swi38(&self) -> SWI38_R {
SWI38_R::new(((self.bits >> 6) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 3 - Software interrupt on line 35"]
#[inline(always)]
pub fn swi35(&mut self) -> SWI35_W {
SWI35_W { w: self }
}
#[doc = "Bit 4 - Software interrupt on line 36"]
#[inline(always)]
pub fn swi36(&mut self) -> SWI36_W {
SWI36_W { w: self }
}
#[doc = "Bit 5 - Software interrupt on line 37"]
#[inline(always)]
pub fn swi37(&mut self) -> SWI37_W {
SWI37_W { w: self }
}
#[doc = "Bit 6 - Software interrupt on line 38"]
#[inline(always)]
pub fn swi38(&mut self) -> SWI38_W {
SWI38_W { w: self }
}
}
|
pub fn static_kv() {
println!("static_kv")
} |
extern crate failure;
extern crate log;
extern crate packt_core;
#[macro_use]
extern crate quicli;
use packt_core::problem;
use quicli::prelude::*;
use std::{fs::OpenOptions, io, path::PathBuf};
#[derive(Debug, StructOpt)]
struct Cli {
/// Amount of rectangles to generate
#[structopt(long = "count", short = "n")]
count: usize,
/// Whether solutions are allowed to rotate rectangles.
/// Will be generated randomly by default.
#[structopt(long = "rotation", short = "r")]
rotation: Option<bool>,
/// The height to which the solutions are bound.
/// This value should be greater than or equal to <count>.
/// Will be generated randomly by default.
#[structopt(long = "variant", short = "f")]
variant: Option<problem::Variant>,
/// Output file, stdout if not present
#[structopt(parse(from_os_str))]
output: Option<PathBuf>,
#[structopt(flatten)]
verbosity: Verbosity,
}
main!(|args: Cli, log_level: verbosity| {
let n = args.count;
let variant = args.variant;
let rotation = args.rotation;
let problem = problem::generate(n, variant, rotation);
let mut dest: Box<dyn io::Write> = match args.output {
Some(path) => Box::new(OpenOptions::new().write(true).create(true).open(path)?),
None => Box::new(io::stdout()),
};
dest.write_all(problem.to_string().as_bytes())?;
});
|
use gotham::state::State;
use gotham::prelude::FromState;
use gotham::hyper::Uri;
use std::env;
fn sample(state: State) -> (State, String) {
let uri = Uri::borrow_from(&state);
println!("path={}", uri);
let res = format!("ok:{}", uri);
(state, res)
}
fn main() {
let port = env::var("APP_PORT").unwrap_or("3000".to_owned());
let addr = format!("0.0.0.0:{}", port);
println!("listening: {}", addr);
gotham::start(addr, || Ok(sample)).unwrap();
}
|
use std::error::Error;
use regex_automata::{
hybrid::{
dfa::{self, DFA},
regex::Regex,
OverlappingState,
},
nfa::thompson,
HalfMatch, MatchError, MatchKind, MultiMatch,
};
use crate::util::{BunkPrefilter, SubstringPrefilter};
// Tests that too many cache resets cause the lazy DFA to quit.
//
// We only test this on 64-bit because the test is gingerly crafted based on
// implementation details of cache sizes. It's not a great test because of
// that, but it does check some interesting properties around how positions are
// reported when a search "gives up."
#[test]
#[cfg(target_pointer_width = "64")]
fn too_many_cache_resets_cause_quit() -> Result<(), Box<dyn Error>> {
// This is a carefully chosen regex. The idea is to pick one that requires
// some decent number of states (hence the bounded repetition). But we
// specifically choose to create a class with an ASCII letter and a
// non-ASCII letter so that we can check that no new states are created
// once the cache is full. Namely, if we fill up the cache on a haystack
// of 'a's, then in order to match one 'β', a new state will need to be
// created since a 'β' is encoded with multiple bytes. Since there's no
// room for this state, the search should quit at the very first position.
let pattern = r"[aβ]{100}";
let dfa = DFA::builder()
.configure(
// Configure it so that we have the minimum cache capacity
// possible. And that if any resets occur, the search quits.
DFA::config()
.skip_cache_capacity_check(true)
.cache_capacity(0)
.minimum_cache_clear_count(Some(0)),
)
.build(pattern)?;
let mut cache = dfa.create_cache();
let haystack = "a".repeat(101).into_bytes();
let err = MatchError::GaveUp { offset: 25 };
assert_eq!(dfa.find_earliest_fwd(&mut cache, &haystack), Err(err.clone()));
assert_eq!(dfa.find_leftmost_fwd(&mut cache, &haystack), Err(err.clone()));
assert_eq!(
dfa.find_overlapping_fwd(
&mut cache,
&haystack,
&mut OverlappingState::start()
),
Err(err.clone())
);
let haystack = "β".repeat(101).into_bytes();
let err = MatchError::GaveUp { offset: 0 };
assert_eq!(dfa.find_earliest_fwd(&mut cache, &haystack), Err(err));
// no need to test that other find routines quit, since we did that above
// OK, if we reset the cache, then we should be able to create more states
// and make more progress with searching for betas.
cache.reset(&dfa);
let err = MatchError::GaveUp { offset: 26 };
assert_eq!(dfa.find_earliest_fwd(&mut cache, &haystack), Err(err));
// ... switching back to ASCII still makes progress since it just needs to
// set transitions on existing states!
let haystack = "a".repeat(101).into_bytes();
let err = MatchError::GaveUp { offset: 13 };
assert_eq!(dfa.find_earliest_fwd(&mut cache, &haystack), Err(err));
Ok(())
}
// Tests that quit bytes in the forward direction work correctly.
#[test]
fn quit_fwd() -> Result<(), Box<dyn Error>> {
let dfa = DFA::builder()
.configure(DFA::config().quit(b'x', true))
.build("[[:word:]]+$")?;
let mut cache = dfa.create_cache();
assert_eq!(
dfa.find_earliest_fwd(&mut cache, b"abcxyz"),
Err(MatchError::Quit { byte: b'x', offset: 3 })
);
assert_eq!(
dfa.find_leftmost_fwd(&mut cache, b"abcxyz"),
Err(MatchError::Quit { byte: b'x', offset: 3 })
);
assert_eq!(
dfa.find_overlapping_fwd(
&mut cache,
b"abcxyz",
&mut OverlappingState::start()
),
Err(MatchError::Quit { byte: b'x', offset: 3 })
);
Ok(())
}
// Tests that quit bytes in the reverse direction work correctly.
#[test]
fn quit_rev() -> Result<(), Box<dyn Error>> {
let dfa = DFA::builder()
.configure(DFA::config().quit(b'x', true))
.thompson(thompson::Config::new().reverse(true))
.build("^[[:word:]]+")?;
let mut cache = dfa.create_cache();
assert_eq!(
dfa.find_earliest_rev(&mut cache, b"abcxyz"),
Err(MatchError::Quit { byte: b'x', offset: 3 })
);
assert_eq!(
dfa.find_leftmost_rev(&mut cache, b"abcxyz"),
Err(MatchError::Quit { byte: b'x', offset: 3 })
);
Ok(())
}
// Tests that if we heuristically enable Unicode word boundaries but then
// instruct that a non-ASCII byte should NOT be a quit byte, then the builder
// will panic.
#[test]
#[should_panic]
fn quit_panics() {
DFA::config().unicode_word_boundary(true).quit(b'\xFF', false);
}
// This tests an intesting case where even if the Unicode word boundary option
// is disabled, setting all non-ASCII bytes to be quit bytes will cause Unicode
// word boundaries to be enabled.
#[test]
fn unicode_word_implicitly_works() -> Result<(), Box<dyn Error>> {
let mut config = DFA::config();
for b in 0x80..=0xFF {
config = config.quit(b, true);
}
let dfa = DFA::builder().configure(config).build(r"\b")?;
let mut cache = dfa.create_cache();
let expected = HalfMatch::must(0, 1);
assert_eq!(dfa.find_leftmost_fwd(&mut cache, b" a"), Ok(Some(expected)));
Ok(())
}
// Tests that we can provide a prefilter to a Regex, and the search reports
// correct results.
#[test]
fn prefilter_works() -> Result<(), Box<dyn Error>> {
let mut re = Regex::new(r"a[0-9]+").unwrap();
re.set_prefilter(Some(Box::new(SubstringPrefilter::new("a"))));
let mut cache = re.create_cache();
let text = b"foo abc foo a1a2a3 foo a123 bar aa456";
let matches: Vec<(usize, usize)> = re
.find_leftmost_iter(&mut cache, text)
.map(|m| (m.start(), m.end()))
.collect();
assert_eq!(
matches,
vec![(12, 14), (14, 16), (16, 18), (23, 27), (33, 37),]
);
Ok(())
}
// This test confirms that a prefilter is active by using a prefilter that
// reports false negatives.
#[test]
fn prefilter_is_active() -> Result<(), Box<dyn Error>> {
let text = b"za123";
let mut re = Regex::new(r"a[0-9]+").unwrap();
let mut cache = re.create_cache();
re.set_prefilter(Some(Box::new(SubstringPrefilter::new("a"))));
assert_eq!(
re.find_leftmost(&mut cache, b"za123"),
Some(MultiMatch::must(0, 1, 5))
);
assert_eq!(
re.find_leftmost(&mut cache, b"a123"),
Some(MultiMatch::must(0, 0, 4))
);
re.set_prefilter(Some(Box::new(BunkPrefilter::new())));
assert_eq!(re.find_leftmost(&mut cache, b"za123"), None);
// This checks that the prefilter is used when first starting the search,
// instead of waiting until at least one transition has occurred.
assert_eq!(re.find_leftmost(&mut cache, b"a123"), None);
Ok(())
}
|
//! This module defines utilities for working with the `Result` type.
/// Adds utilities to the `Result` type.
pub trait ResultOps {
type Item;
type Error;
/// Call the given handler if this is an error and promote `Result` to `Option`.
fn handle_err<F>(self, f:F) -> Option<Self::Item> where F : FnOnce(Self::Error);
}
impl<T,E> ResultOps for Result<T,E> {
type Item = T;
type Error = E;
fn handle_err<F>(self, f:F) -> Option<Self::Item> where F : FnOnce(Self::Error) {
self.map_err(f).ok()
}
}
|
extern crate chrono;
use self::chrono::prelude::{DateTime, Utc};
use portfolio::Portfolio;
use strategy::{StrategyCollection, StrategyType};
use order::{Order, OrderStatus};
#[derive(PartialEq, Debug)]
pub struct OrderPair<'a> {
pub entry_order: &'a Order,
pub exit_order: &'a Order
}
fn get_execution_datetime(order: &Order) -> DateTime<Utc> {
match *order.status() {
OrderStatus::Filled(ref execution) => execution.datetime().clone(),
_ => panic!("Order is not executed")
}
}
pub fn get_order_pairs<'a>(portfolio: &'a Portfolio,
strategy_collection: &StrategyCollection) -> Vec<OrderPair<'a>>
{
let mut result = vec![];
for (order_id, order) in portfolio.closed_orders().iter() {
let strategy_id = strategy_collection.order_strategy.get(order_id)
.expect(format!("Can't find strategy for order #{}", order.id().clone()).as_str());
let strategy_type = strategy_collection.strategy_types.get(strategy_id)
.expect(format!("Can't find strategy type for strategy #{}", strategy_id).as_str());
if let &StrategyType::ExitStrategy(_strategy_id, _model, ref entry_order_id) = strategy_type {
if let &OrderStatus::Filled(_) = order.status() {
result.push(OrderPair {
entry_order: portfolio.closed_orders().get(entry_order_id).unwrap(),
exit_order: order
});
}
}
}
result.sort_by_key(|order_pair| get_execution_datetime(order_pair.entry_order));
result
}
#[cfg(test)]
mod test {
use super::*;
extern crate chrono;
use self::chrono::prelude::{DateTime, Utc, TimeZone};
use order::{OrderId, OrderStatus};
use execution::Execution;
use direction::Direction;
use symbol::SymbolId;
use strategy::{Strategy, StrategyType, StrategyCollection};
use model::{Model, ModelId};
use signal::detector::{DetectSignal, DetectSignalError};
use order::policy::MarketOrderPolicy;
use signal::Signal;
pub struct AlwaysDetectSignal {
symbol_id: SymbolId
}
impl DetectSignal for AlwaysDetectSignal {
fn detect_signal(&self, datetime: &DateTime<Utc>) -> Result<Option<Signal>, DetectSignalError> {
let signal = Signal::new(
self.symbol_id.clone(),
Direction::Long,
datetime.clone(),
String::from("always detect signal")
);
Ok(Some(signal))
}
}
pub struct OrderEveryCandle {
symbol_id: SymbolId
}
impl Model for OrderEveryCandle {
fn id(&self) -> ModelId {
ModelId::from("order every candle")
}
fn entry_strategy(&self) -> Strategy {
Strategy::new(
Box::new(AlwaysDetectSignal { symbol_id: self.symbol_id.clone() }),
Box::new(MarketOrderPolicy::new())
)
}
fn exit_strategies(&self, _order: &Order) -> Vec<Strategy> {
let strategy = Strategy::new(
Box::new(AlwaysDetectSignal { symbol_id: self.symbol_id.clone() }),
Box::new(MarketOrderPolicy::new())
);
vec![strategy]
}
}
#[test]
fn test_get_order_pairs() {
let mut portfolio = Portfolio::new();
let symbol_id = SymbolId::from("eur/usd");
let datetime = Utc.ymd(2017, 1, 1).and_hms(14, 0, 0);
let model = OrderEveryCandle {symbol_id: symbol_id.clone()};
let entry_strategy = model.entry_strategy();
let entry_order_id = OrderId::from("entry order");
let entry_order = entry_strategy.run(&datetime).unwrap().unwrap().1
.set_id(entry_order_id.clone())
.set_status(
OrderStatus::Filled(
Execution::new(
SymbolId::from("eur/usd"),
0, 1., datetime.clone()
)
)
)
.build()
.expect("failed to create entry order");
let exit_strategy = model.exit_strategies(&entry_order).remove(0);
let exit_order_id = OrderId::from("exit order");
let exit_order = exit_strategy.run(&datetime).unwrap().unwrap().1
.set_id(exit_order_id.clone())
.set_status(
OrderStatus::Filled(
Execution::new(
SymbolId::from("eur/usd"),
0, 1., datetime.clone()
)
)
)
.build()
.expect("failed to create exit order");
portfolio.add_orders(vec![entry_order, exit_order]);
let mut strategy_collection = StrategyCollection::new();
strategy_collection.order_strategy.insert(
entry_order_id.clone(),
entry_strategy.id().clone(),
);
strategy_collection.strategy_types.insert(
entry_strategy.id().clone(),
StrategyType::EntryStrategy(entry_strategy.id().clone(), &model)
);
strategy_collection.order_strategy.insert(
exit_order_id.clone(),
exit_strategy.id().clone(),
);
strategy_collection.strategy_types.insert(
exit_strategy.id().clone(),
StrategyType::ExitStrategy(
entry_strategy.id().clone(), &model, entry_order_id.clone()
)
);
assert_eq!(
get_order_pairs(&portfolio, &strategy_collection),
vec![
OrderPair {
entry_order: portfolio.closed_orders().get(&entry_order_id).unwrap(),
exit_order: portfolio.closed_orders().get(&exit_order_id).unwrap()
}
]
);
}
} |
use shrev::EventChannel;
use crate::event::*;
use std::collections::HashMap;
use std::collections::HashSet;
pub mod system;
#[derive(Default)]
pub struct InputHandler {
keyset: HashSet<String>,
}
impl InputHandler {
pub fn new() -> Self {
Default::default()
}
pub fn press(&mut self, key: &String) {
self.keyset.insert(key.clone());
}
pub fn release(&mut self, key: &String) {
self.keyset.remove(key);
}
pub fn is_pressed(&self, key: &String) -> bool {
self.keyset.get(key).is_some()
}
} |
use juniper::graphql_interface;
#[graphql_interface]
trait Character {
fn __id(&self) -> &str;
}
fn main() {}
|
use salvo::prelude::*;
use tracing_subscriber;
use tracing_subscriber::fmt::format::FmtSpan;
#[fn_handler]
async fn index(req: &mut Request, res: &mut Response) {
res.render_plain_text(&format!("remote address: {:?}", req.remote_addr()));
}
#[tokio::main]
async fn main() {
let filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "remote_addr=debug,salvo=debug".to_owned());
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_span_events(FmtSpan::CLOSE)
.init();
let router = Router::new().get(index);
Server::new(router).bind(([0, 0, 0, 0], 7878)).await;
}
|
use std::{fmt, result};
use crate::lexer::State::*;
#[derive(Clone, Debug, PartialEq)]
pub enum Token {
Charset(Vec<u8>),
Encoding(Vec<u8>),
EncodedText(Vec<u8>),
ClearText(Vec<u8>),
}
pub type Tokens = Vec<Token>;
enum State {
Charset,
Encoding,
EncodedText,
ClearText,
}
#[derive(Debug)]
pub enum Error {
ParseCharsetError,
ParseEncodingError,
ParseEncodedTextError,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::ParseCharsetError => {
write!(f, "the charset section is invalid or not terminated")
}
Error::ParseEncodingError => {
write!(f, "the encoding section is invalid or not terminated")
}
Error::ParseEncodedTextError => {
write!(f, "the encoded text section is invalid or not terminated")
}
}
}
}
type Result<T> = result::Result<T, Error>;
pub fn run(encoded_bytes: &[u8]) -> Result<Tokens> {
let mut encoded_bytes_iter = encoded_bytes.iter();
let mut curr_byte = encoded_bytes_iter.next();
let mut tokens = vec![];
let mut state = ClearText;
let mut buffer: Vec<u8> = vec![];
// 61 = Equal symbol '='
// 63 = Question mark symbol '?'
loop {
match state {
Charset => match curr_byte {
Some(63) => {
state = Encoding;
tokens.push(Token::Charset(buffer.clone()));
buffer.clear();
}
Some(b) => buffer.push(*b),
None => return Err(Error::ParseCharsetError),
},
Encoding => match curr_byte {
Some(63) => {
state = EncodedText;
tokens.push(Token::Encoding(buffer.clone()));
buffer.clear();
}
Some(b) => buffer.push(*b),
None => return Err(Error::ParseEncodingError),
},
EncodedText => match curr_byte {
Some(63) => {
curr_byte = encoded_bytes_iter.next();
match curr_byte {
Some(61) => {
state = ClearText;
tokens.push(Token::EncodedText(buffer.clone()));
buffer.clear();
}
_ => {
buffer.push(63);
continue;
}
}
}
Some(b) => buffer.push(*b),
None => return Err(Error::ParseEncodedTextError),
},
ClearText => match curr_byte {
Some(61) => {
curr_byte = encoded_bytes_iter.next();
match curr_byte {
Some(63) => {
state = Charset;
if !buffer.is_empty() {
tokens.push(Token::ClearText(buffer.clone()));
buffer.clear()
}
}
_ => {
buffer.push(61);
continue;
}
}
}
Some(b) => buffer.push(*b),
None => {
if !buffer.is_empty() {
tokens.push(Token::ClearText(buffer.clone()));
}
break;
}
},
}
curr_byte = encoded_bytes_iter.next();
}
Ok(tokens)
}
|
use super::Entry;
use anyhow::Error;
use nom::character::complete::{alpha1, anychar, char as ch, digit1, space1};
use nom::combinator::{map, map_opt};
use nom::sequence::{separated_pair, tuple};
use nom::{Finish, IResult};
impl Entry {
pub fn parse(input: &str) -> IResult<&str, Self> {
let range = map_opt(
separated_pair(digit1, ch('-'), digit1),
|(low, high): (&str, &str)| {
Some(low.parse::<usize>().ok()?..=high.parse::<usize>().ok()?)
},
);
map(
tuple((range, space1, anychar, ch(':'), space1, alpha1)),
|(r, _, c, _, _, pass)| Self {
range: r,
character: c,
password: pass.to_owned(),
},
)(input)
}
}
impl std::str::FromStr for Entry {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
let (_, entry) = Self::parse(s).finish().map_err(|err| nom::error::Error {
input: err.input.to_owned(),
code: err.code,
})?;
Ok(entry)
}
}
|
use regex::Regex;
use std::fs;
fn main() {
let result = solve_puzzle("input");
println!("And the result is {}", result);
}
fn solve_puzzle(file_name: &str) -> u64 {
let data = read_data(file_name);
data.lines().fold(0, |sum, line| sum + compute(line))
}
fn read_data(file_name: &str) -> String {
fs::read_to_string(file_name).expect("Error")
}
fn compute_simple(expression: &str) -> u64 {
let mut text = expression.replace(")", "").replace("(", "").to_string();
let re = Regex::new(r"(?P<segment>\d+( \+ \d+)+)").unwrap();
for cap in re.captures_iter(&text.clone()) {
let segment = cap["segment"].to_string();
let addition = segment
.split(" + ")
.fold(0, |acc, number| acc + number.parse::<u64>().unwrap());
text = text.replacen(&segment, &addition.to_string(), 1);
}
text.split(" * ")
.fold(1, |acc, number| acc * number.parse::<u64>().unwrap())
}
fn compute(expression: &str) -> u64 {
let mut text = expression.to_string();
let re = Regex::new(r"(?P<segment>\([\d\s\+\*]*\))").unwrap();
while text.chars().find(|x| *x == '(' || *x == ')').is_some() {
for cap in re.captures_iter(&text.clone()) {
let segment = cap["segment"].to_string();
text = text.replace(&segment, &compute_simple(&segment).to_string());
}
}
compute_simple(&text)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_input() {
assert_eq!(60807587180737, solve_puzzle("input"));
}
#[test]
fn test_basic_example() {
assert_eq!(51, compute("1 + (2 * 3) + (4 * (5 + 6))"));
}
#[test]
fn test_example_with_parenthesis() {
assert_eq!(46, compute("2 * 3 + (4 * 5)"));
}
#[test]
fn test_other_example_with_parenthesis() {
assert_eq!(1445, compute("5 + (8 * 3 + 9 + 3 * 4 * 3)"));
}
#[test]
fn test_example_with_nested_parenthesis() {
assert_eq!(669060, compute("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))"));
}
#[test]
fn test_example_with_multiple_nested_parenthesis() {
assert_eq!(
23340,
compute("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2")
);
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{bail, Error},
fidl_fuchsia_wlan_device as fidl_wlan_dev,
fidl_fuchsia_wlan_mlme::{self as fidl_mlme, DeviceInfo},
fuchsia_cobalt::CobaltSender,
fuchsia_wlan_dev as wlan_dev,
futures::{
channel::mpsc,
future::{Future, FutureExt, FutureObj},
select,
stream::{FuturesUnordered, Stream, StreamExt, TryStreamExt},
},
log::{error, info},
std::{marker::Unpin, sync::Arc},
wlan_sme::{self, clone_utils},
};
use crate::{
device_watch::{self, NewIfaceDevice},
mlme_query_proxy::MlmeQueryProxy,
station,
stats_scheduler::{self, StatsScheduler},
watchable_map::WatchableMap,
Never,
};
pub struct PhyDevice {
pub proxy: fidl_wlan_dev::PhyProxy,
pub device: wlan_dev::Device,
}
pub type ClientSmeServer = mpsc::UnboundedSender<super::station::client::Endpoint>;
pub type ApSmeServer = mpsc::UnboundedSender<super::station::ap::Endpoint>;
pub type MeshSmeServer = mpsc::UnboundedSender<super::station::mesh::Endpoint>;
pub enum SmeServer {
Client(ClientSmeServer),
Ap(ApSmeServer),
Mesh(MeshSmeServer),
}
pub struct IfaceDevice {
pub sme_server: SmeServer,
pub stats_sched: StatsScheduler,
pub device: wlan_dev::Device,
pub mlme_query: MlmeQueryProxy,
pub device_info: DeviceInfo,
}
pub type PhyMap = WatchableMap<u16, PhyDevice>;
pub type IfaceMap = WatchableMap<u16, IfaceDevice>;
pub async fn serve_phys(phys: Arc<PhyMap>) -> Result<Never, Error> {
let mut new_phys = device_watch::watch_phy_devices()?;
let mut active_phys = FuturesUnordered::new();
loop {
select! {
// OK to fuse directly in the `select!` since we bail immediately
// when a `None` is encountered.
new_phy = new_phys.next().fuse() => match new_phy {
None => bail!("new phy stream unexpectedly finished"),
Some(Err(e)) => bail!("new phy stream returned an error: {}", e),
Some(Ok(new_phy)) => {
let fut = serve_phy(&phys, new_phy);
active_phys.push(fut);
}
},
() = active_phys.select_next_some() => {},
}
}
}
async fn serve_phy(phys: &PhyMap, new_phy: device_watch::NewPhyDevice) {
info!("new phy #{}: {}", new_phy.id, new_phy.device.path().to_string_lossy());
let id = new_phy.id;
let event_stream = new_phy.proxy.take_event_stream();
phys.insert(id, PhyDevice { proxy: new_phy.proxy, device: new_phy.device });
let r = await!(event_stream.map_ok(|_| ()).try_collect::<()>());
phys.remove(&id);
if let Err(e) = r {
error!("error reading from the FIDL channel of phy #{}: {}", id, e);
}
info!("phy removed: #{}", id);
}
pub async fn serve_ifaces(
ifaces: Arc<IfaceMap>,
cobalt_sender: CobaltSender,
) -> Result<Never, Error> {
let mut new_ifaces = device_watch::watch_iface_devices()?;
let mut active_ifaces = FuturesUnordered::new();
loop {
select! {
new_iface = new_ifaces.next().fuse() => match new_iface {
None => bail!("new iface stream unexpectedly finished"),
Some(Err(e)) => bail!("new iface stream returned an error: {}", e),
Some(Ok(new_iface)) => {
let fut = query_and_serve_iface(new_iface, &ifaces, cobalt_sender.clone());
active_ifaces.push(fut);
}
},
() = active_ifaces.select_next_some() => {},
}
}
}
async fn query_and_serve_iface(
new_iface: NewIfaceDevice,
ifaces: &IfaceMap,
cobalt_sender: CobaltSender,
) {
let NewIfaceDevice { id, device, proxy } = new_iface;
let event_stream = proxy.take_event_stream();
let (stats_sched, stats_reqs) = stats_scheduler::create_scheduler();
let device_info = match await!(proxy.query_device_info()) {
Ok(x) => x,
Err(e) => {
error!("Failed to query new iface '{}': {}", device.path().display(), e);
return;
}
};
let result = create_sme(proxy.clone(), event_stream, &device_info, stats_reqs, cobalt_sender);
let (sme, sme_fut) = match result {
Ok(x) => x,
Err(e) => {
error!("Failed to create SME for new iface '{}': {}", device.path().display(), e);
return;
}
};
info!(
"new iface #{} with role '{:?}': {}",
id,
device_info.role,
device.path().to_string_lossy()
);
let mlme_query = MlmeQueryProxy::new(proxy);
ifaces
.insert(id, IfaceDevice { sme_server: sme, stats_sched, device, mlme_query, device_info });
let r = await!(sme_fut);
if let Err(e) = r {
error!("Error serving station for iface #{}: {}", id, e);
}
ifaces.remove(&id);
info!("iface removed: {}", id);
}
fn create_sme<S>(
proxy: fidl_mlme::MlmeProxy,
event_stream: fidl_mlme::MlmeEventStream,
device_info: &DeviceInfo,
stats_requests: S,
cobalt_sender: CobaltSender,
) -> Result<(SmeServer, impl Future<Output = Result<(), Error>>), Error>
where
S: Stream<Item = stats_scheduler::StatsRequest> + Send + Unpin + 'static,
{
let role = device_info.role;
let device_info = wlan_sme::DeviceInfo {
addr: device_info.mac_addr,
bands: clone_utils::clone_bands(&device_info.bands),
driver_features: device_info.driver_features.clone(),
};
match role {
fidl_mlme::MacRole::Client => {
let (sender, receiver) = mpsc::unbounded();
let fut = station::client::serve(
proxy,
device_info,
event_stream,
receiver,
stats_requests,
cobalt_sender,
);
Ok((SmeServer::Client(sender), FutureObj::new(Box::new(fut))))
}
fidl_mlme::MacRole::Ap => {
let (sender, receiver) = mpsc::unbounded();
let fut =
station::ap::serve(proxy, device_info, event_stream, receiver, stats_requests);
Ok((SmeServer::Ap(sender), FutureObj::new(Box::new(fut))))
}
fidl_mlme::MacRole::Mesh => {
let (sender, receiver) = mpsc::unbounded();
let fut =
station::mesh::serve(proxy, device_info, event_stream, receiver, stats_requests);
Ok((SmeServer::Mesh(sender), FutureObj::new(Box::new(fut))))
}
}
}
|
/*
Simple enum with two variants.
*/
use abomonation_derive::Abomonation;
#[derive(Debug, PartialEq, Copy, Clone, Abomonation)]
pub enum Either<D1, D2> {
Left(D1),
Right(D2),
}
|
pub struct Register {
pub v: [u8; 16],
pub I: u16,
pub pc: u16,
pub sp: u16,
}
impl Register {
pub fn new() -> Self {
Register {
v: [0; 16],
I: 0,
pc: 0x200,
sp: 0,
}
}
}
pub struct Cpu {
pub register: Register,
pub stack: [u16; 16],
pub delay_timer: u8,
pub sound_timer: u8,
}
impl Cpu {
pub fn new() -> Self {
Cpu {
register: Register::new(),
stack: [0; 16],
delay_timer: 0,
sound_timer: 0,
}
}
}
|
#![allow(dead_code)]
use std::mem;
use std::collections::{HashMap};
use parse::lexer::*;
use parse::tokens::*;
use ast::{Stmt, Expr, Block, TType, Local, Decl, OptionalTypeExprTupleList, OptionalParamInfoList, OptionalIdTypePairs};
use ast::Stmt::*;
use ast::Expr::*;
use ast::TType::*;
use ast::Decl::*;
//use ast::*;
use ptr::{B};
//use ast::{Expr, Stmt};
type BlockStack = Vec<Block>;
pub struct Parser{
lexer : Lexer,
block_stack : BlockStack,
paren_stack : Vec<char>,
square_stack : Vec<char>,
seq_expr_list : Vec<B<Expr>>,
last_expr_type : Option<TType>
}
impl Parser{
pub fn new(src : String)->Self{
Parser {
lexer : Lexer::new(src),
block_stack : BlockStack::new(),
paren_stack : Vec::new(),
square_stack : Vec::new(),
seq_expr_list : Vec::new(),
last_expr_type : None
}
}
pub fn start_lexer(&mut self){
self.lexer.get_char();
self.lexer.get_token();
}
pub fn run(& mut self)->Option<Block>{
self.parse_block()
//self.block.generate();
}
fn parse_block(& mut self)->Option<Block>{
//let mut b = Block::new();
//self.block_stack.push(b);
self.lexer.get_char();
self.program(); //begin parsing
debug_assert!(self.block_stack.len() == 1, "Only parent block should be on
the stack when the parsing is finished");
let main_block = self.block_stack.pop().unwrap();
//main_block.generate();
//if main_block.statements.len() == 0{
if !main_block.expr.is_some(){
None
}
else{
Some(main_block)
}
}
fn program(&mut self){
loop{
match self.lexer.get_token(){
//FIXME semicolon handling should change:
Token::SemiColon => continue,
Token::Nil |
Token::Number |
Token::LeftParen |
Token::Minus |
Token::If |
Token::While |
Token::For |
Token::Break |
Token::Let |
Token::Function |
Token::Ident |
Token::TokString => {
let expr = Some(self.expr().unwrap().1);
self.block_stack.last_mut().unwrap().expr = expr;
//FIXME should we break?
break;
},
/*Token::Do => {
debug_assert!(self.block_stack.len() > 0, "No parent block on the stack");
self.block_stack.push(Block::new());
self.expr();
if self.lexer.curr_token == Token::End{
//TODO make sure we track all block openings
let block = self.block_stack.pop().unwrap();
let mut curr_block = self.block_stack.last_mut().unwrap();
//curr_block.statements.push(Self::mk_block_stmt(block));
}
},*/
Token::Eof => {return},
Token::End => {
//TODO block stack pop
return
//continue;
},
_ => {panic!("Invalid token");}
}
}
}
//FIXME temporarily pub for integration testing
pub fn expr(&mut self) -> Option<(TType, B<Expr>)> {
match self.lexer.curr_token{
Token::Nil => {
Some((TNil, B(NilExpr)))
},
Token::Number => {
self.parse_num_expr()
//B(NumExpr(self.lexer.curr_string.clone().parse::<i32>().unwrap()))
},
Token::Ident => {
self.parse_ident_expr()
},
Token::TokString => {
self.parse_string_expr()
},
Token::Let =>{
self.parse_let_expr()
},
// Token::Function => {
// return self.parse_function_decl()
// },
Token::LeftParen => { //seqexpr
self.paren_stack.push('(');
while self.lexer.get_token() != Token::RightParen {
//Be careful when you set value of self.lexer.curr_token between here and self.expr()
//since logic in expr() assumes that self.lexer.curr_token will already be set
if self.lexer.curr_token == Token::SemiColon { continue; }
if self.lexer.curr_token == Token::Eof { panic!("Unexpected eof encountered") }
let optional_expr = self.expr();
if optional_expr.is_some() {
let (ty, e) = optional_expr.unwrap();
self.seq_expr_list.push(e);
self.last_expr_type = Some(ty);
}
//check closing paren here because self.expr() above could have curr_token set to it
if self.lexer.curr_token == Token::RightParen{
break;
}
}
self.paren_stack.pop();
if !self.paren_stack.is_empty() {
panic!("Missing ')'");
}
let last_type = mem::replace(&mut self.last_expr_type, None);
let expr_list = mem::replace(&mut self.seq_expr_list, Vec::new());
Some((last_type.unwrap(), B(SeqExpr(Some(expr_list)))))
},
Token::If => {
self.parse_if_then_else_expr()
},
Token::While => {
self.parse_while_expr()
},
Token::For => {
self.parse_for_expr()
},
Token::Array => {
self.parse_array_expr()
},
// Token::RightParen => {
// if self.paren_stack.is_empty(){
// panic!("Mismatched parenthesis");
// }
// self.paren_stack.pop();
// //TODO mem::replace self.seq_expr_list with Vec::new and assign it to SeqExpr
// Some(B(SeqExpr(None)))
// },
Token::End => panic!("Unexpected 'end'. Expected an expr."),
Token::RightSquare => {
panic!("");
},
t =>{ println!("{:?}", t); panic!("FIXME: handle more patterns")}
}
}
fn parse_let_expr(&mut self) -> Option<(TType, B<Expr>)>{
let b = Block::new();
//set parent-child relationship
self.block_stack.push(b);
let mut decls : Vec<Decl> = Vec::new();
loop{
match self.lexer.get_token() {
Token::Type => { //typedec
self.parse_type_decl(&mut decls);
},
Token::Var => { //Vardec
self.parse_var_decl(&mut decls);
},
Token::Function => { //functiondec
self.parse_function_decl(&mut decls);
},
Token::NewLine => continue,
//FIXME probably all these following guards are useless?
Token::In => break,
//FIXME Eof occurrence is an error
Token::Eof => break,
//FIXME End occurrence is an error
Token::End => break,
t => {println!("{:?}", t);panic!("Unexpected token. Expected a declaration or 'in'") }
}
//this is needed because a var decl parse can set the curr_token to 'in'
if self.lexer.curr_token == Token::In{
break;
}
}//let loop ends
let (_ty, _expr) =
if self.lexer.curr_token == Token::In{
//FIXME get the list of exprs and the type of the last expr in the list
self.lexer.get_token();
let expr = self.expr();
debug_assert!(expr.is_some(), "expr expected after 'in'");
expr.unwrap()
}
else{
panic!("Expected 'in' after declarations");
};
Some((_ty, B(LetExpr(decls, Some(_expr)))))
}
fn parse_type_decl(&mut self, decls : &mut Vec<Decl>){
match self.lexer.get_token() {
Token::Ident => {
let id = self.lexer.curr_string.clone();
match self.lexer.get_token(){
Token::Equals => {
match self.lexer.get_token(){
Token::Int => decls.push(TypeDec(id, TInt32)),
Token::TokString => decls.push(TypeDec(id, TString)),
Token::Ident => decls.push(TypeDec(id, TCustom(self.lexer.curr_string.clone()))),
Token::Array => {
match self.lexer.get_token() {
Token::Of => {
match self.lexer.get_token() {
Token::Int => {},
Token::TokString => {},
Token::Ident => {},
_ => panic!("Expected either int, string or type-id")
}
},
_ => panic!("Expected 'of' after 'array'")
}
},
Token::LeftCurly => { //rectype
},
_ => panic!("Expected either int, string, type-id, array of, '{' after '='")
}
},
_ => panic!("Expected '=' after type-id")
}
},
_ => panic!("Expected identifier after 'type'")
}
}
fn parse_record_decl(&mut self) -> OptionalIdTypePairs{
match self.lexer.get_token(){
Token::ColonEquals => {
self.parse_record_fields()
},
_ => panic!("Expected ':=' after 'rec'")
}
}
fn parse_record_fields(&mut self) -> OptionalIdTypePairs {
match self.lexer.get_token(){
Token::LeftCurly => {
let mut field_decs : Vec<(String, TType)> = Vec::new();
loop{
match self.lexer.get_token() {
Token::Comma => continue,
Token::RightCurly => {
break;
},
Token::Eof => panic!("Unexpected eof encountered. Expected a ')' after field-declaration."),
Token::Ident => {
let id = self.lexer.curr_string.clone();
//FIXME should we verify duplicate params here?
//HashMap and BTreeMap do not respect the order of insertions
//which is required to set up args during call.
//Vec will respect the order but cost O(n) for the verification
//Need multi_index kind of a structure from C++ Boost
if field_decs.iter().any(|ref tup| tup.0 == id){
panic!(format!("parameter '{}' found more than once", id));
}
match self.lexer.get_token() {
Token::Colon => {
match self.lexer.get_token() {
Token::Int |
Token::TokString |
Token::Ident => {
let ty = Self::get_ty_from_string(self.lexer.curr_string.as_str());
field_decs.push((id, ty));
},
_ => panic!("Expected type-id after ':'")
}
},
_ => panic!("Expected ':' after id")
}
},
_ => panic!("Expected a ')' or parameter id")
}
}
if field_decs.is_empty() {
None
}
else {
Some(field_decs)
}
},
_ => panic!("Expected a '{' after ':='")
}
}
fn parse_var_decl(&mut self, decls : &mut Vec<Decl>){
match self.lexer.get_token() {
Token::Ident => {
let id = self.lexer.curr_string.clone();
match self.lexer.get_token() {
Token::Colon => {
match self.lexer.get_token() {
Token::Int => {
match self.lexer.get_token(){
Token::ColonEquals => {
//get rhs expr and its type
let (ty, expr) = self.get_nxt_and_parse();
self.block_stack.last_mut().unwrap().sym_tab.borrow_mut().insert(id.clone(), ty);
decls.push(VarDec(id.clone(), TInt32, expr));
},
_ => panic!("Expected ':='")
}
},
Token::TokString => {
match self.lexer.get_token(){
Token::ColonEquals => {
self.expr();
},
_ => panic!("Expected ':='")
}
},
//FIXME this is just a hack to test arrays
//tiger doesn't mention specifying ':' for arrays
//so we are going to tweak the way arrays are declared
//by doing something like - var a : array := arrayof int[dim] of init;
Token::Array => {
match self.lexer.get_token(){
Token::ColonEquals => {
match self.lexer.get_token(){
Token::Array => {
//Some((TArray(B(array_ty)), B(ArrayExpr(arr_ty, dim_expr, init_expr))))
let (_ty, _expr) = self.parse_array_expr().unwrap();
decls.push(VarDec(id.clone(), _ty, _expr));
},
_ => panic!("Expected 'array' keyword after ':='")
}
},
_ => panic!("Expected ':='")
}
},
Token::Rec => {
let field_decls = self.parse_record_decl();
decls.push(VarDec(id.clone(), TRecord, B(RecordExpr(field_decls))));
},
_ => panic!("expr : pattern not covered")
}
},
_ => panic!("Expected ':' after identifier")
}
},
_ => panic!("Expected an identifier")
}
}
fn parse_ident_expr(&mut self) -> Option<(TType, B<Expr>)>{
//check if symbol defined in the sym tab
//if self.block_stack.last().unwrap().contains(self.lexer.curr_string)
let op1 = B(IdExpr(self.lexer.curr_string.clone()));
let fn_name = self.lexer.curr_string.clone();
match self.lexer.get_token(){
Token::LeftSquare => { //a[
//FIXME check nested brackets
//self.square_stack.push('[');
let idx_expr = self.get_nxt_and_parse();
match self.lexer.curr_token{
Token::RightSquare =>{
//FIXME can something be done about cloning the expression?
let subscript_expr = Some((TVoid, B(SubscriptExpr(fn_name.clone(), idx_expr.1.clone()))));
//check if something getting assigned to the subscript
match self.lexer.get_token(){
Token::ColonEquals => { //a[i] :=
//let rhs_expr = self.get_nxt_and_parse();
return Some((TVoid, B(AssignExpr(B(SubscriptExpr(fn_name.clone(), idx_expr.1)),
self.get_nxt_and_parse().1))))
},
_ => {
return subscript_expr
}
}
},
_ => {
println!("{:?}", self.lexer.curr_token);
panic!("");
}
}
}, //subscript
Token::Dot => {
println!("parsing field access");
return Some((TNil, B(FieldExpr(op1,
match self.lexer.get_token(){
Token::Ident => {
self.parse_ident_expr().unwrap().1
},
Token::End => {
B(NoOpExpr)
},
_ => panic!("Expected an identifier during field access")
}
))))
}, //fieldexp
Token::LeftParen => { //callexpr
println!("parsing call");
let args_list = self.parse_call_args();
//FIXME should a marker type be used instead of TVoid to indicate that the type should be verified by the type-checker?
match self.lexer.curr_token{
Token::Plus => {
let (_, op2) = self.get_nxt_and_parse();
return Some((TInt32, B(AddExpr(B(CallExpr(fn_name, args_list)), op2))))
},
Token::Minus => {
let (_, op2) = self.get_nxt_and_parse();
return Some((TInt32, B(SubExpr(B(CallExpr(fn_name, args_list)), op2))))
},
Token::Mul => {
let (_, op2) = self.get_nxt_and_parse();
return Some((TInt32, B(MulExpr(B(CallExpr(fn_name, args_list)), op2))))
},
Token::Div => {
let (_, op2) = self.get_nxt_and_parse();
return Some((TInt32, B(DivExpr(B(CallExpr(fn_name, args_list)), op2))))
},
_ => {}
}
if let IdExpr(ref fn_name) = *op1 {
return Some((TVoid, B(CallExpr(fn_name.clone(), args_list))))
};
},
Token::Plus => {
let (_, op2) = self.get_nxt_and_parse();
return Some((TInt32, B(AddExpr(op1, op2))))
//FIXME it's better to let the type-checker do the checking
//if t == TInt32{
//return Some((TInt32, B(AddExpr(op1, op2))))
//}
//else{
//panic!("Expected i32 as the type of rhs expression");
//}
},
Token::ColonEquals => {
return Some((TVoid, B(AssignExpr(B(IdExpr(fn_name.clone())),
self.get_nxt_and_parse().1))))
},
Token::Equals => {
let (_, op2) = self.get_nxt_and_parse();
return Some((TVoid, B(EqualsExpr(op1, op2))))
},
_ => {
//TVoid because we dont know the type of the identifier yet.
return Some((TVoid, op1))
}
}
Some((TVoid, op1))
}
fn parse_string_expr(&mut self) -> Option<(TType, B<Expr>)>{
Some((TString, B(StringExpr(self.lexer.curr_string.clone()))))
}
fn parse_num_expr(&mut self) -> Option<(TType, B<Expr>)>{
let num = self.lexer.curr_string.parse::<i32>().unwrap();
let op1 = B(NumExpr(num));
match self.lexer.get_token(){
Token::Plus => {
let (t, op2) = self.get_nxt_and_parse();
//FIXME it's better to use a type-checker
if t == TInt32{
Some((TInt32, B(AddExpr(op1, op2))))
}
else{
panic!("Expected i32 as the type of rhs expression");
}
},
Token::Minus => {
let (t, op2) = self.get_nxt_and_parse();
//FIXME it's better to use a type-checker
if t == TInt32{
Some((TInt32, B(SubExpr(op1, op2))))
}
else{
panic!("Expected i32 as the type of rhs expression");
}
},
Token::Mul => {
let (t, op2) = self.get_nxt_and_parse();
//FIXME it's better to use a type-checker
if t == TInt32{
Some((TInt32, B(MulExpr(op1, op2))))
}
else{
panic!("Expected i32 as the type of rhs expression");
}
},
Token::Div => {
let (t, op2) = self.get_nxt_and_parse();
//FIXME it's better to use a type-checker
if t == TInt32{
Some((TInt32, B(DivExpr(op1, op2))))
}
else{
panic!("Expected i32 as the type of rhs expression");
}
},
Token::Equals => {
let (_, op2) = self.get_nxt_and_parse();
Some((TVoid, B(EqualsExpr(op1, op2))))
},
Token::LessThan => {
let (_, op2) = self.get_nxt_and_parse();
Some((TVoid, B(LessThanExpr(op1, op2))))
},
Token::GreaterThan => {
let (_, op2) = self.get_nxt_and_parse();
Some((TVoid, B(GreaterThanExpr(op1, op2))))
},
Token::LessThanGreaterThan => {
let (_, op2) = self.get_nxt_and_parse();
Some((TVoid, B(NotEqualsExpr(op1, op2))))
},
//FIXME ';', ')' can be a encountered as well. deal with it.
_ => {
Some((TInt32, op1))
}
}
}
fn parse_function_decl(&mut self, decls : &mut Vec<Decl>){
match self.lexer.get_token(){
Token::Ident => {
let id = self.lexer.curr_string.clone();
//parse the parameters list
let field_decs = self.parse_function_params_list();
//parse return type
let ret_type = self.parse_function_ret_type();
//parse body here
let e = self.expr();
debug_assert!(e.is_some(), "Function body cannot be empty");
let body = e.unwrap();
//function id ( fieldDec; ) : tyId = exp
decls.push(FunDec(id, field_decs, ret_type, body.1, body.0));
},
_ => panic!("Expected an id after 'function'")
}
}
fn parse_function_params_list(&mut self) -> OptionalParamInfoList {
match self.lexer.get_token(){
Token::LeftParen => {
let mut field_decs : Vec<(String, TType)> = Vec::new();
loop{
match self.lexer.get_token() {
Token::Comma => continue,
Token::RightParen => { //parameterless function
break;
},
Token::Eof => panic!("Unexpected eof encountered. Expected a ')' after field-declaration."),
Token::Ident => {
let id = self.lexer.curr_string.clone();
//FIXME should we verify duplicate params here?
//HashMap and BTreeMap do not respect the order of insertions
//which is required to set up args during call.
//Vec will respect the order but cost O(n) for the verification
//Need multi_index kind of a structure from C++ Boost
if field_decs.iter().any(|ref tup| tup.0 == id){
panic!(format!("parameter '{}' found more than once", id));
}
match self.lexer.get_token() {
Token::Colon => {
match self.lexer.get_token() {
Token::Int |
Token::TokString |
Token::Ident => {
let ty = Self::get_ty_from_string(self.lexer.curr_string.as_str());
field_decs.push((id, ty));
},
_ => panic!("Expected type-id after ':'")
}
},
_ => panic!("Expected ':' after id")
}
},
_ => panic!("Expected a ')' or parameter id")
}
}
if field_decs.is_empty() {None} else {Some(field_decs)}
},
_ => panic!("Expected a '(' after function id")
}
}
fn parse_call_args(&mut self) -> OptionalTypeExprTupleList{
let mut args_list = Vec::new();
loop {
println!("loop");
match self.lexer.get_token() {
Token::RightParen => break,
Token::Number |
Token::Ident |
Token::TokString => {
println!("{:?}", self.lexer.curr_token);
let e = self.expr();
if e.is_some() {
args_list.push(e.unwrap());
}
},
_ => {
panic!("Invalid expression used as a call argument");
}
//_ => panic!("Invalid expression used as a call argument")
}
if self.lexer.curr_token == Token::RightParen {
break
}
}
self.lexer.get_token();
if args_list.is_empty() {None} else {Some(args_list)}
}
fn parse_function_ret_type(&mut self) -> TType{
match self.lexer.get_token() {
Token::Colon => {
match self.lexer.get_token() {
Token::Int |
Token::TokString |
Token::Ident => {
let ty = Self::get_ty_from_string(self.lexer.curr_string.as_str());
match self.lexer.get_token(){
Token::Equals => {self.lexer.get_token();},
_ => panic!("Expected '=' after the return type")
}
ty
},
_ => panic!("Expected a type after ':'")
}
}
Token::Equals => {
self.lexer.get_token(); //eat '='
TVoid
}
_ => panic!("Expected ':' or '=' after the parameter list")
}
}
fn get_ty_from_string(str_ : &str) -> TType{
match str_ {
"int" => TInt32,
"string" => TString,
_ => TCustom(str_.to_string())
}
}
fn get_nxt_and_parse(&mut self) -> (TType, B<Expr>){
self.lexer.get_token();
self.expr().unwrap()
}
fn parse_while_expr(&mut self) -> Option<(TType, B<Expr>)>{
self.lexer.get_token();
let opt_tup = self.expr().unwrap();
//Because ident-expr parsing advances to the next token
//and returns a TVoid, there is an extra check on the
//curr_token
if opt_tup.0 != TInt32 && self.lexer.curr_token != Token::Do{
self.lexer.get_token();
}
match self.lexer.curr_token {
Token::Do => {
self.lexer.get_token();
let (ty, body) = self.expr().unwrap();
Some((ty, B(WhileExpr(opt_tup.1, body))))
},
_ => panic!("Expected 'do' after the while expression")
}
}
fn parse_if_then_else_expr(&mut self) -> Option<(TType, B<Expr>)>{
//eat 'if'
self.lexer.get_token();
//parse the conditional expr
let opt_tup = self.expr().unwrap();
//since only arithmetic expr parsing advances to point to the next token,
//we do a typecheck in order to determine if we match on the curr_token
//or call get_token()
if opt_tup.0 != TInt32 && self.lexer.curr_token != Token::Then{
self.lexer.get_token();
}
match self.lexer.curr_token {
Token::Then => {
self.lexer.get_token(); //advance to the next token
let (_, then_expr) = self.expr().unwrap();
match self.lexer.curr_token {
Token::Else => {
self.lexer.get_token(); //advance to the next token
let (_, else_body) = self.expr().unwrap();
return Some((TVoid, B(IfThenElseExpr(opt_tup.1, then_expr, else_body))))
}
t => {} //FIXME this isn't an if-then-else expr. should we do something here?
}
Some((TVoid, B(IfThenExpr(opt_tup.1, then_expr))))
},
_ => panic!("Expected then after the if expression")
}
}
fn parse_for_expr(&mut self) -> Option<(TType, B<Expr>)>{
match self.lexer.get_token(){
Token::Ident => {
let id = self.lexer.curr_string.clone();
match self.lexer.get_token(){
Token::ColonEquals => {
self.lexer.get_token();
let (_, id_expr) = self.expr().unwrap();
match self.lexer.curr_token{
Token::To => {
self.lexer.get_token();
let (_, to_expr) = self.expr().unwrap();
match self.lexer.curr_token{
Token::Do => {
self.lexer.get_token();
let (_, do_expr) = self.expr().unwrap();
Some((TVoid, B(ForExpr(id, id_expr, to_expr, do_expr))))
},
_ => panic!("Expected 'do' after expression")
}
},
_ => panic!("Expected 'to' after expression")
}
},
_ => panic!("Expected := after ident in a for construct")
}
},
_ => panic!("Expected an ident after 'for'")
}
}
fn parse_array_expr(&mut self) -> Option<(TType, B<Expr>)>{
match self.lexer.get_token(){
Token::Of => {
let mut array_ty = TNil;
match self.lexer.get_token(){
Token::Int => array_ty = TInt32,
Token::TokString => array_ty = TString,
_ => panic!("Invalid array type")
}
match self.lexer.get_token(){
Token::LeftSquare => {
let (dim_ty, dim_expr) = self.get_nxt_and_parse();
//match self.lexer.get_token(){
// Token::RightSquare => {
match self.lexer.get_token(){
Token::Of => {
let (init_ty, init_expr) = self.get_nxt_and_parse();
let arr_ty = array_ty.clone();
Some((TArray(B(array_ty)), B(ArrayExpr(arr_ty, dim_expr, init_expr))))
},
_ => panic!("Expected array initialization expression")
}
// },
// _ => {println!("{:?}", self.lexer.curr_token); panic!("Expected ']' after dimension expression");}
//}
},
_ => panic!("Expected '[' after 'of'")
}
},
_ => panic!("Expected 'of' after 'array'")
}
}
}
#[cfg(test)]
mod tests {
use parse::tokens::*;
use ast::TType::*;
use ast::Decl::*;
use ast::Expr::*;
use super::*;
#[test]
fn test_func_decl_no_params() {
let mut p = Parser::new("function foo()=print(\"ab\")".to_string());
p.start_lexer();
let mut decls = Vec::new();
p.parse_function_decl(&mut decls);
assert_eq!(decls.len(), 1);
match &decls[0]{
&FunDec(ref name, _, ref ty, ref b_expr, ref b_type) => {
assert_eq!(String::from("foo"), *name);
assert_eq!(TVoid, *ty);
match &**b_expr {
&CallExpr(ref name, _) => assert_eq!(String::from("print"), *name),
_ => {}
}
},
_ => {}
}
}
#[test]
#[should_panic(expected="parameter 'a' found more than once")]
fn test_parse_function_params_list_duplicate_params() {
let mut p = Parser::new("foo(a:int, a:int)".to_string());
p.start_lexer();
p.parse_function_params_list();
}
#[test]
fn test_parse_call_expr_num_expr(){
let mut p = Parser::new("f(1)".to_string());
p.start_lexer();
let tup = p.expr();
assert_eq!(tup.is_some(), true);
let (ty, b_expr) = tup.unwrap();
assert_eq!(ty, TVoid);
match *b_expr {
CallExpr(ref n, ref type_expr_lst) => {
assert_eq!(n, "f");
assert_eq!(type_expr_lst.is_some(), true);
match type_expr_lst{
&Some(ref l) => {
assert_eq!(l.len(), 1);
let (ref ty, ref b_expr) = l[0usize];
assert_eq!(*ty, TInt32);
match &**b_expr {
&NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_parse_call_expr_ident_expr(){
let mut p = Parser::new("f(abc)".to_string());
p.start_lexer();
let tup = p.expr();
assert_eq!(tup.is_some(), true);
let (ty, b_expr) = tup.unwrap();
assert_eq!(ty, TVoid);
match *b_expr {
CallExpr(ref n, ref type_expr_lst) => {
assert_eq!(n, "f");
assert_eq!(type_expr_lst.is_some(), true);
match type_expr_lst{
&Some(ref l) => {
assert_eq!(l.len(), 1);
let (ref ty, ref b_expr) = l[0usize];
assert_eq!(*ty, TVoid);
match &**b_expr {
&IdExpr(ref id) => assert_eq!(*id, "abc"),
_ => {}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_only_string_expr() {
let mut p = Parser::new("\"abc\"".to_string());
p.start_lexer();
assert_eq!(p.lexer.curr_token, Token::TokString);
}
#[test]
fn test_parse_call_expr_string_arg(){
let mut p = Parser::new("f(\"abc\")".to_string());
p.start_lexer();
let tup = p.expr();
assert_eq!(tup.is_some(), true);
let (ty, b_expr) = tup.unwrap();
assert_eq!(ty, TVoid);
match *b_expr {
CallExpr(ref n, ref type_expr_lst) => {
assert_eq!(n, "f");
assert_eq!(type_expr_lst.is_some(), true);
match type_expr_lst{
&Some(ref l) => {
assert_eq!(l.len(), 1);
let (ref ty, ref b_expr) = l[0usize];
assert_eq!(*ty, TString);
match &**b_expr {
&StringExpr(ref value) => assert_eq!(*value, "abc"),
_ => {}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_parse_call_expr_inum_ident_exprs(){
let mut p = Parser::new("f(1, abc)".to_string());
p.start_lexer();
let tup = p.expr();
assert_eq!(tup.is_some(), true);
let (ty, b_expr) = tup.unwrap();
assert_eq!(ty, TVoid);
match *b_expr {
CallExpr(ref n, ref type_expr_lst) => {
assert_eq!(n, "f");
assert_eq!(type_expr_lst.is_some(), true);
match type_expr_lst{
&Some(ref l) => {
assert_eq!(l.len(), 2);
let (ref ty, ref b_expr) = l[1usize];
assert_eq!(*ty, TVoid);
match &**b_expr {
&IdExpr(ref id) => assert_eq!(*id, "abc"),
_ => {}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_parse_call_expr_add_expr(){
let mut p = Parser::new("f(1+2)".to_string());
p.start_lexer();
let tup = p.expr();
assert_eq!(tup.is_some(), true);
let (ty, b_expr) = tup.unwrap();
assert_eq!(ty, TVoid);
match *b_expr {
CallExpr(ref n, ref type_expr_lst) => {
assert_eq!(n, "f");
assert_eq!(type_expr_lst.is_some(), true);
match type_expr_lst{
&Some(ref l) => {
assert_eq!(l.len(), 1);
let (ref ty, ref b_expr) = l[0usize];
assert_eq!(*ty, TInt32);
match &**b_expr {
&AddExpr(ref op1, ref op2) => {
match &**op1 {
&NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
match &**op2 {
&NumExpr(n) => assert_eq!(n, 2),
_ => {}
}
},
_ => {}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_parse_call_expr_add_expr_with_call_expr_and_num_expr(){
let mut p = Parser::new("f(a()+2)".to_string());
p.start_lexer();
let tup = p.expr();
assert_eq!(tup.is_some(), true);
let (ty, b_expr) = tup.unwrap();
assert_eq!(ty, TVoid);
match *b_expr {
CallExpr(ref n, ref type_expr_lst) => {
assert_eq!(n, "f");
assert_eq!(type_expr_lst.is_some(), true);
match type_expr_lst{
&Some(ref l) => {
//assert_eq!(l.len(), 1);
let (ref ty, ref b_expr) = l[0usize];
//assert_eq!(*ty, TInt32);
match &**b_expr {
&AddExpr(ref op1, ref op2) => {
match &**op1 {
&NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
match &**op2 {
&NumExpr(n) => assert_eq!(n, 2),
_ => {}
}
},
&NumExpr(_) => panic!("num expr") ,
&CallExpr(_, _) => panic!("callexpr"),
_ => {panic!("Different expr found")}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_parse_call_expr_no_args(){
let mut p = Parser::new("f()".to_string());
p.start_lexer();
let tup = p.expr();
assert_eq!(tup.is_some(), true);
let (ty, b_expr) = tup.unwrap();
assert_eq!(ty, TVoid);
match *b_expr {
CallExpr(ref n, _) => assert_eq!(n, "f"),
_ => {}
}
}
#[test]
fn test_parse_func_ret_type_void(){
let mut p = Parser::new(")=".to_string());
p.start_lexer();
let ty = p.parse_function_ret_type();
assert_eq!(ty, TVoid);
}
#[test]
fn test_parse_func_ret_type_int(){
let mut p = Parser::new(") : int =".to_string());
p.start_lexer();
let ty = p.parse_function_ret_type();
assert_eq!(ty, TInt32);
}
#[test]
fn test_parse_func_ret_type_string(){
let mut p = Parser::new(") : string =".to_string());
p.start_lexer();
let ty = p.parse_function_ret_type();
assert_eq!(ty, TString);
}
#[test]
fn test_parse_func_ret_type_custom(){
let mut p = Parser::new(") : custom =".to_string());
p.start_lexer();
let ty = p.parse_function_ret_type();
assert_eq!(ty, TCustom("custom".to_string()));
}
#[test]
fn test_field_decs_none(){
let mut p = Parser::new("f()".to_string());
p.start_lexer();
let m = p.parse_function_params_list();
assert_eq!(m, None);
}
#[test]
fn test_field_decs_one_dec(){
let mut p = Parser::new("f(a: int)".to_string());
p.start_lexer();
let m = p.parse_function_params_list();
assert_eq!(m.is_some(), true);
assert_eq!(m.unwrap().len(), 1);
}
#[test]
fn test_field_decs_two_decs(){
let mut p = Parser::new("f(a: int, b:int)".to_string());
p.start_lexer();
let m = p.parse_function_params_list();
assert_eq!(m.is_some(), true);
assert_eq!(m.unwrap().len(), 2);
}
#[test]
fn test_field_decs_two_decs_int_string(){
let mut p = Parser::new("f(a: int, b:string)".to_string());
p.start_lexer();
let m = p.parse_function_params_list().unwrap();
assert_eq!(m.len(), 2);
assert_eq!(m[0].1, TInt32);
assert_eq!(m[1].1, TString);
}
#[test]
fn test_field_decs_one_dec_with_alias(){
let mut p = Parser::new("f(a: myint)".to_string());
p.start_lexer();
let m = p.parse_function_params_list().unwrap();
assert_eq!(m[0].1, TCustom("myint".to_string()));
}
#[test]
#[should_panic(expected="Unexpected eof encountered. Expected a ')' after field-declaration.")]
fn test_field_decs_no_closing_paren(){
let mut p = Parser::new("f(a: myint".to_string());
p.start_lexer();
p.parse_function_params_list();
}
#[test]
fn test_let_var_decl_returns_block() {
let mut p = Parser::new("let var a : int := 1 in 1+1 end".to_string());
assert_eq!(p.run().is_some(), true);
}
#[test]
fn test_let_var_decl_returns_let_expr() {
let mut p = Parser::new("let var a : int := 1 in a end".to_string());
let b = p.run().unwrap();
match *b.expr.unwrap(){
LetExpr(ref v, ref o) => {
assert_eq!(v.len(), 1);
assert_eq!(o.is_some(), true);
match v[0]{
VarDec(ref id, ref ty, ref e) => {
assert_eq!(*id, "a".to_string());
match **e{ //**e means deref deref B<T> which results in T
NumExpr(n) => assert_eq!(1, n),
_ => {}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_let_var_decl_sym_tab_count() {
let mut p = Parser::new("let var a : int := 1 in a end".to_string());
let b = p.run().unwrap();
assert_eq!(b.sym_tab.borrow().len(), 1);
assert_eq!(b.sym_tab.borrow().get(&"a".to_string()), Some(&TInt32));
}
#[test]
fn test_let_add_expr() {
let mut p = Parser::new("let var a : int := 1 + 3 + 1 in a end".to_string());
let b = p.run().unwrap();
match *b.expr.unwrap(){
LetExpr(ref v, ref o) => {
assert_eq!(v.len(), 1);
assert_eq!(o.is_some(), true);
match v[0]{
VarDec(ref id, ref ty, ref e) => {
assert_eq!(*id, "a".to_string());
match **e{ //**e means deref deref B<T> which results in T
AddExpr(ref e1, ref e2) => {
match **e1{
NumExpr(n) => assert_eq!(n, 1),
_ => panic!("num expr expected")
}
match **e2{
AddExpr(ref e1, ref e2) => {
match **e1{
NumExpr(n) => assert_eq!(n, 3),
_ => panic!("num expr expected")
}
match **e2{
NumExpr(n) => assert_eq!(n, 1),
_ => panic!("num expr expected")
}
},
_ => panic!("add expr expected")
}
},
_ => panic!("add expr expected")
}
},
_ => panic!("ver decl expected")
}
},
_ => panic!("let expr expected")
}
}
#[test]
fn test_parse_2_vars_in_let() {
let mut p = Parser::new("let var a : int := 1\nvar b : int:=2\n in b end".to_string());
let b = p.run().unwrap();
match *b.expr.unwrap(){
LetExpr(ref v, ref o) => {
assert_eq!(v.len(), 2);
},
_ => {}
}
}
#[test]
fn test_1_seq_expr_able_to_parse() {
let mut p = Parser::new("(1;)".to_string());
p.start_lexer();
assert_eq!(p.expr().is_some(), true);
}
#[test]
fn test_1_seq_expr_last_type_int() {
let mut p = Parser::new("(1;)".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
SeqExpr(ref o) => {
assert_eq!(o.as_ref().unwrap().len(), 1);
match *o.as_ref().unwrap()[0]{
NumExpr(n) => {
assert_eq!(n, 1);
},
_ => {}
}
},
_ => panic!("Invalid expr")
}
}
#[test]
fn test_1_seq_expr_last_type_void() {
let mut p = Parser::new("(a;)".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
assert_eq!(ty, TVoid);
}
#[test]
fn test_2_seq_exprs_last_type_void() {
let mut p = Parser::new("(1;a;)".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
assert_eq!(ty, TVoid);
}
#[test]
fn test_2_seq_exprs_last_type_int() {
let mut p = Parser::new("(a;1;)".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
assert_eq!(ty, TInt32);
}
#[test]
fn test_1_seq_expr_without_semicolon_type_int() {
let mut p = Parser::new("(1)".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
assert_eq!(ty, TInt32);
}
#[test]
fn test_1_seq_expr_add_expr() {
let mut p = Parser::new("(5+16)".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
SeqExpr(ref o) => {
assert_eq!(o.as_ref().unwrap().len(), 1);
match *o.as_ref().unwrap()[0]{
AddExpr(ref e1, ref e2) => {
match **e1 {
NumExpr(n) => assert_eq!(n, 5),
_ => {}
}
match **e2 {
NumExpr(n) => assert_eq!(n, 16),
_ => {}
}
},
_ => {}
}
},
_ => panic!("Invalid expr")
}
}
#[test]
fn test_1_seq_expr_assignexpr_callexpr() {
let mut p = Parser::new("(a[1]:=1; print(a[1]);)".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
SeqExpr(ref o) => {
assert_eq!(o.as_ref().unwrap().len(), 2);
match *o.as_ref().unwrap()[0]{
AssignExpr(ref e1, ref e2) => {
match **e1 {
SubscriptExpr(_, _) => {},
_ => {panic!("Expected a subscript_expr");}
}
match **e2 {
NumExpr(n) => assert_eq!(n, 1),
_ => {panic!("Expected a num expr");}
}
},
_ => {panic!("Expected an assign expr");}
}
match *o.as_ref().unwrap()[1]{
CallExpr(_, _) => {
},
_ => {panic!("Expected a call expr");}
}
},
_ => panic!("Invalid expr")
}
}
#[test]
fn test_get_ty(){
assert_eq!(Parser::get_ty_from_string("int"), TInt32);
assert_eq!(Parser::get_ty_from_string("string"), TString);
assert_eq!(Parser::get_ty_from_string("index_type"), TCustom("index_type".to_string()));
}
#[test]
fn test_if_then_expr(){
let mut p = Parser::new("if 1 then 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenExpr(ref conditional_expr, ref then_expr) => {
match **conditional_expr{
NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_if_then_equality_as_conditional_expr(){
let mut p = Parser::new("if 1=1 then 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenExpr(ref conditional_expr, ref then_expr) => {
match **conditional_expr{
EqualsExpr(ref e1, ref e2) => {},
_ => panic!("Expected an equals expr")
}
},
_ => panic!("Expected an if-then expr")
}
}
#[test]
fn test_if_then_with_ident_as_conditional_expr(){
let mut p = Parser::new("if a then 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenExpr(ref conditional_expr, _) => {
match **conditional_expr{
IdExpr(ref i) => assert_eq!(*i, String::from("a")),
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_if_then_with_ident_involving_equality_test_conditional_expr(){
let mut p = Parser::new("if a=1 then 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenExpr(ref conditional_expr, _) => {
match **conditional_expr{
EqualsExpr(ref e1, ref e2) => {},
_ => panic!("Expected equality expression")
}
},
_ => panic!("Expected if-then expression")
}
}
#[test]
fn test_if_then_with_add_as_conditional_expr(){
let mut p = Parser::new("if 1+1 then 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenExpr(ref conditional_expr, ref then_expr) => {
match **conditional_expr{
AddExpr(ref l, ref r) => {
match **l{
NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_if_then_with_string_as_conditional_expr(){
let mut p = Parser::new("if \"abhi\" then 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenExpr(ref conditional_expr, ref then_expr) => {
match **conditional_expr{
StringExpr(ref s) => assert_eq!(*s, String::from("abhi")),
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_if_then_else_expr(){
let mut p = Parser::new("if 1 then foo() else foo()".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenElseExpr(ref conditional_expr, ref then_expr, ref else_expr) => {
match **conditional_expr{
NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
match **else_expr{
CallExpr(ref fn_name, _) => assert_eq!(*fn_name, String::from("foo")),
_ => panic!("not covered")
}
},
_ => {panic!("bingo!")}
}
}
#[test]
fn test_if_then_else_expr_with_num_expressions(){
let mut p = Parser::new("if 1 then 1 else 0".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenElseExpr(ref conditional_expr, ref then_expr, ref else_expr) => {
match **conditional_expr{
NumExpr(n) => assert_eq!(n, 1),
_ => {panic!("Unexpected expression")}
}
match **else_expr{
NumExpr(n) => assert_eq!(n, 0),
_ => panic!("not covered")
}
},
_ => {panic!("bingo!")}
}
}
#[test]
fn test_if_expr_with_string_expr_as_conditional_expr(){
let mut p = Parser::new("if \"abhi\" then 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenExpr(ref conditional_expr, _) => match **conditional_expr {
StringExpr(ref s) => assert_eq!(*s, "abhi"),
_ => panic!("This will not exhecute")
},
_ => panic!("This will not execute")
}
}
#[test]
#[should_panic(expected="Type mismatch between the then and else expressions")]
fn test_if_then_else_expr_fail_string_return(){
let mut p = Parser::new("if 1 then 1 else \"abhi\"".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
IfThenElseExpr(_, _, ref else_expr) => {
match **else_expr{
StringExpr(_) => panic!("Type mismatch between the then and else expressions"),
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_while_expr(){
let mut p = Parser::new("while 1 do 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
WhileExpr(ref conditional_expr, ref do_expr) => {
match **conditional_expr{
NumExpr(n) => assert_eq!(n, 1),
_ => panic!("This will not execute")
}
match **do_expr{
NumExpr(n) => assert_eq!(n, 1),
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_while_expr_with_string_as_conditional_expr(){
let mut p = Parser::new("while \"abhi\" do 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
WhileExpr(ref conditional_expr, ref do_expr) => {
match **conditional_expr{
StringExpr(ref s) => assert_eq!(*s, "abhi"),
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_while_expr_with_addexpr_as_conditional_expr(){
let mut p = Parser::new("while 1+1 do 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
WhileExpr(ref conditional_expr, ref do_expr) => {
match **conditional_expr{
AddExpr(ref l, ref r) => {
match **l{
NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
},
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_while_expr_with_less_than_cmp_as_conditional_expr(){
let mut p = Parser::new("while 1<1 do 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
WhileExpr(ref conditional_expr, ref do_expr) => {
match **conditional_expr{
LessThanExpr(ref l, ref r) => {
match **l{
NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
},
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_while_expr_with_greater_than_cmp_as_conditional_expr(){
let mut p = Parser::new("while 1>1 do 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
WhileExpr(ref conditional_expr, ref do_expr) => {
match **conditional_expr{
GreaterThanExpr(ref l, ref r) => {
match **l{
NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
},
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_while_expr_with_ident_as_conditional_expr(){
let mut p = Parser::new("while a do 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
WhileExpr(ref conditional_expr, ref do_expr) => {
match **conditional_expr{
IdExpr(ref id) => {
assert_eq!(*id, String::from("a"));
},
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_for_expr(){
let mut p = Parser::new("for id:= 1 to 10 do 1+1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
ForExpr(ref id, ref from_expr, ref to_expr, ref do_expr) => {
assert_eq!(*id, String::from("id"));
match **from_expr{
NumExpr(n) => assert_eq!(n, 1),
_ => panic!("This will not execute")
}
match **to_expr{
NumExpr(n) => assert_eq!(n, 10),
_ => panic!("This will not execute")
}
match **do_expr{
AddExpr(ref l, ref r) => {
match **l{
NumExpr(n) => assert_eq!(n, 1),
_ => {}
}
},
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_for_expr_with_ident_as_from_expr(){
let mut p = Parser::new("for id:= a to 10 do 1+1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
ForExpr(ref id, ref from_expr, _, _) => {
match **from_expr{
IdExpr(ref i) => assert_eq!(*i, String::from("a")),
_ => panic!("this will not execute")
}
},
_ => panic!("this will not execute")
}
}
#[test]
fn test_for_expr_with_ident_as_to_and_from_expr(){
let mut p = Parser::new("for id:= a to b do 1+1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
ForExpr(ref id, ref from_expr, ref to_expr, _) => {
match **to_expr{
IdExpr(ref i) => assert_eq!(*i, String::from("b")),
_ => panic!("This will not execute")
}
match **from_expr{
IdExpr(ref i) => assert_eq!(*i, String::from("a")),
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
match *expr{
ForExpr(ref id, ref from_expr, ref to_expr, _) => {
match **to_expr{
IdExpr(ref i) => assert_eq!(*i, String::from("b")),
_ => panic!("This will not execute")
}
match **from_expr{
IdExpr(ref i) => assert_eq!(*i, String::from("a")),
_ => panic!("This will not execute")
}
},
_ => panic!("This will not execute")
}
}
#[test]
fn test_int_array_with_dim_1_init_1(){
let mut p = Parser::new("array of int[1] of 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
ArrayExpr(ref ty, ref dim_expr, ref init_expr) => {
match **dim_expr{
NumExpr(i) => assert_eq!(i, 1),
_ => panic!("Expected a num expression")
}
match **init_expr{
NumExpr(i) => assert_eq!(i, 1),
_ => panic!("Expected a num expression")
}
},
_ => panic!("this will not execute")
}
}
#[test]
fn test_int_array_with_dim_add_expr_init_add_expr(){
let mut p = Parser::new("array of int[1+1] of 1+1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
ArrayExpr(ref ty, ref dim_expr, ref init_expr) => {
match **dim_expr{
AddExpr(_, _ ) => {},
_ => panic!("Expected a num expression")
}
match **init_expr{
AddExpr(_, _ ) => {},
_ => panic!("Expected a num expression")
}
},
_ => panic!("Expected an array expression")
}
}
#[test]
fn test_var_as_int_array_with_dim_add_expr_init_add_expr(){
let mut p = Parser::new("let var a : array := array of int[1+1] of 1+1 in a end".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
LetExpr(ref v, ref o) => {
match v[0]{
VarDec(ref id, ref ty, ref e) => {
assert_eq!(*id, "a".to_string());
match **e{ //**e means deref deref B<T> which results in T
NumExpr(n) => assert_eq!(1, n),
ArrayExpr(ref ty, ref dim_expr, ref init_expr) => {
assert_eq!(*ty, TInt32);
match **dim_expr{
AddExpr(ref l, ref r) => { },
_ => panic!("Expected add expr")
}
match **init_expr{
AddExpr(ref l, ref r) => { },
_ => panic!("Expected add expr")
}
},
_ => {panic!("expected an array expr")}
}
},
_ => {}
}
},
_ => {}
}
}
#[test]
fn test_subscript_expr(){
let mut p = Parser::new("a[b[0]]".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
SubscriptExpr(ref name, ref expr) => {
assert_eq!(*name, String::from("a"));
},
_ => panic!("Expected a subscript expression")
}
}
#[test]
fn test_subscript_expr_assign(){
let mut p = Parser::new("a[0] := 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
AssignExpr(ref lhs, ref rhs) => {
match **lhs{
SubscriptExpr(ref name, _) =>{
assert_eq!(*name, String::from("a"));
},
_ => {panic!("Expected a SubscriptExpr");}
}
match **rhs{
NumExpr(i) => {assert_eq!(i, 1);},
_ => {panic!("Expected a NumExpr");}
}
//assert_eq!(*name, String::from("a"));
},
_ => panic!("Expected an assignment expression")
}
}
#[test]
fn test_int_var_assign(){
let mut p = Parser::new("a := 1".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
AssignExpr(ref lhs, ref rhs) => {
match **lhs{
IdExpr(ref name) =>{
assert_eq!(*name, String::from("a"));
},
_ => {panic!("Expected a SubscriptExpr");}
}
match **rhs{
NumExpr(i) => {assert_eq!(i, 1);},
_ => {panic!("Expected a NumExpr");}
}
//assert_eq!(*name, String::from("a"));
},
_ => panic!("Expected an assignment expression")
}
}
#[test]
fn test_record_decl_with_one_int_field(){
let mut p = Parser::new("let var a : rec := {f:int} in a end".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
LetExpr(ref v, ref o) => {
match v[0]{
VarDec(ref id, ref ty, ref e) => {
assert_eq!(*id, "a".to_string());
match **e{ //**e means deref deref B<T> which results in T
RecordExpr(ref field_decls) => {
assert_eq!((field_decls.as_ref().unwrap()).len(), 1);
assert_eq!((field_decls.as_ref().unwrap())[0].0, String::from("f"));
assert_eq!((field_decls.as_ref().unwrap())[0].1, TInt32);
},
_ => {panic!("expected a rec expr")}
}
},
_ => {panic!("expected var decl")}
}
},
_ => {panic!("expected let expr")}
}
}
#[test]
fn test_record_decl_with_two_fields(){
let mut p = Parser::new("let var a : rec := {f:int, g:string} in a end".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
LetExpr(ref v, ref o) => {
match v[0]{
VarDec(ref id, ref ty, ref e) => {
assert_eq!(*id, "a".to_string());
match **e{ //**e means deref deref B<T> which results in T
RecordExpr(ref field_decls) => {
assert_eq!((field_decls.as_ref().unwrap()).len(), 2);
assert_eq!((field_decls.as_ref().unwrap())[0].0, String::from("f"));
assert_eq!((field_decls.as_ref().unwrap())[0].1, TInt32);
assert_eq!((field_decls.as_ref().unwrap())[1].0, String::from("g"));
assert_eq!((field_decls.as_ref().unwrap())[1].1, TString);
},
_ => {panic!("expected a rec expr")}
}
},
_ => {panic!("expected var decl")}
}
},
_ => {panic!("expected let expr")}
}
}
#[test]
fn test_record_access_one_level(){
let mut p = Parser::new("let var a : rec := {f:int, g:string} in a.f end".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
LetExpr(ref v, ref o) => {
match v[0]{
VarDec(ref id, ref ty, ref e) => {
assert_eq!(*id, "a".to_string());
match **e{ //**e means deref deref B<T> which results in T
RecordExpr(ref field_decls) => {
assert_eq!((field_decls.as_ref().unwrap()).len(), 2);
assert_eq!((field_decls.as_ref().unwrap())[0].0, String::from("f"));
assert_eq!((field_decls.as_ref().unwrap())[0].1, TInt32);
assert_eq!((field_decls.as_ref().unwrap())[1].0, String::from("g"));
assert_eq!((field_decls.as_ref().unwrap())[1].1, TString);
},
_ => {panic!("expected a rec expr")}
}
},
_ => {panic!("expected var decl")}
}
match **o.as_ref().unwrap(){
FieldExpr(ref head, ref tail) =>{
match **head{
IdExpr(ref id) => assert_eq!(*id, "a"),
_ => panic!("Expected id expression")
}
match **tail{
IdExpr(ref id) =>{
assert_eq!(*id, "f");
}
_ => {panic!("Expected field expression")}
}
},
_ => {panic!("Expected a field expression")}
}
},
_ => {panic!("expected let expr")}
}
}
#[test]
fn test_record_access_two_level(){
let mut p = Parser::new("let var a : rec := {f:int, g:string} in a.f.e end".to_string());
p.start_lexer();
let (ty, expr) = p.expr().unwrap();
match *expr{
LetExpr(ref v, ref o) => {
match v[0]{
VarDec(ref id, ref ty, ref e) => {
assert_eq!(*id, "a".to_string());
match **e{ //**e means deref deref B<T> which results in T
RecordExpr(ref field_decls) => {
assert_eq!((field_decls.as_ref().unwrap()).len(), 2);
assert_eq!((field_decls.as_ref().unwrap())[0].0, String::from("f"));
assert_eq!((field_decls.as_ref().unwrap())[0].1, TInt32);
assert_eq!((field_decls.as_ref().unwrap())[1].0, String::from("g"));
assert_eq!((field_decls.as_ref().unwrap())[1].1, TString);
},
_ => {panic!("expected a rec expr")}
}
},
_ => {panic!("expected var decl")}
}
match **o.as_ref().unwrap(){
FieldExpr(ref head, ref tail) =>{
match **head{
IdExpr(ref id) => assert_eq!(*id, "a"),
_ => panic!("Expected id expression")
}
match **tail{
FieldExpr(ref head, ref tail)=>
{
match **head{
IdExpr(ref id) =>{
assert_eq!(*id, "f");
},
_ => {panic!("Expected id expression")}
}
match **tail{
IdExpr(ref id) =>{
assert_eq!(*id, "e");
},
_ => panic!("Expected id expression")
}
}
_ => {panic!("Expected field expression")}
}
},
_ => {panic!("Expected a field expression")}
}
},
_ => {panic!("expected let expr")}
}
}
}
|
//! A single-producer, multi-consumer channel that only retains the *last* sent
//! value.
//!
//! This channel is useful for watching for changes to a value from multiple
//! points in the code base, for example, changes to configuration values.
//!
//! # Usage
//!
//! [`channel`] returns a [`Sender`] / [`Receiver`] pair. These are the producer
//! and sender halves of the channel. The channel is created with an initial
//! value. `Receiver::poll` will always be ready upon creation and will yield
//! either this initial value or the latest value that has been sent by
//! `Sender`.
//!
//! Calls to [`Receiver::poll`] and [`Receiver::poll_ref`] will always yield
//! the latest value.
//!
//! # Examples
//!
//! ```
//! # extern crate futures;
//! extern crate tokio;
//!
//! use tokio::prelude::*;
//! use tokio::sync::watch;
//!
//! # tokio::run(futures::future::lazy(|| {
//! let (mut tx, rx) = watch::channel("hello");
//!
//! tokio::spawn(rx.for_each(|value| {
//! println!("received = {:?}", value);
//! Ok(())
//! }).map_err(|_| ()));
//!
//! tx.broadcast("world").unwrap();
//! # Ok(())
//! # }));
//! ```
//!
//! # Closing
//!
//! [`Sender::poll_close`] allows the producer to detect when all [`Sender`]
//! handles have been dropped. This indicates that there is no further interest
//! in the values being produced and work can be stopped.
//!
//! # Thread safety
//!
//! Both [`Sender`] and [`Receiver`] are thread safe. They can be moved to other
//! threads and can be used in a concurrent environment. Clones of [`Receiver`]
//! handles may be moved to separate threads and also used concurrently.
//!
//! [`Sender`]: struct.Sender.html
//! [`Receiver`]: struct.Receiver.html
//! [`channel`]: fn.channel.html
//! [`Sender::poll_close`]: struct.Sender.html#method.poll_close
//! [`Receiver::poll`]: struct.Receiver.html#method.poll
//! [`Receiver::poll_ref`]: struct.Receiver.html#method.poll_ref
use fnv::FnvHashMap;
use futures::task::AtomicTask;
use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream};
use std::ops;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, Weak};
/// Receives values from the associated `Sender`.
///
/// Instances are created by the [`channel`](fn.channel.html) function.
#[derive(Debug)]
pub struct Receiver<T> {
/// Pointer to the shared state
shared: Arc<Shared<T>>,
/// Pointer to the watcher's internal state
inner: Arc<WatchInner>,
/// Watcher ID.
id: u64,
/// Last observed version
ver: usize,
}
/// Sends values to the associated `Receiver`.
///
/// Instances are created by the [`channel`](fn.channel.html) function.
#[derive(Debug)]
pub struct Sender<T> {
shared: Weak<Shared<T>>,
}
/// Returns a reference to the inner value
///
/// Outstanding borrows hold a read lock on the inner value. This means that
/// long lived borrows could cause the produce half to block. It is recommended
/// to keep the borrow as short lived as possible.
#[derive(Debug)]
pub struct Ref<'a, T: 'a> {
inner: RwLockReadGuard<'a, T>,
}
pub mod error {
//! Watch error types
use std::fmt;
/// Error produced when receiving a value fails.
#[derive(Debug)]
pub struct RecvError {
pub(crate) _p: (),
}
/// Error produced when sending a value fails.
#[derive(Debug)]
pub struct SendError<T> {
pub(crate) inner: T,
}
// ===== impl RecvError =====
impl fmt::Display for RecvError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use std::error::Error;
write!(fmt, "{}", self.description())
}
}
impl ::std::error::Error for RecvError {
fn description(&self) -> &str {
"channel closed"
}
}
// ===== impl SendError =====
impl<T: fmt::Debug> fmt::Display for SendError<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use std::error::Error;
write!(fmt, "{}", self.description())
}
}
impl<T: fmt::Debug> ::std::error::Error for SendError<T> {
fn description(&self) -> &str {
"channel closed"
}
}
}
#[derive(Debug)]
struct Shared<T> {
/// The most recent value
value: RwLock<T>,
/// The current version
///
/// The lowest bit represents a "closed" state. The rest of the bits
/// represent the current version.
version: AtomicUsize,
/// All watchers
watchers: Mutex<Watchers>,
/// Task to notify when all watchers drop
cancel: AtomicTask,
}
#[derive(Debug)]
struct Watchers {
next_id: u64,
watchers: FnvHashMap<u64, Arc<WatchInner>>,
}
#[derive(Debug)]
struct WatchInner {
task: AtomicTask,
}
const CLOSED: usize = 1;
/// Create a new watch channel, returning the "send" and "receive" handles.
///
/// All values sent by `Sender` will become visible to the `Receiver` handles.
/// Only the last value sent is made available to the `Receiver` half. All
/// intermediate values are dropped.
///
/// # Examples
///
/// ```
/// # extern crate futures;
/// extern crate tokio;
///
/// use tokio::prelude::*;
/// use tokio::sync::watch;
///
/// # tokio::run(futures::future::lazy(|| {
/// let (mut tx, rx) = watch::channel("hello");
///
/// tokio::spawn(rx.for_each(|value| {
/// println!("received = {:?}", value);
/// Ok(())
/// }).map_err(|_| ()));
///
/// tx.broadcast("world").unwrap();
/// # Ok(())
/// # }));
/// ```
pub fn channel<T>(init: T) -> (Sender<T>, Receiver<T>) {
const INIT_ID: u64 = 0;
let inner = Arc::new(WatchInner::new());
// Insert the watcher
let mut watchers = FnvHashMap::with_capacity_and_hasher(0, Default::default());
watchers.insert(INIT_ID, inner.clone());
let shared = Arc::new(Shared {
value: RwLock::new(init),
version: AtomicUsize::new(2),
watchers: Mutex::new(Watchers {
next_id: INIT_ID + 1,
watchers,
}),
cancel: AtomicTask::new(),
});
let tx = Sender {
shared: Arc::downgrade(&shared),
};
let rx = Receiver {
shared,
inner,
id: INIT_ID,
ver: 0,
};
(tx, rx)
}
impl<T> Receiver<T> {
/// Returns a reference to the most recently sent value
///
/// Outstanding borrows hold a read lock. This means that long lived borrows
/// could cause the send half to block. It is recommended to keep the borrow
/// as short lived as possible.
///
/// # Examples
///
/// ```
/// # extern crate tokio;
/// # use tokio::sync::watch;
/// let (_, rx) = watch::channel("hello");
/// assert_eq!(*rx.get_ref(), "hello");
/// ```
pub fn get_ref(&self) -> Ref<T> {
let inner = self.shared.value.read().unwrap();
Ref { inner }
}
/// Attempts to receive the latest value sent via the channel.
///
/// If a new, unobserved, value has been sent, a reference to it is
/// returned. If no new value has been sent, then `NotReady` is returned and
/// the current task is notified once a new value is sent.
///
/// Only the **most recent** value is returned. If the receiver is falling
/// behind the sender, intermediate values are dropped.
pub fn poll_ref(&mut self) -> Poll<Option<Ref<T>>, error::RecvError> {
// Make sure the task is up to date
self.inner.task.register();
let state = self.shared.version.load(SeqCst);
let version = state & !CLOSED;
if version != self.ver {
// Track the latest version
self.ver = version;
let inner = self.shared.value.read().unwrap();
return Ok(Some(Ref { inner }).into());
}
if CLOSED == state & CLOSED {
// The `Store` handle has been dropped.
return Ok(None.into());
}
Ok(Async::NotReady)
}
}
impl<T: Clone> Stream for Receiver<T> {
type Item = T;
type Error = error::RecvError;
fn poll(&mut self) -> Poll<Option<T>, error::RecvError> {
let item = try_ready!(self.poll_ref());
Ok(Async::Ready(item.map(|v_ref| v_ref.clone())))
}
}
impl<T> Clone for Receiver<T> {
fn clone(&self) -> Self {
let inner = Arc::new(WatchInner::new());
let shared = self.shared.clone();
let id = {
let mut watchers = shared.watchers.lock().unwrap();
let id = watchers.next_id;
watchers.next_id += 1;
watchers.watchers.insert(id, inner.clone());
id
};
let ver = self.ver;
Receiver {
shared: shared,
inner,
id,
ver,
}
}
}
impl<T> Drop for Receiver<T> {
fn drop(&mut self) {
let mut watchers = self.shared.watchers.lock().unwrap();
watchers.watchers.remove(&self.id);
}
}
impl WatchInner {
fn new() -> Self {
WatchInner {
task: AtomicTask::new(),
}
}
}
impl<T> Sender<T> {
/// Broadcast a new value via the channel, notifying all receivers.
pub fn broadcast(&mut self, value: T) -> Result<(), error::SendError<T>> {
let shared = match self.shared.upgrade() {
Some(shared) => shared,
// All `Watch` handles have been canceled
None => return Err(error::SendError { inner: value }),
};
// Replace the value
{
let mut lock = shared.value.write().unwrap();
*lock = value;
}
// Update the version. 2 is used so that the CLOSED bit is not set.
shared.version.fetch_add(2, SeqCst);
// Notify all watchers
notify_all(&*shared);
// Return the old value
Ok(())
}
/// Returns `Ready` when all receivers have dropped.
///
/// This allows the producer to get notified when interest in the produced
/// values is canceled and immediately stop doing work.
pub fn poll_close(&mut self) -> Poll<(), ()> {
match self.shared.upgrade() {
Some(shared) => {
shared.cancel.register();
Ok(Async::NotReady)
}
None => Ok(Async::Ready(())),
}
}
}
impl<T> Sink for Sender<T> {
type SinkItem = T;
type SinkError = error::SendError<T>;
fn start_send(&mut self, item: T) -> StartSend<T, error::SendError<T>> {
let _ = self.broadcast(item)?;
Ok(AsyncSink::Ready)
}
fn poll_complete(&mut self) -> Poll<(), error::SendError<T>> {
Ok(().into())
}
}
/// Notify all watchers of a change
fn notify_all<T>(shared: &Shared<T>) {
let watchers = shared.watchers.lock().unwrap();
for watcher in watchers.watchers.values() {
// Notify the task
watcher.task.notify();
}
}
impl<T> Drop for Sender<T> {
fn drop(&mut self) {
if let Some(shared) = self.shared.upgrade() {
shared.version.fetch_or(CLOSED, SeqCst);
notify_all(&*shared);
}
}
}
// ===== impl Ref =====
impl<'a, T: 'a> ops::Deref for Ref<'a, T> {
type Target = T;
fn deref(&self) -> &T {
self.inner.deref()
}
}
// ===== impl Shared =====
impl<T> Drop for Shared<T> {
fn drop(&mut self) {
self.cancel.notify();
}
}
|
#[macro_use]
pub mod macros;
pub mod ast;
pub mod class;
pub mod expr;
pub mod op;
pub mod statement;
pub mod stream;
pub mod subroutine;
pub mod term;
pub mod types;
pub mod writer;
use crate::token::Tokens;
pub use ast::*;
use stream::Stream;
use anyhow::Result;
pub fn parse(tokens: Tokens) -> Result<ASTs> {
let source = tokens.source.clone();
debug!("==== Start : parse : {}", source.path.display());
let mut stream = Stream::new(tokens);
let class = class::parse_class(&mut stream)?;
debug!("==== End : parse : {}\n", source.path.display());
Ok(ASTs { source, class })
}
pub fn write_asts(asts: ASTs) -> Result<()> {
writer::write_asts(asts)
}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use anyhow::*;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::runtime::registry::pid_to_process;
macro_rules! is_not_alive {
($name:ident) => {
is_not_alive(stringify!($name), $name)
};
}
#[native_implemented::function(erlang:group_leader/2)]
pub fn result(process: &Process, group_leader: Term, pid: Term) -> exception::Result<Term> {
let group_leader_pid: Pid = term_try_into_local_pid!(group_leader)?;
if (group_leader_pid == process.pid()) || pid_to_process(&group_leader_pid).is_some() {
let pid_pid: Pid = term_try_into_local_pid!(pid)?;
if process.pid() == pid_pid {
process.set_group_leader_pid(group_leader_pid);
Ok(true.into())
} else {
match pid_to_process(&pid_pid) {
Some(pid_arc_process) => {
pid_arc_process.set_group_leader_pid(group_leader_pid);
Ok(true.into())
}
None => is_not_alive!(pid),
}
}
} else {
is_not_alive!(group_leader)
}
}
fn is_not_alive(name: &'static str, value: Term) -> exception::Result<Term> {
Err(anyhow!("{} ({}) is not alive", name, value)).map_err(From::from)
}
|
#![no_std]
#![no_main]
extern crate pine64_hal as hal;
use crate::hal::dma::{Descriptor, Transfer, TransferResources};
use crate::hal::pac::dma::DMA;
use core::fmt::Write;
use core::pin::Pin;
use hal::ccu::Clocks;
use hal::console_writeln;
use hal::display::hdmi::HdmiDisplay;
use hal::pac::{
ccu::CCU, de::DE, de_mixer::MIXER1, hdmi::HDMI, pio::PIO, tcon1::TCON1, uart0::UART0,
uart_common::NotConfigured,
};
use hal::prelude::*;
use hal::serial::Serial;
fn kernel_entry() -> ! {
let clocks = Clocks::read();
let ccu = unsafe { CCU::from_paddr() };
let mut ccu = ccu.constrain();
let pio = unsafe { PIO::from_paddr() };
let gpio = pio.split(&mut ccu);
let dma = unsafe { DMA::from_paddr() };
let hdmi = unsafe { HDMI::from_paddr() };
let tcon1 = unsafe { TCON1::from_paddr() };
let mixer1 = unsafe { MIXER1::from_paddr() };
let de = unsafe { DE::from_paddr() };
let tx = gpio.pb.pb8.into_alternate_af2();
let rx = gpio.pb.pb9.into_alternate_af2();
let uart0: UART0<NotConfigured> = unsafe { UART0::from_paddr() };
let serial = Serial::uart0(uart0, (tx, rx), 115_200.bps(), clocks, &mut ccu);
let (mut serial, _rx) = serial.split();
console_writeln!(serial, "HDMI raw display + DMA example");
console_writeln!(serial, "{:#?}", clocks);
// TODO - use display info to set this up...
const WIDTH: usize = 1920;
const HEIGHT: usize = 1080;
const BPP: usize = 4;
const BUFFER_SIZE: usize = WIDTH * HEIGHT * BPP;
const BUFFER_SIZE_U32: usize = BUFFER_SIZE / 4;
static mut BACK_BUFFER_MEM: [u32; BUFFER_SIZE_U32] = [0; BUFFER_SIZE_U32];
static mut FRAME_BUFFER_MEM: [u32; BUFFER_SIZE_U32] = [0; BUFFER_SIZE_U32];
let mut back_buffer_mem = unsafe { Pin::new(&mut BACK_BUFFER_MEM[..]) };
let mut frame_buffer_mem = unsafe { Pin::new(&mut FRAME_BUFFER_MEM[..]) };
console_writeln!(serial, "BUFFER_SIZE {} == 0x{:X}", BUFFER_SIZE, BUFFER_SIZE);
console_writeln!(
serial,
"BUFFER_SIZE_U32 {} == 0x{:X}",
BUFFER_SIZE_U32,
BUFFER_SIZE_U32
);
console_writeln!(
serial,
"Back buffer addr 0x{:X}",
back_buffer_mem.as_ptr() as usize
);
console_writeln!(
serial,
"Frame buffer addr 0x{:X}",
frame_buffer_mem.as_ptr() as usize
);
console_writeln!(serial, "Creating the display");
let display = HdmiDisplay::new(tcon1, mixer1, de, hdmi, &frame_buffer_mem, &mut ccu);
console_writeln!(&mut serial, "EDID: {:#?}", display.edid());
console_writeln!(&mut serial, "Timing: {:#?}", display.timing());
let mut dma = dma.split(&mut ccu).ch0;
static mut DESC: Descriptor = Descriptor::new();
let mut desc = unsafe { Pin::new(&mut DESC) };
const RED: u32 = 0xFF_FF_00_00;
const GREEN: u32 = 0xFF_00_FF_00;
const BLUE: u32 = 0xFF_00_00_FF;
loop {
for color in &[RED, GREEN, BLUE] {
for pixel in back_buffer_mem.as_mut().iter_mut() {
*pixel = *color;
}
let res = TransferResources::mem_to_mem(desc, back_buffer_mem, frame_buffer_mem);
let txfr = Transfer::new(res, &mut dma);
let txfr = txfr.start(&mut dma);
let res = txfr.wait(&mut dma);
desc = res.desc;
back_buffer_mem = res.src_buffer;
frame_buffer_mem = res.dst_buffer;
}
}
}
pine64_boot::entry!(kernel_entry);
|
//! GraphQL support for [bson](https://github.com/mongodb/bson-rust) types.
use crate::{graphql_scalar, InputValue, ScalarValue, Value};
#[graphql_scalar(with = object_id, parse_token(String))]
type ObjectId = bson::oid::ObjectId;
mod object_id {
use super::*;
pub(super) fn to_output<S: ScalarValue>(v: &ObjectId) -> Value<S> {
Value::scalar(v.to_hex())
}
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<ObjectId, String> {
v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| {
ObjectId::parse_str(s).map_err(|e| format!("Failed to parse `ObjectId`: {e}"))
})
}
}
#[graphql_scalar(with = utc_date_time, parse_token(String))]
type UtcDateTime = bson::DateTime;
mod utc_date_time {
use super::*;
pub(super) fn to_output<S: ScalarValue>(v: &UtcDateTime) -> Value<S> {
Value::scalar(
(*v).try_to_rfc3339_string()
.unwrap_or_else(|e| panic!("failed to format `UtcDateTime` as RFC3339: {e}")),
)
}
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<UtcDateTime, String> {
v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| {
UtcDateTime::parse_rfc3339_str(s)
.map_err(|e| format!("Failed to parse `UtcDateTime`: {e}"))
})
}
}
#[cfg(test)]
mod test {
use bson::{oid::ObjectId, DateTime as UtcDateTime};
use crate::{graphql_input_value, FromInputValue, InputValue};
#[test]
fn objectid_from_input() {
let raw = "53e37d08776f724e42000000";
let input: InputValue = graphql_input_value!((raw));
let parsed: ObjectId = FromInputValue::from_input_value(&input).unwrap();
let id = ObjectId::parse_str(raw).unwrap();
assert_eq!(parsed, id);
}
#[test]
fn utcdatetime_from_input() {
use chrono::{DateTime, Utc};
let raw = "2020-03-23T17:38:32.446+00:00";
let input: InputValue = graphql_input_value!((raw));
let parsed: UtcDateTime = FromInputValue::from_input_value(&input).unwrap();
let date_time = UtcDateTime::from_chrono(
DateTime::parse_from_rfc3339(raw)
.unwrap()
.with_timezone(&Utc),
);
assert_eq!(parsed, date_time);
}
}
|
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let f = File::open("/etc/hosts")
.expect("Unable to open file");
let f = BufReader::new(f);
for line in f.lines() {
let line = line.expect("Unable to read line");
println!("Line: {}", line);
}
}
|
use btknmle_keydb::Store;
use btmgmt::client::Client;
use btmgmt::packet::ControllerIndex;
use btmgmt::packet::{
command as cmd, AdvDataScanResp, AdvertisingFlag, IoCapability, Privacy, SecureConnections,
Settings, SystemConfigurationParameter,
};
pub(crate) async fn setup(
devid: u16,
store: &Store,
io_capability: IoCapability,
) -> anyhow::Result<Client> {
let client = Client::open()?;
let info = client.call(devid, cmd::ReadControllerInformation).await?;
let mut current_settings = *info.current_settings();
if current_settings.contains(Settings::Powered) {
current_settings = *client.call(devid, cmd::SetPowered::new(false)).await?;
}
if !current_settings.contains(Settings::LowEnergy) {
current_settings = *client.call(devid, cmd::SetLowEnergy::new(true)).await?;
}
if current_settings.contains(Settings::BasicRateEnhancedDataRate) {
current_settings = *client.call(devid, cmd::SetBrEdr::new(false)).await?;
}
if !current_settings.contains(Settings::SecureConnections) {
current_settings = *client
.call(
devid,
cmd::SetSecureConnections::new(SecureConnections::Enable),
)
.await?;
}
client
.call(devid, cmd::SetIoCapability::new(io_capability))
.await?;
client
.call(
devid,
cmd::SetPrivacy::new(Privacy::Enable, *store.key_for_resolvable_private_address()),
)
.await?;
client.call(devid, cmd::SetApperance::new(0x03c0)).await?;
client
.call(
devid,
cmd::SetLocalName::new("btknmle".parse()?, "btknmle".parse()?),
)
.await?;
if !current_settings.contains(Settings::Bondable) {
current_settings = *client.call(devid, cmd::SetBondable::new(true)).await?;
}
if current_settings.contains(Settings::Connectable) {
current_settings = *client.call(devid, cmd::SetConnectable::new(false)).await?;
}
log::debug!("current settings: {:?}", current_settings);
client
.call(
devid,
store
.iter_irks()
.cloned()
.collect::<cmd::LoadIdentityResolvingKeys>(),
)
.await?;
client
.call(
devid,
store.iter_ltks().cloned().collect::<cmd::LoadLongTermKey>(),
)
.await?;
client
.call(
devid,
vec![
SystemConfigurationParameter::LEAdvertisementMinInterval(224), // 140ms
SystemConfigurationParameter::LEAdvertisementMaxInterval(338), // 211.25ms
]
.into_iter()
.collect::<cmd::SetDefaultSystemConfiguration>(),
)
.await?;
client.call(devid, cmd::SetPowered::new(true)).await?;
Ok(client)
}
pub(crate) async fn start_advertising(
client: &Client,
devid: ControllerIndex,
timeout: u16,
) -> anyhow::Result<()> {
client
.call(
devid,
cmd::AddAdvertising::new(
1.into(),
AdvertisingFlag::SwitchIntoConnectableMode
| AdvertisingFlag::AdvertiseAsLimitedDiscoverable
| AdvertisingFlag::AddFlagsFieldToAdvData
| AdvertisingFlag::AddAppearanceFieldToScanResp
| AdvertisingFlag::AddLocalNameInScanResp,
0,
timeout,
AdvDataScanResp::new(vec![], vec![0x03, 0x03, 0x12, 0x18]),
),
)
.await?;
Ok(())
}
pub(crate) async fn stop_advertising(
client: &Client,
devid: ControllerIndex,
) -> anyhow::Result<()> {
client
.call(devid, cmd::RemoveAdvertising::new(1.into()))
.await?;
Ok(())
}
pub(crate) async fn is_advertising_enabled(
client: &Client,
devid: ControllerIndex,
) -> anyhow::Result<bool> {
let info = client.call(devid, cmd::ReadAdvertisingFeature).await?;
let mut instances = info.instances().iter();
Ok(instances.next().is_some())
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct MessageBitField1(u8);
impl MessageBitField1
{
#[inline(always)]
fn query_response(self) -> MessageType
{
unsafe { transmute(self.0 & 0b1000_000) }
}
#[inline(always)]
fn raw_opcode(self) -> u8
{
(self.0 & 0b0111_1000) >> 3
}
#[inline(always)]
fn authoritative_answer(self) -> bool
{
self.0 & 0b0000_0100 != 0
}
#[inline(always)]
fn is_truncated(self) -> bool
{
self.0 & 0b0000_0010 != 0
}
#[inline(always)]
fn recursion_desired(self) -> bool
{
self.0 & 0b0000_0001 != 0
}
}
|
/// Generic types.
pub mod generic {
use crypto::HashValue;
use serde::{Deserialize, Serialize};
use types::peer_info::PeerInfo;
/// Consensus is mostly opaque to us
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct ConsensusMessage {
/// Message payload.
pub data: Vec<u8>,
}
/// Status sent on connection.
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct Status {
/// Protocol version.
pub version: u32,
/// Minimum supported version.
pub min_supported_version: u32,
/// Genesis block hash.
pub genesis_hash: HashValue,
pub info: PeerInfo,
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub enum Message {
/// Consensus protocol message.
Consensus(ConsensusMessage),
/// Status message for handshake
Status(Status),
}
}
|
#[macro_use]
extern crate gb_io;
extern crate regex;
use std::cmp;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io;
use std::io::Write;
use std::process;
use gb_io::reader::SeqReader;
use regex::Regex;
// Translation table 11 from https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi.
// Indexing into this array is as follows:
// T = 0, C = 1, A = 2, G = 3
// index = (16 * first_base) + (4 * second_base) + third_base
// So... TTT = 0, TTC = 1, TTA = 2, ... , GGC = 61, GGA = 62, GGG = 63
const GENETIC_CODE: &str = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG";
// some codons can be used as Met in the start position
const STARTS: &str = "---M------**--*----M------------MMMM---------------M------------";
// ERR_BAD_NT is an error value for an invalid nucleotide
const ERR_BAD_NT: usize = 99;
// map a base for indexing the GENETIC_CODE string
// x (char): base to look up
// returns: usize
fn lookup(x: char) -> usize {
match x {
'T' => 0,
'C' => 1,
'A' => 2,
'G' => 3,
_ => ERR_BAD_NT, // unknown base
}
}
// get the three-letter equivalent of an amino acid
// aa (char): the amino acid to translate, eg 'A' -> "Ala"
// returns: String
fn three_letter_code(aa: char) -> String {
let three_letter_map: HashMap<char, &str> = [
('A', "Ala"),
('B', "???"),
('C', "Cys"),
('D', "Asp"),
('E', "Glu"),
('F', "Phe"),
('G', "Gly"),
('H', "His"),
('I', "Ile"),
('J', "???"),
('K', "Lys"),
('L', "Leu"),
('M', "Met"),
('N', "Asn"),
('O', "Pyr"),
('P', "Pro"),
('Q', "Gln"),
('R', "Arg"),
('S', "Ser"),
('T', "Thr"),
('U', "Sel"),
('V', "Val"),
('W', "Trp"),
('X', "???"),
('Y', "Tyr"),
('Z', "???"),
('*', "***"),
]
.iter()
.copied()
.collect();
// check input.
let re = Regex::new(r"[A-Z*]").unwrap();
if !re.is_match(&aa.to_string()) {
println!("Invalid amino acid: {}", aa);
process::exit(1);
}
three_letter_map[&aa].to_string()
}
// translate a codon into its corresponding amino acid
// triplet (&str): a three-letter codon eg "ATG"
// i (usize): codon position. if 0, use the STARTS table
// returns: char
fn translate(triplet: &str, i: usize) -> char {
let mut codon = vec![ERR_BAD_NT; 3];
for (i, base) in triplet.chars().enumerate() {
codon[i] = lookup(base);
}
if codon.contains(&ERR_BAD_NT) {
println!("Something went wrong in translation!");
println!("{:?}", codon);
process::exit(1);
}
let index: usize = (codon[0] * 16) + (codon[1] * 4) + codon[2];
// translate the codon into single-letter code
let c = if (i == 0) && (STARTS.chars().nth(index).unwrap() == 'M') {
'M'
} else {
GENETIC_CODE.chars().nth(index).unwrap()
};
c
}
// print a pretty DNA sequence and its translation, plus line numbering
// eg: 001 MetSerIle...
// 001 ATGAGTATT...
//
// s (&str): DNA sequence to print
fn print_seq(s: &str) {
let line_len = 72; // print 72 bases per line (24 amino acids)
// how many lines to print
let n_lines = if s.len() % line_len != 0 {
(s.len() / line_len) + 1
} else {
s.len() / line_len
};
// how wide does the numbering block need to be?
let n_digits = count_digits(s.len() as u16);
// get the translation of this sequence
let mut peptide = String::new();
let n_codons = s.len() / 3;
for i in 0..n_codons {
let codon = &s[i * 3..(i * 3) + 3]; // take a 3-base slice of the sequence
let aa = translate(&codon, i);
// translate and add to the string
peptide.push_str(&three_letter_code(aa));
}
for i in 0..n_lines {
let begin = i * line_len;
// adjust 'end' if near the end of the sequence
let end = cmp::min((i * line_len) + line_len, s.len());
// print translation
println!(
"{number:>0width$} {}",
&peptide[begin..end],
number = (begin / 3) + 1, // divide by 3 b/c 3 bases/amino acid
width = n_digits
);
// print DNA
println!(
"{number:>0width$} {}\n",
&s[begin..end],
number = (begin) + 1,
width = n_digits
);
}
}
// count the digits in a number
// n (u16): number to count
// returns: usize
//
// NOTE: n is type u16, so allowable input is 0..65535.
fn count_digits(mut n: u16) -> usize {
let mut digits: usize = 1;
while n > 0 {
n /= 10;
if n >= 1 {
digits += 1;
}
}
digits
}
fn main() {
// file to process; user can override on the command line
let mut filename = "nc_005816.gb";
// check to see if user provided an alternate file name...
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
filename = &args[1];
}
if !std::path::Path::new(filename).exists() {
println!("File '{}' does not exist.", filename);
process::exit(1);
}
println!("\nReading records from file '{}'...", filename);
let file = File::open(filename).unwrap();
// vectors to hold gene names and gene descriptions
let mut genes = Vec::<String>::new();
let mut descs = Vec::<String>::new();
// HashMap holding counts of each feature type, eg, "("CDS", 5)"
let mut feature_map: HashMap<String, usize> = HashMap::new();
// length of the longest feature type, for printing
let mut feat_len = 0;
for r in SeqReader::new(file) {
let seq = r.unwrap();
let mut gene_count = 0;
let mut feat_count = 0;
let record_name = seq.name.clone().unwrap();
println!("Record name: {}", record_name);
println!("Sequence length: {}", seq.len());
for f in &seq.features {
feat_count += 1;
// count the different feature types. if a type hasn't been seen
// before, set its value to zero and add 1
*feature_map.entry(f.kind.to_string()).or_insert(0) += 1;
if f.kind.to_string().len() > feat_len {
feat_len = f.kind.to_string().len();
}
// collect protein_id, product, and location data for each "CDS", ie gene
if f.kind == feature_kind!("CDS") {
let gene = f
.qualifier_values(qualifier_key!("protein_id"))
.next()
.unwrap()
.to_string()
.replace('\n', "");
genes.push(gene);
let desc = f
.qualifier_values(qualifier_key!("product"))
.next()
.unwrap()
.to_string()
.replace('\n', "");
descs.push(desc);
gene_count += 1;
}
}
println!(
"\nFound {} features, including {} genes.",
feat_count, gene_count
);
for (key, count) in feature_map.iter() {
println!("{k:<0l$}: {}", count, k = key, l = feat_len + 1);
}
println!();
for i in 0..gene_count {
println!("{}) {}: {}", i, genes[i], descs[i]);
}
if gene_count > 0 {
let range = {
if gene_count == 1 {
"0".to_string()
} else {
format!("0-{}", gene_count - 1)
}
};
print!("\nSelect a gene number [{}] or 'q' to quit: ", range);
// flush buffer...
io::stdout().flush().unwrap();
// get input...
let mut ret_val = String::new();
io::stdin()
.read_line(&mut ret_val)
.expect("Failed to read from stdin");
// use trim() to delete the trailing newline ('\n') char
ret_val = ret_val.trim().to_string();
if (ret_val == "q") || (ret_val == "Q") {
process::exit(0);
}
let selection = match ret_val.parse::<usize>() {
Ok(i) => i, // if good input, just return the number
Err(_) => {
println!("Invalid input: '{}'", ret_val);
process::exit(1);
}
};
if selection > gene_count - 1 {
println!("Invalid input: '{}'", selection);
process::exit(1);
}
// find the requested gene and print it.
for f in &seq.features {
if f.kind == feature_kind!("CDS")
&& f.qualifier_values(qualifier_key!("protein_id"))
.next()
.unwrap()
== genes[selection]
{
let s = String::from_utf8(
seq.extract_location(&f.location.clone()).unwrap().to_vec(),
)
.unwrap()
.to_ascii_uppercase();
println!("\n{}: {}", genes[selection], descs[selection]);
print_seq(&s);
println!("DNA: {:>5} bases", s.len());
println!("Protein: {:>5} amino acids\n", s.len() / 3)
}
}
}
}
}
// tests
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_translate_atg() {
assert_eq!(translate("ATG", 1), 'M');
}
#[test]
fn test_translate_atg_as_start() {
assert_eq!(translate("ATG", 0), 'M');
}
#[test]
fn test_translate_gtg() {
assert_eq!(translate("GTG", 1), 'V');
}
#[test]
fn test_translate_gtg_as_start() {
assert_eq!(translate("GTG", 0), 'M');
}
#[test]
fn test_translate_tag() {
assert_eq!(translate("TAG", 1), '*');
}
#[test]
fn test_translate_ttt() {
assert_eq!(translate("TTT", 1), 'F');
}
#[test]
fn test_one_to_three_translate() {
assert_eq!(three_letter_code(translate("ATG", 0)), "Met");
}
#[test]
fn test_translate_pyr() {
assert_eq!(three_letter_code('O'), "Pyr");
}
#[test]
fn test_translate_sel() {
assert_eq!(three_letter_code('U'), "Sel");
}
#[test]
fn translate_bad_aa() {
assert_eq!(three_letter_code('J'), "???");
}
#[test]
fn test_count_digits1() {
assert_eq!(count_digits(10000), 5);
}
#[test]
fn test_count_digits2() {
assert_eq!(count_digits(2500), 4);
}
}
|
// Demonstrating a weird syntax for match default cases.
fn main() {
let x = 3;
match x {
1 => println!("1"),
2 => println!("2"),
a => println!("{}!!!!", a),
}
}
|
extern crate content_inspector;
use std::env;
use std::fs::File;
use std::io::{Error, Read};
use std::path::Path;
use std::process::exit;
const MAX_PEEK_SIZE: usize = 1024;
fn main() -> Result<(), Error> {
let mut args = env::args();
if args.len() < 2 {
eprintln!("USAGE: inspect FILE [FILE...]");
exit(1);
}
args.next();
for filename in args {
if !Path::new(&filename).is_file() {
continue;
}
let file = File::open(&filename)?;
let mut buffer: Vec<u8> = vec![];
file.take(MAX_PEEK_SIZE as u64).read_to_end(&mut buffer)?;
let content_type = content_inspector::inspect(&buffer);
println!("{}: {}", filename, content_type);
}
Ok(())
}
|
use image::{
imageops::{self, FilterType::Triangle},
ImageError,
};
use std::fmt::{self, Display};
pub struct Hash {
backing: Vec<u64>,
size: usize,
}
impl Display for Hash {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut nibbles = self.size as i64 / 4;
let mut index = 0;
while nibbles > 0 {
let width = usize::min(nibbles as usize, 16);
f.write_fmt(format_args!(
"{:0width$x}",
self.backing[index],
width = width,
))?;
nibbles -= 16;
index += 1;
}
Ok(())
}
}
struct HashBuilder {
backing: Vec<u64>,
target_size: usize,
size: usize,
}
pub enum HashError {
NotEnoughBits,
DecoderError(ImageError),
}
impl From<ImageError> for HashError {
fn from(from: ImageError) -> Self {
HashError::DecoderError(from)
}
}
impl Display for HashError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
match &self {
HashError::NotEnoughBits => f.write_fmt(format_args!("Not enough bits in the buffer")),
HashError::DecoderError(inner) => f.write_fmt(format_args!("Decoder Error: {}", inner)),
}
}
}
impl HashBuilder {
fn new(size: usize) -> HashBuilder {
let full_words = size / 64;
let extra_word_needed = size % 64 > 0;
let word_count = full_words + if extra_word_needed { 1 } else { 0 };
HashBuilder {
backing: Vec::with_capacity(word_count),
target_size: size,
size: 0,
}
}
fn add_bit(&mut self, is_one: bool) {
if self.size % 64 == 0 {
self.backing.push(if is_one { 1 } else { 0 });
} else {
let hash_part = self
.backing
.last_mut()
.expect("This cannot happen because the size would be zero otherwise");
*hash_part <<= 1;
if is_one {
*hash_part ^= 1;
}
}
self.size += 1;
}
fn finalize(self) -> Result<Hash, HashError> {
if self.size < self.target_size {
return Err(HashError::NotEnoughBits);
}
Ok(Hash {
backing: self.backing,
size: self.target_size,
})
}
}
pub fn hash_img(filename: &str, hash_width: u32, hash_height: u32) -> Result<Hash, HashError> {
let img = image::open(filename)?;
let img = imageops::grayscale(&img.resize_exact(hash_width, hash_height, Triangle));
let hash_size: usize = (hash_height * hash_width) as usize;
let sum: u64 = img.pixels().map(|p| p[0] as u64).sum();
let avg = sum / (hash_size as u64);
let mut hash = HashBuilder::new(hash_size);
for p in img.pixels() {
hash.add_bit(p[0] as u64 >= avg);
}
hash.finalize()
}
|
use std::{fmt, io};
use async_std::fs::File;
use async_std::prelude::*;
use failure_derive::Fail;
use futures::io::{AsyncBufReadExt, BufReader};
use futures::join;
use serde::de::DeserializeOwned;
use surf::Client;
mod photos;
pub use crate::photos::{Posts, TotalPosts};
mod better_photos;
pub use crate::better_photos::{Photo, Post};
mod macros;
mod uri;
use crate::uri::{QueryParameters, UriPath};
mod response;
use crate::response::Response;
const MAX_PAGE_SIZE: &'static str = "20";
type SurfError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "api error: {}", _0)]
Api(String),
#[fail(display = "json error: {}", _0)]
Json(serde_json::error::Error),
#[fail(display = "io error: {}", _0)]
Io(io::Error),
#[fail(display = "surf error: {}", _0)]
Surf(SurfError),
}
impl From<serde_json::error::Error> for Error {
fn from(error: serde_json::error::Error) -> Error {
Error::Json(error)
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::Io(error)
}
}
impl From<SurfError> for Error {
fn from(error: SurfError) -> Error {
Error::Surf(error)
}
}
pub struct Blog<C, E>
where
C: surf::middleware::HttpClient<Error = E>,
E: std::error::Error + Send + Sync + 'static,
{
client: Client<C>,
api_key: String,
blog_identifier: String,
}
impl<C, E> Blog<C, E>
where
C: surf::middleware::HttpClient<Error = E>,
E: std::error::Error + Send + Sync + 'static,
{
pub fn new(client: Client<C>, api_key: String, blog_identifier: String) -> Blog<C, E> {
Blog {
client,
api_key,
blog_identifier,
}
}
async fn tumblr_get<'a, 'de, T>(
&self,
path: UriPath,
params: QueryParameters<'a>,
) -> Result<Response<T>, Error>
where
T: 'static + Clone + fmt::Debug + DeserializeOwned,
{
let uri = uri::tumblr_uri(&self.blog_identifier, &path, ¶ms);
let v: Response<T> = self.client.get(uri).recv_json().await?;
if v.meta.is_success() {
Ok(v)
} else {
Err(Error::Api(v.meta.msg.clone()))
}
}
pub async fn fetch_post_count(&self) -> Result<usize, Error> {
let path = uri_path![posts / photo];
let params = uri_params! { api_key => &self.api_key, limit => "1" };
let v: Response<TotalPosts> = self.tumblr_get::<TotalPosts>(path, params).await?;
Ok(v.response.amount)
}
pub async fn fetch_posts_page(&self, page_start_index: usize) -> Result<Vec<Post>, Error> {
let path = uri_path![posts / photo];
let params = uri_params! {
api_key => &self.api_key,
limit => MAX_PAGE_SIZE,
offset => format!("{}", page_start_index)
};
let v: Response<Posts> = self.tumblr_get::<Posts>(path, params).await?;
Ok(v.response.posts.into_iter().map(Post::from).collect())
}
pub async fn download_post(&self, post: Post) -> Result<(), Error> {
for (index, photo) in post.photos.iter().enumerate() {
let filename = format!(
"/tmp/pics/{slug}-{id}-{index}",
slug = post.slug,
id = post.id,
index = index
);
let future_file = File::create(filename);
let future_response = self.client.get(&photo.url);
let (file, response) = join!(future_file, future_response);
let (mut file, mut response) = (file?, response?);
let reader = BufReader::with_capacity(32_768, response);
reader.copy_buf_into(&mut file).await?;
}
Ok(())
}
}
|
pub mod news_crawler;
pub mod photo_crawler;
pub mod video_crawler;
|
use crate::helpers::ID;
use crate::render::DrawMap;
use crate::ui::PerMapUI;
use crate::ui::UI;
use ezgui::{Color, EventCtx, GfxCtx, Key, Line, Text};
use map_model::raw_data::StableRoadID;
use map_model::Map;
use sim::{CarID, Sim};
use std::collections::BTreeMap;
pub struct ObjectDebugger {
tooltip_key_held: bool,
debug_tooltip_key_held: bool,
selected: Option<ID>,
}
impl ObjectDebugger {
pub fn new() -> ObjectDebugger {
ObjectDebugger {
tooltip_key_held: false,
debug_tooltip_key_held: false,
selected: None,
}
}
pub fn event(&mut self, ctx: &mut EventCtx, ui: &UI) {
self.selected = ui.primary.current_selection.clone();
if self.tooltip_key_held {
self.tooltip_key_held = !ctx.input.key_released(Key::LeftControl);
} else {
// TODO Can't really display an OSD action if we're not currently selecting something.
// Could only activate sometimes, but that seems a bit harder to use.
self.tooltip_key_held = ctx
.input
.unimportant_key_pressed(Key::LeftControl, "hold to show tooltips");
}
if self.debug_tooltip_key_held {
self.debug_tooltip_key_held = !ctx.input.key_released(Key::RightControl);
} else {
self.debug_tooltip_key_held = ctx
.input
.unimportant_key_pressed(Key::RightControl, "hold to show debug tooltips");
}
if let Some(ref id) = self.selected {
if ctx.input.contextual_action(Key::D, "debug") {
dump_debug(
id.clone(),
&ui.primary.map,
&ui.primary.sim,
&ui.primary.draw_map,
);
}
}
}
pub fn draw(&self, g: &mut GfxCtx, ui: &UI) {
if self.tooltip_key_held {
if let Some(ref id) = self.selected {
let txt = tooltip_lines(id.clone(), g, &ui.primary);
g.draw_mouse_tooltip(&txt);
}
}
if self.debug_tooltip_key_held {
if let Some(pt) = g.canvas.get_cursor_in_map_space() {
if let Some(gps) = pt.to_gps(ui.primary.map.get_gps_bounds()) {
let mut txt = Text::new();
txt.add(Line(pt.to_string()));
txt.add(Line(gps.to_string()));
txt.add(Line(format!("zoom: {}", g.canvas.cam_zoom)));
g.draw_mouse_tooltip(&txt);
}
}
}
}
}
fn dump_debug(id: ID, map: &Map, sim: &Sim, draw_map: &DrawMap) {
match id {
ID::Road(id) => {
map.get_r(id).dump_debug();
}
ID::Lane(id) => {
map.get_l(id).dump_debug();
sim.debug_lane(id);
}
ID::Intersection(id) => {
map.get_i(id).dump_debug();
sim.debug_intersection(id, map);
}
ID::Turn(id) => {
map.get_t(id).dump_debug();
}
ID::Building(id) => {
map.get_b(id).dump_debug();
for (cars, descr) in vec![
(
sim.get_parked_cars_by_owner(id),
format!("currently parked cars are owned by {}", id),
),
(
sim.get_offstreet_parked_cars(id),
format!("cars are parked inside {}", id),
),
] {
println!(
"{} {}: {:?}",
cars.len(),
descr,
cars.iter().map(|p| p.vehicle.id).collect::<Vec<CarID>>()
);
}
}
ID::Car(id) => {
sim.debug_car(id);
}
ID::Pedestrian(id) => {
sim.debug_ped(id);
}
ID::PedCrowd(members) => {
println!("Crowd with {} members", members.len());
for p in members {
sim.debug_ped(p);
}
}
ID::ExtraShape(id) => {
let es = draw_map.get_es(id);
for (k, v) in &es.attributes {
println!("{} = {}", k, v);
}
println!("associated road: {:?}", es.road);
}
ID::BusStop(id) => {
map.get_bs(id).dump_debug();
}
ID::Area(id) => {
map.get_a(id).dump_debug();
}
ID::Trip(id) => {
sim.debug_trip(id);
}
}
}
fn tooltip_lines(id: ID, g: &mut GfxCtx, ctx: &PerMapUI) -> Text {
let (map, sim, draw_map) = (&ctx.map, &ctx.sim, &ctx.draw_map);
let mut txt = Text::new();
match id {
ID::Road(id) => {
let r = map.get_r(id);
txt.add_appended(vec![
Line(format!("{} (originally {}) is ", r.id, r.stable_id)),
Line(r.get_name()).fg(Color::CYAN),
]);
txt.add(Line(format!("From OSM way {}", r.osm_way_id)));
}
ID::Lane(id) => {
let l = map.get_l(id);
let r = map.get_r(l.parent);
txt.add_appended(vec![
Line(format!("{} is ", l.id)),
Line(r.get_name()).fg(Color::CYAN),
]);
txt.add(Line(format!(
"Parent {} (originally {}) points to {}",
r.id, r.stable_id, r.dst_i
)));
txt.add(Line(format!(
"Lane is {} long, parent {} is {} long",
l.length(),
r.id,
r.center_pts.length()
)));
styled_kv(&mut txt, &r.osm_tags);
if l.is_parking() {
txt.add(Line(format!(
"Has {} parking spots",
l.number_parking_spots()
)));
} else if l.is_driving() {
txt.add(Line(format!(
"Parking blackhole redirect? {:?}",
l.parking_blackhole
)));
}
if let Some(types) = l.get_turn_restrictions(r) {
txt.add(Line(format!("Turn restriction for this lane: {:?}", types)));
}
for (restriction, to) in &r.turn_restrictions {
txt.add(Line(format!(
"Restriction from this road to {}: {}",
to, restriction
)));
}
}
ID::Intersection(id) => {
txt.add(Line(id.to_string()));
let i = map.get_i(id);
txt.add(Line(format!("Roads: {:?}", i.roads)));
txt.add(Line(format!(
"Orig roads: {:?}",
i.roads
.iter()
.map(|r| map.get_r(*r).stable_id)
.collect::<Vec<StableRoadID>>()
)));
txt.add(Line(format!("Originally {}", i.stable_id)));
}
ID::Turn(id) => {
let t = map.get_t(id);
txt.add(Line(format!("{}", id)));
txt.add(Line(format!("{:?}", t.turn_type)));
}
ID::Building(id) => {
let b = map.get_b(id);
txt.add(Line(format!("Building #{:?}", id)));
txt.add(Line(format!(
"Dist along sidewalk: {}",
b.front_path.sidewalk.dist_along()
)));
styled_kv(&mut txt, &b.osm_tags);
}
ID::Car(id) => {
for line in sim.car_tooltip(id) {
txt.add_wrapped_line(&g.canvas, line);
}
}
ID::Pedestrian(id) => {
for line in sim.ped_tooltip(id) {
txt.add_wrapped_line(&g.canvas, line);
}
}
ID::PedCrowd(members) => {
txt.add(Line(format!("Crowd of {}", members.len())));
}
ID::ExtraShape(id) => {
styled_kv(&mut txt, &draw_map.get_es(id).attributes);
}
ID::BusStop(id) => {
txt.add(Line(id.to_string()));
for r in map.get_all_bus_routes() {
if r.stops.contains(&id) {
txt.add(Line(format!("- Route {}", r.name)));
}
}
}
ID::Area(id) => {
let a = map.get_a(id);
txt.add(Line(format!("{}", id)));
styled_kv(&mut txt, &a.osm_tags);
}
ID::Trip(_) => {}
};
txt
}
fn styled_kv(txt: &mut Text, tags: &BTreeMap<String, String>) {
for (k, v) in tags {
txt.add_appended(vec![
Line(k).fg(Color::RED),
Line(" = "),
Line(v).fg(Color::CYAN),
]);
}
}
|
#[derive(Default)]
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Clone)]
pub struct NodeVersion {
pub path: String,
pub name: String
}
|
use std::cell::RefCell;
use std::collections::HashMap;
use std::hash::Hash;
use std::rc::{Rc, Weak};
//edgelist
pub struct EdgeListGraph<E, ID> {
v: Vec<(E, ID, ID)>,
}
type Rcc<T> = Rc<RefCell<T>>;
pub fn rcc<T>(t: T) -> Rcc<T> {
Rc::new(RefCell::new(t))
}
// Pointer based
pub struct RccGraph<T> {
nodes: Vec<Rcc<RccNode<T>>>,
}
pub struct RccNode<T> {
data: T,
edges: Vec<Weak<RefCell<RccNode<T>>>>,
}
// MapBased
pub struct MapGraph<T, E, ID: Hash> {
mp: HashMap<ID, T>,
edges: Vec<(E, ID, ID)>,
}
//MapPointer
pub struct MapPGraph<T, E, ID: Hash + Eq> {
data: HashMap<ID, (T, Vec<ID>)>,
edges: HashMap<ID, (E, ID, ID)>,
}
pub struct MapRcGraph<T, E, ID: Hash + Eq> {
data: HashMap<ID, (T, Vec<Rc<(E, ID, ID)>>)>,
}
|
use crate::quic_tunnel::tlv;
use crate::Shutdown;
use anyhow::Result;
use quinn::{RecvStream, SendStream, VarInt};
use std::net::SocketAddr;
use tokio::net::{tcp, TcpStream};
use tokio::prelude::*;
use tokio::sync::{broadcast, mpsc};
use tracing::{debug, error, instrument};
// tcp payload size based on 1500 MTU
const TCP_BUF_SIZE: usize = 1480;
const QUIC_BUF_SIZE: usize = 1480;
pub struct Connection {
pub shutdown: Shutdown,
// when `Connection` is dropped it
// Notifies the main process after shutting stream and tcp connection
pub _shutdown_complete: mpsc::Sender<()>,
}
struct QuicToTcp {
pub quic_recv: quinn::RecvStream,
pub tcp_write: tcp::OwnedWriteHalf,
pub shutdown: Shutdown,
pub _shutdown_complete: mpsc::Sender<()>,
}
struct TcpToQuic {
pub tcp_read: tcp::OwnedReadHalf,
pub quic_send: quinn::SendStream,
pub shutdown: Shutdown,
pub _shutdown_complete: mpsc::Sender<()>,
}
impl Connection {
pub async fn run_client_conn(
&mut self,
tcp_dest_addr: SocketAddr,
tcp_streamer: TcpStream,
mut quic_send: SendStream,
mut quic_recv: RecvStream,
) -> Result<()> {
let (notify_shutdown, _) = broadcast::channel(1);
let (shutdown_complete_tx, mut shutdown_complete_rx) = mpsc::channel(1);
let mut buf = [0; 20];
// send TCP Connect TLV
let n = tlv::new_tcp_connect(&mut buf, &tcp_dest_addr);
if let Err(e) = n {
error!("error while creating tcp connect tlv {}", e);
return Ok(());
}
if let Err(e) = quic_send.write_all(&buf[..n.unwrap()]).await {
error!("error sending tcp connect data to quic stream {}", e);
};
// End TLV
let n = tlv::new_tcp_connect_ok(&mut buf);
if let Err(e) = n {
error!("error while creating tcp ok connect tlv {}", e);
return Ok(());
}
if let Err(e) = quic_send.write_all(&buf[..n.unwrap()]).await {
error!("error sending tcp connect data to quic stream {}", e);
};
// wait for TCP Connect OK TLV
let quic_read_count = quic_recv.read(&mut buf).await;
if let Err(ref e) = quic_read_count {
error!("error reading quic stream {}", e);
tcp_streamer.shutdown(std::net::Shutdown::Both)?;
return Ok(());
}
let quic_read_count = quic_read_count.unwrap();
if quic_read_count.is_none() {
tcp_streamer.shutdown(std::net::Shutdown::Both)?;
return Ok(());
}
let n = quic_read_count.unwrap();
if !tlv::is_tcp_connect_ok(&buf[..n]) {
tcp_streamer.shutdown(std::net::Shutdown::Both)?;
return Ok(());
}
let (tcp_read, tcp_write) = tcp_streamer.into_split();
let mut quic_to_tcp = QuicToTcp {
quic_recv,
tcp_write,
shutdown: Shutdown::new(notify_shutdown.subscribe()),
_shutdown_complete: shutdown_complete_tx.clone(),
};
let mut tcp_to_quic = TcpToQuic {
tcp_read,
quic_send,
shutdown: Shutdown::new(notify_shutdown.subscribe()),
_shutdown_complete: shutdown_complete_tx.clone(),
};
// Spawn a new tasks to handle bidirectional communication.
tokio::spawn(async move {
if let Err(err) = quic_to_tcp.handle().await {
error!(cause = ? err, "stream error");
}
});
tokio::spawn(async move {
if let Err(err) = tcp_to_quic.handle().await {
error!(cause = ? err, "stream error");
}
});
drop(shutdown_complete_tx);
tokio::select! {
_ = self.shutdown.recv() => {
drop(notify_shutdown);
let _ = shutdown_complete_rx.recv().await;
}
_ = shutdown_complete_rx.recv() => {}
};
Ok(())
}
pub async fn run_concentrator_conn(
&mut self,
mut quic_send: SendStream,
mut quic_recv: RecvStream,
) -> Result<()> {
let (notify_shutdown, _) = broadcast::channel(1);
let (shutdown_complete_tx, mut shutdown_complete_rx) = mpsc::channel(1);
// wait for quic tunnel tlv
let mut buf = [0; 1024];
let n = quic_recv.read(&mut buf).await;
// TODO:parse tlv
if let Err(ref e) = n {
error!("error reading quic tlv stream close TCP connection?{}", e);
return Ok(());
}
let remote_addr = match n.unwrap() {
Some(_) => tlv::parse_tcp_connect(&buf),
None => {
// the quic stream is finished close TCP connection
return Ok(());
}
};
if let Err(e) = remote_addr {
error!(" TCP Connect TLV parse error {}", e);
return Ok(());
}
// initiate tcp connection
let remote_addr = remote_addr.unwrap();
let dest_tcp = TcpStream::connect(&remote_addr).await;
// If unable to connect to remote tcp destination return error tlv
if let Err(e) = dest_tcp {
error!(
"unable to establish tcp connection to {} err: {}",
remote_addr, e
);
let n = tlv::new_error_tlv(&mut buf).unwrap();
quic_send.write(&mut buf[..n]).await?;
return Ok(());
}
// send TCP Connect OK TLV
let n = tlv::new_tcp_connect_ok(&mut buf).unwrap();
quic_send.write(&mut buf[..n]).await?;
let (tcp_read, tcp_write) = dest_tcp.unwrap().into_split();
let mut quic_to_tcp = QuicToTcp {
quic_recv,
tcp_write,
shutdown: Shutdown::new(notify_shutdown.subscribe()),
_shutdown_complete: shutdown_complete_tx.clone(),
};
let mut tcp_to_quic = TcpToQuic {
tcp_read,
quic_send,
shutdown: Shutdown::new(notify_shutdown.subscribe()),
_shutdown_complete: shutdown_complete_tx.clone(),
};
// Spawn a new tasks to handle bidirectional communication.
tokio::spawn(async move {
if let Err(err) = quic_to_tcp.handle().await {
error!(cause = ? err, "stream error");
}
});
tokio::spawn(async move {
if let Err(err) = tcp_to_quic.handle().await {
error!(cause = ? err, "stream error");
}
});
drop(shutdown_complete_tx);
tokio::select! {
_ = self.shutdown.recv() => {
drop(notify_shutdown);
let _ = shutdown_complete_rx.recv().await;
}
_ = shutdown_complete_rx.recv() => {}
};
Ok(())
}
}
impl TcpToQuic {
#[instrument(skip(self))]
async fn handle(&mut self) -> Result<()> {
let mut tcp_buf = [0; TCP_BUF_SIZE];
while !self.shutdown.is_shutdown() {
tokio::select! {
// wait for data from tcp and send to quic
count = self.tcp_read.read(&mut tcp_buf) => {
match count {
Ok(0) => {
// graceful TCP->QUIC shutdown
debug!("graceful TCP->QUIC shutdown");
if let Err(e) = self.quic_send.finish().await {
debug!("error closing quic write stream {}",e);
}
return Ok(());
},
Ok(n) => {
debug!("tcp data size {}\n", n);
if let Err(e) = self.quic_send.write_all(&tcp_buf[..n]).await {
// handle remote TCP RST
// forced QUIC->TCP shutdown
debug!("error in writing to quic stream forced QUIC->TCP shutdown - {}", e);
return Ok(());
};
},
Err(err) => {
// handle TCP RST
// forced TCP->QUIC shutdown
debug!("error in reading tcp stream forced TCP->QUIC shutdown - {}", err);
let err_code:VarInt = VarInt::from_u32(0);
self.quic_send.reset(err_code);
return Ok(());
},
}
},
// wait for shutdown signal
_ = self.shutdown.recv() => {
debug!("shutdown down TcpToQuic");
if let Err(e) = self.quic_send.finish().await {
debug!("error gracefully shutting send stream {}",e);
}
return Ok(());
}
};
}
Ok(())
}
}
impl QuicToTcp {
#[instrument(skip(self))]
async fn handle(&mut self) -> Result<()> {
let mut quic_buf = [0; QUIC_BUF_SIZE];
while !self.shutdown.is_shutdown() {
tokio::select! {
// wait for data from quic and send to tcp
count = self.quic_recv.read(&mut quic_buf) => {
if let Err(ref e) = count {
// handle REMOTE TCP RST
// forced QUIC->TCP shutdown
debug!("error reading quic stream forced QUIC->TCP shutdown - {}",e);
if let Err(e) = self.tcp_write.shutdown().await {
debug!("error closing tcp write stream {}",e);
};
return Ok(());
}
match count.unwrap() {
Some(n) => {
if let Err(err) = self.tcp_write.write_all(&quic_buf[..n]).await {
// handle TCP RST
// forced TCP->QUIC shutdown
debug!("error in writing data to tcp stream forced TCP->QUIC shutdown - {}", err);
// TODO: Fix this in future update
// https://github.com/tokio-rs/tokio/issues/2968
// Since in tokio there is no way to check if socket is closed without
// writing it. if there is in error we will act as connection is RST
let err_code = VarInt::from_u32(0);
if let Err(e) = self.quic_recv.stop(err_code) {
debug!("error closing quic write stream {:?}",e);
}
return Ok(());
};
},
None => {
// graceful QUIC->TCP shutdown
debug!("graceful QUIC->TCP shutdown");
if let Err(e) = self.tcp_write.shutdown().await {
debug!("error closing tcp write stream {}",e);
};
return Ok(());
}
}
},
// wait for shutdown signal
_ = self.shutdown.recv() => {
debug!("shutdown down QuicToTcp");
let err_code = VarInt::from_u32(0);
if let Err(e) = self.quic_recv.stop(err_code) {
debug!("error closing quic write stream {:?}",e);
}
return Ok(());
}
};
}
Ok(())
}
}
|
extern crate reqwest;
use std::io::Read;
//use reqwest::get;
/// returns a list of coin prices from coinmarketcap
///
/// # Arguments
///
/// * `limit` - the number of results to return
///
/// # Example
///
/// ```
/// use getcointicker::coinprices;
///
/// let cp = match coinprices(4) {
/// Result::Ok(val) => {val},
/// Result::Err(err) => {format!("OH NO")}
/// };
/// println!("{}",cp);
/// ```
pub fn coinprices(limit: i32) -> Result<String, reqwest::Error> {
let mut uri: String = "https://api.coinmarketcap.com/v1/ticker/?limit=".to_owned();
uri.push_str(&(limit.to_string()));
let mut resp = reqwest::get(&uri)?;
assert!(resp.status().is_success());
let mut content = String::new();
resp.read_to_string(&mut content)
.expect("could not read prices");;
Ok(content)
}
/// returns a coin's price from coinmarketcap
///
/// # Arguments
///
/// * `id` - the number of results to return
///
/// # Example
///
/// ```
/// use getcointicker::coinprice_id;
///
/// let cp = match coinprice_id("bitcoin".to_owned()) {
/// Result::Ok(val) => {val},
/// Result::Err(err) => {format!("OH NO")}
/// };
/// println!("{}",cp);
/// ```
pub fn coinprice_id(id: String) -> Result<String, reqwest::Error> {
println!("retrieving price information for: {}",&id);
let mut uri: String = "https://api.coinmarketcap.com/v1/ticker/".to_owned();
uri.push_str(&id);
let mut resp = reqwest::get(&uri)?;
assert!(resp.status().is_success());
let mut content = String::new();
resp.read_to_string(&mut content)
.expect("could not read prices");
Ok(content)
}
////////////////////////////////////////
//Test code
///////////////////////////////////////
extern crate serde_json;
// JSON Parsing and Construction
// https://github.com/serde-rs/json
//unused imports are allowed here because this is just for test code
#[allow(unused_imports)]
use serde_json::from_str;
#[allow(unused_imports)]
use serde_json::Value;
#[test]
fn test_pull_id() {
let cp = match coinprice_id("bitcoin".to_owned()) {
Result::Ok(val) => val,
Result::Err(err) => format!("coinprice_id failed: {}", err),
};
let v: Value = serde_json::from_str(&cp).unwrap();
println!("{}", v);
assert!(v[0]["symbol"] == "BTC");
}
#[test]
fn test_pull_count() {
let cp = match coinprices(4) {
Result::Ok(val) => val,
Result::Err(err) => format!("coinprices failed: {}", err),
};
let v: Value = serde_json::from_str(&cp).unwrap();
assert!(v.as_array().unwrap().len() == 4);
}
|
#[doc = "Reader of register CFG3"]
pub type R = crate::R<u32, super::CFG3>;
#[doc = "Writer for register CFG3"]
pub type W = crate::W<u32, super::CFG3>;
#[doc = "Register CFG3 `reset()`'s with value 0"]
impl crate::ResetValue for super::CFG3 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TRIM1_NG_CCRPD`"]
pub type TRIM1_NG_CCRPD_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRIM1_NG_CCRPD`"]
pub struct TRIM1_NG_CCRPD_W<'a> {
w: &'a mut W,
}
impl<'a> TRIM1_NG_CCRPD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `TRIM1_NG_CC1A5`"]
pub type TRIM1_NG_CC1A5_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRIM1_NG_CC1A5`"]
pub struct TRIM1_NG_CC1A5_W<'a> {
w: &'a mut W,
}
impl<'a> TRIM1_NG_CC1A5_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 4)) | (((value as u32) & 0x1f) << 4);
self.w
}
}
#[doc = "Reader of field `TRIM1_NG_CC3A0`"]
pub type TRIM1_NG_CC3A0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRIM1_NG_CC3A0`"]
pub struct TRIM1_NG_CC3A0_W<'a> {
w: &'a mut W,
}
impl<'a> TRIM1_NG_CC3A0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 9)) | (((value as u32) & 0x0f) << 9);
self.w
}
}
#[doc = "Reader of field `TRIM2_NG_CCRPD`"]
pub type TRIM2_NG_CCRPD_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRIM2_NG_CCRPD`"]
pub struct TRIM2_NG_CCRPD_W<'a> {
w: &'a mut W,
}
impl<'a> TRIM2_NG_CCRPD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16);
self.w
}
}
#[doc = "Reader of field `TRIM2_NG_CC1A5`"]
pub type TRIM2_NG_CC1A5_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRIM2_NG_CC1A5`"]
pub struct TRIM2_NG_CC1A5_W<'a> {
w: &'a mut W,
}
impl<'a> TRIM2_NG_CC1A5_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 20)) | (((value as u32) & 0x1f) << 20);
self.w
}
}
#[doc = "Reader of field `TRIM2_NG_CC3A0`"]
pub type TRIM2_NG_CC3A0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRIM2_NG_CC3A0`"]
pub struct TRIM2_NG_CC3A0_W<'a> {
w: &'a mut W,
}
impl<'a> TRIM2_NG_CC3A0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 25)) | (((value as u32) & 0x0f) << 25);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - TRIM1_NG_CCRPD"]
#[inline(always)]
pub fn trim1_ng_ccrpd(&self) -> TRIM1_NG_CCRPD_R {
TRIM1_NG_CCRPD_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:8 - TRIM1_NG_CC1A5"]
#[inline(always)]
pub fn trim1_ng_cc1a5(&self) -> TRIM1_NG_CC1A5_R {
TRIM1_NG_CC1A5_R::new(((self.bits >> 4) & 0x1f) as u8)
}
#[doc = "Bits 9:12 - TRIM1_NG_CC3A0"]
#[inline(always)]
pub fn trim1_ng_cc3a0(&self) -> TRIM1_NG_CC3A0_R {
TRIM1_NG_CC3A0_R::new(((self.bits >> 9) & 0x0f) as u8)
}
#[doc = "Bits 16:19 - TRIM2_NG_CCRPD"]
#[inline(always)]
pub fn trim2_ng_ccrpd(&self) -> TRIM2_NG_CCRPD_R {
TRIM2_NG_CCRPD_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 20:24 - TRIM2_NG_CC1A5"]
#[inline(always)]
pub fn trim2_ng_cc1a5(&self) -> TRIM2_NG_CC1A5_R {
TRIM2_NG_CC1A5_R::new(((self.bits >> 20) & 0x1f) as u8)
}
#[doc = "Bits 25:28 - TRIM2_NG_CC3A0"]
#[inline(always)]
pub fn trim2_ng_cc3a0(&self) -> TRIM2_NG_CC3A0_R {
TRIM2_NG_CC3A0_R::new(((self.bits >> 25) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - TRIM1_NG_CCRPD"]
#[inline(always)]
pub fn trim1_ng_ccrpd(&mut self) -> TRIM1_NG_CCRPD_W {
TRIM1_NG_CCRPD_W { w: self }
}
#[doc = "Bits 4:8 - TRIM1_NG_CC1A5"]
#[inline(always)]
pub fn trim1_ng_cc1a5(&mut self) -> TRIM1_NG_CC1A5_W {
TRIM1_NG_CC1A5_W { w: self }
}
#[doc = "Bits 9:12 - TRIM1_NG_CC3A0"]
#[inline(always)]
pub fn trim1_ng_cc3a0(&mut self) -> TRIM1_NG_CC3A0_W {
TRIM1_NG_CC3A0_W { w: self }
}
#[doc = "Bits 16:19 - TRIM2_NG_CCRPD"]
#[inline(always)]
pub fn trim2_ng_ccrpd(&mut self) -> TRIM2_NG_CCRPD_W {
TRIM2_NG_CCRPD_W { w: self }
}
#[doc = "Bits 20:24 - TRIM2_NG_CC1A5"]
#[inline(always)]
pub fn trim2_ng_cc1a5(&mut self) -> TRIM2_NG_CC1A5_W {
TRIM2_NG_CC1A5_W { w: self }
}
#[doc = "Bits 25:28 - TRIM2_NG_CC3A0"]
#[inline(always)]
pub fn trim2_ng_cc3a0(&mut self) -> TRIM2_NG_CC3A0_W {
TRIM2_NG_CC3A0_W { w: self }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.