text stringlengths 8 4.13M |
|---|
#[doc =
"Pulls type information out of the AST and attaches it to the document"];
import rustc::syntax::ast;
import rustc::syntax::print::pprust;
import rustc::middle::ast_map;
export mk_pass;
fn mk_pass() -> pass {
run
}
fn run(
srv: astsrv::srv,
doc: doc::cratedoc
) -> doc::cratedoc {
let fold = fold::fold({
fold_fn: fold_fn,
fold_const: fold_const
with *fold::default_seq_fold(srv)
});
fold.fold_crate(fold, doc)
}
fn fold_fn(
fold: fold::fold<astsrv::srv>,
doc: doc::fndoc
) -> doc::fndoc {
let srv = fold.ctxt;
~{
args: merge_arg_tys(srv, doc.id, doc.args),
return: merge_ret_ty(srv, doc.id, doc.return),
sig: get_fn_sig(srv, doc.id)
with *doc
}
}
fn get_fn_sig(srv: astsrv::srv, fn_id: doc::ast_id) -> option<str> {
astsrv::exec(srv) {|ctxt|
alt ctxt.map.get(fn_id) {
ast_map::node_item(@{
ident: ident,
node: ast::item_fn(decl, _, blk), _
}) {
some(pprust::fun_to_str(decl, ident, []))
}
}
}
}
#[test]
fn should_add_fn_sig() {
let source = "fn a() -> int { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
assert doc.topmod.fns[0].sig == some("fn a() -> int");
}
fn merge_ret_ty(
srv: astsrv::srv,
fn_id: doc::ast_id,
doc: doc::retdoc
) -> doc::retdoc {
alt get_ret_ty(srv, fn_id) {
some(ty) {
{
ty: some(ty)
with doc
}
}
none { doc }
}
}
fn get_ret_ty(srv: astsrv::srv, fn_id: doc::ast_id) -> option<str> {
astsrv::exec(srv) {|ctxt|
alt ctxt.map.get(fn_id) {
ast_map::node_item(@{
node: ast::item_fn(decl, _, _), _
}) {
if decl.output.node != ast::ty_nil {
some(pprust::ty_to_str(decl.output))
} else {
// Nil-typed return values are not interesting
none
}
}
}
}
}
#[test]
fn should_add_fn_ret_types() {
let source = "fn a() -> int { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
assert doc.topmod.fns[0].return.ty == some("int");
}
#[test]
fn should_not_add_nil_ret_type() {
let source = "fn a() { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
assert doc.topmod.fns[0].return.ty == none;
}
fn merge_arg_tys(
srv: astsrv::srv,
fn_id: doc::ast_id,
args: [doc::argdoc]
) -> [doc::argdoc] {
let tys = get_arg_tys(srv, fn_id);
vec::map2(args, tys) {|arg, ty|
// Sanity check that we're talking about the same args
assert arg.name == tuple::first(ty);
~{
ty: some(tuple::second(ty))
with *arg
}
}
}
fn get_arg_tys(srv: astsrv::srv, fn_id: doc::ast_id) -> [(str, str)] {
astsrv::exec(srv) {|ctxt|
alt ctxt.map.get(fn_id) {
ast_map::node_item(@{
node: ast::item_fn(decl, _, _), _
}) {
vec::map(decl.inputs) {|arg|
(arg.ident, pprust::ty_to_str(arg.ty))
}
}
}
}
}
#[test]
fn should_add_arg_types() {
let source = "fn a(b: int, c: bool) { }";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
let fn_ = doc.topmod.fns[0];
assert fn_.args[0].ty == some("int");
assert fn_.args[1].ty == some("bool");
}
fn fold_const(
fold: fold::fold<astsrv::srv>,
doc: doc::constdoc
) -> doc::constdoc {
let srv = fold.ctxt;
~{
ty: some(astsrv::exec(srv) {|ctxt|
alt ctxt.map.get(doc.id) {
ast_map::node_item(@{
node: ast::item_const(ty, _), _
}) {
pprust::ty_to_str(ty)
}
}
})
with *doc
}
}
#[test]
fn should_add_const_types() {
let source = "const a: bool = true;";
let srv = astsrv::mk_srv_from_str(source);
let doc = extract::from_srv(srv, "");
let doc = run(srv, doc);
assert doc.topmod.consts[0].ty == some("bool");
} |
use std::clone::Clone;
use std::default::Default;
use std::option::Option;
use std::option::Option::Some;
use std::result::Result::Ok;
use gdk::{EventButton, EventType};
use gio::prelude::*;
use gtk::prelude::*;
use gtk::{
ApplicationWindow, Builder, ButtonExt, GtkWindowExt, Inhibit, ListBox, ListBoxExt, PopoverExt,
PopoverMenu, WidgetExt,
};
const GLADE_SRC: &str = include_str!("grid.glade");
#[derive(Clone)]
struct AppCtx {
window: gtk::ApplicationWindow,
meta_context_menu: PopoverMenu,
search_buttons: SearchButtons,
list_box: ListBox,
}
#[derive(Clone)]
struct SearchButtons {
pub button_one: gtk::Button,
pub button_two: gtk::Button,
pub button_three: gtk::Button,
}
impl SearchButtons {
pub fn get_button_one(&self) -> gtk::Button {
self.button_one.clone()
}
pub fn get_button_two(&self) -> gtk::Button {
self.button_two.clone()
}
pub fn get_button_three(&self) -> gtk::Button {
self.button_three.clone()
}
}
impl AppCtx {
pub fn new(application: >k::Application) -> Self {
let builder = Builder::new_from_string(GLADE_SRC);
let window: ApplicationWindow = builder.get_object("window").expect("Couldn't get window");
window.set_application(Some(application));
let meta_context_menu: PopoverMenu = builder
.get_object("meta_context_menu")
.expect("Couldn't get meta_context_menu");
let meta_button_one: gtk::Button = builder
.get_object("meta_button_one")
.expect("Couldn't get meta_button_one");
let meta_button_two: gtk::Button = builder
.get_object("meta_button_two")
.expect("Couldn't get meta_button_two");
let meta_button_three: gtk::Button = builder
.get_object("meta_button_three")
.expect("Couldn't get meta_button_three");
let list_box: gtk::ListBox = builder
.get_object("list_box")
.expect("Couldn't get list_box");
let search_buttons = SearchButtons {
button_one: meta_button_one,
button_two: meta_button_two,
button_three: meta_button_three,
};
AppCtx {
window,
meta_context_menu,
search_buttons,
list_box,
}
}
pub fn open_meta_context_menu(&self) {
self.meta_context_menu.popup()
}
pub fn close_meta_context_menu(&self) {
self.meta_context_menu.popdown()
}
pub fn setup_search_buttons(&self) {
self.clone().setup_button_one_clicked();
self.clone().setup_button_two_clicked();
self.clone().setup_button_three_clicked();
}
pub fn set_meta_context_menu_relative_to<P: IsA<gtk::Widget>>(&self, widget: Option<&P>) {
self.meta_context_menu.set_relative_to(widget)
}
pub fn get_window(&self) -> gtk::ApplicationWindow {
self.window.clone()
}
fn connect_mouse_events(self, list_box: ListBox, event_button: EventButton) -> Inhibit {
if let EventType::ButtonPress = event_button.get_event_type() {
if let Some(row) = ListBoxExt::get_selected_row(&list_box) {
self.set_meta_context_menu_relative_to(Some(&row));
self.setup_search_buttons();
match event_button.get_button() {
// Left click
1 => {
// debug!("Detected left click on {:?}: {:?}", search_type, text);
Inhibit(false)
}
// Right click
3 => {
// debug!("Detected right click on {:?}: {:?}", search_type, text);
self.open_meta_context_menu();
Inhibit(true)
}
// Ignore other button presses
_ => Inhibit(true),
}
} else {
Inhibit(false)
}
} else {
Inhibit(false)
}
}
pub fn setup_button_one_clicked(self) {
let ctx = self.clone();
ctx.search_buttons
.get_button_one()
.connect_clicked(move |_s| {
ctx.close_meta_context_menu();
// do thing
dbg!("one clicked");
});
}
pub fn setup_button_two_clicked(self) {
let ctx = self.clone();
ctx.search_buttons
.get_button_two()
.connect_clicked(move |_s| {
ctx.close_meta_context_menu();
// do thing
dbg!("two clicked");
});
}
pub fn setup_button_three_clicked(self) {
let ctx = self.clone();
ctx.search_buttons
.get_button_three()
.connect_clicked(move |_s| {
ctx.close_meta_context_menu();
// do thing
dbg!("three clicked");
});
}
fn setup_meta_list(self) {
self.clone().list_box.connect_button_press_event(
move |list_box: &ListBox, event_button: &EventButton| {
self.clone()
.connect_mouse_events(list_box.clone(), event_button.clone())
},
);
}
}
fn build_ui(application: >k::Application) -> std::io::Result<()> {
let app_ctx = AppCtx::new(application);
let window = app_ctx.get_window();
app_ctx.setup_meta_list();
window.show_all();
Ok(())
}
fn main() -> anyhow::Result<()> {
let application = gtk::Application::new(Some("org.evanjs.popover-help"), Default::default())?;
application.connect_activate(|app| {
build_ui(app).unwrap();
});
application.run(&[]);
Ok(())
}
|
use std::fs;
fn main() {
// Read input from file
let contents = fs::read_to_string("input.txt").expect("Failed reading input file");
let program: Vec<&str> = contents.lines().collect();
// Challenge1
let state = run_program(&program);
println!("Challenge1: {}", state.1);
// Challenge2
for (i, line) in program.iter().enumerate() {
let mut params = line.split(" ");
let command = params.next().unwrap();
match command {
"nop" => {
let mut new_prog = program.clone();
let arg = params.next().unwrap();
new_prog.remove(i);
let sub = &format!("jmp {}", arg);
new_prog.insert(i, sub);
let state = run_program(&new_prog);
if state.0 != -1 {
println!("Challenge2: {}", state.1);
break;
}
},
"jmp" => {
let mut new_prog = program.clone();
let arg = params.next().unwrap();
new_prog.remove(i);
let sub = &format!("nop {}", arg);
new_prog.insert(i, sub);
let state = run_program(&new_prog);
if state.0 != -1 {
println!("Challenge2: {}", state.1);
break;
}
},
_ => {},
}
}
}
fn run_program(program: &Vec<&str>) -> (isize, isize) {
let mut state: (isize, isize) = (0, 0);
let mut done: Vec<isize> = Vec::new();
while state.0 != -1 && state.0 != program.len() as isize {
state = run(program[state.0 as usize], &state, &mut done);
}
state
}
fn run(instruction: &str, state: &(isize, isize), done: &mut Vec<isize>) -> (isize, isize) {
let lineno = state.0;
let acc = state.1;
if done.contains(&lineno) {
(-1, acc)
} else {
done.push(lineno);
let mut params = instruction.split(" ");
let command = params.next().unwrap();
let arg: isize = params.next().unwrap().parse().unwrap();
match command {
"nop" => (lineno + 1, acc),
"jmp" => (lineno + arg, acc),
"acc" => (lineno + 1, acc + arg),
_ => (-1, acc),
}
}
}
|
//! Simple writer to file descriptor using libc.
//!
//! ## Features:
//!
//! - `std` - Enables `std::io::Write` implementation.
//!
#![cfg_attr(not(test), no_std)]
#![warn(missing_docs)]
#[cfg(feature = "std")]
extern crate std;
use core::{slice, cmp, mem, ptr, fmt};
const BUFFER_CAPACITY: usize = 4096;
///Wrapper into file descriptor.
pub struct FdWriter {
fd: libc::c_int,
len: u16,
buffer: mem::MaybeUninit<[u8; BUFFER_CAPACITY]>,
}
impl FdWriter {
///Creates new instance which writes into `fd`
pub const fn new(fd: libc::c_int) -> Self {
Self {
fd,
len: 0,
buffer: mem::MaybeUninit::uninit(),
}
}
#[inline(always)]
///Returns pointer to first element in underlying buffer.
pub const fn as_ptr(&self) -> *const u8 {
&self.buffer as *const _ as *const _
}
#[inline(always)]
///Returns pointer to first element in underlying buffer.
pub fn as_mut_ptr(&mut self) -> *mut u8 {
self.buffer.as_mut_ptr() as *mut _ as *mut _
}
#[inline]
///Returns immutable slice with current elements
pub fn as_slice(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(self.as_ptr(), self.len as _)
}
}
fn inner_flush(&mut self) {
let text = unsafe {
core::str::from_utf8_unchecked(self.as_slice())
};
unsafe {
libc::write(self.fd.into(), text.as_ptr() as *const _, text.len() as _);
}
self.len = 0;
}
///Flushes buffer, clearing buffer.
pub fn flush(&mut self) {
if self.len > 0 {
self.inner_flush();
}
}
#[inline]
fn copy_data<'a>(&mut self, data: &'a [u8]) -> &'a [u8] {
let write_len = cmp::min(BUFFER_CAPACITY.saturating_sub(self.len as _), data.len());
unsafe {
ptr::copy_nonoverlapping(data.as_ptr(), self.as_mut_ptr().add(self.len as _), write_len);
}
self.len += write_len as u16;
&data[write_len..]
}
///Writes data unto buffer.
///
///Flushing if it ends with `\n` automatically
pub fn write_data(&mut self, mut data: &[u8]) {
loop {
data = self.copy_data(data);
if data.len() == 0 {
break;
} else {
self.flush();
}
}
if self.as_slice()[self.len as usize - 1] == b'\n' {
self.flush();
}
}
}
impl fmt::Write for FdWriter {
#[inline]
fn write_str(&mut self, text: &str) -> fmt::Result {
self.write_data(text.as_bytes());
Ok(())
}
}
#[cfg(feature = "std")]
impl std::io::Write for FdWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.write_data(buf);
Ok(buf.len())
}
#[inline(always)]
fn flush(&mut self) -> std::io::Result<()> {
self.flush();
Ok(())
}
}
impl Drop for FdWriter {
#[inline]
fn drop(&mut self) {
self.flush();
}
}
|
use std::{cmp, num::NonZeroU32};
use metrics::gauge;
use super::{Clock, RealClock};
const INTERVAL_TICKS: u64 = 1_000_000;
/// Errors produced by [`Stable`].
#[derive(thiserror::Error, Debug, Clone, Copy)]
pub(crate) enum Error {
/// Requested capacity is greater than maximum allowed capacity.
#[error("Capacity")]
Capacity,
}
#[derive(Debug)]
/// A throttle type.
///
/// This throttle is stable in that it will steadily refil units at a known rate and does not inspect the target in any way, compare to `Predictive` in that regard.
pub(crate) struct Stable<C = RealClock> {
last_tick: u64,
/// The capacity left in `Stable` after a user request.
spare_capacity: u64,
/// The maximum capacity of `Stable` past which no more capacity will be
/// added.
maximum_capacity: u64,
/// Per tick, how much capacity is added to the throttle.
refill_per_tick: u64,
/// The clock that `Stable` will use.
clock: C,
}
impl<C> Stable<C>
where
C: Clock + Send + Sync,
{
#[inline]
pub(crate) async fn wait(&mut self) -> Result<(), Error> {
// SAFETY: 1_u32 is a non-zero u32.
let one = unsafe { NonZeroU32::new_unchecked(1_u32) };
self.wait_for(one).await
}
pub(crate) async fn wait_for(&mut self, request: NonZeroU32) -> Result<(), Error> {
// Okay, here's the idea. At the base of `Stable` is a cell rate
// algorithm. We have bucket that gradually fills up and when it's full
// it doesn't fill up anymore. Callers draw down on this capacity and if
// they draw down more than is available in the bucket they're made to
// wait.
gauge!("throttle_refills_per_tick", self.refill_per_tick as f64);
// Fast bail-out. There's no way for this to ever be satisfied and is a
// bug on the part of the caller, arguably.
if u64::from(request.get()) > self.maximum_capacity {
return Err(Error::Capacity);
}
// Now that the preliminaries are out of the way, wake up and compute
// how much the throttle capacity is refilled since we were last
// called. Depending on how long ago this was we may have completely
// filled up throttle capacity.
let ticks_since_start = self.clock.ticks_elapsed();
let ticks_since_last_wait = ticks_since_start.saturating_sub(self.last_tick);
self.last_tick = ticks_since_start;
let refilled_capacity: u64 = cmp::min(
ticks_since_last_wait
.saturating_mul(self.refill_per_tick)
.saturating_add(self.spare_capacity),
self.maximum_capacity,
);
let capacity_request = u64::from(request.get());
if refilled_capacity > capacity_request {
// If the refilled capacity is greater than the request we respond
// to the caller immediately and store the spare capacity for next
// call.
self.spare_capacity = refilled_capacity - capacity_request;
} else {
// If the refill is not sufficient we calculate how many ticks will
// need to pass before capacity is sufficient, force the client to
// wait that amount of time.
self.spare_capacity = 0;
let slop = (capacity_request - refilled_capacity) / self.refill_per_tick;
self.clock.wait(slop).await;
}
Ok(())
}
pub(crate) fn with_clock(maximum_capacity: NonZeroU32, clock: C) -> Self {
// We set the maximum capacity of the bucket, X. We say that an
// 'interval' happens once every second. If we allow for the tick of
// Throttle to be one per microsecond that's 1x10^6 ticks per interval.
// We do not want a situation where refill never happens. If the maximum
// capacity is less than INTERVAL_TICKS we set the floor at 1.
let refill_per_tick = cmp::max(1, u64::from(maximum_capacity.get()) / INTERVAL_TICKS);
Self {
last_tick: clock.ticks_elapsed(),
maximum_capacity: u64::from(maximum_capacity.get()),
refill_per_tick,
spare_capacity: 0,
clock,
}
}
}
|
// Copyright (c) 2020 kprotty
//
// 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 core::{
cell::{Cell, UnsafeCell},
marker::PhantomData,
mem::MaybeUninit,
ptr::NonNull,
};
#[derive(Debug)]
pub struct Node<T> {
prev: Cell<MaybeUninit<Option<NonNull<Self>>>>,
next: Cell<MaybeUninit<Option<NonNull<Self>>>>,
tail: Cell<MaybeUninit<Option<NonNull<Self>>>>,
value: UnsafeCell<T>,
}
impl<T: Default> Default for Node<T> {
fn default() -> Self {
Self::from(T::default())
}
}
impl<T> From<T> for Node<T> {
fn from(value: T) -> Self {
Self::new(value)
}
}
impl<T> Node<T> {
pub const fn new(value: T) -> Self {
Self {
prev: Cell::new(MaybeUninit::uninit()),
next: Cell::new(MaybeUninit::uninit()),
tail: Cell::new(MaybeUninit::uninit()),
value: UnsafeCell::new(value),
}
}
pub fn get(&self) -> *mut T {
self.value.get()
}
}
#[derive(Debug, Default)]
pub struct List<T> {
head: Option<NonNull<Node<T>>>,
}
impl<T> List<T> {
pub const fn new() -> Self {
Self { head: None }
}
pub fn is_empty(&self) -> bool {
self.head.is_none()
}
pub unsafe fn iter<'a>(&'a self) -> ListIter<'a, T> {
ListIter {
node: self.head,
_lifetime: PhantomData,
}
}
pub unsafe fn drain(&mut self) -> ListDrain<'_, T> {
ListDrain(self)
}
pub unsafe fn push(&mut self, node: NonNull<Node<T>>) {
self.push_back(node)
}
pub unsafe fn push_back(&mut self, node: NonNull<Node<T>>) {
node.as_ref().next.set(MaybeUninit::new(None));
node.as_ref().tail.set(MaybeUninit::new(Some(node)));
if let Some(head) = self.head {
let tail = head.as_ref().tail.get().assume_init().unwrap();
node.as_ref().prev.set(MaybeUninit::new(Some(tail)));
tail.as_ref().next.set(MaybeUninit::new(Some(node)));
head.as_ref().tail.set(MaybeUninit::new(Some(node)));
} else {
self.head = Some(node);
node.as_ref().prev.set(MaybeUninit::new(None));
}
}
pub unsafe fn push_front(&mut self, node: NonNull<Node<T>>) {
node.as_ref().prev.set(MaybeUninit::new(None));
node.as_ref().next.set(MaybeUninit::new(self.head));
if let Some(head) = std::mem::replace(&mut self.head, Some(node)) {
node.as_ref().tail.set(head.as_ref().tail.get());
head.as_ref().prev.set(MaybeUninit::new(Some(node)));
}
}
pub unsafe fn pop(&mut self) -> Option<NonNull<Node<T>>> {
self.pop_front()
}
pub unsafe fn pop_front(&mut self) -> Option<NonNull<Node<T>>> {
self.head.map(|head| {
let node = head;
assert!(self.try_remove(node));
node
})
}
pub unsafe fn pop_back(&mut self) -> Option<NonNull<Node<T>>> {
self.head.map(|head| {
let node = head.as_ref().tail.get().assume_init().unwrap();
assert!(self.try_remove(node));
node
})
}
pub unsafe fn try_remove(&mut self, node: NonNull<Node<T>>) -> bool {
let prev = node.as_ref().prev.get().assume_init();
let next = node.as_ref().next.get().assume_init();
let head = match self.head {
Some(head) => head,
None => return false,
};
if let Some(prev) = prev {
prev.as_ref().next.set(MaybeUninit::new(next));
}
if let Some(next) = next {
next.as_ref().prev.set(MaybeUninit::new(prev));
}
if head == NonNull::from(node) {
self.head = next;
if let Some(new_head) = self.head {
new_head.as_ref().tail.set(head.as_ref().tail.get());
}
} else if head.as_ref().tail.get().assume_init() == Some(NonNull::from(node)) {
head.as_ref().tail.set(MaybeUninit::new(prev));
}
node.as_ref().next.set(MaybeUninit::new(None));
node.as_ref().prev.set(MaybeUninit::new(None));
node.as_ref().tail.set(MaybeUninit::new(None));
true
}
}
pub struct ListIter<'a, T> {
node: Option<NonNull<Node<T>>>,
_lifetime: PhantomData<&'a List<T>>,
}
impl<'a, T> Iterator for ListIter<'a, T> {
type Item = NonNull<Node<T>>;
fn next(&mut self) -> Option<Self::Item> {
self.node.map(|node| unsafe {
self.node = node.as_ref().next.get().assume_init();
node
})
}
}
pub struct ListDrain<'a, T>(&'a mut List<T>);
impl<'a, T> Iterator for ListDrain<'a, T> {
type Item = NonNull<Node<T>>;
fn next(&mut self) -> Option<Self::Item> {
unsafe { self.0.pop() }
}
}
|
/*
* Copyright (C) 2018 Kubos Corporation
*
* 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.
*/
#![deny(warnings)]
use kubos_app::ServiceConfig;
use std::panic;
mod utils;
pub use crate::utils::*;
#[test]
fn uninstall_app() {
let mut fixture = AppServiceFixture::setup();
let config = format!(
"{}",
fixture
.registry_dir
.path()
.join("config.toml")
.to_string_lossy()
);
let mut app = MockAppBuilder::new("dummy", "a-b-c-d-e");
app.active(true)
.run_level("OnBoot")
.version("0.0.1")
.author("user");
app.install(&fixture.registry_dir.path());
fixture.start_service(false);
let result = panic::catch_unwind(|| {
let result = send_query(
ServiceConfig::new_from_path("app-service", config.to_owned()),
r#"mutation {
uninstall(uuid: "a-b-c-d-e", version: "0.0.1") {
errors,
success
}
}"#,
);
assert!(result["uninstall"]["success"].as_bool().unwrap());
let result = send_query(
ServiceConfig::new_from_path("app-service", config.to_owned()),
"{ apps { active } }",
);
assert_eq!(result["apps"].as_array().expect("Not an array").len(), 0);
});
fixture.teardown();
assert!(result.is_ok());
}
|
#[doc = "Reader of register SPINLOCK11"]
pub type R = crate::R<u32, super::SPINLOCK11>;
impl R {}
|
extern crate two_timer;
use two_timer::{parsable, parse, Config, TimeError};
extern crate chrono;
use chrono::naive::NaiveDate;
use chrono::{Duration, Local, NaiveDateTime};
// a debugging method to print out the parse tree
// fn show_me(p: &str) {
// println!("{}", two_timer::MATCHER.parse(p).unwrap());
// }
#[test]
fn can_use_parsable() {
assert!(parsable("2019/1/1"));
}
#[test]
fn always() {
let alpha = NaiveDate::MIN.and_hms_milli_opt(0, 0, 0, 0).unwrap();
let omega = NaiveDate::MAX.and_hms_milli_opt(23, 59, 59, 999).unwrap();
for phrase in [
"always",
"ever",
"all time",
"forever",
"from beginning to end",
"from the beginning to the end",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(alpha, start);
assert_eq!(omega, end);
}
}
#[test]
fn yesterday() {
let now = Local::now().naive_local();
let (start, end, _) = parse("yesterday", Some(Config::new().now(now))).unwrap();
assert!(start < now);
assert!(end < now);
let then = now - Duration::days(1);
assert!(start < then);
assert!(then < end);
let then = then - Duration::days(1);
assert!(then < start);
}
#[test]
fn tomorrow() {
let now = Local::now().naive_local();
let (start, end, _) = parse("tomorrow", Some(Config::new().now(now))).unwrap();
assert!(start > now);
assert!(end > now);
let then = now + Duration::days(1);
assert!(start < then);
assert!(then < end);
let then = then + Duration::days(1);
assert!(then > end);
}
#[test]
fn today() {
let now = Local::now().naive_local();
let (start, end, _) = parse("today", Some(Config::new().now(now))).unwrap();
assert!(start < now);
assert!(end > now);
let then = now + Duration::days(1);
assert!(start < then);
assert!(then > end);
let then = now - Duration::days(1);
assert!(then < start);
assert!(then < end);
}
#[test]
fn day_5_6_69_at_3_30_pm() {
let then = precise_moment(1969, 5, 6, 15, 30, 0);
for phrase in [
"at 3:30 PM on 5-6-69",
"3:30 p.m. on 5-6-69",
"at 15:30 on 5-6-69",
"15:30 on 5-6-69",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn day_5_6_69_at_3_pm() {
let then = precise_moment(1969, 5, 6, 15, 0, 0);
for phrase in [
"at 3 PM on 5-6-69",
"3 p.m. on 5-6-69",
"at 15 on 5-6-69",
"15 on 5-6-69",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn day_5_6_69_at_3_30_00_pm() {
let then = precise_moment(1969, 5, 6, 15, 30, 0);
for phrase in [
"at 3:30:00 PM on 5-6-69",
"3:30:00 p.m. on 5-6-69",
"at 15:30:00 on 5-6-69",
"15:30:00 on 5-6-69",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn day_5_6_69_at_3_30_01_pm() {
let then = precise_moment(1969, 5, 6, 15, 30, 1);
for phrase in [
"at 3:30:01 PM on 5-6-69",
"3:30:01 p.m. on 5-6-69",
"at 15:30:01 on 5-6-69",
"15:30:01 on 5-6-69",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn day_5_6_69_at_3_30_01_am() {
let then = precise_moment(1969, 5, 6, 3, 30, 1);
for phrase in [
"at 3:30:01 AM on 5-6-69",
"3:30:01 a.m. on 5-6-69",
"at 3:30:01 on 5-6-69",
"3:30:01 on 5-6-69",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn at_3_pm() {
let now = precise_moment(1969, 5, 6, 16, 0, 0);
let then = precise_moment(1969, 5, 6, 15, 0, 0);
for phrase in ["3 PM", "3 pm", "15"].iter() {
let (start, end, _) = parse(phrase, Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn at_3_pm_default_to_future() {
let now = precise_moment(1969, 5, 6, 14, 0, 0);
let then = precise_moment(1969, 5, 6, 15, 0, 0);
for phrase in ["3 PM", "3 pm", "15"].iter() {
let (start, end, _) =
parse(phrase, Some(Config::new().now(now).default_to_past(false))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn at_3_00_pm() {
let now = precise_moment(1969, 5, 6, 16, 0, 0);
let then = precise_moment(1969, 5, 6, 15, 0, 0);
for phrase in ["3:00 PM", "3:00 pm", "15:00"].iter() {
let (start, end, _) = parse(phrase, Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn at_3_00_00_pm() {
let now = precise_moment(1969, 5, 6, 16, 0, 0);
let then = precise_moment(1969, 5, 6, 15, 0, 0);
for phrase in ["3:00:00 PM", "3:00:00 pm", "15:00:00"].iter() {
let (start, end, _) = parse(phrase, Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn at_3_pm_yesterday() {
let now = precise_moment(1969, 5, 6, 14, 0, 0);
let then = precise_moment(1969, 5, 5, 15, 0, 0);
for phrase in ["3 PM yesterday", "3 pm yesterday", "15 yesterday"].iter() {
let (start, end, _) = parse(phrase, Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
}
#[test]
fn alphabetic_5_6_69() {
let then = first_moment_of_day(1969, 5, 6);
for phrase in [
"May 6, 1969",
"May 6, '69",
"May 6, 69",
"6 May 1969",
"6 May '69",
"6 May 69",
"Tuesday, May 6, 1969",
"Tuesday, May 6, '69",
"Tuesday, May 6, 69",
"Tues, May 6, 1969",
"Tues, May 6, '69",
"Tues, May 6, 69",
"Tue, May 6, 1969",
"Tue, May 6, '69",
"Tue, May 6, 69",
"Tu, May 6, 1969",
"Tu, May 6, '69",
"Tu, May 6, 69",
"Tues., May 6, 1969",
"Tues., May 6, '69",
"Tues., May 6, 69",
"Tue., May 6, 1969",
"Tue., May 6, '69",
"Tue., May 6, 69",
"Tu., May 6, 1969",
"Tu., May 6, '69",
"Tu., May 6, 69",
"T, May 6, 1969",
"T, May 6, '69",
"T, May 6, 69",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::days(1), end);
}
}
#[test]
fn ymd_5_31_69() {
let then = first_moment_of_day(1969, 5, 31);
for phrase in [
"5-31-69",
"5/31/69",
"5.31.69",
"5/31/1969",
"5-31-1969",
"5.31.1969",
"69-5-31",
"69/5/31",
"69.5.31",
"1969/5/31",
"1969-5-31",
"1969.5.31",
"5-31-'69",
"5/31/'69",
"5.31.'69",
"'69-5-31",
"'69/5/31",
"'69.5.31",
"31-5-69",
"31/5/69",
"31.5.69",
"31/5/1969",
"31-5-1969",
"31.5.1969",
"69-31-5",
"69/31/5",
"69.31.5",
"1969/31/5",
"1969-31-5",
"1969.31.5",
"31-5-'69",
"31/5/'69",
"31.5.'69",
"'69-31-5",
"'69/31/5",
"'69.31.5",
"05-31-69",
"05/31/69",
"05.31.69",
"05/31/1969",
"05-31-1969",
"05.31.1969",
"69-05-31",
"69/05/31",
"69.05.31",
"1969/05/31",
"1969-05-31",
"1969.05.31",
"05-31-'69",
"05/31/'69",
"05.31.'69",
"'69-05-31",
"'69/05/31",
"'69.05.31",
"31-05-69",
"31/05/69",
"31.05.69",
"31/05/1969",
"31-05-1969",
"31.05.1969",
"69-31-05",
"69/31/05",
"69.31.05",
"1969/31/05",
"1969-31-05",
"1969.31.05",
"31-05-'69",
"31/05/'69",
"31.05.'69",
"'69-31-05",
"'69/31/05",
"'69.31.05",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::days(1), end);
}
}
#[test]
fn leap_day() {
let rv = parse("2019-02-29", None);
assert!(rv.is_err());
let rv = parse("2020-02-29", None);
assert!(rv.is_ok());
}
#[test]
fn may_1969() {
let m1 = first_moment_of_day(1969, 5, 1);
let m2 = first_moment_of_day(1969, 6, 1);
for phrase in ["May 1969", "May '69"].iter() {
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(m1, start);
assert_eq!(m2, end);
}
}
#[test]
fn short_year_past_vs_future() {
let m1 = first_moment_of_day(1969, 5, 1);
let m2 = first_moment_of_day(1969, 6, 1);
let now = first_moment_of_day(2020, 5, 6);
let (start, end, _) = parse("May '69", Some(Config::new().now(now))).unwrap();
assert_eq!(m1, start);
assert_eq!(m2, end);
let m1 = first_moment_of_day(2069, 5, 1);
let m2 = first_moment_of_day(2069, 6, 1);
let (start, end, _) = parse(
"May '69",
Some(Config::new().now(now).default_to_past(false)),
)
.unwrap();
assert_eq!(m1, start);
assert_eq!(m2, end);
}
#[test]
fn this_month() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 1);
let d2 = first_moment_of_day(1969, 6, 1);
let (start, end, _) = parse("this month", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_month() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 6, 1);
let d2 = first_moment_of_day(1969, 7, 1);
let (start, end, _) = parse("next month", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_month() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 4, 1);
let d2 = first_moment_of_day(1969, 5, 1);
let (start, end, _) = parse("last month", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_year() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 1, 1);
let d2 = first_moment_of_day(1970, 1, 1);
let (start, end, _) = parse("this year", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_year() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1970, 1, 1);
let d2 = first_moment_of_day(1971, 1, 1);
let (start, end, _) = parse("next year", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_year() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1968, 1, 1);
let d2 = first_moment_of_day(1969, 1, 1);
let (start, end, _) = parse("last year", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_week() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 5);
let d2 = first_moment_of_day(1969, 5, 12);
let (start, end, _) = parse("this week", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn the_week() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 5);
let d2 = first_moment_of_day(1969, 5, 12);
let (start, end, _) = parse("the week", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_week() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 12);
let d2 = first_moment_of_day(1969, 5, 19);
let (start, end, _) = parse("next week", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_week() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 4, 28);
let d2 = first_moment_of_day(1969, 5, 5);
let (start, end, _) = parse("last week", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_week_sunday_starts() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 4);
let d2 = first_moment_of_day(1969, 5, 11);
let (start, end, _) = parse(
"this week",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_week_sunday_starts() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 11);
let d2 = first_moment_of_day(1969, 5, 18);
let (start, end, _) = parse(
"next week",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_week_sunday_starts() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 4, 27);
let d2 = first_moment_of_day(1969, 5, 4);
let (start, end, _) = parse(
"last week",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_pay_period() {
let now = first_moment_of_day(1969, 5, 6);
// two-week pay period beginning about a year before "now" on a Sunday
let config = Config::new()
.pay_period_start(Some(precise_day(1968, 5, 5)))
.pay_period_length(14)
.now(now);
let d1 = first_moment_of_day(1969, 5, 4);
let d2 = first_moment_of_day(1969, 5, 18);
for pp in ["pp", "pay period", "payperiod"].iter() {
let (start, end, _) = parse(format!("this {}", pp).as_ref(), Some(config.clone())).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
}
#[test]
fn bare_pay_period() {
let now = first_moment_of_day(1969, 5, 6);
// two-week pay period beginning about a year before "now" on a Sunday
let config = Config::new()
.pay_period_start(Some(precise_day(1968, 5, 5)))
.pay_period_length(14)
.now(now);
let d1 = first_moment_of_day(1969, 5, 4);
let d2 = first_moment_of_day(1969, 5, 18);
for pp in ["pp", "pay period", "payperiod"].iter() {
let (start, end, _) = parse(pp, Some(config.clone())).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
}
#[test]
fn next_pay_period() {
let now = first_moment_of_day(1969, 5, 6);
// two-week pay period beginning about a year before "now" on a Sunday
let config = Config::new()
.pay_period_start(Some(precise_day(1968, 5, 5)))
.pay_period_length(14)
.now(now);
let d1 = first_moment_of_day(1969, 5, 18);
let d2 = first_moment_of_day(1969, 6, 1);
for pp in ["pp", "pay period", "payperiod"].iter() {
let (start, end, _) = parse(&format!("next {}", pp), Some(config.clone())).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
}
#[test]
fn last_pay_period() {
let now = first_moment_of_day(1969, 5, 6);
// two-week pay period beginning about a year before "now" on a Sunday
let config = Config::new()
.pay_period_start(Some(precise_day(1968, 5, 5)))
.pay_period_length(14)
.now(now);
let d1 = first_moment_of_day(1969, 4, 20);
let d2 = first_moment_of_day(1969, 5, 4);
for pp in ["pp", "pay period", "payperiod"].iter() {
let (start, end, _) = parse(&format!("last {}", pp), Some(config.clone())).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
}
#[test]
fn this_pay_period_weird() {
let now = first_moment_of_day(1969, 5, 6);
// two-week pay period beginning about a year *after* "now" on a Sunday
let config = Config::new()
.pay_period_start(Some(precise_day(1970, 4, 5)))
.pay_period_length(14)
.now(now);
let d1 = first_moment_of_day(1969, 5, 4);
let d2 = first_moment_of_day(1969, 5, 18);
for pp in ["pp", "pay period", "payperiod"].iter() {
let (start, end, _) = parse(&format!("this {}", pp), Some(config.clone())).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
}
#[test]
fn next_pay_period_weird() {
let now = first_moment_of_day(1969, 5, 6);
// two-week pay period beginning about a year *after* "now" on a Sunday
let config = Config::new()
.pay_period_start(Some(precise_day(1970, 4, 5)))
.pay_period_length(14)
.now(now);
let d1 = first_moment_of_day(1969, 5, 18);
let d2 = first_moment_of_day(1969, 6, 1);
for pp in ["pp", "pay period", "payperiod"].iter() {
let (start, end, _) = parse(&format!("next {}", pp), Some(config.clone())).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
}
#[test]
fn last_pay_period_weird() {
let now = first_moment_of_day(1969, 5, 6);
// two-week pay period beginning about a year *after* "now" on a Sunday
let config = Config::new()
.pay_period_start(Some(precise_day(1970, 4, 5)))
.pay_period_length(14)
.now(now);
let d1 = first_moment_of_day(1969, 4, 20);
let d2 = first_moment_of_day(1969, 5, 4);
for pp in ["pp", "pay period", "payperiod"].iter() {
let (start, end, _) = parse(&format!("last {}", pp), Some(config.clone())).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
}
#[test]
fn this_april() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 4, 1);
let d2 = first_moment_of_day(1969, 5, 1);
let (start, end, _) = parse("this april", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_april() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1970, 4, 1);
let d2 = first_moment_of_day(1970, 5, 1);
let (start, end, _) = parse("next april", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_april() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1968, 4, 1);
let d2 = first_moment_of_day(1968, 5, 1);
let (start, end, _) = parse("last april", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_friday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 9);
let d2 = first_moment_of_day(1969, 5, 10);
let (start, end, _) = parse("this friday", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_friday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 16);
let d2 = first_moment_of_day(1969, 5, 17);
let (start, end, _) = parse("next friday", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_friday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 2);
let d2 = first_moment_of_day(1969, 5, 3);
let (start, end, _) = parse("last friday", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_monday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 5);
let d2 = first_moment_of_day(1969, 5, 6);
let (start, end, _) = parse("this monday", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_monday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 12);
let d2 = first_moment_of_day(1969, 5, 13);
let (start, end, _) = parse("next monday", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_monday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 4, 28);
let d2 = first_moment_of_day(1969, 4, 29);
let (start, end, _) = parse("last monday", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn dawn_of_time() {
let then = NaiveDate::MIN.and_hms_milli_opt(0, 0, 0, 0).unwrap();
for phrase in [
"the beginning",
"the beginning of time",
"the first moment",
"the start",
"the very start",
"the first instant",
"the dawn of time",
"the big bang",
"the birth of the universe",
]
.iter()
{
let (start, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::minutes(1), end);
}
}
#[test]
fn the_crack_of_doom() {
let then = NaiveDate::MAX.and_hms_milli_opt(23, 59, 59, 999).unwrap();
for phrase in [
"the end",
"the end of time",
"the very end",
"the last moment",
"eternity",
"infinity",
"doomsday",
"the crack of doom",
"armageddon",
"ragnarok",
"the big crunch",
"the heat death of the universe",
"doom",
"death",
"perdition",
"the last hurrah",
"ever after",
"the last syllable of recorded time",
]
.iter()
{
let (_, end, _) = parse(phrase, None).unwrap();
assert_eq!(then, end);
}
}
#[test]
fn friday() {
let now = first_moment_of_day(1969, 5, 6);
let then = first_moment_of_day(1969, 5, 2);
let (start, end, _) = parse("Friday", Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::days(1), end);
}
#[test]
fn tuesday() {
let now = first_moment_of_day(1969, 5, 6);
let then = first_moment_of_day(1969, 4, 29);
let (start, end, _) = parse("Tuesday", Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::days(1), end);
}
#[test]
fn monday() {
let now = first_moment_of_day(1969, 5, 6);
let then = first_moment_of_day(1969, 5, 5);
let (start, end, _) = parse("Monday", Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::days(1), end);
}
#[test]
fn monday_default_to_future() {
let now = first_moment_of_day(1969, 5, 6);
let then = first_moment_of_day(1969, 5, 12);
let (start, end, _) = parse(
"Monday",
Some(Config::new().now(now).default_to_past(false)),
)
.unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::days(1), end);
}
#[test]
fn friday_at_3_pm() {
let now = first_moment_of_day(1969, 5, 6);
let then = precise_moment(1969, 5, 2, 15, 0, 0);
let (start, end, _) = parse("Friday at 3 pm", Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
#[test]
fn tuesday_at_3_pm() {
let now = first_moment_of_day(1969, 5, 6);
let then = precise_moment(1969, 4, 29, 15, 0, 0);
let (start, end, _) = parse("Tuesday at 3 pm", Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
#[test]
fn monday_at_3_pm() {
let now = first_moment_of_day(1969, 5, 6);
let then = precise_moment(1969, 5, 5, 15, 0, 0);
let (start, end, _) = parse("Monday at 3 pm", Some(Config::new().now(now))).unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
#[test]
fn monday_at_3_pm_default_to_future() {
let now = first_moment_of_day(1969, 5, 6);
let then = precise_moment(1969, 5, 12, 15, 0, 0);
let (start, end, _) = parse(
"Monday at 3 pm",
Some(Config::new().now(now).default_to_past(false)),
)
.unwrap();
assert_eq!(then, start);
assert_eq!(then + Duration::seconds(1), end);
}
#[test]
fn just_may() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 1);
let d2 = first_moment_of_day(1969, 6, 1);
let (start, end, _) = parse("May", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn just_april() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 4, 1);
let d2 = first_moment_of_day(1969, 5, 1);
let (start, end, _) = parse("April", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn just_june() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1968, 6, 1);
let d2 = first_moment_of_day(1968, 7, 1);
let (start, end, _) = parse("June", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn just_june_default_to_future() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 6, 1);
let d2 = first_moment_of_day(1969, 7, 1);
let (start, end, _) =
parse("June", Some(Config::new().now(now).default_to_past(false))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn monday_through_friday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 5);
let d2 = first_moment_of_day(1969, 5, 10);
let (start, end, _) = parse("Monday through Friday", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn monday_through_friday_default_to_future() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 12);
let d2 = first_moment_of_day(1969, 5, 17);
let (start, end, _) = parse(
"Monday through Friday",
Some(Config::new().now(now).default_to_past(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn tuesday_through_friday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 4, 29);
let d2 = first_moment_of_day(1969, 5, 3);
let (start, end, _) = parse("Tuesday through Friday", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn tuesday_through_3_pm_on_friday() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 4, 29);
let d2 = precise_moment(1969, 5, 2, 15, 0, 1);
let (start, end, _) = parse(
"Tuesday through 3 PM on Friday",
Some(Config::new().now(now)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_year_through_today() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 1, 1);
let d2 = first_moment_of_day(1969, 5, 7);
let (start, end, _) = parse("this year through today", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn noon_yesterday_through_midnight_today() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = precise_moment(1969, 5, 5, 12, 0, 0);
let d2 = precise_moment(1969, 5, 7, 0, 0, 1);
let (start, end, _) = parse(
"noon yesterday through midnight today",
Some(Config::new().now(now)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn very_specific_through_very_specific() {
let d1 = precise_moment(2014, 10, 6, 8, 57, 29);
let d2 = precise_moment(2020, 3, 6, 17, 28, 34);
let (start, end, _) = parse("2014-10-06 08:57:29 - 2020-03-06 17:28:33", None).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn very_specific_up_to_very_specific() {
let d1 = precise_moment(2014, 10, 6, 8, 57, 29);
let d2 = precise_moment(2020, 3, 6, 17, 28, 33);
let (start, end, _) = parse("2014-10-06 08:57:29 up to 2020-03-06 17:28:33", None).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn somewhat_specific_through_somewhat_specific() {
let d1 = precise_moment(2014, 10, 6, 8, 57, 00);
let d2 = precise_moment(2020, 3, 6, 17, 28, 01);
let (start, end, _) = parse("2014-10-06 08:57 - 2020-03-06 17:28", None).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn somewhat_specific_up_to_somewhat_specific() {
let d1 = precise_moment(2014, 10, 6, 8, 57, 00);
let d2 = precise_moment(2020, 3, 6, 17, 28, 00);
let (start, end, _) = parse("2014-10-06 08:57 up to 2020-03-06 17:28", None).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn april_3_25_bc() {
let d1 = precise_moment(-24, 4, 3, 0, 0, 0);
let d2 = d1 + Duration::days(1);
let (start, end, _) = parse("April 3, 25 BC", None).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn april_3_25_ad() {
let d1 = first_moment_of_day(25, 4, 3);
let d2 = d1 + Duration::days(1);
let (start, end, _) = parse("April 3, 25 AD", None).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn april_3_25bc() {
let d1 = precise_moment(-24, 4, 3, 0, 0, 0);
let d2 = d1 + Duration::days(1);
let (start, end, _) = parse("April 3, 25BC", None).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn april_3_25ad() {
let d1 = first_moment_of_day(25, 4, 3);
let d2 = d1 + Duration::days(1);
let (start, end, _) = parse("April 3, 25AD", None).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_weekend() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 10);
let d2 = first_moment_of_day(1969, 5, 12);
let (start, end, _) = parse("this weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_weekend() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 3);
let d2 = first_moment_of_day(1969, 5, 5);
let (start, end, _) = parse("last weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_weekend() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = first_moment_of_day(1969, 5, 17);
let d2 = first_moment_of_day(1969, 5, 19);
let (start, end, _) = parse("next weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_weekend_on_saturday() {
let now = first_moment_of_day(1969, 5, 10);
let d1 = first_moment_of_day(1969, 5, 10);
let d2 = first_moment_of_day(1969, 5, 12);
let (start, end, _) = parse("this weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_weekend_on_saturday() {
let now = first_moment_of_day(1969, 5, 10);
let d1 = first_moment_of_day(1969, 5, 3);
let d2 = first_moment_of_day(1969, 5, 5);
let (start, end, _) = parse("last weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_weekend_on_saturday() {
let now = first_moment_of_day(1969, 5, 10);
let d1 = first_moment_of_day(1969, 5, 17);
let d2 = first_moment_of_day(1969, 5, 19);
let (start, end, _) = parse("next weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_weekend_on_sunday() {
let now = first_moment_of_day(1969, 5, 11);
let d1 = first_moment_of_day(1969, 5, 10);
let d2 = first_moment_of_day(1969, 5, 12);
let (start, end, _) = parse("this weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_weekend_on_sunday() {
let now = first_moment_of_day(1969, 5, 11);
let d1 = first_moment_of_day(1969, 5, 3);
let d2 = first_moment_of_day(1969, 5, 5);
let (start, end, _) = parse("last weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_weekend_on_sunday() {
let now = first_moment_of_day(1969, 5, 11);
let d1 = first_moment_of_day(1969, 5, 17);
let d2 = first_moment_of_day(1969, 5, 19);
let (start, end, _) = parse("next weekend", Some(Config::new().now(now))).unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_weekend_on_sunday_when_sunday_starts_week() {
let now = first_moment_of_day(1969, 5, 11);
let d1 = first_moment_of_day(1969, 5, 10);
let d2 = first_moment_of_day(1969, 5, 12);
let (start, end, _) = parse(
"this weekend",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_weekend_on_sunday_when_sunday_starts_week() {
let now = first_moment_of_day(1969, 5, 11);
let d1 = first_moment_of_day(1969, 5, 3);
let d2 = first_moment_of_day(1969, 5, 5);
let (start, end, _) = parse(
"last weekend",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_weekend_on_sunday_when_sunday_starts_week() {
let now = first_moment_of_day(1969, 5, 11);
let d1 = first_moment_of_day(1969, 5, 17);
let d2 = first_moment_of_day(1969, 5, 19);
let (start, end, _) = parse(
"next weekend",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn this_weekend_on_saturday_when_sunday_starts_week() {
let now = first_moment_of_day(1969, 5, 10);
let d1 = first_moment_of_day(1969, 5, 10);
let d2 = first_moment_of_day(1969, 5, 12);
let (start, end, _) = parse(
"this weekend",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn last_weekend_on_saturday_when_sunday_starts_week() {
let now = first_moment_of_day(1969, 5, 10);
let d1 = first_moment_of_day(1969, 5, 3);
let d2 = first_moment_of_day(1969, 5, 5);
let (start, end, _) = parse(
"last weekend",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn next_weekend_on_saturday_when_sunday_starts_week() {
let now = first_moment_of_day(1969, 5, 10);
let d1 = first_moment_of_day(1969, 5, 17);
let d2 = first_moment_of_day(1969, 5, 19);
let (start, end, _) = parse(
"next weekend",
Some(Config::new().now(now).monday_starts_week(false)),
)
.unwrap();
assert_eq!(d1, start);
assert_eq!(d2, end);
}
#[test]
fn regression_12pm() {
let d1 = first_moment_of_day(2018, 5, 21);
let d2 = d1 + Duration::seconds(1);
if let Ok((start, end, _)) = parse("12 pm on May 21, 2018", None) {
assert_eq!(d1, start);
assert_eq!(d2, end);
} else {
assert!(false);
}
}
#[test]
fn year_2000() {
let d1 = first_moment_of_day(2000, 1, 1);
let d2 = first_moment_of_day(2001, 1, 1);
if let Ok((start, end, _)) = parse("2000", None) {
assert_eq!(d1, start);
assert_eq!(d2, end);
} else {
assert!(false);
}
}
#[test]
fn ordinals() {
let patterns = [
(1, "1st", "first", "Monday"),
(2, "2nd", "second", "Tuesday"),
(3, "3rd", "third", "Wednesday"),
(4, "4th", "fourth", "Thursday"),
(5, "5th", "fifth", "Friday"),
(6, "6th", "sixth", "Saturday"),
(7, "7th", "seventh", "Sunday"),
(8, "8th", "eighth", "Monday"),
(9, "9th", "ninth", "Tuesday"),
(10, "10th", "tenth", "Wednesday"),
(11, "11th", "eleventh", "Thursday"),
(12, "12th", "twelfth", "Friday"),
(13, "13th", "thirteenth", "Saturday"),
(14, "14th", "fourteenth", "Sunday"),
(15, "15th", "fifteenth", "Monday"),
(16, "16th", "sixteenth", "Tuesday"),
(17, "17th", "seventeenth", "Wednesday"),
(18, "18th", "eighteenth", "Thursday"),
(19, "19th", "nineteenth", "Friday"),
(20, "20th", "twentieth", "Saturday"),
(21, "21st", "twenty-first", "Sunday"),
(22, "22nd", "twenty-second", "Monday"),
(23, "23rd", "twenty-third", "Tuesday"),
(24, "24th", "twenty-fourth", "Wednesday"),
(25, "25th", "twenty-fifth", "Thursday"),
(26, "26th", "twenty-sixth", "Friday"),
(27, "27th", "twenty-seventh", "Saturday"),
(28, "28th", "twenty-eighth", "Sunday"),
(29, "29th", "twenty-ninth", "Monday"),
(30, "30th", "thirtieth", "Tuesday"),
(31, "31st", "thirty-first", "Wednesday"),
];
let base_date = first_moment_of_day(2018, 1, 1);
for (cardinal, abbv, ordinal, weekday) in patterns.iter() {
let d1 = base_date + Duration::days(*cardinal as i64 - 1);
let d2 = d1 + Duration::days(1);
let subpatterns = [
format!("January {}, 2018", abbv),
format!("{}, January {}, 2018", weekday, abbv),
format!("January {}, 2018", ordinal),
format!("{}, January {}, 2018", weekday, ordinal),
format!("the {} of January 2018", abbv),
format!("{}, the {} of January 2018", weekday, abbv),
format!("the {} of January 2018", ordinal),
format!("{}, the {} of January 2018", weekday, ordinal),
];
for p in subpatterns.iter() {
match parse(p, None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
}
#[test]
fn kalends_nones_ids() {
let months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
for (i, m) in months.iter().enumerate() {
let i = (i + 1) as u32;
let big_month = match i {
3 | 5 | 7 | 10 => true,
_ => false,
};
// kalends
let d1 = precise_moment(2018, i, 1, 0, 0, 0);
let d2 = d1 + Duration::days(1);
let p = format!("the kalends of {} 2018", m);
match parse(&p, None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
// nones
let d1 = precise_moment(2018, i, if big_month { 7 } else { 5 }, 0, 0, 0);
let d2 = d1 + Duration::days(1);
let p = format!("the nones of {} 2018", m);
match parse(&p, None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
// ides
let d1 = precise_moment(2018, i, if big_month { 15 } else { 13 }, 0, 0, 0);
let d2 = d1 + Duration::days(1);
let p = format!("the ides of {} 2018", m);
match parse(&p, None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn day_and_month() {
let now = first_moment_of_day(1969, 5, 10);
let d1 = first_moment_of_day(1969, 5, 15);
let d2 = d1 + Duration::days(1);
let patterns = [
"the ides of May",
"5-15",
"the fifteenth",
"May fifteenth",
"May the 15th",
"May the fifteenth",
];
for p in patterns.iter() {
match parse(p, Some(Config::new().now(now))) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn day_and_month_default_to_future() {
let now = first_moment_of_day(1969, 6, 16);
let d1 = first_moment_of_day(1970, 5, 15);
let d2 = d1 + Duration::days(1);
let patterns = [
"the ides of May",
"5-15",
"May fifteenth",
"May the 15th",
"May the fifteenth",
];
for p in patterns.iter() {
match parse(p, Some(Config::new().now(now).default_to_past(false))) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn one_week_before_may_6_1969() {
let d1 = first_moment_of_day(1969, 5, 6) - Duration::days(7);
let patterns = ["one week before May 6, 1969", "1 week before May 6, 1969"];
for p in patterns.iter() {
match parse(p, None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d1, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn one_week_after_may_6_1969() {
let d1 = first_moment_of_day(1969, 5, 7) + Duration::days(7);
let patterns = ["one week after May 6, 1969", "1 week after May 6, 1969"];
for p in patterns.iter() {
match parse(p, None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d1, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn one_week_before_and_after_may_6_1969() {
let d = first_moment_of_day(1969, 5, 6);
let d1 = d - Duration::days(7);
let d2 = d + Duration::days(7);
let patterns = [
"one week before and after May 6, 1969",
"1 week before and after May 6, 1969",
];
for p in patterns.iter() {
match parse(p, None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn one_week_around_may_6_1969() {
let d1 = first_moment_of_day(1969, 5, 6) - Duration::milliseconds(7 * 24 * 60 * 60 * 1000 / 2);
let d2 = d1 + Duration::days(7);
let patterns = ["one week around May 6, 1969", "1 week around May 6, 1969"];
for p in patterns.iter() {
match parse(p, None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn number_before_test() {
let d = precise_moment(1969, 5, 6, 13, 0, 0);
let nums = [
"two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
];
for (i, p) in nums.iter().enumerate() {
let d = d - Duration::seconds((i + 2) as i64);
let p = format!("{} seconds before May 6, 1969 at 1:00 PM", p);
match parse(&p, None) {
Ok((start, end, _)) => {
assert_eq!(d, start);
assert_eq!(d, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn noon() {
let d1 = precise_moment(1969, 5, 6, 12, 0, 0);
let d2 = d1 + Duration::seconds(1);
match parse("noon on May 6, 1969", None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
let now = first_moment_of_day(1969, 5, 6);
match parse("noon on May 6, 1969", Some(Config::new().now(now))) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
#[test]
fn simple_noon_past_and_future() {
let now = first_moment_of_day(1969, 5, 6);
let d1 = precise_moment(1969, 5, 5, 12, 0, 0);
let d2 = d1 + Duration::seconds(1);
match parse("noon", Some(Config::new().now(now))) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
let d1 = d1 + Duration::days(1);
let d2 = d2 + Duration::days(1);
match parse("noon", Some(Config::new().now(now).default_to_past(false))) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
#[test]
fn midnight() {
let d1 = first_moment_of_day(1969, 5, 7);
let d2 = d1 + Duration::seconds(1);
match parse("midnight on May 6, 1969", None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
#[derive(Debug)]
enum Period {
Week,
Day,
Hour,
Minute,
Second,
}
#[test]
fn displacement() {
let displacements = [
("week", Period::Week),
("day", Period::Day),
("hour", Period::Hour),
("minute", Period::Minute),
("second", Period::Second),
];
let now = first_moment_of_day(1969, 5, 10);
for (phrase, period) in displacements.iter() {
for n in [1, 2, 3].iter() {
let phrase = if *n == 1 {
String::from(*phrase)
} else {
String::from(*phrase) + "s"
};
let (displacement1, displacement2) = match period {
Period::Week => (Duration::weeks(*n), Duration::weeks(1)),
Period::Day => (Duration::days(*n), Duration::days(1)),
Period::Hour => (Duration::hours(*n), Duration::hours(1)),
Period::Minute => (Duration::minutes(*n), Duration::minutes(1)),
_ => (Duration::seconds(*n), Duration::seconds(1)),
};
let d1 = now - displacement1;
let d2 = d1 + displacement2;
let expression = format!("{} {} ago", n, phrase);
match parse(&expression, Some(Config::new().now(now))) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
let d1 = now + displacement1;
let d2 = d1 + displacement2;
let expression = format!("{} {} from now", n, phrase);
match parse(&expression, Some(Config::new().now(now))) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
}
#[test]
fn friday_the_13th() {
let now = first_moment_of_day(1969, 5, 10);
let d1 = first_moment_of_day(1968, 12, 13);
match parse("Friday the 13th", Some(Config::new().now(now))) {
Ok((start, _, _)) => {
assert_eq!(d1, start);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
#[test]
fn the_31st() {
let now = first_moment_of_day(1969, 4, 10);
let d1 = first_moment_of_day(1969, 3, 31);
match parse("the 31st", Some(Config::new().now(now))) {
Ok((start, _, _)) => {
assert_eq!(d1, start);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
#[test]
fn specific_time() {
let d1 = precise_moment(1969, 5, 6, 12, 3, 5);
let d2 = d1 + Duration::seconds(1);
match parse("1969-05-06 12:03:05", None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
#[test]
fn no_space_before_pm() {
let d1 = precise_moment(1969, 5, 6, 13, 0, 0);
let d2 = d1 + Duration::seconds(1);
match parse("1969-05-06 at 1PM", None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
match parse("1969-05-06 at 1:00PM", None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
match parse("1969-05-06 at 1:00:00PM", None) {
Ok((start, end, _)) => {
assert_eq!(d1, start);
assert_eq!(d2, end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
#[test]
fn relative_time_regression() {
parse("24", None).unwrap();
assert!(true, "'24' didn't cause a panic");
}
#[test]
fn since_yesterday() {
let then = first_moment_of_day(1969, 5, 10);
let now = then + Duration::hours(5);
match parse("since yesterday", Some(Config::new().now(now))) {
Ok((start, end, two_times)) => {
assert!(!two_times, "isn't a two-time expression");
assert!(then == start);
assert!(now == end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
#[test]
fn since_noon() {
let then = precise_moment(1969, 5, 10, 12, 0, 0);
let now = then + Duration::hours(5);
for expr in &[
"since noon",
"since noon today",
"since 12",
"since 12am",
"since 12am today",
"since 12:00",
"since 12:00:00",
] {
match parse(expr, Some(Config::new().now(now))) {
Ok((start, end, two_times)) => {
assert!(!two_times, "isn't a two-time expression");
assert!(then == start);
assert!(now == end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn since_may() {
let then = first_moment_of_day(1969, 5, 1);
let now = then + Duration::hours(5);
for expr in &[
"since may",
"since the start of may",
"since the beginning of may",
"after may",
"after the start of may",
"after the beginning of may",
] {
match parse(expr, Some(Config::new().now(now))) {
Ok((start, end, two_times)) => {
assert!(!two_times, "isn't a two-time expression");
assert!(then == start);
assert!(now == end);
}
Err(e) => {
println!("{:?}", e);
assert!(false, "didn't match");
}
}
}
}
#[test]
fn since_the_end_of_may_misordered() {
let then = first_moment_of_day(1969, 5, 1);
let now = then + Duration::hours(5);
for expr in &["since the end of may", "after the end of may"] {
match parse(expr, Some(Config::new().now(now))) {
Ok((..)) => assert!(false, "this should not succeed"),
Err(e) => match e {
TimeError::Misordered(_) => assert!(true, "correct error"),
_ => assert!(false, "unexpected error: {:?}", e),
},
}
}
}
fn first_moment_of_day(year: i32, month: u32, day: u32) -> NaiveDateTime {
NaiveDate::from_ymd_opt(year, month, day)
.unwrap()
.and_hms_opt(0, 0, 0)
.unwrap()
}
fn precise_moment(
year: i32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
) -> NaiveDateTime {
NaiveDate::from_ymd_opt(year, month, day)
.unwrap()
.and_hms_opt(hour, minute, second)
.unwrap()
}
fn precise_day(year: i32, month: u32, day: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(year, month, day).unwrap()
}
|
use std::mem;
use std::cmp;
use std::str;
use std::ptr;
use spin::Mutex;
use constants;
use super::MemoryError;
static MEMORY: Mutex<Manager> = Mutex::new(Manager::new());
#[derive(Debug, Clone, Copy)]
struct Block {
base: *mut u8,
end: *mut u8,
next: *mut Block,
last: *mut Block,
}
struct Manager {
hint: usize,
free: *mut Block
}
// Manager is an internally-managed singleton
unsafe impl Sync for Manager {}
unsafe impl Send for Manager {}
impl Manager {
#[inline]
const fn new() -> Manager {
Manager {
hint: 0,
free: ptr::null_mut()
}
}
#[inline]
fn hint(&self) -> usize {
self.hint
}
unsafe fn find_around(&self, around: *mut u8) -> (*mut Block, *mut Block) {
// walk until we find the last free block before and the first free block after
let mut pointer = self.free;
if pointer as usize > around as usize {
// the free list is entirely past around
return (ptr::null_mut(), pointer);
}
while !pointer.is_null() {
if pointer as usize <= around as usize {
let next = pointer.as_ref().unwrap().next;
if next as usize > around as usize || next.is_null() {
return (pointer, pointer.as_mut().unwrap().next);
}
}
pointer = pointer.as_ref().unwrap().next;
}
(ptr::null_mut(), ptr::null_mut())
}
unsafe fn insert_between(&mut self, before: *mut Block, after: *mut Block, new: *mut Block) {
if self.free.is_null() {
self.free = new;
let free = self.free.as_mut().unwrap();
free.last = ptr::null_mut();
free.next = ptr::null_mut();
return;
}
debug_assert!(!new.is_null());
if let Some(before) = before.as_mut() {
before.next = new;
} else {
self.free = new;
}
let new = new.as_mut().unwrap();
new.last = before;
new.next = after;
if let Some(after) = after.as_mut() {
after.last = new;
}
}
unsafe fn register(&mut self, ptr: *mut u8, size: usize) -> Result<usize, MemoryError> {
// find the blocks around the given area
let (before, after) = self.find_around(ptr);
// TODO check_invariants
let new_block = (ptr as *mut Block).as_mut().unwrap();
new_block.base = ptr;
new_block.end = ptr.offset(size as isize);
self.insert_between(before, after, new_block);
// TODO coalesce
self.hint += size;
Ok(size)
}
unsafe fn forget(&mut self, ptr: *mut u8, size: usize) -> Result<usize, MemoryError> {
let (before, _) = self.find_around(ptr);
let (last, after) = self.find_around(ptr.offset(size as isize));
if last.is_null() {
// do nothing
return Err(MemoryError::NoPlace);
}
if (last.as_ref().unwrap().end as usize) < ptr as usize + size {
// no block overlaps our region
let before = before.as_mut().unwrap();
let after = after.as_mut().unwrap();
before.end = ptr;
before.next = after;
after.last = before;
} else {
// save values before they might get clobbered
let before = before.as_mut().unwrap();
let maybe_last = before.last;
let end = last.as_ref().unwrap().end;
// truncate before and last and hook them up
let new_block = (ptr.offset(size as isize) as *mut Block).as_mut().unwrap();
new_block.base = ptr.offset(size as isize);
new_block.end = end;
if before as *mut Block as usize != ptr as usize {
before.end = ptr;
self.insert_between(before, after, new_block);
} else {
self.insert_between(maybe_last, after, new_block);
}
}
// TODO maybe improve this
self.hint -= size;
Ok(size)
}
unsafe fn allocate(&mut self, size: usize, align: usize) -> Result<*mut u8, MemoryError> {
let size = granularity(size, align);
let mut pointer = self.free;
while !pointer.is_null() {
let aligned_base = constants::align(pointer as usize, align);
let block_end = pointer.as_ref().unwrap().end as usize;
if block_end > aligned_base && block_end - aligned_base >= size {
self.hint -= size;
return self.forget(constants::align(pointer as usize, align) as *mut u8, size)
.map(|_| constants::align(pointer as usize, align) as *mut u8)
}
pointer = pointer.as_ref().unwrap().next;
}
Err(MemoryError::OutOfMemory)
}
unsafe fn release(&mut self, ptr: *mut u8, size: usize, align: usize) -> Result<usize, MemoryError> {
let size = granularity(size, align);
let registered_size = try!(self.register(ptr, size));
trace!("{}", registered_size);
if registered_size == size {
self.hint += size;
Ok(size)
} else {
Err(MemoryError::Overlap)
}
}
unsafe fn grow(&mut self, ptr: *mut u8, old_size: usize, size: usize, align: usize) -> Result<(), MemoryError> {
let size = granularity(size, align);
let old_size = granularity(old_size, align);
let (before, _) = self.find_around(ptr.offset(old_size as isize));
if before as usize != ptr as usize {
return Err(MemoryError::OutOfSpace)
}
let before = before.as_mut().unwrap();
if before.end < ptr.offset(size as isize) {
return Err(MemoryError::OutOfSpace)
}
self.forget(ptr.offset(old_size as isize), size - old_size).map(|_| ())
}
unsafe fn shrink(&mut self, ptr: *mut u8, old_size: usize, mut size: usize, align: usize) -> Result<(), MemoryError> {
// adjust size
size = granularity(size, align);
if size >= granularity(old_size, align) {
return Ok(());
}
let difference = size - old_size;
let registered_size = try!(self.register((ptr as *mut u8).offset(size as isize) as *mut u8, difference));
trace!("f: {}, {}", difference, registered_size);
if registered_size != difference {
return Err(MemoryError::Overlap);
} else {
return Ok(());
}
}
unsafe fn resize(&mut self, ptr: *mut u8, old_size: usize, size: usize, align: usize) -> Result<*mut u8, MemoryError> {
trace!("Resizing at {:?} to 0x{:x} with align 0x{:x}", ptr, size, align);
if (ptr as usize) & (align - 1) == 0 {
// pointer is already aligned
trace!("Trying inplace");
if granularity(size, align) > granularity(old_size, align) {
trace!("Growing");
if self.grow(ptr, old_size, size, align).is_ok() {
return Ok(ptr);
}
} else if granularity(size, align) < granularity(old_size, align) {
trace!("Shrinking");
if self.shrink(ptr, old_size, size, align).is_ok() {
return Ok(ptr);
}
} else {
// pointer is aligned and the right size, do nothing
trace!("Doing nothing");
return Ok(ptr);
}
}
// keep data that might be clobbered by release
let diff_size: usize = cmp::min(mem::size_of::<Block>(), size);
let mut store: Block = mem::zeroed();
trace!("Copying: 0x{:x}", diff_size);
ptr::copy(ptr as *mut u8, (&mut store as *mut _ as *mut u8), diff_size);
trace!("0x{:x}", diff_size);
if let Err(e) = self.release(ptr, old_size, align) {
error!("Failed to free pointer on resize: {}", e);
return Err(e);
}
if let Ok(new_ptr) = self.allocate(size, align) {
trace!("{:?}, {:?}, 0x{:x}", ptr, new_ptr, old_size);
// copy the data from the old pointer
ptr::copy(ptr as *mut u8, new_ptr as *mut u8, old_size);
trace!("{:?}, 0x{:x}", (&mut store as *mut _ as *mut u8), diff_size);
// some bytes at the beginning might have been clobbered
// copy data that might have been clobbered
ptr::copy((&mut store as *mut _ as *mut u8), new_ptr as *mut u8, diff_size);
// succeeded!
Ok(new_ptr)
} else {
// roll back
if old_size > size {
// this should really rarely happen
assert!(self.register(ptr.offset(size as isize), old_size - size).is_ok());
} else {
assert!(self.forget(ptr.offset(old_size as isize), size - old_size).is_ok());
}
// failed
Err(MemoryError::OutOfMemory)
}
}
}
#[inline]
pub fn hint() -> usize {
MEMORY.lock().hint()
}
#[inline]
pub unsafe fn register(ptr: *mut u8, size: usize) -> Result<usize, MemoryError> {
MEMORY.lock().register(ptr, size)
}
#[inline]
pub unsafe fn forget(ptr: *mut u8, size: usize) -> Result<usize, MemoryError> {
MEMORY.lock().forget(ptr, size)
}
#[inline]
pub unsafe fn allocate(size: usize, align: usize) -> Result<*mut u8, MemoryError> {
MEMORY.lock().allocate(size, align)
}
#[inline]
pub unsafe fn release(ptr: *mut u8, size: usize, align: usize) -> Result<usize, MemoryError> {
MEMORY.lock().release(ptr, size, align)
}
#[inline]
pub unsafe fn grow(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> Result<(), MemoryError> {
MEMORY.lock().grow(ptr, old_size, size, align)
}
#[inline]
pub unsafe fn shrink(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> Result<(), MemoryError> {
MEMORY.lock().shrink(ptr, old_size, size, align)
}
#[inline]
pub unsafe fn resize(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> Result<*mut u8, MemoryError> {
MEMORY.lock().resize(ptr, old_size, size, align)
}
#[inline]
pub fn granularity(size: usize, _: usize) -> usize {
if size < 32 {
32
} else {
size
}
}
|
fn main() {
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "pathfinder=info");
}
tracing_subscriber::fmt::init();
// simple tool for running and timing the database migrations on a given file.
let path = match std::env::args().nth(1) {
Some(name) if std::env::args().count() == 2 => name,
_ => {
println!(
"USAGE: {} db_file",
std::env::args().next().as_deref().unwrap_or("migrate_db")
);
std::process::exit(1);
}
};
let path = std::path::PathBuf::from(path);
let size_before = std::fs::metadata(&path).expect("Path does not exist").len() as i64;
let started_at = std::time::Instant::now();
let storage = pathfinder_lib::storage::Storage::migrate(
path.clone(),
pathfinder_lib::storage::JournalMode::WAL,
)
.unwrap();
let migrated_at = std::time::Instant::now();
let size_after_migration = std::fs::metadata(&path)
.expect("Migration removed the database?")
.len() as i64;
println!(
"migrated in {:?}, size change: {}",
migrated_at - started_at,
size_after_migration - size_before
);
// in general one does not want to do the full vacuum because it's going to take a long time
if false {
let conn = storage.connection().unwrap();
let vacuum_started = std::time::Instant::now();
let vacuum_ret = conn.execute("VACUUM", []).expect("vacuum failed");
drop(conn);
drop(storage);
let vacuumed_at = std::time::Instant::now();
let size_after_vacuum = std::fs::metadata(&path)
.expect("Vacuuming removed the database?")
.len() as i64;
println!(
"vacuumed in {:?}, size change: {}, VACUUM returned {}",
vacuumed_at - vacuum_started,
size_after_vacuum - size_after_migration,
vacuum_ret
);
}
}
|
use std::io::{Result, Write};
use std::borrow::Cow;
use pulldown_cmark::{Tag, Event};
use crate::gen::{State, States, Generator, Document};
#[derive(Debug)]
pub struct Link<'a> {
dst: Cow<'a, str>,
title: Cow<'a, str>,
text: Vec<u8>,
}
impl<'a> State<'a> for Link<'a> {
fn new(tag: Tag<'a>, gen: &mut Generator<'a, impl Document<'a>, impl Write>) -> Result<Self> {
let (dst, title) = match tag {
Tag::Link(dst, title) => (dst, title),
_ => unreachable!(),
};
Ok(Link {
dst,
title,
text: Vec::new(),
})
}
fn output_redirect(&mut self) -> Option<&mut dyn Write> {
Some(&mut self.text)
}
fn finish(self, gen: &mut Generator<'a, impl Document<'a>, impl Write>, peek: Option<&Event<'a>>) -> Result<()> {
let out = gen.get_out();
// TODO: handle all links properly
// Markdown Types of links: https://github.com/google/pulldown-cmark/issues/141
// * [@foo]: biber reference (transformed in main.rs:refsolve)
// * [#foo]: \cref (reference to section)
// * dst="#foo", title="#foo", text="#foo"
// * [#Foo]: \Cref (capital reference to section)
// * dst="#foo", title="#Foo", text="#Foo"
// * [img/fig/tbl/fnote:bar]: \cref (reference to images / figures / footnotes)
// * dst="img/fig/fnote:bar", title="img/fig/fnote:bar", text="img/fig/tbl/fnote:bar"
// * [Img/Fig/Tbl/Fnote:bar]: \cref (capital reference to images / figures / footnotes)
// * dst="img/fig/fnote:bar", title="Img/Fig/Fnote:bar", text="Img/Fig/Tbl/Fnote:bar"
// * [bar] (with bar defined): Handle link as above
// * dst="link", title="title", text="bar"
// * [text](link "title"): handle link as in previous examples, but use hyperref
// * dst="link", title="title", text="text"
// * [text][ref]: same as [text](link "title")
// * dst="link", title="title", text="text"
// TODO: use title
let text = String::from_utf8(self.text).expect("invalid UTF8");
let uppercase = self.dst.chars().nth(0).unwrap().is_ascii_uppercase();
let dst = self.dst.to_ascii_lowercase();
let dst_eq_text = dst == text.to_ascii_lowercase();
if dst.starts_with('#') || dst.starts_with("img:") || dst.starts_with("fig:") {
let dst = if dst.starts_with('#') { &dst[1..] } else { dst.as_str() };
let text = if text.starts_with('#') { &text[1..] } else { text.as_str() };
if text.is_empty() || dst_eq_text {
if uppercase {
write!(out, "\\Cref{{{}}}", dst)?;
} else {
write!(out, "\\cref{{{}}}", dst)?;
}
} else {
write!(out, "\\hyperref[{}]{{{}}}", dst, text)?;
}
} else {
if text.is_empty() || dst_eq_text {
write!(out, "\\url{{{}}}", dst)?;
} else {
write!(out, "\\href{{{}}}{{{}}}", dst, text)?;
}
}
Ok(())
}
}
|
use crate::size::*;
use crate::point::*;
#[derive(Copy, Clone, Debug)]
pub struct Rect {
pub position: Point,
pub size: Size
}
impl Rect {
pub fn new() -> Self {
Rect {
position: Point::new(),
size: Size::new()
}
}
// todo rename me
pub fn from_numbers(x:f64,y:f64,w:f64,h:f64) -> Self {
let mut r = Rect {
position: Point::new(),
size: Size::new()
};
r.position.x = x;
r.position.y = y;
r.size.width = w;
r.size.height = h;
r
}
}
|
pub use crate::state::gameplay::GameplayState;
mod gameplay;
|
use std::thread;
use std::thread::{JoinHandle};
use std::sync::mpsc::{Sender, Receiver};
use castnow::{Command, KeyCommand};
use state::State;
use shell::Launcher;
use std::error::Error;
pub struct Processor {
}
impl Processor {
pub fn new() -> Processor {
Processor {}
}
pub fn start(&self, rx: Receiver<Command>, tx: Sender<State>) -> JoinHandle<()> {
thread::spawn(move || {
let mut exit = false;
while !exit {
match rx.recv() {
Ok(cmd) => {
let new_state = Self::process(&cmd);
match tx.send(new_state) {
Ok(_) => println!("Command processed. New state {:?}", new_state),
Err(e) => println!("Error processing command {:?}", e)
}
},
Err(err) => {
//todo: If we're exiting, check that and don't try receive again so we don't end up with this error
println!("Error on recv {:?} {:?} {:?}", err, err.cause(), err.description());
exit = true;
}
}
}
})
}
fn process(cmd: &Command) -> State {
let result = match cmd.key {
KeyCommand::Load => Launcher::load(&cmd.state),
_ => Launcher::execute(&cmd.key)
};
State::next(&cmd.current, result.is_ok())
}
} |
//! This module contains functionality for parsing a regular expression into the intermediate
//! representation in repr.rs (from which it is compiled into a state graph), and optimizing that
//! intermediate representation.
#![allow(dead_code)]
use std::iter::FromIterator;
use std::ops::{Index, Range, RangeFull};
use std::str::FromStr;
use crate::repr::{AnchorLocation, Pattern, Repetition};
/// The entry point for this module: Parse a string into a `Pattern` that can be optimized and/or
/// compiled.
pub fn parse(s: &str) -> Result<Pattern, String> {
let src: Vec<char> = s.chars().collect();
parse_re(ParseState::new(&src)).map(|t| t.0)
}
/// ParseStack contains already parsed elements of a regular expression, and is used for parsing
/// textual regular expressions (as the parsing algorithm is stack-based). It can be converted to
/// an Pattern.
struct ParseStack {
s: Vec<Pattern>,
}
impl ParseStack {
fn new() -> ParseStack {
ParseStack {
s: Vec::with_capacity(4),
}
}
fn push(&mut self, p: Pattern) {
self.s.push(p)
}
fn pop(&mut self) -> Option<Pattern> {
self.s.pop()
}
fn empty(&self) -> bool {
self.s.is_empty()
}
fn to_pattern(mut self) -> Pattern {
if self.s.len() > 1 {
Pattern::Concat(self.s)
} else if self.s.len() == 1 {
self.s.pop().unwrap()
} else {
panic!("empty stack")
}
}
}
/// State of the parser, quite a simple struct. It contains the current substring that a parser
/// function is concerned with as well as the position within the overall parsed string, so that
/// useful positions can be reported to users. In addition, it provides functions to cheaply create
/// "sub-ParseStates" containing a substring of its current string.
///
/// It also supports indexing by ranges and index.
struct ParseState<'a> {
/// The string to parse. This may be a substring of the "overall" matched string.
src: &'a [char],
/// The position within the overall string (for error reporting).
pos: usize,
}
impl<'a> ParseState<'a> {
/// new returns a new ParseState operating on the specified input string.
fn new(s: &'a [char]) -> ParseState<'a> {
ParseState { src: s, pos: 0 }
}
/// from returns a new ParseState operating on the [from..] sub-string of the current
/// ParseState.
fn from(&self, from: usize) -> ParseState<'a> {
self.sub(from, self.len())
}
/// pos returns the overall position within the input regex.
fn pos(&self) -> usize {
self.pos
}
/// sub returns a sub-ParseState containing [from..to] of the current one.
fn sub(&self, from: usize, to: usize) -> ParseState<'a> {
ParseState {
src: &self.src[from..to],
pos: self.pos + from,
}
}
/// len returns how many characters this ParseState contains.
fn len(&self) -> usize {
self.src.len()
}
/// err returns a formatted error string containing the specified message and the overall
/// position within the original input string.
fn err<T>(&self, s: &str, i: usize) -> Result<T, String> {
Err(format!("{} at :{}", s, self.pos + i))
}
}
impl<'a> Index<Range<usize>> for ParseState<'a> {
type Output = [char];
fn index(&self, r: Range<usize>) -> &Self::Output {
&self.src[r]
}
}
impl<'a> Index<RangeFull> for ParseState<'a> {
type Output = [char];
fn index(&self, r: RangeFull) -> &Self::Output {
&self.src[r]
}
}
impl<'a> Index<usize> for ParseState<'a> {
type Output = char;
fn index(&self, i: usize) -> &Self::Output {
&self.src[i]
}
}
impl<'a> Clone for ParseState<'a> {
fn clone(&self) -> ParseState<'a> {
ParseState {
src: self.src,
pos: self.pos,
}
}
}
/// parse_re is the parser entry point; like all parser functions, it returns either a pair of
/// (parsed pattern, new ParseState) or an error string.
fn parse_re<'a>(mut s: ParseState<'a>) -> Result<(Pattern, ParseState<'a>), String> {
// The stack assists us in parsing the linear parts of a regular expression, e.g. non-pattern
// characters, or character sets.
let mut stack = ParseStack::new();
loop {
if s.len() == 0 {
break;
}
match s[0] {
'.' => {
stack.push(Pattern::Any);
s = s.from(1);
}
'$' => {
if s.len() == 1 {
stack.push(Pattern::Anchor(AnchorLocation::End));
} else {
stack.push(Pattern::Char('$'))
}
s = s.from(1);
}
'^' => {
if s.pos() == 0 {
stack.push(Pattern::Anchor(AnchorLocation::Begin));
} else {
stack.push(Pattern::Char('^'));
}
s = s.from(1);
}
r @ '+' | r @ '*' | r @ '?' => {
if let Some(p) = stack.pop() {
let rep = match r {
'+' => Repetition::OnceOrMore(p),
'*' => Repetition::ZeroOrMore(p),
'?' => Repetition::ZeroOrOnce(p),
_ => unimplemented!(),
};
stack.push(Pattern::Repeated(Box::new(rep)));
s = s.from(1);
} else {
return s.err("+ without pattern to repeat", 0);
}
}
// Alternation: Parse the expression on the right of the pipe sign and push an
// alternation between what we've already seen and the stuff on the right.
'|' => {
let (rest, newst) = parse_re(s.from(1))?;
let left = stack.to_pattern();
stack = ParseStack::new();
stack.push(Pattern::Alternate(vec![left, rest]));
s = newst;
}
'(' => {
match split_in_parens(s.clone(), ROUND_PARENS) {
Some((parens, newst)) => {
// Parse the sub-regex within parentheses.
let (pat, rest) = parse_re(parens)?;
assert!(rest.len() == 0);
stack.push(Pattern::Submatch(Box::new(pat)));
// Set the current state to contain the string after the parentheses.
s = newst;
}
None => return s.err("unmatched (", s.len()),
}
}
')' => return s.err("unopened ')'", 0),
'[' => match parse_char_set(s) {
Ok((pat, newst)) => {
stack.push(pat);
s = newst;
}
Err(e) => return Err(e),
},
']' => return s.err("unopened ']'", 0),
'{' => {
match split_in_parens(s.clone(), CURLY_BRACKETS) {
Some((rep, newst)) => {
if let Some(p) = stack.pop() {
let rep = parse_specific_repetition(rep, p)?;
stack.push(rep);
s = newst;
} else {
return s.err("repetition {} without pattern to repeat", 0);
}
}
None => return s.err("unmatched {", s.len()),
};
}
c => {
stack.push(Pattern::Char(c));
s = s.from(1);
}
}
}
Ok((stack.to_pattern(), s))
}
/// parse_char_set parses the character set at the start of the input state.
/// Valid states are [a], [ab], [a-z], [-a-z], [a-z-] and [a-fh-kl].
fn parse_char_set<'a>(s: ParseState<'a>) -> Result<(Pattern, ParseState<'a>), String> {
if let Some((cs, rest)) = split_in_parens(s.clone(), SQUARE_BRACKETS) {
let mut chars: Vec<char> = vec![];
let mut ranges: Vec<Pattern> = vec![];
let mut st = cs;
loop {
// Try to match a range "a-z" by looking for the dash; if no dash, add character to set
// and advance.
if st.len() >= 3 && st[1] == '-' {
ranges.push(Pattern::CharRange(st[0], st[2]));
st = st.from(3);
} else if st.len() > 0 {
chars.push(st[0]);
st = st.from(1);
} else {
break;
}
}
assert_eq!(st.len(), 0);
if chars.len() == 1 {
ranges.push(Pattern::Char(chars.pop().unwrap()));
} else if !chars.is_empty() {
ranges.push(Pattern::CharSet(chars));
}
if ranges.len() == 1 {
Ok((ranges.pop().unwrap(), rest))
} else {
let pat = Pattern::Alternate(ranges);
Ok((pat, rest))
}
} else {
s.err("unmatched [", s.len())
}
}
/// Parse a repetition spec inside curly braces: {1} | {1,} | {,1} | {1,2}
fn parse_specific_repetition<'a>(rep: ParseState<'a>, p: Pattern) -> Result<Pattern, String> {
let mut nparts = 0;
let mut parts: [Option<&[char]>; 2] = Default::default();
for p in rep[..].split(|c| *c == ',') {
parts[nparts] = Some(p);
nparts += 1;
if nparts == 2 {
break;
}
}
if nparts == 0 {
// {}
return rep.err("empty {} spec", 0);
} else if nparts == 1 {
// {1}
if let Ok(n) = u32::from_str(&String::from_iter(parts[0].unwrap().iter())) {
return Ok(Pattern::Repeated(Box::new(Repetition::Specific(
p, n, None,
))));
} else {
return Err(format!(
"invalid repetition '{}'",
String::from_iter(rep[..].iter())
));
}
} else if nparts == 2 {
fn errtostr(r: Result<u32, std::num::ParseIntError>) -> Result<u32, String> {
match r {
Ok(u) => Ok(u),
Err(e) => Err(format!("{}", e)),
}
}
let (p0, p1) = (parts[0].unwrap(), parts[1].unwrap());
// {2,3}
if !p0.is_empty() && !p1.is_empty() {
let min = errtostr(u32::from_str(&String::from_iter(p0.iter())))?;
let max = errtostr(u32::from_str(&String::from_iter(p1.iter())))?;
return Ok(Pattern::Repeated(Box::new(Repetition::Specific(
p,
min,
Some(max),
))));
} else if p0.is_empty() && !p1.is_empty() {
// {,3}
let min = 0;
let max = errtostr(u32::from_str(&String::from_iter(p1.iter())))?;
return Ok(Pattern::Repeated(Box::new(Repetition::Specific(
p,
min,
Some(max),
))));
} else if !p0.is_empty() && p1.is_empty() {
// {3,}
let min = errtostr(u32::from_str(&String::from_iter(p0.iter())))?;
let repetition =
Pattern::Repeated(Box::new(Repetition::Specific(p.clone(), min, None)));
return Ok(Pattern::Concat(vec![
repetition,
Pattern::Repeated(Box::new(Repetition::ZeroOrMore(p))),
]));
}
}
Err(format!("invalid repetition pattern {:?}", &rep[..]))
}
/// Constants for generalizing parsing of parentheses.
const ROUND_PARENS: (char, char) = ('(', ')');
/// Constants for generalizing parsing of parentheses.
const SQUARE_BRACKETS: (char, char) = ('[', ']');
/// Constants for generalizing parsing of parentheses.
const CURLY_BRACKETS: (char, char) = ('{', '}');
/// split_in_parens returns two new ParseStates; the first one containing the contents of the
/// parenthesized clause starting at s[0], the second one containing the rest.
fn split_in_parens<'a>(
s: ParseState<'a>,
parens: (char, char),
) -> Option<(ParseState<'a>, ParseState<'a>)> {
if let Some(end) = find_closing_paren(s.clone(), parens) {
Some((s.sub(1, end), s.from(end + 1)))
} else {
None
}
}
/// find_closing_paren returns the index of the parenthesis closing the opening parenthesis at the
/// beginning of the state's string.
fn find_closing_paren<'a>(s: ParseState<'a>, parens: (char, char)) -> Option<usize> {
if s[0] != parens.0 {
return None;
}
let mut count = 0;
for i in 0..s.len() {
if s[i] == parens.0 {
count += 1;
} else if s[i] == parens.1 {
count -= 1;
}
if count == 0 {
return Some(i);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compile::*;
use crate::repr::*;
use crate::state::dot;
#[test]
fn test_find_closing_paren() {
for case in &[
("(abc)de", Some(4)),
("()a", Some(1)),
("(abcd)", Some(5)),
("(abc", None),
] {
let src: Vec<char> = case.0.chars().collect();
assert_eq!(
find_closing_paren(ParseState::new(src.as_ref()), ROUND_PARENS),
case.1
);
}
}
#[test]
fn test_parse_charset() {
for case in &[
("[a]", Pattern::Char('a')),
("[ab]", Pattern::CharSet(vec!['a', 'b'])),
("[ba-]", Pattern::CharSet(vec!['b', 'a', '-'])),
("[a-z]", Pattern::CharRange('a', 'z')),
(
"[a-z-]",
Pattern::Alternate(vec![Pattern::CharRange('a', 'z'), Pattern::Char('-')]),
),
(
"[-a-z-]",
Pattern::Alternate(vec![
Pattern::CharRange('a', 'z'),
Pattern::CharSet(vec!['-', '-']),
]),
),
(
"[a-zA-Z]",
Pattern::Alternate(vec![
Pattern::CharRange('a', 'z'),
Pattern::CharRange('A', 'Z'),
]),
),
(
"[a-zA-Z-]",
Pattern::Alternate(vec![
Pattern::CharRange('a', 'z'),
Pattern::CharRange('A', 'Z'),
Pattern::Char('-'),
]),
),
] {
let src: Vec<char> = case.0.chars().collect();
let st = ParseState::new(&src);
assert_eq!(parse_char_set(st).unwrap().0, case.1);
}
}
#[test]
fn test_parse_subs() {
let case1 = (
"a(b)c",
Pattern::Concat(vec![
Pattern::Char('a'),
Pattern::Submatch(Box::new(Pattern::Char('b'))),
Pattern::Char('c'),
]),
);
let case2 = ("(b)", Pattern::Submatch(Box::new(Pattern::Char('b'))));
for c in &[case1, case2] {
assert_eq!(c.1, parse(c.0).unwrap());
}
}
#[test]
fn test_parse_res() {
let case1 = (
"a(Bcd)e",
Pattern::Concat(vec![
Pattern::Char('a'),
Pattern::Submatch(Box::new(Pattern::Concat(vec![
Pattern::Char('B'),
Pattern::Char('c'),
Pattern::Char('d'),
]))),
Pattern::Char('e'),
]),
);
for c in &[case1] {
assert_eq!(c.1, parse(c.0).unwrap());
}
}
#[test]
fn test_parse_res_errors() {
let case1 = ("ac)d", "unopened ')' at :2");
let case2 = ("(ac)d)", "unopened ')' at :5");
let case3 = ("[ac]d]", "unopened ']' at :5");
let case4 = ("(ac)d]", "unopened ']' at :5");
for c in &[case1, case2, case3, case4] {
assert_eq!(c.1, parse(c.0).unwrap_err());
}
}
#[test]
fn test_parse_repetition_manual() {
println!(
"digraph st {{ {} }}",
dot(&start_compile(&parse("[abc]{1,5}").unwrap()))
);
}
#[test]
fn test_parse_manual() {
let rep = parse("a|[bed]|(c|d|e)|f").unwrap();
println!("{:?}", rep.clone());
let dot = dot(&start_compile(&rep));
println!("digraph st {{ {} }}", dot);
}
#[test]
fn test_parse_manual2() {
println!("{:?}", parse("abcdef"));
}
}
|
fn main() {
// boolean
let x = true;
let y: bool = false;
println!("x: {},y: {}",x,y);
// char
let x = 'x';
let two_hearts = '💕';
println!("x: {},two_hearts: {}",x,two_hearts);
// 整数型
let x = 42;
let y = 1.0;
println!("x: {},y: {}",x,y);
// 配列
let a: [i32; 3] = [1,2,3];
let mut m = [1,2,3];
println!("a: {:?},m: {:?}",a,m);
let a = [0;20];
println!("a is {:?}\na has {} elements",a,a.len());
let names: [&str;3] = ["Graydon","Brian","Niko"];
println!("The second name is: {}",names[1]);
// slice
let a = [0,1,2,3,4];
let complete = &a[..];
let middle = &a[1..4];
println!("complete: {:?},middle :{:?}",complete,middle);
// tuple
let x:(i32,&str) = (1,"hello");
let (a,b,c) = (1,2,3);
println!("x: {:?}\na is {}",x,a);
let tuple = (1,2,3);
let d = tuple.0;
let e = tuple.1;
println!("d: {},e: {}",d,e);
fn foo(x: i32) -> i32 {x}
let x: fn(i32) -> i32 = foo;
println!("foo(2): {}",x(2));
}
|
pub struct IntoIter<T>(List<T>);
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
// access fields of a tuple struct numerically
self.0.pop()
}
}
pub struct List<T> {
head: Link<T>
}
|
//! Composite types.
pub use self::strukt::StructType;
pub use self::seq::*;
pub mod strukt;
pub mod seq;
use ir::Type;
/// A composite type.
pub struct CompositeType<'ctx>(Type<'ctx>);
impl_subtype!(CompositeType => Type);
|
/// AnnotatedTag represents an annotated tag
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct AnnotatedTag {
pub message: Option<String>,
pub object: Option<crate::annotated_tag_object::AnnotatedTagObject>,
pub sha: Option<String>,
pub tag: Option<String>,
pub tagger: Option<crate::commit_user::CommitUser>,
pub url: Option<String>,
pub verification: Option<crate::payload_commit_verification::PayloadCommitVerification>,
}
impl AnnotatedTag {
/// Create a builder for this object.
#[inline]
pub fn builder() -> AnnotatedTagBuilder {
AnnotatedTagBuilder {
body: Default::default(),
}
}
#[inline]
pub fn get_tag() -> AnnotatedTagGetBuilder<crate::generics::MissingOwner, crate::generics::MissingRepo, crate::generics::MissingSha> {
AnnotatedTagGetBuilder {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
_param_sha: core::marker::PhantomData,
}
}
}
impl Into<AnnotatedTag> for AnnotatedTagBuilder {
fn into(self) -> AnnotatedTag {
self.body
}
}
/// Builder for [`AnnotatedTag`](./struct.AnnotatedTag.html) object.
#[derive(Debug, Clone)]
pub struct AnnotatedTagBuilder {
body: self::AnnotatedTag,
}
impl AnnotatedTagBuilder {
#[inline]
pub fn message(mut self, value: impl Into<String>) -> Self {
self.body.message = Some(value.into());
self
}
#[inline]
pub fn object(mut self, value: crate::annotated_tag_object::AnnotatedTagObject) -> Self {
self.body.object = Some(value.into());
self
}
#[inline]
pub fn sha(mut self, value: impl Into<String>) -> Self {
self.body.sha = Some(value.into());
self
}
#[inline]
pub fn tag(mut self, value: impl Into<String>) -> Self {
self.body.tag = Some(value.into());
self
}
#[inline]
pub fn tagger(mut self, value: crate::commit_user::CommitUser) -> Self {
self.body.tagger = Some(value.into());
self
}
#[inline]
pub fn url(mut self, value: impl Into<String>) -> Self {
self.body.url = Some(value.into());
self
}
#[inline]
pub fn verification(mut self, value: crate::payload_commit_verification::PayloadCommitVerification) -> Self {
self.body.verification = Some(value.into());
self
}
}
/// Builder created by [`AnnotatedTag::get_tag`](./struct.AnnotatedTag.html#method.get_tag) method for a `GET` operation associated with `AnnotatedTag`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct AnnotatedTagGetBuilder<Owner, Repo, Sha> {
inner: AnnotatedTagGetBuilderContainer,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
_param_sha: core::marker::PhantomData<Sha>,
}
#[derive(Debug, Default, Clone)]
struct AnnotatedTagGetBuilderContainer {
param_owner: Option<String>,
param_repo: Option<String>,
param_sha: Option<String>,
}
impl<Owner, Repo, Sha> AnnotatedTagGetBuilder<Owner, Repo, Sha> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> AnnotatedTagGetBuilder<crate::generics::OwnerExists, Repo, Sha> {
self.inner.param_owner = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// name of the repo
#[inline]
pub fn repo(mut self, value: impl Into<String>) -> AnnotatedTagGetBuilder<Owner, crate::generics::RepoExists, Sha> {
self.inner.param_repo = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// sha of the tag. The Git tags API only supports annotated tag objects, not lightweight tags.
#[inline]
pub fn sha(mut self, value: impl Into<String>) -> AnnotatedTagGetBuilder<Owner, Repo, crate::generics::ShaExists> {
self.inner.param_sha = Some(value.into());
unsafe { std::mem::transmute(self) }
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for AnnotatedTagGetBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ShaExists> {
type Output = AnnotatedTag;
const METHOD: http::Method = http::Method::GET;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/git/tags/{sha}", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?"), sha=self.inner.param_sha.as_ref().expect("missing parameter sha?")).into()
}
}
impl crate::client::ResponseWrapper<AnnotatedTag, AnnotatedTagGetBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ShaExists>> {
#[inline]
pub fn message(&self) -> Option<String> {
self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
#[inline]
pub fn url(&self) -> Option<String> {
self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
}
|
use generics::{Generic, Prod, Unit};
trait Accumulate {
fn acc(self) -> u64;
}
impl Accumulate for u64 {
fn acc(self) -> u64 {
self
}
}
impl Accumulate for Unit {
fn acc(self) -> u64 {
0
}
}
impl<A, B> Accumulate for Prod<A, B>
where
A: Accumulate,
B: Accumulate,
{
fn acc(self) -> u64 {
let Prod(a, b) = self;
a.acc() + b.acc()
}
}
#[derive(Generic)]
struct Two {
a: u64,
b: u64,
}
#[derive(Generic)]
struct Four {
a: Two,
b: Two,
}
#[test]
fn struct_nested() {
let foo = Four {
a: Two { a: 18, b: 23 },
b: Two { a: 19, b: 24 },
};
assert_eq!(foo.into_repr().acc(), 84);
}
|
#[doc = "Register `VCTR57` reader"]
pub type R = crate::R<VCTR57_SPEC>;
#[doc = "Register `VCTR57` writer"]
pub type W = crate::W<VCTR57_SPEC>;
#[doc = "Field `B1824` reader - B1824"]
pub type B1824_R = crate::BitReader;
#[doc = "Field `B1824` writer - B1824"]
pub type B1824_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1825` reader - B1825"]
pub type B1825_R = crate::BitReader;
#[doc = "Field `B1825` writer - B1825"]
pub type B1825_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1826` reader - B1826"]
pub type B1826_R = crate::BitReader;
#[doc = "Field `B1826` writer - B1826"]
pub type B1826_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1827` reader - B1827"]
pub type B1827_R = crate::BitReader;
#[doc = "Field `B1827` writer - B1827"]
pub type B1827_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1828` reader - B1828"]
pub type B1828_R = crate::BitReader;
#[doc = "Field `B1828` writer - B1828"]
pub type B1828_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1829` reader - B1829"]
pub type B1829_R = crate::BitReader;
#[doc = "Field `B1829` writer - B1829"]
pub type B1829_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1830` reader - B1830"]
pub type B1830_R = crate::BitReader;
#[doc = "Field `B1830` writer - B1830"]
pub type B1830_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1831` reader - B1831"]
pub type B1831_R = crate::BitReader;
#[doc = "Field `B1831` writer - B1831"]
pub type B1831_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1832` reader - B1832"]
pub type B1832_R = crate::BitReader;
#[doc = "Field `B1832` writer - B1832"]
pub type B1832_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1833` reader - B1833"]
pub type B1833_R = crate::BitReader;
#[doc = "Field `B1833` writer - B1833"]
pub type B1833_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1834` reader - B1834"]
pub type B1834_R = crate::BitReader;
#[doc = "Field `B1834` writer - B1834"]
pub type B1834_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1835` reader - B1835"]
pub type B1835_R = crate::BitReader;
#[doc = "Field `B1835` writer - B1835"]
pub type B1835_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1836` reader - B1836"]
pub type B1836_R = crate::BitReader;
#[doc = "Field `B1836` writer - B1836"]
pub type B1836_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1837` reader - B1837"]
pub type B1837_R = crate::BitReader;
#[doc = "Field `B1837` writer - B1837"]
pub type B1837_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1838` reader - B1838"]
pub type B1838_R = crate::BitReader;
#[doc = "Field `B1838` writer - B1838"]
pub type B1838_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1839` reader - B1839"]
pub type B1839_R = crate::BitReader;
#[doc = "Field `B1839` writer - B1839"]
pub type B1839_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1840` reader - B1840"]
pub type B1840_R = crate::BitReader;
#[doc = "Field `B1840` writer - B1840"]
pub type B1840_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1841` reader - B1841"]
pub type B1841_R = crate::BitReader;
#[doc = "Field `B1841` writer - B1841"]
pub type B1841_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1842` reader - B1842"]
pub type B1842_R = crate::BitReader;
#[doc = "Field `B1842` writer - B1842"]
pub type B1842_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1843` reader - B1843"]
pub type B1843_R = crate::BitReader;
#[doc = "Field `B1843` writer - B1843"]
pub type B1843_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1844` reader - B1844"]
pub type B1844_R = crate::BitReader;
#[doc = "Field `B1844` writer - B1844"]
pub type B1844_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1845` reader - B1845"]
pub type B1845_R = crate::BitReader;
#[doc = "Field `B1845` writer - B1845"]
pub type B1845_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1846` reader - B1846"]
pub type B1846_R = crate::BitReader;
#[doc = "Field `B1846` writer - B1846"]
pub type B1846_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1847` reader - B1847"]
pub type B1847_R = crate::BitReader;
#[doc = "Field `B1847` writer - B1847"]
pub type B1847_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1848` reader - B1848"]
pub type B1848_R = crate::BitReader;
#[doc = "Field `B1848` writer - B1848"]
pub type B1848_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1849` reader - B1849"]
pub type B1849_R = crate::BitReader;
#[doc = "Field `B1849` writer - B1849"]
pub type B1849_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1850` reader - B1850"]
pub type B1850_R = crate::BitReader;
#[doc = "Field `B1850` writer - B1850"]
pub type B1850_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1851` reader - B1851"]
pub type B1851_R = crate::BitReader;
#[doc = "Field `B1851` writer - B1851"]
pub type B1851_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1852` reader - B1852"]
pub type B1852_R = crate::BitReader;
#[doc = "Field `B1852` writer - B1852"]
pub type B1852_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1853` reader - B1853"]
pub type B1853_R = crate::BitReader;
#[doc = "Field `B1853` writer - B1853"]
pub type B1853_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1854` reader - B1854"]
pub type B1854_R = crate::BitReader;
#[doc = "Field `B1854` writer - B1854"]
pub type B1854_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `B1855` reader - B1855"]
pub type B1855_R = crate::BitReader;
#[doc = "Field `B1855` writer - B1855"]
pub type B1855_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - B1824"]
#[inline(always)]
pub fn b1824(&self) -> B1824_R {
B1824_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - B1825"]
#[inline(always)]
pub fn b1825(&self) -> B1825_R {
B1825_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - B1826"]
#[inline(always)]
pub fn b1826(&self) -> B1826_R {
B1826_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - B1827"]
#[inline(always)]
pub fn b1827(&self) -> B1827_R {
B1827_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - B1828"]
#[inline(always)]
pub fn b1828(&self) -> B1828_R {
B1828_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - B1829"]
#[inline(always)]
pub fn b1829(&self) -> B1829_R {
B1829_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - B1830"]
#[inline(always)]
pub fn b1830(&self) -> B1830_R {
B1830_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - B1831"]
#[inline(always)]
pub fn b1831(&self) -> B1831_R {
B1831_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - B1832"]
#[inline(always)]
pub fn b1832(&self) -> B1832_R {
B1832_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - B1833"]
#[inline(always)]
pub fn b1833(&self) -> B1833_R {
B1833_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - B1834"]
#[inline(always)]
pub fn b1834(&self) -> B1834_R {
B1834_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - B1835"]
#[inline(always)]
pub fn b1835(&self) -> B1835_R {
B1835_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - B1836"]
#[inline(always)]
pub fn b1836(&self) -> B1836_R {
B1836_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - B1837"]
#[inline(always)]
pub fn b1837(&self) -> B1837_R {
B1837_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - B1838"]
#[inline(always)]
pub fn b1838(&self) -> B1838_R {
B1838_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - B1839"]
#[inline(always)]
pub fn b1839(&self) -> B1839_R {
B1839_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - B1840"]
#[inline(always)]
pub fn b1840(&self) -> B1840_R {
B1840_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - B1841"]
#[inline(always)]
pub fn b1841(&self) -> B1841_R {
B1841_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - B1842"]
#[inline(always)]
pub fn b1842(&self) -> B1842_R {
B1842_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - B1843"]
#[inline(always)]
pub fn b1843(&self) -> B1843_R {
B1843_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - B1844"]
#[inline(always)]
pub fn b1844(&self) -> B1844_R {
B1844_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - B1845"]
#[inline(always)]
pub fn b1845(&self) -> B1845_R {
B1845_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - B1846"]
#[inline(always)]
pub fn b1846(&self) -> B1846_R {
B1846_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - B1847"]
#[inline(always)]
pub fn b1847(&self) -> B1847_R {
B1847_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - B1848"]
#[inline(always)]
pub fn b1848(&self) -> B1848_R {
B1848_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - B1849"]
#[inline(always)]
pub fn b1849(&self) -> B1849_R {
B1849_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - B1850"]
#[inline(always)]
pub fn b1850(&self) -> B1850_R {
B1850_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - B1851"]
#[inline(always)]
pub fn b1851(&self) -> B1851_R {
B1851_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - B1852"]
#[inline(always)]
pub fn b1852(&self) -> B1852_R {
B1852_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - B1853"]
#[inline(always)]
pub fn b1853(&self) -> B1853_R {
B1853_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - B1854"]
#[inline(always)]
pub fn b1854(&self) -> B1854_R {
B1854_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - B1855"]
#[inline(always)]
pub fn b1855(&self) -> B1855_R {
B1855_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - B1824"]
#[inline(always)]
#[must_use]
pub fn b1824(&mut self) -> B1824_W<VCTR57_SPEC, 0> {
B1824_W::new(self)
}
#[doc = "Bit 1 - B1825"]
#[inline(always)]
#[must_use]
pub fn b1825(&mut self) -> B1825_W<VCTR57_SPEC, 1> {
B1825_W::new(self)
}
#[doc = "Bit 2 - B1826"]
#[inline(always)]
#[must_use]
pub fn b1826(&mut self) -> B1826_W<VCTR57_SPEC, 2> {
B1826_W::new(self)
}
#[doc = "Bit 3 - B1827"]
#[inline(always)]
#[must_use]
pub fn b1827(&mut self) -> B1827_W<VCTR57_SPEC, 3> {
B1827_W::new(self)
}
#[doc = "Bit 4 - B1828"]
#[inline(always)]
#[must_use]
pub fn b1828(&mut self) -> B1828_W<VCTR57_SPEC, 4> {
B1828_W::new(self)
}
#[doc = "Bit 5 - B1829"]
#[inline(always)]
#[must_use]
pub fn b1829(&mut self) -> B1829_W<VCTR57_SPEC, 5> {
B1829_W::new(self)
}
#[doc = "Bit 6 - B1830"]
#[inline(always)]
#[must_use]
pub fn b1830(&mut self) -> B1830_W<VCTR57_SPEC, 6> {
B1830_W::new(self)
}
#[doc = "Bit 7 - B1831"]
#[inline(always)]
#[must_use]
pub fn b1831(&mut self) -> B1831_W<VCTR57_SPEC, 7> {
B1831_W::new(self)
}
#[doc = "Bit 8 - B1832"]
#[inline(always)]
#[must_use]
pub fn b1832(&mut self) -> B1832_W<VCTR57_SPEC, 8> {
B1832_W::new(self)
}
#[doc = "Bit 9 - B1833"]
#[inline(always)]
#[must_use]
pub fn b1833(&mut self) -> B1833_W<VCTR57_SPEC, 9> {
B1833_W::new(self)
}
#[doc = "Bit 10 - B1834"]
#[inline(always)]
#[must_use]
pub fn b1834(&mut self) -> B1834_W<VCTR57_SPEC, 10> {
B1834_W::new(self)
}
#[doc = "Bit 11 - B1835"]
#[inline(always)]
#[must_use]
pub fn b1835(&mut self) -> B1835_W<VCTR57_SPEC, 11> {
B1835_W::new(self)
}
#[doc = "Bit 12 - B1836"]
#[inline(always)]
#[must_use]
pub fn b1836(&mut self) -> B1836_W<VCTR57_SPEC, 12> {
B1836_W::new(self)
}
#[doc = "Bit 13 - B1837"]
#[inline(always)]
#[must_use]
pub fn b1837(&mut self) -> B1837_W<VCTR57_SPEC, 13> {
B1837_W::new(self)
}
#[doc = "Bit 14 - B1838"]
#[inline(always)]
#[must_use]
pub fn b1838(&mut self) -> B1838_W<VCTR57_SPEC, 14> {
B1838_W::new(self)
}
#[doc = "Bit 15 - B1839"]
#[inline(always)]
#[must_use]
pub fn b1839(&mut self) -> B1839_W<VCTR57_SPEC, 15> {
B1839_W::new(self)
}
#[doc = "Bit 16 - B1840"]
#[inline(always)]
#[must_use]
pub fn b1840(&mut self) -> B1840_W<VCTR57_SPEC, 16> {
B1840_W::new(self)
}
#[doc = "Bit 17 - B1841"]
#[inline(always)]
#[must_use]
pub fn b1841(&mut self) -> B1841_W<VCTR57_SPEC, 17> {
B1841_W::new(self)
}
#[doc = "Bit 18 - B1842"]
#[inline(always)]
#[must_use]
pub fn b1842(&mut self) -> B1842_W<VCTR57_SPEC, 18> {
B1842_W::new(self)
}
#[doc = "Bit 19 - B1843"]
#[inline(always)]
#[must_use]
pub fn b1843(&mut self) -> B1843_W<VCTR57_SPEC, 19> {
B1843_W::new(self)
}
#[doc = "Bit 20 - B1844"]
#[inline(always)]
#[must_use]
pub fn b1844(&mut self) -> B1844_W<VCTR57_SPEC, 20> {
B1844_W::new(self)
}
#[doc = "Bit 21 - B1845"]
#[inline(always)]
#[must_use]
pub fn b1845(&mut self) -> B1845_W<VCTR57_SPEC, 21> {
B1845_W::new(self)
}
#[doc = "Bit 22 - B1846"]
#[inline(always)]
#[must_use]
pub fn b1846(&mut self) -> B1846_W<VCTR57_SPEC, 22> {
B1846_W::new(self)
}
#[doc = "Bit 23 - B1847"]
#[inline(always)]
#[must_use]
pub fn b1847(&mut self) -> B1847_W<VCTR57_SPEC, 23> {
B1847_W::new(self)
}
#[doc = "Bit 24 - B1848"]
#[inline(always)]
#[must_use]
pub fn b1848(&mut self) -> B1848_W<VCTR57_SPEC, 24> {
B1848_W::new(self)
}
#[doc = "Bit 25 - B1849"]
#[inline(always)]
#[must_use]
pub fn b1849(&mut self) -> B1849_W<VCTR57_SPEC, 25> {
B1849_W::new(self)
}
#[doc = "Bit 26 - B1850"]
#[inline(always)]
#[must_use]
pub fn b1850(&mut self) -> B1850_W<VCTR57_SPEC, 26> {
B1850_W::new(self)
}
#[doc = "Bit 27 - B1851"]
#[inline(always)]
#[must_use]
pub fn b1851(&mut self) -> B1851_W<VCTR57_SPEC, 27> {
B1851_W::new(self)
}
#[doc = "Bit 28 - B1852"]
#[inline(always)]
#[must_use]
pub fn b1852(&mut self) -> B1852_W<VCTR57_SPEC, 28> {
B1852_W::new(self)
}
#[doc = "Bit 29 - B1853"]
#[inline(always)]
#[must_use]
pub fn b1853(&mut self) -> B1853_W<VCTR57_SPEC, 29> {
B1853_W::new(self)
}
#[doc = "Bit 30 - B1854"]
#[inline(always)]
#[must_use]
pub fn b1854(&mut self) -> B1854_W<VCTR57_SPEC, 30> {
B1854_W::new(self)
}
#[doc = "Bit 31 - B1855"]
#[inline(always)]
#[must_use]
pub fn b1855(&mut self) -> B1855_W<VCTR57_SPEC, 31> {
B1855_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "MPCBBx vector register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`vctr57::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`vctr57::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct VCTR57_SPEC;
impl crate::RegisterSpec for VCTR57_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`vctr57::R`](R) reader structure"]
impl crate::Readable for VCTR57_SPEC {}
#[doc = "`write(|w| ..)` method takes [`vctr57::W`](W) writer structure"]
impl crate::Writable for VCTR57_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets VCTR57 to value 0xffff_ffff"]
impl crate::Resettable for VCTR57_SPEC {
const RESET_VALUE: Self::Ux = 0xffff_ffff;
}
|
use crate::layout::LayoutBox;
use crate::paint::entity::{DisplayCommand, DisplayList};
use crate::paint::utils::get_color;
pub fn render_background(list: &mut DisplayList, layout_box: &LayoutBox) {
// FIXME: background-colorにしか対応していないので、background両方に対応させたい
get_color(layout_box, "background-color").map(|color| {
list.push(DisplayCommand::SolidColor(
color,
layout_box.dimensions.border_box(),
));
});
}
|
fn main() {
println!("Hola, soy un mensaje de la linea 3");
println!("Hola, soy un mensaje de la linea 5");
panic!("El programa finaliza de forma inesperada!!");
println!("Hola, soy un mensaje de la linea 9");
println!("Hola, soy un mensaje de la linea 11");
println!("Hola, soy un mensaje de la linea 13");
}
|
// Copyright (c) 2016, <daggerbot@gmail.com>
// This software is available under the terms of the zlib license.
// See COPYING.md for more information.
extern crate aurum_display;
use aurum_display::{Display, Event, WindowStyle};
fn main () {
let display = Display::open().unwrap();
let device = display.default_device().unwrap();
let pixel_format = device.default_pixel_format().unwrap();
let window = device.new_window(&pixel_format, (500, 500), WindowStyle::Normal).unwrap();
window.set_title("Event Debugger").unwrap();
window.set_visible(true).unwrap();
loop {
let event = display.wait_event().unwrap();
println!("{:?}", event);
match event {
Event::CloseRequest(_) | Event::Destroy(_) => { break; },
_ => {},
}
}
}
|
extern crate kafka;
use kafka::client::KafkaClient;
/// This program demonstrates consuming messages through `KafkaClient`. This is the top level
/// client that will fit most use cases. Note that consumed messages are tracked by Kafka so you
/// can only consume them once. This is what you want for most use cases, you can look at
/// examples/fetch.rs for a lower level API.
fn main() {
let broker = "localhost:9092";
let topic = "my-topic";
println!("About to consume messages at {} from: {}", broker, topic);
let mut client = KafkaClient::new(vec!(broker.to_owned()));
if let Err(e) = client.load_metadata_all() {
println!("Failed to load meta data from {}: {}", broker, e);
return;
}
// ~ make sure to print out a warning message when the target
// topic does not yet exist
if !client.topic_partitions.contains_key(topic) {
println!("No such topic at {}: {}", broker, topic);
return;
}
let con = kafka::consumer::Consumer::new(client, "test-group".to_owned(), topic.to_owned())
.fallback_offset(-2);
for msg in con {
println!("{:?}", msg);
}
println!("No more messages.")
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::path::PathBuf;
use std::process::Command;
use std::process::ExitStatus;
pub struct GdbClientCommand {
gdb: PathBuf,
program_to_run: PathBuf,
init_command_to_queue: Vec<String>,
command_to_queue: Vec<String>,
}
impl GdbClientCommand {
pub fn new<P: Into<PathBuf>>(gdb_client: P, program_to_run: P) -> Self {
GdbClientCommand {
gdb: gdb_client.into(),
program_to_run: program_to_run.into(),
command_to_queue: Vec::new(),
init_command_to_queue: Vec::new(),
}
}
pub fn init_command<P: Into<String>>(&mut self, command: P) -> &mut Self {
self.init_command_to_queue.push(command.into());
self
}
pub fn init_commands<P, S>(&mut self, commands: P) -> &mut Self
where
P: IntoIterator<Item = S>,
S: Into<String>,
{
commands.into_iter().for_each(|ex| {
self.init_command_to_queue.push(ex.into());
});
self
}
pub fn command<P: Into<String>>(&mut self, command: P) -> &mut Self {
self.command_to_queue.push(command.into());
self
}
pub fn commands<P, S>(&mut self, commands: P) -> &mut Self
where
P: IntoIterator<Item = S>,
S: Into<String>,
{
commands.into_iter().for_each(|ex| {
self.command_to_queue.push(ex.into());
});
self
}
pub fn status(&mut self) -> io::Result<ExitStatus> {
let mut command = Command::new(&self.gdb);
command.arg(&self.program_to_run);
command.arg("-nh");
command.arg("--batch");
command.arg("-q");
command.arg("-l");
command.arg("2");
command.arg("-iex");
command.arg("set debug remote 1");
command.arg("-iex");
// NB: host io generates tons of packets which are not interesting,
// try not to get our remote (debug) packets too cluttered.
command.arg("set remote hostio-open-packet 0");
self.init_command_to_queue.iter().for_each(|iex| {
command.arg("-iex");
command.arg(format!("{}", iex));
});
self.command_to_queue.iter().for_each(|ex| {
command.arg("-ex");
command.arg(format!("{}", ex));
});
command.status()
}
}
|
fn main() {
//Rust中数组的语法
let a = [1, 2, 3, 4, 5];
let a:[i32;5] = [1, 2, 3, 4, 5];//[类型:元素数量]
let a:[3;5];//[初始值:元素数量]=>[3, 3, 3, 3, 3]
//访问元素数量
let first = a[0];
let second = a[1];
//Rust安全原则,当索引超出数组的长度时,编译时不会报错。
//但在运行时,会产生panic
}
|
use {DataHelper, EntityIter};
#[derive(Default, System)]
#[system_type(Entity)]
#[process(process)]
#[aspect(all(player, transform))]
pub struct CameraFollow;
fn process(_: &mut CameraFollow, mut players: EntityIter, data: &mut DataHelper) {
if let Some(player) = players.nth(0) {
let player_pos = data.components.transform[player].pos;
let cam_pos = data.services.camera.pos;
let shifted = 0.8 * player_pos + 0.2 * cam_pos;
data.services.camera.pos = shifted;
}
}
|
//! An alternative solver based around the SLG algorithm, which
//! implements the well-formed semantics. See the README.md
//! file for details.
#![cfg_attr(not(test), allow(dead_code))] // FOR NOW
crate mod forest;
mod logic;
mod stack;
mod strand;
mod table;
mod tables;
mod test;
use ir::ProgramEnvironment;
use solve::Solution;
use solve::slg::UCanonicalGoal;
use std::sync::Arc;
use self::forest::Forest;
/// Convenience fn for solving a root goal. It would be better to
/// createa a `Forest` so as to enable cahcing between goals, however.
crate fn solve_root_goal(
max_size: usize,
program: &Arc<ProgramEnvironment>,
root_goal: &UCanonicalGoal,
) -> Option<Solution> {
let mut forest = Forest::new(program, max_size);
forest.solve(root_goal)
}
|
use crate::input::keyboard::Key;
use crate::input::{mouse::ViewportPosition, InputPreprocessor};
use crate::message_prelude::*;
use glam::{DAffine2, Vec2Swizzles};
use graphene::Operation;
#[derive(Clone, Debug, Default)]
pub struct Resize {
pub drag_start: ViewportPosition,
pub path: Option<Vec<LayerId>>,
}
impl Resize {
pub fn calculate_transform(&self, center: Key, lock_ratio: Key, ipp: &InputPreprocessor) -> Option<Message> {
let mut start = self.drag_start;
let stop = ipp.mouse.position;
let mut size = stop - start;
if ipp.keyboard.get(lock_ratio as usize) {
size = size.abs().max(size.abs().yx()) * size.signum();
}
if ipp.keyboard.get(center as usize) {
start -= size;
size *= 2.;
}
self.path.clone().map(|path| {
Operation::SetLayerTransformInViewport {
path,
transform: DAffine2::from_scale_angle_translation(size, 0., start).to_cols_array(),
}
.into()
})
}
}
|
mod bubblesort;
mod insertionsort;
mod quicksort;
mod selectionsort;
use std::fmt::Debug;
pub use bubblesort::BubbleSort;
pub use insertionsort::InsertionSort;
pub use quicksort::Quicksort;
pub use selectionsort::SelectionSort;
pub trait Sorter {
fn sort<T>(self, slice: &mut [T])
where
T: Ord + Clone + Debug;
}
|
use crate::transaction::{Address, Authorization, CoinId, Input, Output, Transaction};
use bincode::serialize;
use ed25519_dalek::Keypair;
use rand::rngs::OsRng;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use std::{error, fmt};
pub const COIN_CF: &str = "COIN";
pub const KEYPAIR_CF: &str = "KEYPAIR"; // &Address to &KeyPairPKCS8
pub type Result<T> = std::result::Result<T, WalletError>;
/// A data structure to maintain key pairs and their coins, and to generate transactions.
pub struct Wallet {
/// The underlying RocksDB handle.
db: rocksdb::DB,
/// Keep key pair (in pkcs8 bytes) in memory for performance, it's duplicated in database as well.
keypairs: Mutex<HashMap<Address, Keypair>>,
counter: AtomicUsize,
}
#[derive(Debug)]
pub enum WalletError {
InsufficientBalance,
MissingKeyPair,
DBError(rocksdb::Error),
}
impl fmt::Display for WalletError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
WalletError::InsufficientBalance => write!(f, "insufficient balance"),
WalletError::MissingKeyPair => write!(f, "missing key pair for the requested address"),
WalletError::DBError(ref e) => e.fmt(f),
}
}
}
impl error::Error for WalletError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
WalletError::DBError(ref e) => Some(e),
_ => None,
}
}
}
impl From<rocksdb::Error> for WalletError {
fn from(err: rocksdb::Error) -> WalletError {
WalletError::DBError(err)
}
}
impl Wallet {
fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
let coin_cf = rocksdb::ColumnFamilyDescriptor::new(COIN_CF, rocksdb::Options::default());
let keypair_cf =
rocksdb::ColumnFamilyDescriptor::new(KEYPAIR_CF, rocksdb::Options::default());
let mut db_opts = rocksdb::Options::default();
db_opts.create_missing_column_families(true);
db_opts.create_if_missing(true);
let handle = rocksdb::DB::open_cf_descriptors(&db_opts, path, vec![coin_cf, keypair_cf])?;
Ok(Self {
db: handle,
keypairs: Mutex::new(HashMap::new()),
counter: AtomicUsize::new(0),
})
}
pub fn new<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
rocksdb::DB::destroy(&rocksdb::Options::default(), &path)?;
Self::open(path)
}
pub fn number_of_coins(&self) -> usize {
self.counter.load(Ordering::Relaxed)
}
/// Generate a new key pair
pub fn generate_keypair(&self) -> Result<Address> {
let _cf = self.db.cf_handle(KEYPAIR_CF).unwrap();
let mut csprng: OsRng = OsRng::new().unwrap();
let keypair: Keypair = Keypair::generate(&mut csprng);
self.load_keypair(keypair)
}
pub fn load_keypair(&self, keypair: Keypair) -> Result<Address> {
let cf = self.db.cf_handle(KEYPAIR_CF).unwrap();
let addr: Address =
ring::digest::digest(&ring::digest::SHA256, &keypair.public.as_bytes().as_ref()).into();
self.db.put_cf(cf, &addr, &keypair.to_bytes().to_vec())?;
let mut keypairs = self.keypairs.lock().unwrap();
keypairs.insert(addr, keypair);
Ok(addr)
}
/// Get the list of addresses for which we have a key pair
pub fn addresses(&self) -> Result<Vec<Address>> {
let keypairs = self.keypairs.lock().unwrap();
let addrs = keypairs.keys().cloned().collect();
Ok(addrs)
}
fn contains_keypair(&self, addr: &Address) -> bool {
let keypairs = self.keypairs.lock().unwrap();
if keypairs.contains_key(addr) {
return true;
}
false
}
pub fn apply_diff(&self, add: &[(CoinId, Output)], remove: &[CoinId]) -> Result<()> {
let mut batch = rocksdb::WriteBatch::default();
let cf = self.db.cf_handle(COIN_CF).unwrap();
for coin in add {
if self.contains_keypair(&coin.1.recipient) {
let key = serialize(&coin.0).unwrap();
let val = serialize(&coin.1).unwrap();
batch.put_cf(cf, &key, &val)?;
self.counter.fetch_add(1, Ordering::Relaxed);
}
}
for coin in remove {
let key = serialize(&coin).unwrap();
batch.delete_cf(cf, &key)?;
}
self.db.write(batch)?;
Ok(())
}
/// Returns the sum of values of all the coin in the wallet
pub fn balance(&self) -> Result<u64> {
let cf = self.db.cf_handle(COIN_CF).unwrap();
let iter = self.db.iterator_cf(cf, rocksdb::IteratorMode::Start)?;
let balance = iter
.map(|(_, v)| {
let coin_data: Output = bincode::deserialize(v.as_ref()).unwrap();
coin_data.value
})
.sum::<u64>();
Ok(balance)
}
/// Create a transaction using the wallet coins
pub fn create_transaction(
&self,
recipient: Address,
value: u64,
previous_used_coin: Option<CoinId>,
) -> Result<Transaction> {
let mut coins_to_use: Vec<CoinId> = vec![];
let mut inputs: Vec<Input> = vec![];
let mut value_sum = 0u64;
let cf = self.db.cf_handle(COIN_CF).unwrap();
let iter = match previous_used_coin {
Some(c) => {
let prev_key = serialize(&c).unwrap();
self.db.iterator_cf(
cf,
rocksdb::IteratorMode::From(&prev_key, rocksdb::Direction::Forward),
)?
}
None => self.db.iterator_cf(cf, rocksdb::IteratorMode::Start)?,
};
// iterate through our wallet
for (k, v) in iter {
let coin_id: CoinId = bincode::deserialize(k.as_ref()).unwrap();
let coin_data: Output = bincode::deserialize(v.as_ref()).unwrap();
value_sum += coin_data.value;
coins_to_use.push(coin_id);
inputs.push(Input {
coin: coin_id,
value: coin_data.value,
owner: coin_data.recipient,
}); // coins that will be used for this transaction
if value_sum >= value {
// if we already have enough money, break
break;
}
}
if value_sum < value {
// we don't have enough money in wallet
return Err(WalletError::InsufficientBalance);
}
// if we have enough money in our wallet, create tx
// remove used coin from wallet
self.apply_diff(&[], &coins_to_use)?;
// create the output
let mut output = vec![Output { recipient, value }];
if value_sum > value {
// transfer the remaining value back to self
let recipient = self.addresses()?[0];
output.push(Output {
recipient,
value: value_sum - value,
});
}
let mut owners: Vec<Address> = inputs.iter().map(|input| input.owner).collect();
let unsigned = Transaction {
input: inputs,
output,
authorization: vec![],
hash: RefCell::new(None),
};
let mut authorization = vec![];
owners.sort_unstable();
owners.dedup();
let raw_inputs = bincode::serialize(&unsigned.input).unwrap();
let raw_outputs = bincode::serialize(&unsigned.output).unwrap();
let raw_unsigned = [&raw_inputs[..], &raw_outputs[..]].concat();
for owner in owners.iter() {
let keypairs = self.keypairs.lock().unwrap();
if let Some(v) = keypairs.get(&owner) {
authorization.push(Authorization {
pubkey: v.public.to_bytes().to_vec(),
signature: v.sign(&raw_unsigned).to_bytes().to_vec(),
});
} else {
return Err(WalletError::MissingKeyPair);
}
drop(keypairs);
}
self.counter
.fetch_sub(unsigned.input.len(), Ordering::Relaxed);
Ok(Transaction {
authorization,
..unsigned
})
}
}
#[cfg(test)]
pub mod tests {}
|
use crate::prelude::*;
use crate::responses::DeleteDocumentResponse;
use azure_core::modify_conditions::IfMatchCondition;
use azure_core::prelude::*;
use chrono::{DateTime, Utc};
use http::StatusCode;
use std::convert::TryInto;
#[derive(Debug, Clone)]
pub struct DeleteDocumentBuilder<'a> {
document_client: &'a DocumentClient,
if_match_condition: Option<IfMatchCondition<'a>>,
if_modified_since: Option<IfModifiedSince>,
user_agent: Option<azure_core::UserAgent<'a>>,
activity_id: Option<azure_core::ActivityId<'a>>,
consistency_level: Option<ConsistencyLevel>,
allow_tentative_writes: TenativeWritesAllowance,
}
impl<'a> DeleteDocumentBuilder<'a> {
pub(crate) fn new(document_client: &'a DocumentClient) -> DeleteDocumentBuilder<'a> {
Self {
document_client,
if_match_condition: None,
if_modified_since: None,
user_agent: None,
activity_id: None,
consistency_level: None,
allow_tentative_writes: TenativeWritesAllowance::Deny,
}
}
pub fn document_client(&self) -> &'a DocumentClient {
self.document_client
}
pub fn with_if_match_condition(self, if_match_condition: IfMatchCondition<'a>) -> Self {
Self {
if_match_condition: Some(if_match_condition),
..self
}
}
pub fn with_user_agent(self, user_agent: &'a str) -> Self {
Self {
user_agent: Some(azure_core::UserAgent::new(user_agent)),
..self
}
}
pub fn with_activity_id(self, activity_id: &'a str) -> Self {
Self {
activity_id: Some(azure_core::ActivityId::new(activity_id)),
..self
}
}
pub fn with_consistency_level(self, consistency_level: ConsistencyLevel) -> Self {
Self {
consistency_level: Some(consistency_level),
..self
}
}
pub fn with_allow_tentative_writes(
self,
allow_tentative_writes: TenativeWritesAllowance,
) -> Self {
Self {
allow_tentative_writes,
..self
}
}
pub fn with_if_modified_since(self, if_modified_since: &'a DateTime<Utc>) -> Self {
Self {
if_modified_since: Some(IfModifiedSince::new(if_modified_since.clone())),
..self
}
}
pub async fn execute(&self) -> Result<DeleteDocumentResponse, CosmosError> {
trace!("DeleteDocumentBuilder::execute called");
let mut req = self
.document_client
.prepare_request_with_document_name(http::Method::DELETE);
// add trait headers
req = crate::headers::add_header(self.if_match_condition(), req);
req = crate::headers::add_header(self.if_modified_since(), req);
req = crate::headers::add_header(self.user_agent(), req);
req = crate::headers::add_header(self.activity_id(), req);
req = crate::headers::add_header(self.consistency_level(), req);
req = crate::headers::add_header(Some(self.allow_tentative_writes()), req);
req = crate::headers::add_partition_keys_header(self.document_client.partition_keys(), req);
let req = req.body(EMPTY_BODY.as_ref())?;
debug!("{:?}", req);
Ok(self
.document_client
.http_client()
.execute_request_check_status(req, StatusCode::NO_CONTENT)
.await?
.try_into()?)
}
fn if_match_condition(&self) -> Option<IfMatchCondition<'a>> {
self.if_match_condition
}
fn user_agent(&self) -> Option<azure_core::UserAgent<'a>> {
self.user_agent
}
fn activity_id(&self) -> Option<azure_core::ActivityId<'a>> {
self.activity_id
}
fn consistency_level(&self) -> Option<ConsistencyLevel> {
self.consistency_level.clone()
}
fn allow_tentative_writes(&self) -> TenativeWritesAllowance {
self.allow_tentative_writes
}
}
impl<'a> DeleteDocumentBuilder<'a> {
fn if_modified_since(&self) -> Option<IfModifiedSince> {
self.if_modified_since.clone()
}
}
|
use std::io;
fn main() {
let mut user_input = String::new(); //user_input is a variable name
//let mut user_input = ""; //user_input is a variable name
println!("Type Your Name:");
io::stdin().read_line(&mut user_input).expect("Failed to read line");
//io::stdin().read_line(&mut user_input).unwrap();
println!("You entered : {:#?}",user_input);
println!("You entered : {:#?}",user_input.trim());
let mut height = String::new();
//let mut user_input = ""; //user_input is a variable name
println!("Type Your Height:");
io::stdin().read_line(&mut height).expect("Failed to read line");
//io::stdin().read_line(&mut user_input).unwrap();
println!("You entered : {:#?}",height);
println!("You entered : {:#?}",height.trim());
let height: f32 = height.trim().parse().unwrap();
println!("You entered : {:#?}",height);
loop {
let mut temp = String::new();
//let mut user_input = ""; //user_input is a variable name
println!("Type today Temperature:");
io::stdin().read_line(&mut temp).expect("Failed to read line");
//io::stdin().read_line(&mut user_input).unwrap();
println!("You entered : {:#?}",temp);
println!("You entered : {:#?}",temp.trim());
let temp: f32 = match temp.trim().parse() {
Ok(data) => data,
Err(_) => continue,
};
println!("You entered : {:#?}",temp);
break;
}
let val:u8 = 66;
let age :u8 = 66;
match age {
0...50 => println!("You are young"),
val => println!("You are {} year old",val),
_ => println!("out of range"),
};
}
|
extern crate core;
extern crate itertools;
extern crate glob;
extern crate either;
extern crate redis;
mod file;
mod hash_utils;
pub mod method;
pub mod response;
pub mod address;
pub mod actor;
pub mod log_entry;
pub mod invalid_log_entry;
pub mod nginx_processing_results;
pub mod nginx;
pub mod processor; |
#![cfg_attr(
target_arch = "spirv",
no_std,
feature(register_attr, lang_items),
register_attr(spirv)
)]
// HACK(eddyb) can't easily see warnings otherwise from `spirv-builder` builds.
#![deny(warnings)]
#[cfg(not(target_arch = "spirv"))]
#[macro_use]
pub extern crate spirv_std_macros;
#[allow(unused_imports)]
use glam::{Mat2, Mat3, Mat4, Vec2, Vec3, Vec4, Vec4Swizzles};
#[allow(unused_imports)]
use spirv_std::{Image2d, Sampler, discard,};
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Uniforms {
u_view_position: Vec4, // unused
u_view: Mat4,
u_proj: Mat4,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Light {
pos: Vec4,
color: Vec4,
light_space_mat: Mat4,
}
#[allow(unused_variables)]
#[spirv(fragment)]
pub fn main_fs(
) {
// Intentionally empty
}
#[allow(unused_variables)]
#[spirv(vertex)]
pub fn main_vs(
a_position: Vec3,
a_tex_coords: Vec2,
a_normal: Vec3,
a_tangent: Vec4,
a_bitangent: Vec4,
bone_ids: u32,
bone_weights: Vec4,
model_matrix_0: Vec4,
model_matrix_1: Vec4,
model_matrix_2: Vec4,
model_matrix_3: Vec4,
normal_matrix_0: Vec4,
normal_matrix_1: Vec4,
normal_matrix_2: Vec4,
normal_matrix_3: Vec4,
#[spirv(uniform, descriptor_set = 1, binding = 0)] uniforms: &Uniforms,
#[spirv(storage_buffer, descriptor_set = 2, binding = 0)] lights: &[Light],
#[spirv(position)] out_pos: &mut Vec4,
) {
let model_matrix = Mat4::from_cols(
model_matrix_0,
model_matrix_1,
model_matrix_2,
model_matrix_3,
);
let model_space = model_matrix * a_position.extend(1.0);
*out_pos = lights[0].light_space_mat * model_space;
}
|
extern crate crypto;
use crypto::sha3::Sha3;
use std::vec::Vec;
#[derive(Debug)]
struct Fig {
previous_hash: String,
changes: Vec<String>,
hash: String
}
impl Fig {
fn previous_hash(&self) -> &str {
&self.previous_hash
}
fn hash(&self) -> &str {
&self.hash
}
}
pub fn new(previous_block: Option<&Fig>, changes: Vec<String>) -> Fig {
previous_hash = match previous_block {
Some(fig) => fig.previous_hash(),
None => String::from("0")
};
let joined_str = format!("{}{}",changes.join(""),previous_hash);
let mut hasher = Sha3::sha3_512();
hasher.input_str(joined_str);
Fig { previous_hash: previous_hash, hash: hasher.result_str(), changes: changes }
}
|
use super::{
Config, BalanceOf, Module, Error, RawEvent,
TeamAccounts, CustodyAccounts, TotalCustody
};
use sp_runtime::{Perbill, RuntimeDebug};
use sp_std::prelude::*;
use sp_std::convert::TryFrom;
use codec::{Encode, Decode, HasCompact};
use frame_support::traits::{
Currency, ReservableCurrency, Get, ExistenceRequirement::AllowDeath,
fungible::Inspect,
};
use sp_runtime::traits::{
Zero, Saturating, AtLeast32BitUnsigned,
Convert, StaticLookup, SaturatedConversion
};
use frame_support::{StorageValue, StorageMap, dispatch::DispatchResult};
/// Custody Info
#[derive(PartialEq, Eq, Clone, Encode, Decode, Default, RuntimeDebug)]
pub struct CustodyInfo<AccountId, Balance: HasCompact> {
/// Allocation
#[codec(compact)]
pub allocation: Balance,
/// Current vested amount (increases as payouts are given)
#[codec(compact)]
pub vested: Balance,
/// Custody account
pub custody: AccountId,
/// Reserve account
pub reserve: AccountId,
}
impl<AccountId, Balance> CustodyInfo<AccountId, Balance> where
AccountId: Default,
Balance: AtLeast32BitUnsigned + Saturating + Copy,
{
/// Increase vested amount in self
fn increase_vested(&mut self, amount: Balance) {
self.vested += amount;
}
}
/// Implement Custody sub module functions
impl<T: Config> Module<T> {
/// Get payout frequency
pub fn payout_frequency() -> T::BlockNumber {
T::PayoutFrequency::get()
}
/// Get the custody duration
pub fn custody_duration() -> T::BlockNumber {
T::CustodyDuration::get()
}
/// Get the governance custody duration
pub fn governance_custody_duration() -> T::BlockNumber {
T::GovernanceCustodyDuration::get()
}
/// Check if custody is done
pub fn is_custody_done(block: T::BlockNumber) -> bool {
block > Self::custody_duration()
}
/// Check if governance custody is done
pub fn is_governance_custody_done(block: T::BlockNumber) -> bool {
block > Self::governance_custody_duration()
}
/// Initialize custody for a given account and allocation
pub fn initialize_custody(who: &T::AccountId, amount: BalanceOf<T>) {
// 1. Split allocation: 5.55555556% -> reserve, 94.4444444% -> custody
// NOTE: allocation here is 90% of actual team member allocation, so the reserve
// has 5.55555556% * 0.9 = 5% of total funds
let reserve_ratio = Perbill::from_rational(55_555_556u32, 1_000_000_000u32);
let reserve_balance = reserve_ratio * (amount);
let custody_balance = amount - reserve_balance;
// 2. Create custody account
// Generate custody account for team member using
// the anonymous account function from proxy pallet
let custody_account =
<pallet_proxy::Pallet<T>>::anonymous_account(
who,
&T::CustodyProxy::get(),
0,
None
);
// Deposit amount in custody account
let _ = <T as Config>::Currency::deposit_creating(
&custody_account,
custody_balance
);
// 3. Create reserve account
// Generate reserve account for team member using
// the anonymous account function from proxy pallet
let reserve_account =
<pallet_proxy::Pallet<T>>::anonymous_account(
who,
&T::CustodyProxy::get(),
1,
None
);
// Deposit amount in reserve account
let _ = <T as Config>::Currency::deposit_creating(
&reserve_account.clone(),
reserve_balance
);
// 4. Create custody info
let custody_info = CustodyInfo {
allocation: amount,
vested: Zero::zero(),
custody: custody_account.clone(),
reserve: reserve_account,
};
// 5. Store custody info and custody account
<TeamAccounts<T>>::insert(who, custody_info);
<CustodyAccounts<T>>::insert(&custody_account, ());
// 6. Update total amount under custody
<TotalCustody<T>>::mutate(|n| *n += custody_balance);
<TotalCustody<T>>::mutate(|n| *n += reserve_balance);
}
/// Set the governance proxy of given custody account
fn set_custody_governance_proxy(custody: &T::AccountId, proxy: T::AccountId) -> DispatchResult {
// 1. Remove any proxies
Self::remove_custody_proxies(custody);
// 2. Set new proxy
<pallet_proxy::Pallet<T>>::add_proxy_delegate(
custody,
proxy,
T::CustodyProxy::get(),
Zero::zero()
)
}
/// Remove any proxies of given custody account, refunding team member's deposit if existing
/// NOTE: Any proxies are guaranteed to be only of Governance type
fn remove_custody_proxies(custody: &T::AccountId) {
// Can't call remove_proxies directly, so need to replicate code here
let (_, old_deposit) = <pallet_proxy::Proxies::<T>>::take(custody);
<T as pallet_proxy::Config>::Currency::unreserve(custody, old_deposit.clone());
}
/// Compute payout
fn compute_payout(allocation: BalanceOf<T>) -> BalanceOf<T> {
let payout_ratio = Perbill::from_rational(
Self::payout_frequency(),
Self::custody_duration()
);
payout_ratio * allocation
}
/// Attempt a payout to the given team member account
pub fn try_payout(who: T::AccountId) -> DispatchResult {
// 1. Get the block number from the FRAME System module.
let block = <frame_system::Pallet<T>>::block_number();
// 2. Get custody info for team member
// (can't fail because team member existing is checked before)
let info = <TeamAccounts<T>>::get(&who);
// 3. If custody is over, payout full remaining amount
if Self::is_custody_done(block) {
// 3.1. If any leftover custody amount is still bonded, force unstake
let custody = info.custody.clone();
if <pallet_staking::Bonded<T>>::contains_key(&custody) {
<pallet_staking::Module<T>>::force_unstake(
frame_system::RawOrigin::Root.into(),
custody.clone(),
Zero::zero(),
)?;
}
// 3.2. Remove any proxies on the custody account
Self::remove_custody_proxies(&custody);
// 3.3. Payout remaining amount
Self::do_payout(who.clone(), Zero::zero(), info, false)?;
// 3.4. Emmit custody done event
Self::deposit_event(RawEvent::CustodyDone(who));
return Ok(())
}
// 4. Compute payout according to block
let payout = Self::compute_payout(info.allocation);
let chunks = block / Self::payout_frequency();
let chunks = <T as Config>::BlockNumberToBalance::convert(chunks);
let amount = payout * chunks - info.vested;
if !amount.is_zero() {
// 4.1. Do payout
// NOTE: function does nothing if custody account has only the existential deposit
// transferable balance and reserve funds are exhausted
Self::do_payout(who.clone(), amount, info, true)?;
} else {
// 4.2. Payout not available
Err(Error::<T>::PayoutNotAvailable)?
}
Ok(())
}
/// Do a payout
fn do_payout(
who: T::AccountId, amount: BalanceOf<T>,
mut info: CustodyInfo<T::AccountId, BalanceOf<T>>,
keep_alive: bool,
) -> DispatchResult {
// 1. Get custody transferable balance
// Use Inspect trait here to get transferable balance of Custody account, and use keep
// alive to limit transfers down to existential deposit until end of the custody period
let custody = info.custody.clone();
let custody_transferable_balance =
<T as Config>::Currency::reducible_balance(&custody, keep_alive.clone());
// T::Currency and T::Inspect are both implemented by Balances pallet, so the
// balance type is the same. However, explicit conversion is needed here.
let custody_balance = <BalanceOf<T>>::try_from(
custody_transferable_balance.saturated_into::<u128>()
).ok().unwrap_or(Zero::zero());
// 2. Get reserve balance
// Reserve account is never used in any Reservable or Lockable Currency operations
// However, if funds are taken from the Reserve, we could have a payout that
// leaves dust in the account. This will lead to loss of custody funds, meaning the
// team member never fully vests.
// In order to prevent this, use the Inspect trait here, and use keep alive to
// limit transfers down to existential deposit until end of the custody period
let reserve = info.reserve.clone();
let reserve_transferable_balance =
<T as Config>::Currency::reducible_balance(&reserve, keep_alive.clone());
// T::Currency and T::Inspect are both implemented by Balances pallet, so the
// balance type is the same. However, explicit conversion is needed here.
let reserve_balance = <BalanceOf<T>>::try_from(
reserve_transferable_balance.saturated_into::<u128>()
).ok().unwrap_or(Zero::zero());
// 3. Calculate amounts to withdraw from custody and reserve
// If custody period is done, transfer full amount from both accounts
// in order to not leave any inaccessible funds around
let (withdraw_custody, withdraw_reserve) = if keep_alive {
let from_custody = amount.min(custody_balance);
let from_reserve = amount - from_custody;
(from_custody, from_reserve.min(reserve_balance))
} else {
(custody_balance, reserve_balance)
};
let withdraw = withdraw_custody + withdraw_reserve;
// 4. Make transfer from custody, if possible
if !withdraw_custody.is_zero() {
// Transfer from custody to team member account
<T as Config>::Currency::transfer(
&custody,
&who,
withdraw_custody.into(),
AllowDeath
)?;
// Emmit TeamPayoutCustody event
Self::deposit_event(RawEvent::PayoutFromCustody(who.clone(), withdraw_custody));
}
// 5. Make transfer from reserve, if possible
if !withdraw_reserve.is_zero() {
// Transfer from reserve to team member account
<T as Config>::Currency::transfer(
&reserve,
&who,
withdraw_reserve.into(),
AllowDeath
)?;
// Emmit TeamPayoutReserve event
Self::deposit_event(RawEvent::PayoutFromReserve(who.clone(), withdraw_reserve));
}
// 6. Error if no payout is possible (only before custody ends)
if keep_alive && withdraw.is_zero() {
Err(Error::<T>::PayoutFailedInsufficientFunds)?
}
// 7. Update custody info
// Increase vested amount
info.increase_vested(withdraw);
// Adjust total custody
let custody_deduct = if keep_alive {
// If its not the last payout, then use the total withdraw
withdraw
} else {
// At the last payout, make sure to square total custody correctly based
// on difference between vested and allocation
if info.allocation < info.vested {
// If more was paid out than was allocated, make sure to deduct the difference
let diff = info.vested - info.allocation;
withdraw.saturating_sub(diff)
} else if info.allocation > info.vested {
// If not enough was paid out compared to allocation, make sure to add the difference
let diff = info.allocation - info.vested;
withdraw.saturating_add(diff)
} else {
// Total paid equals allocation, all good
withdraw
}
};
// Note: The logic above has been tested and results in exact amounts being subtracted
// from TotalCustody. Still, use saturating sub here just to be safe and not have panics
<TotalCustody<T>>::mutate(|n| *n = n.clone().saturating_sub(custody_deduct));
// Update or delete info in storage
if keep_alive {
// Insert updated custody info
<TeamAccounts<T>>::insert(&who, info);
} else {
// Delete team member custody info
<TeamAccounts<T>>::remove(&who);
// Delete custody account
<CustodyAccounts<T>>::remove(&info.custody);
}
Ok(())
}
/// Check if the custody period is active, return error if not
fn check_custody() -> DispatchResult {
// Get the block number from the FRAME System module.
let block = <frame_system::Pallet<T>>::block_number();
// If custody should be active but is done, return error
if Self::is_custody_done(block) {
Err(Error::<T>::CustodyPeriodEnded)?
}
Ok(())
}
/// Check if the governance custody period is active/done, return appropriate error
fn check_governance_custody(active: bool) -> DispatchResult {
// Get the block number from the FRAME System module.
let block = <frame_system::Pallet<T>>::block_number();
if active {
// If governance custody should be active but is done, return error
if Self::is_governance_custody_done(block) {
Err(Error::<T>::GovernanceCustodyPeriodEnded)?
}
} else {
// If governance custody should be done but is active, return error
if !Self::is_governance_custody_done(block) {
Err(Error::<T>::GovernanceCustodyActive)?
}
}
Ok(())
}
/// Attempt to bond funds from a custody account
pub fn try_custody_bond(
custody: T::AccountId,
controller: T::AccountId,
value: pallet_staking::BalanceOf<T>,
) -> DispatchResult {
// 1. Return error if custody done
Self::check_custody()?;
// 2. Call bond function
<pallet_staking::Module<T>>::bond(
T::Origin::from(Some(custody).into()),
T::Lookup::unlookup(controller),
value.into()
)
}
/// Attempt to bond extra funds from a custody account
pub fn try_custody_bond_extra(
custody: T::AccountId,
value: pallet_staking::BalanceOf<T>,
) -> DispatchResult {
// 1. Return error if custody done
Self::check_custody()?;
// 2. Call bond extra function
<pallet_staking::Module<T>>::bond_extra(
T::Origin::from(Some(custody).into()),
value.into()
)
}
/// Attempt to set the staking controller of a custody account
pub fn try_custody_set_controller(
custody: T::AccountId,
controller: T::AccountId,
) -> DispatchResult {
// 1. Return error if custody done
Self::check_custody()?;
// 2. Call set controller function
<pallet_staking::Module<T>>::set_controller(
T::Origin::from(Some(custody).into()),
T::Lookup::unlookup(controller)
)
}
/// Attempt to set a governance proxy of a given custody account
pub fn try_custody_set_proxy(
custody: T::AccountId,
proxy: T::AccountId,
) -> DispatchResult {
// 1. Return error if governance custody done
Self::check_governance_custody(true)?;
// 2. Set new governance proxy (removes any previous existing ones)
Self::set_custody_governance_proxy(&custody, proxy)
}
/// Attempt to set a governance proxy of a team member's own custody account
pub fn try_team_custody_set_proxy(who: T::AccountId, proxy: T::AccountId) -> DispatchResult {
// 1. Return error if governance custody is not done
Self::check_governance_custody(false)?;
// 2. Get team member custody account
// (can't fail because team member existing is checked before)
let info = <TeamAccounts<T>>::get(&who);
// 3. Set new governance proxy (removes any previous existing ones)
Self::set_custody_governance_proxy(&info.custody, proxy)
}
/// Update a team member account
pub fn update_team_member(who: T::AccountId, new: T::AccountId) {
// 1. Take info from team accounts
let info = <TeamAccounts<T>>::take(&who);
// 2. Insert info in new account
<TeamAccounts<T>>::insert(&new, info);
}
}
|
pub struct StatusFlags {
pub carry: bool,
pub zero: bool,
pub interrupt_disabled: bool,
pub decimal: bool,
pub breakpoint: bool,
pub unused: bool,
pub overflow: bool,
pub sign: bool,
}
impl StatusFlags {
pub fn to_u8(&self) -> u8 {
let carry = if self.carry { 0x01 } else { 0 };
let zero = if self.zero { 0x02 } else { 0 };
let interrupt_disabled = if self.interrupt_disabled { 0x04 } else { 0 };
let decimal = if self.decimal { 0x08 } else { 0 };
let breakpoint = if self.breakpoint { 0x10 } else { 0 };
let overflow = if self.overflow { 0x40 } else { 0 };
let sign = if self.sign { 0x80 } else { 0 };
carry | zero | interrupt_disabled | decimal | breakpoint | overflow | sign
}
}
impl From<u8> for StatusFlags {
fn from(byte: u8) -> StatusFlags {
StatusFlags {
carry: byte & 0x01 == 0x01,
zero: byte & 0x02 == 0x02,
interrupt_disabled: byte & 0x04 == 0x04,
decimal: byte & 0x08 == 0x08,
breakpoint: byte & 0x10 == 0x10,
unused: false,
overflow: byte & 0x40 == 0x40,
sign: byte & 0x80 == 0x80,
}
}
}
impl Default for StatusFlags {
fn default() -> StatusFlags {
StatusFlags {
carry: false,
zero: false,
interrupt_disabled: true,
decimal: false,
breakpoint: false,
unused: false,
overflow: false,
sign: false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_is_four() {
let f = StatusFlags::default();
assert_eq!(0x04, f.to_u8());
}
#[test]
fn can_convert_to_u8() {
let mut f = StatusFlags::default();
f.carry = true;
assert_eq!(0x05, f.to_u8());
}
#[test]
fn can_convert_to_and_from() {
let f = StatusFlags {
carry: true,
decimal: true,
sign: true,
overflow: true,
interrupt_disabled: false,
..Default::default()
};
let byte = f.to_u8();
let result: StatusFlags = byte.into();
assert_eq!(true, result.carry);
assert_eq!(true, result.decimal);
assert_eq!(true, result.sign);
assert_eq!(true, result.overflow);
assert_eq!(false, result.interrupt_disabled);
assert_eq!(false, result.zero);
assert_eq!(false, result.breakpoint);
assert_eq!(false, result.unused);
}
} |
#[doc = "Register `UR5` reader"]
pub type R = crate::R<UR5_SPEC>;
#[doc = "Field `MESAD_1` reader - Mass erase secured area disabled for bank 1"]
pub type MESAD_1_R = crate::BitReader;
#[doc = "Field `WRPS_1` reader - Write protection for flash bank 1"]
pub type WRPS_1_R = crate::FieldReader;
impl R {
#[doc = "Bit 0 - Mass erase secured area disabled for bank 1"]
#[inline(always)]
pub fn mesad_1(&self) -> MESAD_1_R {
MESAD_1_R::new((self.bits & 1) != 0)
}
#[doc = "Bits 16:23 - Write protection for flash bank 1"]
#[inline(always)]
pub fn wrps_1(&self) -> WRPS_1_R {
WRPS_1_R::new(((self.bits >> 16) & 0xff) as u8)
}
}
#[doc = "SYSCFG user register 5\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ur5::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct UR5_SPEC;
impl crate::RegisterSpec for UR5_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ur5::R`](R) reader structure"]
impl crate::Readable for UR5_SPEC {}
#[doc = "`reset()` method sets UR5 to value 0"]
impl crate::Resettable for UR5_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! [RefCell<T>] and the Interior Mutability Pattern
//!
//! [refcell<t>]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html
/// Message trait to trigger to send a message.
pub trait Messenger {
fn send(&self, message: &str);
}
/// Tracking the limit and call `send()` method of `Messenger` trait implementor.
pub struct LimitTracker<'a, T: 'a + Messenger> {
messenger: &'a T,
value: usize,
max: usize,
}
impl<'a, T: 'a + Messenger> LimitTracker<'a, T> {
pub fn new(messenger: &'a T, max: usize) -> Self {
Self {
messenger,
value: 0,
max,
}
}
pub fn set_value(&mut self, value: usize) {
self.value = value;
let percentage = self.value as f64 / self.max as f64;
if percentage >= 1.0 {
self.messenger.send("Error: You are over your quota!");
} else if percentage >= 0.9 {
self.messenger
.send("Urgent: You've used up over 90% of your quota!");
} else if percentage >= 0.75 {
self.messenger
.send("Warning: You've used up over 75% of your quota!");
}
}
}
#[cfg(test)]
mod tests {
use super::{LimitTracker, Messenger};
use std::cell::RefCell;
#[test]
fn it_sends_an_over_75_percent_warning_message() {
struct MockMessenger(RefCell<Vec<String>>);
impl Messenger for MockMessenger {
fn send(&self, msg: &str) {
self.0.borrow_mut().push(String::from(msg));
}
}
let messenger = MockMessenger(RefCell::new(vec![]));
let mut tracker = LimitTracker::new(&messenger, 100);
tracker.set_value(75);
tracker.set_value(90);
tracker.set_value(100);
let wants = vec![
"Warning: You've used up over 75% of your quota!",
"Urgent: You've used up over 90% of your quota!",
"Error: You are over your quota!",
];
assert_eq!(wants.len(), messenger.0.borrow().len());
for (i, want) in wants.iter().enumerate() {
assert_eq!(*want, &messenger.0.borrow()[i]);
}
}
#[test]
fn double_borrow_ok() {
struct MockMessenger(RefCell<Vec<String>>);
impl Messenger for MockMessenger {
fn send(&self, _msg: &str) {
let one = self.0.borrow();
let two = self.0.borrow();
assert_eq!(0, one.len());
assert_eq!(0, two.len());
}
}
let messenger = MockMessenger(RefCell::new(vec![]));
let mut tracker = LimitTracker::new(&messenger, 100);
tracker.set_value(75);
}
#[test]
#[should_panic(expected = "already borrowed: BorrowMutError")]
fn double_borrow_mut_panic() {
struct MockMessenger(RefCell<Vec<String>>);
impl Messenger for MockMessenger {
fn send(&self, _msg: &str) {
let _a = self.0.borrow_mut();
let _b = self.0.borrow_mut();
}
}
let messenger = MockMessenger(RefCell::new(vec![]));
let mut tracker = LimitTracker::new(&messenger, 100);
tracker.set_value(75);
}
}
|
use std::io::Write;
pub fn main() -> std::io::Result<()> {
let rst = ublox::CfgRstBuilder {
nav_bbr_mask: ublox::NavBbrMask::all(),
reset_mode: ublox::ResetMode::HardwareResetImmediately,
reserved1: 0,
};
let bytes = rst.into_packet_bytes();
let mut file = std::fs::File::create("msg.bin")?;
file.write(&bytes[..])?;
Ok(())
}
|
/**
* MIT License
*
* termail - Copyright (c) 2021 Larry Hao
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Locals
use super::{
TermailActivity, COMPONENT_LABEL_HELP, COMPONENT_TABLE_MAILLIST, COMPONENT_TEXTAREA_MAIL,
COMPONENT_TEXT_ERROR, COMPONENT_TEXT_HELP, COMPONENT_TEXT_MESSAGE,
COMPONENT_TREEVIEW_MAILBOXES,
};
use crate::ui::{draw_area_in, draw_area_top_right};
// Ext
use tui_realm_stdlib::{
Label, LabelPropsBuilder, Paragraph, ParagraphPropsBuilder, Table, TablePropsBuilder, Textarea,
TextareaPropsBuilder,
};
use tuirealm::{
props::{
borders::{BorderType, Borders},
TableBuilder, TextSpan,
},
tui::{
layout::{Alignment, Constraint, Direction, Layout},
style::Color,
widgets::Clear,
},
PropPayload, PropsBuilder, View,
};
// tui
use tui_realm_treeview::{TreeView, TreeViewPropsBuilder};
#[allow(unused)]
impl TermailActivity {
// -- view
/// ### `init_setup`
///
/// Initialize setup view
pub(super) fn init_setup(&mut self) {
// Init view
self.view = View::init();
// Let's mount the component we need
self.view.mount(
COMPONENT_LABEL_HELP,
Box::new(Label::new(
LabelPropsBuilder::default()
.with_foreground(Color::Cyan)
.with_text(format!(
"Press <CTRL+H> for help. Version: {}",
crate::VERSION,
))
.build(),
)),
);
self.view.mount(
COMPONENT_TEXTAREA_MAIL,
Box::new(Textarea::new(
TextareaPropsBuilder::default()
.with_background(Color::Black)
.with_borders(Borders::ALL, BorderType::Rounded, Color::Green)
.with_highlighted_str(Some("\u{1f680}"))
.with_max_scroll_step(4)
.with_title("Mail", Alignment::Left)
.with_texts(vec![
TextSpan::new("No mail available.").fg(Color::LightGreen)
])
.build(),
)),
);
// Scrolltable
self.view.mount(
COMPONENT_TABLE_MAILLIST,
Box::new(Table::new(
TablePropsBuilder::default()
.with_background(Color::Black)
.with_highlighted_str(Some("\u{1f680}"))
.with_highlighted_color(Color::LightBlue)
.with_max_scroll_step(4)
.with_borders(Borders::ALL, BorderType::Thick, Color::Blue)
.scrollable(true)
.with_title("Mail List", Alignment::Left)
.with_header(&["Idx", "Time", "From", "Title"])
.with_widths(&[5, 18, 22, 55])
.with_table(
TableBuilder::default()
.add_col(TextSpan::from("Empty.."))
.add_col(TextSpan::from(""))
.add_col(TextSpan::from(""))
.add_col(TextSpan::from(""))
.build(),
)
.build(),
)),
);
self.view.mount(
COMPONENT_TREEVIEW_MAILBOXES,
Box::new(TreeView::new(
TreeViewPropsBuilder::default()
.with_borders(Borders::ALL, BorderType::Rounded, Color::LightYellow)
.with_foreground(Color::LightYellow)
.with_background(Color::Black)
.with_title("Mailboxes", Alignment::Left)
.with_tree_and_depth(self.tree.root(), 2)
.with_highlighted_str("\u{1f680}")
.keep_state(true)
.build(),
)),
);
// We need to initialize the focus
self.view.active(COMPONENT_TREEVIEW_MAILBOXES);
}
/// View gui
pub(super) fn view(&mut self) {
if let Some(mut ctx) = self.context.take() {
let _drop = ctx.context.draw(|f| {
// Prepare chunks
let chunks_main = Layout::default()
.direction(Direction::Vertical)
.margin(0)
.constraints([Constraint::Min(2), Constraint::Length(1)].as_ref())
.split(f.size());
let chunks_left = Layout::default()
.direction(Direction::Horizontal)
.margin(0)
.constraints([Constraint::Ratio(2, 7), Constraint::Ratio(5, 7)].as_ref())
.split(chunks_main[0]);
let chunks_right = Layout::default()
.direction(Direction::Vertical)
.margin(0)
.constraints([Constraint::Min(2), Constraint::Length(18)].as_ref())
.split(chunks_left[1]);
self.view
.render(COMPONENT_TREEVIEW_MAILBOXES, f, chunks_left[0]);
self.view.render(COMPONENT_LABEL_HELP, f, chunks_main[1]);
self.view
.render(COMPONENT_TABLE_MAILLIST, f, chunks_right[0]);
self.view
.render(COMPONENT_TEXTAREA_MAIL, f, chunks_right[1]);
if let Some(props) = self.view.get_props(COMPONENT_TEXT_HELP) {
if props.visible {
// make popup
let popup = draw_area_in(f.size(), 50, 90);
f.render_widget(Clear, popup);
self.view.render(COMPONENT_TEXT_HELP, f, popup);
}
}
if let Some(props) = self.view.get_props(COMPONENT_TEXT_ERROR) {
if props.visible {
let popup = draw_area_in(f.size(), 50, 10);
f.render_widget(Clear, popup);
// make popup
self.view.render(COMPONENT_TEXT_ERROR, f, popup);
}
}
if let Some(props) = self.view.get_props(COMPONENT_TEXT_MESSAGE) {
if props.visible {
let popup = draw_area_top_right(f.size(), 32, 15);
f.render_widget(Clear, popup);
// make popup
self.view.render(COMPONENT_TEXT_MESSAGE, f, popup);
}
}
});
self.context = Some(ctx);
}
}
// -- mount
// ### mount_error
//
// Mount error box
pub(super) fn mount_error(&mut self, text: &str) {
// Mount
self.view.mount(
COMPONENT_TEXT_ERROR,
Box::new(Paragraph::new(
ParagraphPropsBuilder::default()
.with_foreground(Color::Red)
.bold()
.with_borders(Borders::ALL, BorderType::Rounded, Color::Red)
.with_title("Error", Alignment::Center)
.with_texts(vec![TextSpan::from(text)])
.build(),
)),
);
// Give focus to error
self.view.active(COMPONENT_TEXT_ERROR);
}
/// ### `umount_error`
///
/// Umount error message
pub(super) fn umount_error(&mut self) {
self.view.umount(COMPONENT_TEXT_ERROR);
}
// ### mount_message
//
// Mount message box
pub(super) fn mount_message(&mut self, title: &str, text: &str) {
// Mount
self.view.mount(
COMPONENT_TEXT_MESSAGE,
Box::new(Paragraph::new(
ParagraphPropsBuilder::default()
.with_foreground(Color::Green)
.bold()
.with_borders(Borders::ALL, BorderType::Rounded, Color::Cyan)
.with_title(title, Alignment::Center)
.with_text_alignment(Alignment::Center)
.with_texts(vec![TextSpan::from(text)])
.build(),
)),
);
// Give focus to error
// self.view.active(COMPONENT_TEXT_MESSAGE);
}
/// ### `umount_message`
///
/// Umount error message
pub(super) fn umount_message(&mut self, _title: &str, text: &str) {
if let Some(props) = self.view.get_props(COMPONENT_TEXT_MESSAGE) {
if let Some(PropPayload::Vec(spans)) = props.own.get("spans") {
if let Some(display_text) = spans.get(0) {
if text == display_text.unwrap_text_span().content {
self.view.umount(COMPONENT_TEXT_MESSAGE);
}
}
}
}
}
// /// ### mount_help
// ///
// /// Mount help
pub(super) fn mount_help(&mut self) {
self.view.mount(
COMPONENT_TEXT_HELP,
Box::new(Table::new(
TablePropsBuilder::default()
.with_borders(Borders::ALL, BorderType::Rounded, Color::Green)
.with_title("Help", Alignment::Center)
.with_header(&["Key", "Function"])
.with_widths(&[30, 70])
.with_table(
TableBuilder::default()
.add_col(TextSpan::new("<ESC> or <Q>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Exit"))
.add_row()
.add_col(TextSpan::new("<TAB>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Switch focus"))
.add_row()
.add_col(TextSpan::new("<h,j,k,l,g,G>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Move cursor(vim style)"))
.add_row()
.add_col(TextSpan::new("<f/b>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Seek forward/backward 5 seconds"))
.add_row()
.add_col(TextSpan::new("<F/B>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Seek forward/backward 1 second for lyrics"))
.add_row()
.add_col(TextSpan::new("<F/B>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Before 10 seconds,adjust offset of lyrics"))
.add_row()
.add_col(TextSpan::new("<T>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Switch lyrics if more than 1 available"))
.add_row()
.add_col(TextSpan::new("<n/N/space>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Next/Previous/Pause current song"))
.add_row()
.add_col(TextSpan::new("<+,=/-,_>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Increase/Decrease volume"))
.add_row()
.add_col(TextSpan::new("Library").bold().fg(Color::LightYellow))
.add_row()
.add_col(TextSpan::new("<l/L>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Add one/all songs to playlist"))
.add_row()
.add_col(TextSpan::new("<d>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Delete song or folder"))
.add_row()
.add_col(TextSpan::new("<s>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Download or search song from youtube"))
.add_row()
.add_col(TextSpan::new("<t>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Open tag editor for tag and lyric download"))
.add_row()
.add_col(TextSpan::new("<y/p>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Yank and Paste files"))
.add_row()
.add_col(TextSpan::new("<Enter>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Open sub directory as root"))
.add_row()
.add_col(TextSpan::new("<Backspace>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Go back to parent directory"))
.add_row()
.add_col(TextSpan::new("</>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Search in library"))
.add_row()
.add_col(TextSpan::new("Playlist").bold().fg(Color::LightYellow))
.add_row()
.add_col(TextSpan::new("<d/D>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Delete one/all songs from playlist"))
.add_row()
.add_col(TextSpan::new("<l>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Play selected"))
.add_row()
.add_col(TextSpan::new("<s>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Shuffle playlist"))
.add_row()
.add_col(TextSpan::new("<m>").bold().fg(Color::Cyan))
.add_col(TextSpan::from("Loop mode toggle"))
.build(),
)
.build(),
)),
);
// Active help
self.view.active(COMPONENT_TEXT_HELP);
}
/// ### `umount_help`
///
/// Umount help
pub(super) fn umount_help(&mut self) {
self.view.umount(COMPONENT_TEXT_HELP);
}
}
|
use gumdrop::Options;
use bls_snark::ValidatorSetUpdate;
use zexe_algebra::{Bls12_377, BW6_761};
use zexe_r1cs_core::ConstraintSynthesizer;
use zexe_r1cs_std::test_constraint_counter::ConstraintCounter;
use phase2::parameters::{circuit_to_qap, MPCParameters};
use snark_utils::{log_2, Groth16Params, Result, UseCompression};
use memmap::MmapOptions;
use std::fs::OpenOptions;
#[derive(Debug, Options, Clone)]
pub struct NewOpts {
help: bool,
#[options(help = "the path to the phase1 parameters", default = "phase1")]
pub phase1: String,
#[options(
help = "the total number of coefficients (in powers of 2) which were created after processing phase 1"
)]
pub phase1_size: u32,
#[options(help = "the challenge file name to be created", default = "challenge")]
pub output: String,
#[options(
help = "the number of epochs the snark will prove",
default = "180" // 6 months
)]
pub num_epochs: usize,
#[options(
help = "the number of validators the snark will support",
default = "100"
)]
pub num_validators: usize,
}
const COMPRESSION: UseCompression = UseCompression::No;
pub fn empty_circuit(opt: &NewOpts) -> (ValidatorSetUpdate<Bls12_377>, usize) {
let maximum_non_signers = (opt.num_validators - 1) / 3;
// Create an empty circuit
let valset = ValidatorSetUpdate::empty(
opt.num_validators,
opt.num_epochs,
maximum_non_signers,
None, // The hashes are done over BW6 so no helper is provided for the setup
);
let phase2_size = {
let mut counter = ConstraintCounter::new();
valset
.clone()
.generate_constraints(&mut counter)
.expect("could not calculate number of required constraints");
let phase2_size = counter.num_aux + counter.num_inputs + counter.num_constraints;
let power = log_2(phase2_size) as u32;
// get the nearest power of 2
if phase2_size < 2usize.pow(power) {
2usize.pow(power + 1)
} else {
phase2_size
}
};
(valset, phase2_size)
}
pub fn new(opt: &NewOpts) -> Result<()> {
let phase1_transcript = OpenOptions::new()
.read(true)
.write(true)
.open(&opt.phase1)
.expect("could not read phase 1 transcript file");
let mut phase1_transcript = unsafe {
MmapOptions::new()
.map_mut(&phase1_transcript)
.expect("unable to create a memory map for input")
};
let mut output = OpenOptions::new()
.read(false)
.write(true)
.create_new(true)
.open(&opt.output)
.expect("could not open file for writing the MPC parameters ");
let (valset, phase2_size) = empty_circuit(&opt);
// Read `num_constraints` Lagrange coefficients from the Phase1 Powers of Tau which were
// prepared for this step. This will fail if Phase 1 was too small.
let phase1 = Groth16Params::<BW6_761>::read(
&mut phase1_transcript,
COMPRESSION,
2usize.pow(opt.phase1_size),
phase2_size,
)?;
// Convert it to a QAP
let keypair = circuit_to_qap(valset)?;
// Generate the initial transcript
let mpc = MPCParameters::new(keypair, phase1)?;
mpc.write(&mut output)?;
Ok(())
}
|
use ini::Ini;
use std::process;
use std::io;
use std::io::Write;
use colored::*;
mod utils;
use utils::DataMM;
use utils::{normalize_elem, denormalize_elem, error_invalid_key};
fn main() {
let mut theta_0:f64 = 0.0;
let mut theta_1:f64 = 0.0;
let mut label_x: Option<String> = None;
let mut label_y: Option<String> = None;
let mut mm = DataMM { min_0: 0.0, max_0: 0.0, min_1: 0.0, max_1: 0.0 };
let file = Ini::load_from_file("./data/theta.ini").unwrap();
for (s, prop) in file.iter() {
let section = s.unwrap();
for (k, v) in prop.iter() {
match section {
"thetas" => {
match k {
"theta_0" => {
theta_0 = v.parse::<f64>().unwrap_or_else(|e| {
println!("{}: {}: {}", "error".red().bold(), k, e);
process::exit(1);
})
}
"theta_1" => {
theta_1 = v.parse::<f64>().unwrap_or_else(|e| {
println!("{}: {}: {}", "error".red().bold(), k, e);
process::exit(1);
})
}
_ => {
error_invalid_key(section, k);
}
}
}
"categories" => {
match k {
"x" => {
label_x = Some(v.to_string());
}
"y" => {
label_y = Some(v.to_string());
}
_ => {
error_invalid_key(section, k);
}
}
}
"denormalize" => {
match k {
"min_0" => {
mm.min_0 = v.parse::<f64>().unwrap_or_else(|e| {
println!("{}: {}: {}", "error".red().bold(), k, e);
process::exit(1);
})
}
"max_0" => {
mm.max_0 = v.parse::<f64>().unwrap_or_else(|e| {
println!("{}: {}: {}", "error".red().bold(), k, e);
process::exit(1);
})
}
"min_1" => {
mm.min_1 = v.parse::<f64>().unwrap_or_else(|e| {
println!("{}: {}: {}", "error".red().bold(), k, e);
process::exit(1);
})
}
"max_1" => {
mm.max_1 = v.parse::<f64>().unwrap_or_else(|e| {
println!("{}: {}: {}", "error".red().bold(), k, e);
process::exit(1);
})
}
_ => {
error_invalid_key(section, k);
}
}
}
_ => {
println!("{}: invalid section [{}] in .ini file", "error".red().bold(), k);
process::exit(1);
}
}
}
}
if theta_0 == 0.0 && theta_1 == 0.0 {
println!("{}: {}", "warning".yellow().bold(), "it looks like thetas aren't generated, did you forgot to train the model ?");
process::exit(1);
}
if label_x.is_none() || label_y.is_none() {
println!("{}: {}", "warning".yellow().bold(), "it looks like category names aren't generated, did you forgot to train the model ?");
process::exit(1);
}
let label_x = label_x.unwrap();
let label_y = label_y.unwrap();
let mut user_input_category = String::new();
println!("\nWhich category would you like to predict ?");
println!("{} find {} from {}", "[0]:".bright_cyan(), label_y.bright_blue(), label_x.bright_blue());
println!("{} find {} from {}\n", "[1]:".bright_cyan(), label_x.bright_blue(), label_y.bright_blue());
print!("{}: ", "Enter 0 or 1".bright_cyan());
io::stdout().flush().unwrap(); // force the print to show up
io::stdin().read_line(&mut user_input_category).unwrap_or_else(|e| {
println!("{}: {}", "error".red().bold(), e);
process::exit(1);
});
let category_nb = user_input_category.trim().parse::<String>().unwrap_or_else(|e| {
println!("{}: {}", "error".red().bold(), e);
process::exit(1);
});
let category_needed: String;
let category_predicted: String;
let category_nb:&str = &category_nb;
match category_nb {
"0" => {
category_needed = label_x;
category_predicted = label_y;
},
"1" => {
category_needed = label_y;
category_predicted = label_x;
},
user_answer => {
println!("{}: You must specify 0 or 1. You answered [{}]", "error".red().bold(), user_answer.bright_cyan());
process::exit(1);
}
}
let mut user_input_nb = String::new();
print!("{} {}: ", "Enter".bright_cyan(), category_needed.bright_cyan());
io::stdout().flush().unwrap(); // force the print to show up
io::stdin().read_line(&mut user_input_nb).unwrap_or_else(|e| {
println!("{}: {}", "error".red().bold(), e);
process::exit(1);
});
let user_input_nb = user_input_nb.trim().parse::<f64>().unwrap_or_else(|e| {
println!("{}: {}", "error".red().bold(), e);
process::exit(1);
});
let prediction: f64;
match category_nb {
"0" => prediction = denormalize_elem(theta_0 + theta_1 * normalize_elem(user_input_nb as f64, mm.min_0, mm.max_0), mm.min_1, mm.max_1),
_ => prediction = denormalize_elem((normalize_elem(user_input_nb as f64, mm.min_1, mm.max_1) - theta_0) / theta_1, mm.min_0, mm.max_0)
}
println!("{} {}: {}", "\nExpected".bright_green(), category_predicted.bright_green(), prediction);
}
|
#[doc = "Register `HWCFGR2` reader"]
pub type R = crate::R<HWCFGR2_SPEC>;
#[doc = "Field `OPTIONREG_OUT` reader - OPTIONREG_OUT"]
pub type OPTIONREG_OUT_R = crate::FieldReader;
#[doc = "Field `TRUST_ZONE` reader - TRUST_ZONE"]
pub type TRUST_ZONE_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:7 - OPTIONREG_OUT"]
#[inline(always)]
pub fn optionreg_out(&self) -> OPTIONREG_OUT_R {
OPTIONREG_OUT_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:11 - TRUST_ZONE"]
#[inline(always)]
pub fn trust_zone(&self) -> TRUST_ZONE_R {
TRUST_ZONE_R::new(((self.bits >> 8) & 0x0f) as u8)
}
}
#[doc = "TAMP hardware configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hwcfgr2::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct HWCFGR2_SPEC;
impl crate::RegisterSpec for HWCFGR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`hwcfgr2::R`](R) reader structure"]
impl crate::Readable for HWCFGR2_SPEC {}
#[doc = "`reset()` method sets HWCFGR2 to value 0x0101"]
impl crate::Resettable for HWCFGR2_SPEC {
const RESET_VALUE: Self::Ux = 0x0101;
}
|
use lalrpop_util::lalrpop_mod;
lalrpop_mod!(pub parser, "/parser.rs");
use parser::*;
use crate::ast::*;
use crate::memory::*;
use std::collections::HashMap;
pub mod ast;
pub mod memory;
// EVALUATING FUNCTIONS
fn eval_infix(l: Val, oc: &OpCode, r: Val) -> Val {
match (l, oc, r) {
(Val::Num(l), oc, Val::Num(r)) => match oc {
OpCode::Add => Val::Num(l + r),
OpCode::Sub => Val::Num(l - r),
OpCode::Mul => Val::Num(l * r),
OpCode::Div => Val::Num(l / r),
OpCode::Equal => Val::Bool(l == r),
OpCode::NotEqual => Val::Bool(l != r),
OpCode::Lesser => Val::Bool(l < r),
OpCode::LesserOrEqual => Val::Bool(l <= r),
OpCode::Greater => Val::Bool(l > r),
OpCode::GreaterOrEqual => Val::Bool(l >= r),
_ => panic!("[Infix] Error evaluating num"),
},
(Val::Bool(l), oc, Val::Bool(r)) => Val::Bool(match oc {
OpCode::And => l && r,
OpCode::Or => l || r,
OpCode::Equal => l == r,
_ => panic!("[Infix] Error evaluating bool"),
}),
_ => panic!("[Infix] Error infix doesnt match anything"),
}
}
fn eval_prefix(oc: &OpCode, r: Val) -> Val {
match (oc, r) {
(oc, Val::Num(r)) => match oc {
OpCode::Sub => Val::Num(-r),
OpCode::Add => Val::Num(r),
_ => panic!("[Prefix] Error evaluating num"),
},
(oc, Val::Bool(r)) => match oc {
OpCode::Not => Val::Bool(!r),
_ => panic!("[Prefix] Error evaluating bool"),
},
_ => panic!("[Prefix] Error prefix doesnt match anything"),
}
}
fn eval_expr(e: &Expr, m: &mut Mem, fn_env: &FnEnv) -> Val {
println!("[Expr] Evaluating expr: {:?}", e);
match e {
Expr::Term(l) => match l {
Lit::Num(i) => Val::Num(*i),
Lit::Bool(b) => Val::Bool(*b),
Lit::Id(id) => match m.get(id.to_owned()) {
Some((v, _)) => v.clone(),
None => panic!("[Expr] Identifier not found {:?}", id),
},
_ => panic!("[Expr] Error evaluating term"),
},
Expr::Infix(l, op, r) => {
let l = eval_expr(l, m, fn_env);
let r = eval_expr(r, m, fn_env);
eval_infix(l, op, r)
}
Expr::Prefix(op, r) => {
let r = eval_expr(r, m, fn_env);
eval_prefix(op, r)
},
Expr::Ref(e) => match &**e {
Expr::Term(l) => match l {
Lit::Id(id) => match m.get(id.to_owned()){
Some(_) => Val::Ref(id.to_owned()),
None => panic!("[Expr] Error identifier not found {:?}", id),
},
_ => panic!("[Expr] Error Ref on non identifier"),
},
_ => panic!("[Expr] Error Ref on non term"),
},
Expr::RefMut(e) => match &**e {
Expr::Term(l) => match l {
Lit::Id(id) => match m.get(id.to_owned()){
Some(_) => Val::RefMut(id.to_owned()),
None => panic!("[Expr] Error identifier not found {:?}", id),
},
_ => panic!("[Expr] Error RefMut on non identifier"),
},
_ => panic!("[Expr] Error RefMut on non term"),
},
Expr::DeRef(e) => {
let ev = eval_expr(e, m, fn_env);
println!("[Expr] Dereferencing {:?}", ev);
match ev {
Val::Ref(id) => eval_expr(&Expr::Term(Lit::Id(id)), m, fn_env),
Val::RefMut(id) => eval_expr(&Expr::Term(Lit::Id(id)), m, fn_env),
_ => panic!("[Expr] Error dereference failed"),
}
},
Expr::Stmt(s) => {
println!("[Expr] Interpreting stmt: {:?}", s);
eval_stmts(&vec![s.to_owned()], m, fn_env)
},
Expr::Call(name, exprs) => {
println!("[Expr] Calling function named {:?} with arguments {:?}", name, exprs);
let expr_list: Vec<Box<Expr>> = exprs.0.clone();
let mut mut_refs: Vec<String> = Vec::new();
for e in expr_list.iter(){
match &**e {
Expr::RefMut(s) => {
let id = deref_reference(s).to_owned();
if mut_refs.contains(&id){
panic!("[BorrowCheck] Error cannot borrow mutably {:?} more than once", id);
}
mut_refs.push(id)
},
Expr::Ref(s) => {
let id = deref_reference(s).to_owned();
if mut_refs.contains(&id){
panic!("[BorrowCheck] Error cannot borrow {:?} because its already borrowed as mutable", id);
}
},
_ => {}
};
println!("{:?}", **e);
}
let args: Vec<Val> = exprs.0.iter().map(|expr| eval_expr(expr, m, fn_env)).collect();
eval_fn(name, &args, m, fn_env)
}
_ => unimplemented!("[Expr] Unimplemented expr"),
}
}
fn deref_reference(e: &Expr) -> String {
match e {
Expr::Term(Lit::Id(id)) => id.to_owned(),
Expr::DeRef(e) => {
deref_reference(e)
},
_ => panic!("[Deref] Error no dereference passed as arg")
}
}
fn eval_stmts(stmts: &Vec<Stmt>, m: &mut Mem, fn_env: &FnEnv) -> Val {
let ss = stmts;
m.push_empty_scope();
let mut stmt_val = Val::Unit;
for s in ss {
println!("[Stmt] Stmt: {:?}", s);
println!("[Stmt] Mem: {:?}", m);
stmt_val = match s {
Stmt::Let(b, id, _, e_orig) => {
println!("[Stmt] Let");
m.new_id(id.to_owned(), *b);
match e_orig {
Some(e) => {
let r_expr = &(e.clone());
let val = eval_expr(r_expr, m, fn_env);
let scope = m.get_scope_of_id(id.to_owned());
match val.clone() {
Val::Ref(s) => {
m.add_ref(s.to_owned(),id.to_owned(), Bc::Ref(s.to_owned(), scope))
},
Val::RefMut(s) => {
m.add_ref(s.to_owned(),id.to_owned(), Bc::RefMut(s.to_owned(), scope))
},
_ => {
m.add_ref(id.to_owned(), id.to_owned(), Bc::Owner(id.to_owned(), scope))
},
};
m.update(id.to_owned(), val, false);
Val::Unit
},
_ => Val::Unit,
}
},
Stmt::Assign(l_expr, r_expr) => {
println!("[Stmt] Assign");
let id = deref_reference(l_expr);
let v: Val;
match &**r_expr {
Expr::DeRef(e) => {
let r_ref = deref_reference(e);
let i = m.get_scope_of_id(id.to_owned());
v = eval_expr(r_expr, m, fn_env);
println!("[Deref] {:?} {:?} {:?}", id.to_owned(), r_ref, i);
m.update(id.to_owned(), v, true)
},
Expr::Ref(e) => {
let r_ref = deref_reference(e);
let i = m.get_scope_of_id(r_ref.to_owned());
m.add_ref(r_ref.to_owned(), id.to_owned(), Bc::Ref(r_ref.to_owned(), i));
v = eval_expr(r_expr, m, fn_env);
m.update(id.to_owned(), v, false)
},
Expr::RefMut(e) => {
let r_ref = deref_reference(e);
let i = m.get_scope_of_id(r_ref.to_owned());
m.add_ref(r_ref.to_owned(),id.to_owned(), Bc::RefMut(r_ref.to_owned(), i));
v = eval_expr(r_expr, m, fn_env);
m.update(id.to_owned(), v, false)
}
_ => {
v = eval_expr(r_expr, m, fn_env);
println!("[Deref] {:?} ", id.to_owned());
m.update(id.to_owned(), v, true)
}
};
Val::Unit
},
Stmt::If(expr,s,es) => {
println!("[Stmt] If");
match (eval_expr(expr, m, fn_env), es) {
(Val::Bool(true), _) => eval_stmts(s, m, fn_env),
(Val::Bool(false), Some(es)) => eval_stmts(es, m, fn_env),
(Val::Bool(_), _) => Val::Uninitialized,
_ => panic!("[Stmt] Error if resulted in non boolean condition"),
}
},
Stmt::While(expr,block) => {
println!("[Stmt] While");
while match eval_expr(expr, m, fn_env) {
Val::Bool(b) => b,
_ => panic!("[Stmt] Error while resulted in non boolean condition"),
} {
eval_stmts(block, m, fn_env);
}
Val::Unit
},
Stmt::Expr(e) => {
println!("[Stmt] Expr");
eval_expr(e, m, fn_env)
},
Stmt::Block(block) => {
println!("[Stmt] Block");
eval_stmts(block, m, fn_env)
},
Stmt::Return(e) => {
let ret_val = eval_expr(e, m, fn_env);
println!("[Stmt] Returned with value: {:?}", ret_val);
ret_val
}
Stmt::Semi => Val::Unit,
}
}
m.pop_scope();
stmt_val
}
pub fn eval_fn(name: &str, params: &Vec<Val>, m: &mut Mem, fn_env: &FnEnv) -> Val {
if let Some(decl) = fn_env.get(name) {
println!("[Func] Evaluating function {:?} with params {:?}", name, params);
let mut paramReferenceMutable: Vec<String> = Vec::new();
let mut paramReference: Vec<String> = Vec::new();
for v in params{
match v {
Val::RefMut(s) => {
if paramReferenceMutable.contains(s) {
panic!("[BorrowCheck] Error cannot borrow mutably {:?} more than once",s);
}
if paramReference.contains(s) {
panic!("[BorrowCheck] Error cannot borrow {:?} as immutable because its also borrowed as mutable",s);
}
paramReferenceMutable.push(s.to_string());
},
Val::Ref(s) => {
if paramReferenceMutable.contains(s) {
panic!("[BorrowCheck] Error cannot borrow {:?} as immutable because its also borrowed as mutable",s);
}
paramReference.push(s.to_string());
}
_ => {}
}
}
let id: &Vec<(bool, String)> = &decl.params.0.iter().
map(|param| (param.mutable, param.name.to_owned())).collect();
let raw_params: Vec<(&(bool, String), &Val)> = id.iter().zip(params).collect();
let vars: HashMap<String, (bool, Val, usize)> = raw_params.into_iter().map(|(s,v )| (s.1.clone(), (s.0, v.clone(), 0))).collect();
println!("[Func] Converted params into variables: {:?}", &vars);
m.push_param_scope(vars);
let ret_val = eval_stmts(&decl.body, m, fn_env);
println!("[Func] Function {:?} returned as {:?} and containing the memory \n\t{:?}", name, ret_val, m);
m.pop_scope();
ret_val
} else {
panic!("[Func] Error function named {:?} not found.");
}
}
// END OF EVALUATING FUNCTIONS
fn main() {
let mut m = Mem::new();
let program = &ProgramParser::new().parse(r#"
fn main() {
let mut a = 3;
let b = &mut a;
while *b <= 3 {
*b = add(*b, 1);
}
let d = *b / 3;
}
fn add(a:i32, b:i32) -> i32 {
a+b
}
"#).unwrap();
let fn_env = progam_to_env(program);
let args: Vec<Val> = Vec::new();
println!("{:?}", eval_fn("main", &args, &mut m, &fn_env));
}
#[test]
fn borrow_test_scope(){
let mut m = Mem::new();
let program = &ProgramParser::new().parse(r#"
fn main() {
let borrowed;
if true {
let if_scope = 1;
borrowed = &if_scope;
}
let another_scope = *borrowed; // <-- Error the owners scope is gone
}
"#).unwrap();
let fn_env = progam_to_env(program);
let args: Vec<Val> = Vec::new();
println!("{:?}", eval_fn("main", &args, &mut m, &fn_env));
}
#[test]
fn borrow_test_refchanged(){
let mut m = Mem::new();
let program = &ProgramParser::new().parse(r#"
fn main() {
let mut a = 1;
let mut b = 2;
let mut c = &mut a;
c = &mut b; // first reference to a is dropped in the stack since we changed what 'borrowed' reference to
}
"#).unwrap();
let fn_env = progam_to_env(program);
let args: Vec<Val> = Vec::new();
println!("{:?}", eval_fn("main", &args, &mut m, &fn_env));
}
#[test]
fn borrow_test_mut(){
let mut m = Mem::new();
let program = &ProgramParser::new().parse(r#"
fn main() {
let mut a = 0;
let a1 = &mut a;
*a1 = *a1 + 10;
}
"#).unwrap();
let fn_env = progam_to_env(program);
let args: Vec<Val> = Vec::new();
println!("{:?}", eval_fn("main", &args, &mut m, &fn_env));
}
#[test]
fn borrow_test_func(){
let mut m = Mem::new();
let program = &ProgramParser::new().parse(r#"
fn f(i:&i32, j:&mut i32) -> i32 {
}
fn main() {
let mut a = 0;
let b = &mut a;
let c = &a;
let x = f(b, c);
}
"#).unwrap();
let fn_env = progam_to_env(program);
let args: Vec<Val> = Vec::new();
println!("{:?}", eval_fn("main", &args, &mut m, &fn_env));
} |
use std::fs;
use crate::poc::{BugMetadata, PocMap};
use crate::prelude::*;
use askama::Template;
use once_cell::sync::Lazy;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct UpdateArgs {}
enum LinkStyle {
Image { alt_text: String, image_url: String },
Text(String),
Plaintext,
}
struct MdLink {
style: LinkStyle,
url: String,
}
impl MdLink {
pub fn image(alt_text: impl ToString, image_url: impl ToString, url: impl ToString) -> Self {
MdLink {
style: LinkStyle::Image {
alt_text: alt_text.to_string(),
image_url: image_url.to_string(),
},
url: url.to_string(),
}
}
pub fn text(text: impl ToString, url: impl ToString) -> Self {
MdLink {
style: LinkStyle::Text(text.to_string()),
url: url.to_string(),
}
}
pub fn plaintext(url: impl ToString) -> Self {
MdLink {
style: LinkStyle::Plaintext,
url: url.to_string(),
}
}
}
impl std::fmt::Display for MdLink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.style {
LinkStyle::Image {
alt_text,
image_url,
} => write!(f, "[]({})", alt_text, image_url, self.url),
LinkStyle::Text(text) => write!(f, "[{}]({})", text, self.url),
LinkStyle::Plaintext => write!(f, "{}", self.url),
}
}
}
static GITHUB_ISSUE_PR_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"^https://github.com/(?P<user>[^/]+)/(?P<repo>[^/]+)/(?P<issue_or_pr>issues|pull)/(?P<number>\d+)$").unwrap()
});
static GITLAB_ISSUE_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"^https://gitlab.com/(?P<user>[^/]+)/(?P<repo>[^/]+)/-/issues/(?P<number>\d+)$")
.unwrap()
});
static GITLAB_REDOX_ISSUE_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r"^https://gitlab.redox-os.org/(?P<user>[^/]+)/(?P<repo>[^/]+)/-/issues/(?P<number>\d+)$",
)
.unwrap()
});
static ADVISORY_DB_PR_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"^https://github.com/RustSec/advisory-db/pull/(?P<pr_number>\d+)$").unwrap()
});
fn issue_link(url: &str) -> MdLink {
if let Some(captures) = GITHUB_ISSUE_PR_REGEX.captures(url) {
// GitHub
let user = captures.name("user").unwrap().as_str();
let repo = captures.name("repo").unwrap().as_str();
let issue_or_pr = captures.name("issue_or_pr").unwrap().as_str();
let number = captures.name("number").unwrap().as_str();
let label = format!("{}%2f{}%23{}", user, repo, number);
let image_url = format!(
"https://img.shields.io/github/{}/detail/state/{}/{}/{}?label={}&logo=GitHub&cacheSeconds=3600&style=flat-square",
if issue_or_pr == "pull" {
"pulls"
} else {
issue_or_pr
},
user,
repo,
number,
label
);
MdLink::image("GitHub issue or PR", image_url, url)
} else if let Some(captures) = GITLAB_ISSUE_REGEX
.captures(url)
.or_else(|| GITLAB_REDOX_ISSUE_REGEX.captures(url))
{
// GitLab
let user = captures.name("user").unwrap().as_str();
let repo = captures.name("repo").unwrap().as_str();
let number = captures.name("number").unwrap().as_str();
let label = format!(
"{}%2f{}%23{}",
user.replace("-", "--"),
repo.replace("-", "--"),
number
);
let image_url = format!(
"https://img.shields.io/badge/{}-grey?logo=GitLab&style=flat-square",
label
);
MdLink::image("GitLab issue", image_url, url)
} else {
MdLink::plaintext(url)
}
}
fn rustsec_id_link(rustsec_id: &str) -> MdLink {
MdLink::image(
rustsec_id,
format!(
"https://img.shields.io/badge/RUSTSEC-{}--{}-blue?style=flat-square",
&rustsec_id[8..12],
&rustsec_id[13..17]
),
format!("https://rustsec.org/advisories/{}.html", rustsec_id),
)
}
fn rustsec_url_link(rustsec_url: &str) -> MdLink {
match ADVISORY_DB_PR_REGEX.captures(rustsec_url) {
Some(captures) => {
let pr_number = captures.name("pr_number").unwrap().as_str();
MdLink::image(
"GitHub pull request detail",
format!(
"https://img.shields.io/github/pulls/detail/state/RustSec/advisory-db/{}?style=flat-square",
pr_number
),
rustsec_url,
)
}
None => MdLink::plaintext(rustsec_url),
}
}
#[derive(Template)]
#[template(path = "README.md")]
struct ReadmeTemplate {
lines: Vec<ReadmeTemplateLine>,
}
impl ReadmeTemplate {
pub fn new() -> Self {
ReadmeTemplate { lines: Vec::new() }
}
pub fn push(&mut self, line: ReadmeTemplateLine) {
self.lines.push(line);
}
}
struct ReadmeTemplateLine {
poc_id: MdLink,
krate: MdLink,
bugs: Vec<BugMetadata>,
issue_url: Option<MdLink>,
rustsec_link: Option<MdLink>,
}
mod filters {
use crate::poc::BugMetadata;
pub fn bug_join(vec: &Vec<BugMetadata>) -> askama::Result<String> {
let initials: Vec<_> = vec.iter().map(|bug_meta| bug_meta.initial()).collect();
Ok(initials.join(" / "))
}
pub fn unwrap_or(
s: &Option<impl ToString>,
default_value: &'static str,
) -> askama::Result<String> {
match s.as_ref() {
Some(s) => Ok(s.to_string()),
None => Ok(String::from(default_value)),
}
}
}
pub fn update_readme() -> Result<()> {
println!("Updating README.md...");
let poc_map = PocMap::new()?;
let mut readme_template = ReadmeTemplate::new();
for poc_id in poc_map.iter_ids() {
let metadata = poc_map.read_metadata(poc_id)?;
// 
let krate_name = &metadata.target.krate;
let krate = MdLink::text(
krate_name,
format!("https://crates.io/crates/{}", krate_name),
);
let bugs = metadata.bugs.clone();
let issue_url = metadata.report.issue_url.as_ref().map(|s| issue_link(s));
let rustsec_link = match (
metadata.report.rustsec_id.as_ref(),
metadata.report.rustsec_url.as_ref(),
) {
(Some(rustsec_id), Some(_)) => Some(rustsec_id_link(rustsec_id)),
(Some(_), None) => {
anyhow::bail!("Invalid PoC metadata in {}: Contains RUSTSEC ID without RUSTSEC URL")
}
(None, Some(rustsec_url)) => Some(rustsec_url_link(rustsec_url)),
_ => None,
};
let poc_path = poc_map
.get_path_to_poc_code(poc_id)?
.strip_prefix(&*PROJECT_PATH)?
.to_string_lossy()
.into_owned();
let line = ReadmeTemplateLine {
poc_id: MdLink::text(poc_id, poc_path),
krate,
bugs,
issue_url,
rustsec_link,
};
readme_template.push(line);
}
let readme_content = readme_template.render()?;
fs::write(PROJECT_PATH.join("README.md"), readme_content)?;
println!("Successfully updated README.md");
Ok(())
}
pub fn cmd_update(_args: UpdateArgs) -> Result<()> {
update_readme()?;
Ok(())
}
|
use std::env;
use std::process;
use std::fs::File;
use std::io::{self, BufRead};
fn main() -> Result<(), io::Error> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Too few arguments.");
process::exit(1);
}
let filename = &args[1];
let file = File::open(filename)?;
let mut lines = 0;
let mut words = 0;
let mut chars = 0;
for line in io::BufReader::new(file).lines() {
let l = line?;
lines += 1;
words += l.split(' ').count();
chars += l.chars().count();
}
println!("lines: {}", lines);
println!("words: {}", words);
println!("chars: {}", chars);
Ok(())
}
|
#![no_std]
#[macro_use]
extern crate alloc;
pub mod macros;
mod traits;
pub use traits::Hash;
|
#[doc = "Register `CCR` reader"]
pub type R = crate::R<CCR_SPEC>;
#[doc = "Register `CCR` writer"]
pub type W = crate::W<CCR_SPEC>;
#[doc = "Field `DUAL` reader - Dual ADC mode selection"]
pub type DUAL_R = crate::FieldReader<DUAL_A>;
#[doc = "Dual ADC mode selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum DUAL_A {
#[doc = "0: Independent mode"]
Independent = 0,
#[doc = "1: Dual, combined regular simultaneous + injected simultaneous mode"]
DualRj = 1,
#[doc = "2: Dual, combined regular simultaneous + alternate trigger mode"]
DualRa = 2,
#[doc = "3: Dual, combined interleaved mode + injected simultaneous mode"]
DualIj = 3,
#[doc = "5: Dual, injected simultaneous mode only"]
DualJ = 5,
#[doc = "6: Dual, regular simultaneous mode only"]
DualR = 6,
#[doc = "7: Dual, interleaved mode only"]
DualI = 7,
#[doc = "9: Dual, alternate trigger mode only"]
DualA = 9,
}
impl From<DUAL_A> for u8 {
#[inline(always)]
fn from(variant: DUAL_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for DUAL_A {
type Ux = u8;
}
impl DUAL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<DUAL_A> {
match self.bits {
0 => Some(DUAL_A::Independent),
1 => Some(DUAL_A::DualRj),
2 => Some(DUAL_A::DualRa),
3 => Some(DUAL_A::DualIj),
5 => Some(DUAL_A::DualJ),
6 => Some(DUAL_A::DualR),
7 => Some(DUAL_A::DualI),
9 => Some(DUAL_A::DualA),
_ => None,
}
}
#[doc = "Independent mode"]
#[inline(always)]
pub fn is_independent(&self) -> bool {
*self == DUAL_A::Independent
}
#[doc = "Dual, combined regular simultaneous + injected simultaneous mode"]
#[inline(always)]
pub fn is_dual_rj(&self) -> bool {
*self == DUAL_A::DualRj
}
#[doc = "Dual, combined regular simultaneous + alternate trigger mode"]
#[inline(always)]
pub fn is_dual_ra(&self) -> bool {
*self == DUAL_A::DualRa
}
#[doc = "Dual, combined interleaved mode + injected simultaneous mode"]
#[inline(always)]
pub fn is_dual_ij(&self) -> bool {
*self == DUAL_A::DualIj
}
#[doc = "Dual, injected simultaneous mode only"]
#[inline(always)]
pub fn is_dual_j(&self) -> bool {
*self == DUAL_A::DualJ
}
#[doc = "Dual, regular simultaneous mode only"]
#[inline(always)]
pub fn is_dual_r(&self) -> bool {
*self == DUAL_A::DualR
}
#[doc = "Dual, interleaved mode only"]
#[inline(always)]
pub fn is_dual_i(&self) -> bool {
*self == DUAL_A::DualI
}
#[doc = "Dual, alternate trigger mode only"]
#[inline(always)]
pub fn is_dual_a(&self) -> bool {
*self == DUAL_A::DualA
}
}
#[doc = "Field `DUAL` writer - Dual ADC mode selection"]
pub type DUAL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O, DUAL_A>;
impl<'a, REG, const O: u8> DUAL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Independent mode"]
#[inline(always)]
pub fn independent(self) -> &'a mut crate::W<REG> {
self.variant(DUAL_A::Independent)
}
#[doc = "Dual, combined regular simultaneous + injected simultaneous mode"]
#[inline(always)]
pub fn dual_rj(self) -> &'a mut crate::W<REG> {
self.variant(DUAL_A::DualRj)
}
#[doc = "Dual, combined regular simultaneous + alternate trigger mode"]
#[inline(always)]
pub fn dual_ra(self) -> &'a mut crate::W<REG> {
self.variant(DUAL_A::DualRa)
}
#[doc = "Dual, combined interleaved mode + injected simultaneous mode"]
#[inline(always)]
pub fn dual_ij(self) -> &'a mut crate::W<REG> {
self.variant(DUAL_A::DualIj)
}
#[doc = "Dual, injected simultaneous mode only"]
#[inline(always)]
pub fn dual_j(self) -> &'a mut crate::W<REG> {
self.variant(DUAL_A::DualJ)
}
#[doc = "Dual, regular simultaneous mode only"]
#[inline(always)]
pub fn dual_r(self) -> &'a mut crate::W<REG> {
self.variant(DUAL_A::DualR)
}
#[doc = "Dual, interleaved mode only"]
#[inline(always)]
pub fn dual_i(self) -> &'a mut crate::W<REG> {
self.variant(DUAL_A::DualI)
}
#[doc = "Dual, alternate trigger mode only"]
#[inline(always)]
pub fn dual_a(self) -> &'a mut crate::W<REG> {
self.variant(DUAL_A::DualA)
}
}
#[doc = "Field `DELAY` reader - Delay between 2 sampling phases"]
pub type DELAY_R = crate::FieldReader;
#[doc = "Field `DELAY` writer - Delay between 2 sampling phases"]
pub type DELAY_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O>;
#[doc = "Field `DMACFG` reader - DMA configuration (for multi-ADC mode)"]
pub type DMACFG_R = crate::BitReader;
#[doc = "Field `DMACFG` writer - DMA configuration (for multi-ADC mode)"]
pub type DMACFG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MDMA` reader - Direct memory access mode for multi ADC mode"]
pub type MDMA_R = crate::FieldReader;
#[doc = "Field `MDMA` writer - Direct memory access mode for multi ADC mode"]
pub type MDMA_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `CKMODE` reader - ADC clock mode"]
pub type CKMODE_R = crate::FieldReader<CKMODE_A>;
#[doc = "ADC clock mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum CKMODE_A {
#[doc = "0: Use Kernel Clock adc_ker_ck_input divided by PRESC. Asynchronous to AHB clock"]
Asynchronous = 0,
#[doc = "1: Use AHB clock rcc_hclk3. In this case rcc_hclk must equal sys_d1cpre_ck"]
SyncDiv1 = 1,
#[doc = "2: Use AHB clock rcc_hclk3 divided by 2"]
SyncDiv2 = 2,
#[doc = "3: Use AHB clock rcc_hclk3 divided by 4"]
SyncDiv4 = 3,
}
impl From<CKMODE_A> for u8 {
#[inline(always)]
fn from(variant: CKMODE_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for CKMODE_A {
type Ux = u8;
}
impl CKMODE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CKMODE_A {
match self.bits {
0 => CKMODE_A::Asynchronous,
1 => CKMODE_A::SyncDiv1,
2 => CKMODE_A::SyncDiv2,
3 => CKMODE_A::SyncDiv4,
_ => unreachable!(),
}
}
#[doc = "Use Kernel Clock adc_ker_ck_input divided by PRESC. Asynchronous to AHB clock"]
#[inline(always)]
pub fn is_asynchronous(&self) -> bool {
*self == CKMODE_A::Asynchronous
}
#[doc = "Use AHB clock rcc_hclk3. In this case rcc_hclk must equal sys_d1cpre_ck"]
#[inline(always)]
pub fn is_sync_div1(&self) -> bool {
*self == CKMODE_A::SyncDiv1
}
#[doc = "Use AHB clock rcc_hclk3 divided by 2"]
#[inline(always)]
pub fn is_sync_div2(&self) -> bool {
*self == CKMODE_A::SyncDiv2
}
#[doc = "Use AHB clock rcc_hclk3 divided by 4"]
#[inline(always)]
pub fn is_sync_div4(&self) -> bool {
*self == CKMODE_A::SyncDiv4
}
}
#[doc = "Field `CKMODE` writer - ADC clock mode"]
pub type CKMODE_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, CKMODE_A>;
impl<'a, REG, const O: u8> CKMODE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Use Kernel Clock adc_ker_ck_input divided by PRESC. Asynchronous to AHB clock"]
#[inline(always)]
pub fn asynchronous(self) -> &'a mut crate::W<REG> {
self.variant(CKMODE_A::Asynchronous)
}
#[doc = "Use AHB clock rcc_hclk3. In this case rcc_hclk must equal sys_d1cpre_ck"]
#[inline(always)]
pub fn sync_div1(self) -> &'a mut crate::W<REG> {
self.variant(CKMODE_A::SyncDiv1)
}
#[doc = "Use AHB clock rcc_hclk3 divided by 2"]
#[inline(always)]
pub fn sync_div2(self) -> &'a mut crate::W<REG> {
self.variant(CKMODE_A::SyncDiv2)
}
#[doc = "Use AHB clock rcc_hclk3 divided by 4"]
#[inline(always)]
pub fn sync_div4(self) -> &'a mut crate::W<REG> {
self.variant(CKMODE_A::SyncDiv4)
}
}
#[doc = "Field `PRESC` reader - ADC prescaler"]
pub type PRESC_R = crate::FieldReader;
#[doc = "Field `PRESC` writer - ADC prescaler"]
pub type PRESC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `VREFEN` reader - VREFINT enable"]
pub type VREFEN_R = crate::BitReader<VREFEN_A>;
#[doc = "VREFINT enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VREFEN_A {
#[doc = "0: V_REFINT channel disabled"]
Disabled = 0,
#[doc = "1: V_REFINT channel enabled"]
Enabled = 1,
}
impl From<VREFEN_A> for bool {
#[inline(always)]
fn from(variant: VREFEN_A) -> Self {
variant as u8 != 0
}
}
impl VREFEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VREFEN_A {
match self.bits {
false => VREFEN_A::Disabled,
true => VREFEN_A::Enabled,
}
}
#[doc = "V_REFINT channel disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == VREFEN_A::Disabled
}
#[doc = "V_REFINT channel enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == VREFEN_A::Enabled
}
}
#[doc = "Field `VREFEN` writer - VREFINT enable"]
pub type VREFEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, VREFEN_A>;
impl<'a, REG, const O: u8> VREFEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "V_REFINT channel disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(VREFEN_A::Disabled)
}
#[doc = "V_REFINT channel enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(VREFEN_A::Enabled)
}
}
#[doc = "Field `VSENSESEL` reader - VTS selection"]
pub type VSENSESEL_R = crate::BitReader<VSENSESEL_A>;
#[doc = "VTS selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VSENSESEL_A {
#[doc = "0: Temperature sensor channel disabled"]
Disabled = 0,
#[doc = "1: Temperature sensor channel enabled"]
Enabled = 1,
}
impl From<VSENSESEL_A> for bool {
#[inline(always)]
fn from(variant: VSENSESEL_A) -> Self {
variant as u8 != 0
}
}
impl VSENSESEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VSENSESEL_A {
match self.bits {
false => VSENSESEL_A::Disabled,
true => VSENSESEL_A::Enabled,
}
}
#[doc = "Temperature sensor channel disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == VSENSESEL_A::Disabled
}
#[doc = "Temperature sensor channel enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == VSENSESEL_A::Enabled
}
}
#[doc = "Field `VSENSESEL` writer - VTS selection"]
pub type VSENSESEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, VSENSESEL_A>;
impl<'a, REG, const O: u8> VSENSESEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Temperature sensor channel disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(VSENSESEL_A::Disabled)
}
#[doc = "Temperature sensor channel enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(VSENSESEL_A::Enabled)
}
}
#[doc = "Field `VBATSEL` reader - VBAT selection"]
pub type VBATSEL_R = crate::BitReader<VBATSEL_A>;
#[doc = "VBAT selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VBATSEL_A {
#[doc = "0: V_BAT channel disabled"]
Disabled = 0,
#[doc = "1: V_BAT channel enabled"]
Enabled = 1,
}
impl From<VBATSEL_A> for bool {
#[inline(always)]
fn from(variant: VBATSEL_A) -> Self {
variant as u8 != 0
}
}
impl VBATSEL_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VBATSEL_A {
match self.bits {
false => VBATSEL_A::Disabled,
true => VBATSEL_A::Enabled,
}
}
#[doc = "V_BAT channel disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == VBATSEL_A::Disabled
}
#[doc = "V_BAT channel enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == VBATSEL_A::Enabled
}
}
#[doc = "Field `VBATSEL` writer - VBAT selection"]
pub type VBATSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, VBATSEL_A>;
impl<'a, REG, const O: u8> VBATSEL_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "V_BAT channel disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(VBATSEL_A::Disabled)
}
#[doc = "V_BAT channel enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(VBATSEL_A::Enabled)
}
}
impl R {
#[doc = "Bits 0:4 - Dual ADC mode selection"]
#[inline(always)]
pub fn dual(&self) -> DUAL_R {
DUAL_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bits 8:11 - Delay between 2 sampling phases"]
#[inline(always)]
pub fn delay(&self) -> DELAY_R {
DELAY_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bit 13 - DMA configuration (for multi-ADC mode)"]
#[inline(always)]
pub fn dmacfg(&self) -> DMACFG_R {
DMACFG_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bits 14:15 - Direct memory access mode for multi ADC mode"]
#[inline(always)]
pub fn mdma(&self) -> MDMA_R {
MDMA_R::new(((self.bits >> 14) & 3) as u8)
}
#[doc = "Bits 16:17 - ADC clock mode"]
#[inline(always)]
pub fn ckmode(&self) -> CKMODE_R {
CKMODE_R::new(((self.bits >> 16) & 3) as u8)
}
#[doc = "Bits 18:21 - ADC prescaler"]
#[inline(always)]
pub fn presc(&self) -> PRESC_R {
PRESC_R::new(((self.bits >> 18) & 0x0f) as u8)
}
#[doc = "Bit 22 - VREFINT enable"]
#[inline(always)]
pub fn vrefen(&self) -> VREFEN_R {
VREFEN_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - VTS selection"]
#[inline(always)]
pub fn vsensesel(&self) -> VSENSESEL_R {
VSENSESEL_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - VBAT selection"]
#[inline(always)]
pub fn vbatsel(&self) -> VBATSEL_R {
VBATSEL_R::new(((self.bits >> 24) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:4 - Dual ADC mode selection"]
#[inline(always)]
#[must_use]
pub fn dual(&mut self) -> DUAL_W<CCR_SPEC, 0> {
DUAL_W::new(self)
}
#[doc = "Bits 8:11 - Delay between 2 sampling phases"]
#[inline(always)]
#[must_use]
pub fn delay(&mut self) -> DELAY_W<CCR_SPEC, 8> {
DELAY_W::new(self)
}
#[doc = "Bit 13 - DMA configuration (for multi-ADC mode)"]
#[inline(always)]
#[must_use]
pub fn dmacfg(&mut self) -> DMACFG_W<CCR_SPEC, 13> {
DMACFG_W::new(self)
}
#[doc = "Bits 14:15 - Direct memory access mode for multi ADC mode"]
#[inline(always)]
#[must_use]
pub fn mdma(&mut self) -> MDMA_W<CCR_SPEC, 14> {
MDMA_W::new(self)
}
#[doc = "Bits 16:17 - ADC clock mode"]
#[inline(always)]
#[must_use]
pub fn ckmode(&mut self) -> CKMODE_W<CCR_SPEC, 16> {
CKMODE_W::new(self)
}
#[doc = "Bits 18:21 - ADC prescaler"]
#[inline(always)]
#[must_use]
pub fn presc(&mut self) -> PRESC_W<CCR_SPEC, 18> {
PRESC_W::new(self)
}
#[doc = "Bit 22 - VREFINT enable"]
#[inline(always)]
#[must_use]
pub fn vrefen(&mut self) -> VREFEN_W<CCR_SPEC, 22> {
VREFEN_W::new(self)
}
#[doc = "Bit 23 - VTS selection"]
#[inline(always)]
#[must_use]
pub fn vsensesel(&mut self) -> VSENSESEL_W<CCR_SPEC, 23> {
VSENSESEL_W::new(self)
}
#[doc = "Bit 24 - VBAT selection"]
#[inline(always)]
#[must_use]
pub fn vbatsel(&mut self) -> VBATSEL_W<CCR_SPEC, 24> {
VBATSEL_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "ADC common control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CCR_SPEC;
impl crate::RegisterSpec for CCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ccr::R`](R) reader structure"]
impl crate::Readable for CCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ccr::W`](W) writer structure"]
impl crate::Writable for CCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CCR to value 0"]
impl crate::Resettable for CCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use futures::{future, Future};
use hyper::header::{HeaderName, HeaderValue};
use hyper::service::service_fn;
use hyper::{Body, Request, Response, Server};
use hyper::{Method, StatusCode};
use lazy_static::lazy_static;
use maplit::btreemap;
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
lazy_static! {
static ref MIME_BY_EXTENSION: BTreeMap<String, String> = {
let owned_version = btreemap![
"css" => "text/css",
"html" => "text/html",
"js" => "text/javascript",
"wasm" => "application/wasm",
"woff2" => "font/woff2"
];
owned_version
.iter()
.map(|(key, val)| (String::from(*key), String::from(*val)))
.collect()
};
}
// Just a simple type alias
type BoxFut = Box<dyn Future<Item = Response<Body>, Error = hyper::Error> + Send>;
fn poor_mans_static_server(req: Request<Body>, folder: &str) -> BoxFut {
let mut response = Response::new(Body::empty());
match (req.method(), req.uri().path()) {
(&Method::GET, path) => {
// first, we serve static files
let fs_path = match path {
"" | "/" => format!("{}/index.html", folder),
_ => {
if !path.contains('.') {
format!("{}{}/index.html", folder, path)
} else if path.ends_with('/') {
format!("{}{}index.html", folder, path)
} else {
format!("{}{}", folder, path)
}
}
};
if fs_path.contains("../") {
*response.status_mut() = StatusCode::NOT_FOUND;
println!("[404] {}", fs_path);
return Box::new(future::ok(response));
}
let fallback = format!("{}/404.html", folder);
let as_path = if Path::new(&fs_path).is_file() {
Path::new(&fs_path)
} else {
Path::new(&fallback)
};
if as_path.is_file() {
let text = vec![std::fs::read(as_path).unwrap()];
if let Some(extension) = as_path.extension() {
if let Some(non_html_mime) = MIME_BY_EXTENSION.get(extension.to_str().unwrap())
{
(*response.headers_mut()).insert(
HeaderName::from_static("content-type"),
HeaderValue::from_static(non_html_mime),
);
};
} else {
eprintln!("Content type unset for {:?}", as_path);
}
*response.body_mut() =
Body::wrap_stream(futures::stream::iter_ok::<_, ::std::io::Error>(text));
} else {
*response.status_mut() = StatusCode::NOT_FOUND;
}
}
_ => {
*response.status_mut() = StatusCode::NOT_FOUND;
}
};
println!(
"[{:?} {:?}] {}",
response.version(),
response.status(),
req.uri().path()
);
Box::new(future::ok(response))
}
fn main() {
let first_arg = std::env::args()
.nth(1)
.unwrap_or_else(|| String::from("3000"));
if first_arg == "--help" || first_arg == "-h" {
println!("se - Serve a static folder");
println!();
println!("Usage:");
println!(" se <port> <folder>");
return;
}
let port = first_arg.parse::<u16>().unwrap_or(3000);
let folder_arg = match first_arg.parse::<u16>() {
Ok(_) => 2,
Err(_) => 1,
};
let folder = std::env::args()
.nth(folder_arg)
.unwrap_or_else(|| String::from("."));
let folder_arc = Arc::new(folder.clone());
let server = Server::bind(&([127, 0, 0, 1], port).into())
.serve(move || {
let inner = Arc::clone(&folder_arc);
service_fn(move |req| poor_mans_static_server(req, &inner))
})
.map_err(|e| eprintln!("server error: {}", e));
println!("Serving folder \"{}\" at http://localhost:{}", folder, port);
hyper::rt::run(server)
}
|
// https://adventofcode.com/2017/day/19
extern crate regex;
use std::io::{BufRead, BufReader};
use std::fs::File;
use std::collections::HashSet;
use std::iter::FromIterator;
use regex::Regex;
fn main() {
// Set up regex for matching the different vectors, concat! as raws don't support multiline
let particle_reg = Regex::new(concat!(
r"p=<(\D*\d+),(\D*\d+),(\D*\d+)>, ",
r"v=<(\D*\d+),(\D*\d+),(\D*\d+)>, ",
r"a=<(\D*\d+),(\D*\d+),(\D*\d+)>"
)).unwrap();
let f = BufReader::new(File::open("input.txt").expect("Opening input.txt failed"));
// Parse input
let mut particles = Vec::new();
for line in f.lines() {
let raw_line = line.expect("");
let vec_caps = particle_reg
.captures_iter(&raw_line)
.nth(0)
.expect("Invalid particle") // Get first and only match of the regex
.iter()
.skip(1) // Skip first element as it holds the entire match
.map(|i| i.unwrap().as_str().parse::<i32>().unwrap()) // Parse subsequent matches to i32
.collect::<Vec<i32>>();
// Push pos, vel, acc, alive for particle
particles.push((
[vec_caps[0], vec_caps[1], vec_caps[2]],
[vec_caps[3], vec_caps[4], vec_caps[5]],
[vec_caps[6], vec_caps[7], vec_caps[8]],
));
}
// Simulate system until all particles are accelerating away from origin and
// no recent collisions have happened
let mut some_decelerating = true;
let mut some_closing_in = true;
let mut last_collision = 0;
let mut alive: HashSet<usize> = HashSet::from_iter(0..particles.len());
while some_decelerating || some_closing_in || last_collision < 20 {
some_decelerating = false;
some_closing_in = false;
last_collision += 1;
// Simulate
for &i in &alive {
let p = &mut particles[i];
let old_vel = p.1.clone();
let old_pos = p.0.clone();
p.1 = sum3(&p.1, &p.2);
p.0 = sum3(&p.0, &p.1);
if mlen(&old_vel) > mlen(&p.1) {
some_decelerating = true;
}
if mlen(&old_pos) > mlen(&p.0) {
some_closing_in = true;
}
}
// Handle collisions
let mut new_alive = alive.clone();
for &i in &alive {
for &j in &alive {
if i != j {
if particles[i].0 == particles[j].0 {
new_alive.remove(&i);
new_alive.remove(&j);
last_collision = 0;
}
}
}
}
if last_collision == 0 {
alive = new_alive;
}
}
// Get particle with smallest acceleration (smallest speed, closest to origin if multiple)
// This might not be strictly correct (should probably compare manhattan distance changing
// speed as velocity and increase of that as acceleration), but it already worked ":D"
let mut closest = (0, std::u32::MAX, std::u32::MAX, std::u32::MAX);
for (i, p) in particles.iter().enumerate() {
let pos = mlen(&p.0);
let vel = mlen(&p.1);
let acc = mlen(&p.2);
if acc < closest.3 {
closest = (i, pos, vel, acc);
} else if acc == closest.3 {
if vel < closest.2 {
closest = (i, pos, vel, acc);
} else if vel == closest.2 {
if pos < closest.1 {
closest = (i, pos, vel, acc);
}
}
}
}
// Assert to facilitate further tweaks
assert_eq!(170, closest.0);
assert_eq!(571, alive.len());
println!("Particle {} will stay closest", closest.0);
println!("{} particles remain", alive.len());
}
fn sum3(a: &[i32; 3], b: &[i32; 3]) -> [i32; 3] {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
fn mlen(v: &[i32; 3]) -> u32 {
v.iter().fold(0u32, |acc, &c| acc + c.abs() as u32)
}
|
use crate::common::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
struct Solution;
impl Solution {
pub fn build_tree(inorder: Vec<i32>, mut postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
if inorder.is_empty() {
return None;
}
// 每个元素的下标,元素没有重复的,所以可以这样。
let idx_map: HashMap<i32, usize> = inorder
.iter()
.enumerate()
.map(|(idx, ele)| (*ele, idx))
.collect();
Self::helper(0, inorder.len() - 1, &mut postorder, &idx_map)
}
fn helper(
inorder_left: usize,
inorder_right: usize,
postorder: &mut Vec<i32>,
idx_map: &HashMap<i32, usize>,
) -> Option<Rc<RefCell<TreeNode>>> {
// 没有剩余的节点了
if inorder_left > inorder_right {
return None;
}
// 后序遍历的最后一个元素就是当前子树的根节点
if let Some(root_value) = postorder.pop() {
let mut root = TreeNode::new(root_value);
// 根在中序遍历中的位置
if let Some(inorder_root_idx) = idx_map.get(&root_value) {
root.right = Self::helper(inorder_root_idx + 1, inorder_right, postorder, idx_map);
if *inorder_root_idx > 0 {
root.left =
Self::helper(inorder_left, inorder_root_idx - 1, postorder, idx_map);
}
}
return Some(Rc::new(RefCell::new(root)));
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::tree_node;
#[test]
fn test_build_tree() {
let ans = Solution::build_tree(vec![9, 3, 15, 20, 7], vec![9, 15, 7, 20, 3]);
let want = tree_node(TreeNode {
val: 3,
left: tree_node(TreeNode::new(9)),
right: tree_node(TreeNode {
val: 20,
left: tree_node(TreeNode::new(15)),
right: tree_node(TreeNode::new(7)),
}),
});
assert_eq!(ans, want);
}
}
|
use std::fs;
use std::collections::HashSet;
use std::iter::FromIterator;
fn parse(content: &String) -> Vec<HashSet<char>> {
let mut vec: Vec<HashSet<char>> = Vec::new();
let groups_it = content
.split("\n\n");
for group in groups_it {
let mut ans: HashSet<char> = HashSet::new();
let merged = group.replace("\n", "");
for c in merged.chars() {
ans.insert(c);
}
vec.push(ans);
}
vec
}
fn parse2(content: &String) -> Vec<HashSet<char>> {
let mut vec: Vec<HashSet<char>> = Vec::new();
let groups_it = content
.split("\n\n");
for group in groups_it {
let mut ans: HashSet<char> = HashSet::from_iter("abcdefghijklmnopqrstuvwxyz".chars());
for person in group.lines() {
ans = ans.intersection(&HashSet::from_iter(person.chars())).copied().collect();
}
vec.push(ans);
}
vec
}
fn main() {
let contents = fs::read_to_string("input.txt")
.expect("error loading file");
let answers = parse(&contents);
let answers2 = parse2(&contents);
// part 1
let result1 = answers.iter().fold(0, |acc, x| acc + x.len());
println!("result1 = {}", result1);
// part 2
let result2 = answers2.iter().fold(0, |acc, x| acc + x.len());
println!("result2 = {}", result2);
} |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
//! Custom panic hook with bug report link
//!
//! This crate provides the [`set`] function, which wraps around [`std::panic::set_hook`] and
//! sets up a panic hook that prints a backtrace and invites the user to open an issue to the
//! given URL.
//!
//! By default, the panic handler aborts the process by calling [`std::process::exit`]. This can
//! temporarily be disabled by using an [`AbortGuard`].
use backtrace::Backtrace;
use std::cell::Cell;
use std::io::{self, Write};
use std::marker::PhantomData;
use std::panic::{self, PanicInfo};
use std::thread;
thread_local! {
static ON_PANIC: Cell<OnPanic> = Cell::new(OnPanic::Abort);
}
/// Panic action.
#[derive(Debug, Clone, Copy, PartialEq)]
enum OnPanic {
/// Abort when panic occurs.
Abort,
/// Unwind when panic occurs.
Unwind,
/// Always unwind even if someone changes strategy to Abort afterwards.
NeverAbort,
}
/// Set the panic hook.
///
/// Calls [`std::panic::set_hook`] to set up the panic hook.
///
/// The `bug_url` parameter is an invitation for users to visit that URL to submit a bug report
/// in the case where a panic happens.
pub fn set(bug_url: &str, version: &str) {
panic::set_hook(Box::new({
let version = version.to_string();
let bug_url = bug_url.to_string();
move |c| panic_hook(c, &bug_url, &version)
}));
}
macro_rules! ABOUT_PANIC {
() => {
"
This is a bug. Please report it at:
{}
"
};
}
/// Set aborting flag. Returns previous value of the flag.
fn set_abort(on_panic: OnPanic) -> OnPanic {
ON_PANIC.with(|val| {
let prev = val.get();
match prev {
OnPanic::Abort | OnPanic::Unwind => val.set(on_panic),
OnPanic::NeverAbort => (),
}
prev
})
}
/// RAII guard for whether panics in the current thread should unwind or abort.
///
/// Sets a thread-local abort flag on construction and reverts to the previous setting when dropped.
/// Does not implement `Send` on purpose.
///
/// > **Note**: Because we restore the previous value when dropped, you are encouraged to leave
/// > the `AbortGuard` on the stack and let it destroy itself naturally.
pub struct AbortGuard {
/// Value that was in `ABORT` before we created this guard.
previous_val: OnPanic,
/// Marker so that `AbortGuard` doesn't implement `Send`.
_not_send: PhantomData<std::rc::Rc<()>>,
}
impl AbortGuard {
/// Create a new guard. While the guard is alive, panics that happen in the current thread will
/// unwind the stack (unless another guard is created afterwards).
pub fn force_unwind() -> AbortGuard {
AbortGuard { previous_val: set_abort(OnPanic::Unwind), _not_send: PhantomData }
}
/// Create a new guard. While the guard is alive, panics that happen in the current thread will
/// abort the process (unless another guard is created afterwards).
pub fn force_abort() -> AbortGuard {
AbortGuard { previous_val: set_abort(OnPanic::Abort), _not_send: PhantomData }
}
/// Create a new guard. While the guard is alive, panics that happen in the current thread will
/// **never** abort the process (even if `AbortGuard::force_abort()` guard will be created
/// afterwards).
pub fn never_abort() -> AbortGuard {
AbortGuard { previous_val: set_abort(OnPanic::NeverAbort), _not_send: PhantomData }
}
}
impl Drop for AbortGuard {
fn drop(&mut self) {
set_abort(self.previous_val);
}
}
/// Function being called when a panic happens.
fn panic_hook(info: &PanicInfo, report_url: &str, version: &str) {
let location = info.location();
let file = location.as_ref().map(|l| l.file()).unwrap_or("<unknown>");
let line = location.as_ref().map(|l| l.line()).unwrap_or(0);
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => match info.payload().downcast_ref::<String>() {
Some(s) => &s[..],
None => "Box<Any>",
},
};
let thread = thread::current();
let name = thread.name().unwrap_or("<unnamed>");
let backtrace = Backtrace::new();
let mut stderr = io::stderr();
let _ = writeln!(stderr, "");
let _ = writeln!(stderr, "====================");
let _ = writeln!(stderr, "");
let _ = writeln!(stderr, "Version: {}", version);
let _ = writeln!(stderr, "");
let _ = writeln!(stderr, "{:?}", backtrace);
let _ = writeln!(stderr, "");
let _ = writeln!(stderr, "Thread '{}' panicked at '{}', {}:{}", name, msg, file, line);
let _ = writeln!(stderr, ABOUT_PANIC!(), report_url);
ON_PANIC.with(|val| {
if val.get() == OnPanic::Abort {
::std::process::exit(1);
}
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn does_not_abort() {
set("test", "1.2.3");
let _guard = AbortGuard::force_unwind();
::std::panic::catch_unwind(|| panic!()).ok();
}
#[test]
fn does_not_abort_after_never_abort() {
set("test", "1.2.3");
let _guard = AbortGuard::never_abort();
let _guard = AbortGuard::force_abort();
std::panic::catch_unwind(|| panic!()).ok();
}
}
|
use crate::{
constants::{K256, K512},
util::{load_u32_be, load_u64_be, memcpy, memset, store_u128_be, store_u32_be, store_u64_be},
};
use core::mem;
macro_rules! sha {
(
$name:ident,
$word:ty,
$load_word:ident,
$store_word:ident,
$k:ident,
$length:ty,
$store_length:ident,
$bsig0:tt,
$bsig1:tt,
$ssig0:tt,
$ssig1:tt
) => {
#[derive(Clone)]
pub(crate) struct $name {
state: [$word; 8],
buffer: [u8; 16 * mem::size_of::<$word>()],
offset: usize,
length: $length,
}
impl $name {
/// The internal block size of the hash function.
pub(crate) const BLOCK_SIZE: usize = 16 * Self::WORD_SIZE;
const DIGEST_SIZE: usize = 8 * Self::WORD_SIZE;
const LENGTH_OFFSET: usize = Self::BLOCK_SIZE - Self::LENGTH_SIZE;
const LENGTH_SIZE: usize = mem::size_of::<$length>();
const WORD_SIZE: usize = mem::size_of::<$word>();
/// Construct a new instance.
pub(crate) const fn new(state: [$word; 8]) -> Self {
Self {
state,
buffer: [0; Self::BLOCK_SIZE],
offset: 0,
length: 0,
}
}
/// Add input data to the hash context.
pub(crate) const fn update(&mut self, input: &[u8]) {
let offset = self.offset;
let needed = Self::BLOCK_SIZE - offset;
if needed > input.len() {
memcpy(&mut self.buffer, offset, input, 0, input.len());
self.offset += input.len();
} else {
memcpy(&mut self.buffer, offset, input, 0, needed);
Self::compress(&mut self.state, &self.buffer, 0);
let mut i = needed;
loop {
let remain = input.len() - i;
if remain < Self::BLOCK_SIZE {
memcpy(&mut self.buffer, 0, input, i, remain);
self.offset = remain;
break;
}
Self::compress(&mut self.state, input, i);
i += Self::BLOCK_SIZE;
}
}
self.length += (input.len() as $length) * 8;
}
pub(crate) const fn finalize(mut self) -> [u8; Self::DIGEST_SIZE] {
let mut offset = self.offset;
self.buffer[offset] = 0x80;
offset += 1;
if offset > Self::LENGTH_OFFSET {
memset(&mut self.buffer, offset, 0, Self::BLOCK_SIZE - offset);
Self::compress(&mut self.state, &self.buffer, 0);
offset = 0;
}
memset(&mut self.buffer, offset, 0, Self::LENGTH_OFFSET - offset);
$store_length(&mut self.buffer, Self::LENGTH_OFFSET, self.length);
Self::compress(&mut self.state, &self.buffer, 0);
let mut digest = [0; Self::DIGEST_SIZE];
let mut i = 0;
while i < self.state.len() {
$store_word(&mut digest, i * Self::WORD_SIZE, self.state[i]);
i += 1
}
digest
}
/// SHA compression function.
///
/// This function takes an `offset` because subslices are not supported in
/// `const fn`.
const fn compress(state: &mut [$word; 8], buffer: &[u8], offset: usize) {
#[inline(always)]
const fn ch(x: $word, y: $word, z: $word) -> $word {
(x & y) ^ ((!x) & z)
}
#[inline(always)]
const fn maj(x: $word, y: $word, z: $word) -> $word {
(x & y) ^ (x & z) ^ (y & z)
}
#[inline(always)]
const fn big_sigma0(x: $word) -> $word {
x.rotate_right($bsig0.0) ^ x.rotate_right($bsig0.1) ^ x.rotate_right($bsig0.2)
}
#[inline(always)]
const fn big_sigma1(x: $word) -> $word {
x.rotate_right($bsig1.0) ^ x.rotate_right($bsig1.1) ^ x.rotate_right($bsig1.2)
}
#[inline(always)]
const fn sigma0(x: $word) -> $word {
x.rotate_right($ssig0.0) ^ x.rotate_right($ssig0.1) ^ (x >> $ssig0.2)
}
#[inline(always)]
const fn sigma1(x: $word) -> $word {
x.rotate_right($ssig1.0) ^ x.rotate_right($ssig1.1) ^ (x >> $ssig1.2)
}
let mut w: [$word; $k.len()] = [0; $k.len()];
let mut i = 0;
while i < 16 {
w[i] = $load_word(buffer, offset + i * mem::size_of::<$word>());
i += 1;
}
while i < $k.len() {
w[i] = sigma1(w[i - 2])
.wrapping_add(w[i - 7])
.wrapping_add(sigma0(w[i - 15]))
.wrapping_add(w[i - 16]);
i += 1;
}
let mut a = state[0];
let mut b = state[1];
let mut c = state[2];
let mut d = state[3];
let mut e = state[4];
let mut f = state[5];
let mut g = state[6];
let mut h = state[7];
let mut i = 0;
while i < $k.len() {
let t1 = h
.wrapping_add(big_sigma1(e))
.wrapping_add(ch(e, f, g))
.wrapping_add($k[i])
.wrapping_add(w[i]);
let t2 = big_sigma0(a).wrapping_add(maj(a, b, c));
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
i += 1;
}
state[0] = state[0].wrapping_add(a);
state[1] = state[1].wrapping_add(b);
state[2] = state[2].wrapping_add(c);
state[3] = state[3].wrapping_add(d);
state[4] = state[4].wrapping_add(e);
state[5] = state[5].wrapping_add(f);
state[6] = state[6].wrapping_add(g);
state[7] = state[7].wrapping_add(h);
}
}
};
}
sha!(
Sha256,
u32,
load_u32_be,
store_u32_be,
K256,
u64,
store_u64_be,
(2, 13, 22),
(6, 11, 25),
(7, 18, 3),
(17, 19, 10)
);
sha!(
Sha512,
u64,
load_u64_be,
store_u64_be,
K512,
u128,
store_u128_be,
(28, 34, 39),
(14, 18, 41),
(1, 8, 7),
(19, 61, 6)
);
|
struct MinStack {
v: Vec<i32>,
minv: Vec<i32>
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MinStack {
/** initialize your data structure here. */
fn new() -> Self {
Self{
v: Vec::new(),
minv: Vec::new(),
}
}
fn push(&mut self, x: i32) {
self.v.push(x);
if (self.minv.len() == 0 || self.minv[self.minv.len()-1] > x) {
self.minv.push(x);
} else {
self.minv.push(self.minv[self.minv.len()-1])
}
}
fn pop(&mut self) {
self.minv.pop();
self.v.pop();
}
fn top(&self) -> i32 {
return self.v[self.v.len()-1];
}
fn get_min(&self) -> i32 {
return self.minv[self.minv.len()-1];
}
}
/**
* Your MinStack object will be instantiated and called as such:
* let obj = MinStack::new();
* obj.push(x);
* obj.pop();
* let ret_3: i32 = obj.top();
* let ret_4: i32 = obj.get_min();
*/ |
fn main() {
println!("{:?}", "STDOUT".chars());
}
|
use bevy::prelude::*;
pub struct Explosion;
pub struct ExplosionMaterial(Handle<ColorMaterial>);
pub const EXPLOSION_WIDTH: f32 = 800.;
pub const EXPLOSION_HEIGHT: f32 = 800.;
pub fn init(
commands: &mut Commands,
asset_server: &AssetServer,
materials: &mut ResMut<Assets<ColorMaterial>>,
) {
let plate_sprite = asset_server.load("sprites/explosion.png");
commands.insert_resource(ExplosionMaterial(materials.add(plate_sprite.into())));
}
pub fn spawn(commands: &mut Commands, materials: &Res<ExplosionMaterial>) {
commands
.insert_resource(Explosion)
.spawn(SpriteBundle {
material: materials.0.clone(),
sprite: Sprite::new(Vec2::new(EXPLOSION_WIDTH, EXPLOSION_HEIGHT)),
..Default::default()
})
.with(Explosion);
}
|
use crate::client::Client;
use ureq::{Error};
use serde::{Deserialize};
#[derive(Deserialize)]
pub struct ValidateForVoiceResponse {
pub code: Option<String>,
pub error: Option<String>,
pub formatted_output: Option<String>,
pub id: Option<u64>,
pub sender: Option<String>,
pub success: bool,
pub voice: Option<bool>,
}
#[derive(Default)]
pub struct ValidateForVoiceParams {
pub callback: Option<String>,
pub number: String,
}
pub struct ValidateForVoice {
client: Client
}
impl ValidateForVoice {
pub fn new(client: Client) -> Self {
ValidateForVoice {
client,
}
}
pub fn post(&self, params: ValidateForVoiceParams) -> Result<ValidateForVoiceResponse, Error> {
Ok(self.client.request("POST", "validate_for_voice")
.send_form(&[
("callback", &*params.callback.unwrap_or_default()),
("number", &*params.number),
])?
.into_json::<ValidateForVoiceResponse>()?
)
}
} |
//! Custom derive support for `zeroize`
#![crate_type = "proc-macro"]
#![deny(warnings, unused_import_braces, unused_qualifications)]
#![forbid(unsafe_code)]
extern crate proc_macro;
#[macro_use]
extern crate quote;
#[macro_use]
extern crate syn;
use proc_macro::TokenStream;
macro_rules! q {
($($t:tt)*) => (quote_spanned!(proc_macro2::Span::call_site() => $($t)*))
}
#[proc_macro_derive(Zeroize)]
pub fn derive_zeroize(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap();
let zeroizers = match ast.data {
syn::Data::Struct(ref s) => derive_struct_zeroizers(&s.fields),
syn::Data::Enum(_) => panic!("support for deriving Zeroize on enums not yet unimplemented"),
syn::Data::Union(_) => panic!("can't derive Zeroize on union types"),
};
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let zeroize_impl = q! {
impl #impl_generics Zeroize for #name #ty_generics #where_clause {
fn zeroize(&mut self) {
#zeroizers
}
}
};
zeroize_impl.into()
}
#[proc_macro_derive(ZeroizeOnDrop)]
pub fn derive_zeroize_on_drop(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap();
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let zeroize_on_drop_impl = q! {
impl #impl_generics Drop for #name #ty_generics #where_clause {
fn drop(&mut self) {
self.zeroize();
}
}
impl #impl_generics ZeroizeOnDrop for #name #ty_generics #where_clause {}
};
zeroize_on_drop_impl.into()
}
fn derive_struct_zeroizers(fields: &syn::Fields) -> proc_macro2::TokenStream {
let self_ident = syn::Ident::new("self", proc_macro2::Span::call_site());
match *fields {
syn::Fields::Named(ref fields) => {
derive_field_zeroizers(&self_ident, Some(&fields.named), true)
}
syn::Fields::Unnamed(ref fields) => {
derive_field_zeroizers(&self_ident, Some(&fields.unnamed), false)
}
syn::Fields::Unit => panic!("can't derive Zeroize on unit structs"),
}
}
fn derive_field_zeroizers(
target: &syn::Ident,
fields: Option<&syn::punctuated::Punctuated<syn::Field, Token![,]>>,
named: bool,
) -> proc_macro2::TokenStream {
let empty = Default::default();
let zeroizers = fields.unwrap_or(&empty).iter().enumerate().map(|(i, f)| {
let is_phantom_data = match f.ty {
syn::Type::Path(syn::TypePath {
qself: None,
ref path,
}) => path
.segments
.last()
.map(|x| x.value().ident == "PhantomData")
.unwrap_or(false),
_ => false,
};
if is_phantom_data {
q!()
} else if named {
let ident = f.ident.clone().unwrap();
q!(#target.#ident.zeroize())
} else {
q!(#target.#i.zeroize())
}
});
q!(#(#zeroizers);*)
}
|
use crate::terminal::SIZE;
use crate::util::Size;
pub mod colors;
pub mod events;
pub const SIZE: Size = Size {
width: 26,
height: 12,
};
pub const GRAYSCALE_COLOR_COUNT: SIZE = 24;
pub const INPUT_FIELD_WIDTH: SIZE = GRAYSCALE_COLOR_COUNT;
pub const FOUR_BIT_COLOR_COUNT: SIZE = 8 * 2;
|
use crate::DATABASE;
use rusqlite::NO_PARAMS;
use rusqlite::{Connection, Result};
// Creates the database in case it doesn't exist
pub fn create() -> Result<()> {
let conn = Connection::open(DATABASE.to_owned())?;
conn.execute(
"create table if not exists users (
id integer primary key,
device_id text not null,
public_key text not null,
token text not null,
platform text not null
)",
NO_PARAMS,
)?;
conn.execute(
"create table if not exists pairing (
id integer primary key,
device_one text not null,
device_two text not null,
pairing intefer not null
)",
NO_PARAMS,
)?;
Ok(())
}
|
//#[macro_use]
//extern crate bitflags;
pub mod token;
pub mod lexer;
pub mod parser;
pub mod ast;
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct SrcPos(pub u32, pub u32);
impl SrcPos {
pub fn from_src_pos(pos: &SrcPos) -> SrcPos {
pos.clone()
}
pub fn invalid() -> SrcPos {
SrcPos(0,0)
}
pub fn to(&self, pos: &SrcPos) -> SrcPos {
SrcPos(self.0, pos.1)
}
pub fn as_range(&self) -> std::ops::Range<usize> {
std::ops::Range { start: self.0 as usize, end: self.1 as usize }
}
}
#[derive(Debug, Clone)]
pub enum ParseError {
ExprChoicesWithoutDesignator,
InvalidOpSymbolString,
InvalidDeclarationForEntity,
InvalidDeclarationForPackageBody,
InvalidDeclarationForPackageDecl,
InvalidDeclarationForConfigurationDecl,
MalformedExpr,
MalformedName,
MalformedDiscreteRange,
MalformedGenericMapActual,
MalformedGenericMapFormal,
MalformedArrayDefinition,
MixedArrayDefinition,
PostponedArrayStmt,
PostponedComponentInst,
NoLabelInComponentInst,
SignalKindInNonSignalDecl,
StringIsNotAnOpSymbol,
NoReturnInFunction,
ReturnInProcedure,
PurityInProcedure,
UnexpectedToken(token::Token, String, Vec<token::TokenKind>),
UnexpectedEoF,
Internal,
}
pub type PResult<T>=Result<T, ParseError>;
|
struct Solution;
impl Solution {
// 消除最右边的 1
pub fn range_bitwise_and(m: i32, mut n: i32) -> i32 {
while m < n {
// 使用 &= 性能提升很多??
// n = n & (n - 1);
n &= n - 1;
}
n
}
// 位移法。
pub fn range_bitwise_and2(mut m: i32, mut n: i32) -> i32 {
let mut count = 0;
while m != n {
m >>= 1;
n >>= 1;
count += 1;
}
n << count
}
// 暴力法。
pub fn range_bitwise_and1(m: i32, n: i32) -> i32 {
(m..=n).fold(std::i32::MAX, |acc, n| acc & n)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_range_bitwise_and1() {
assert_eq!(Solution::range_bitwise_and(5, 7), 4);
assert_eq!(Solution::range_bitwise_and(0, 1), 0);
}
}
|
#[macro_use] extern crate lazy_static;
extern crate radix_trie;
#[macro_use] mod macros;
mod lexicon;
mod puzzle;
fn main() {
println!("Hello, world!");
}
|
use messages::{Message, Payload};
use errors::Errors;
use json;
use json::JsonValue;
use v2;
fn get_key<'a>(json : &'a JsonValue, key : &str) -> Result<&'a JsonValue, Errors> {
let j = &json[key];
if j.is_null() {
Err(Errors::Missing(key.to_string()))
} else {
Ok(j)
}
}
fn to_u64(json : &JsonValue, key : &str) -> Result<u64, Errors> {
let j = get_key(json, key)?;
if let Some(ret) = j.as_u64() {
Ok(ret)
} else {
Err(Errors::Parsing(j.to_string()))
}
}
fn to_f64(json : &JsonValue, key : &str) -> Result<f64, Errors> {
let j = json[key].clone();
if j.is_null() {
Err(Errors::Missing(key.to_string()))
} else if let Some(ret) = j.as_f64() {
Ok(ret)
} else {
Err(Errors::Parsing(j.to_string()))
}
}
fn to_v2(json : &JsonValue, key : &str) -> Result<v2::V2, Errors> {
let j = get_key(json, key)?;
let x = to_f64(j, "x")?;
let y = to_f64(j, "y")?;
Ok(v2::V2::new(x,y))
}
impl Payload {
fn from_raw(msg_str : &str, j : &json::JsonValue) -> Result<Payload, Errors> {
use messages::{
HelloInfo,
PlayerUpdateInfo
};
let as_string = msg_str.to_string();
let ret = match msg_str {
"hello" => {
Payload::Hello(
HelloInfo {
name: j["name"].to_string()
})
}
"playerUpdate" => {
Payload::PlayerUpdate(
PlayerUpdateInfo {
pos: to_v2(j,"pos")?,
vel: to_v2(j,"vel")?,
})
}
"nothing" | "raw" | "pong" => {
Payload::Unknown(as_string.clone())
}
_ => {
Payload::Unknown(as_string.clone())
}
};
Ok(ret)
}
}
impl Message {
pub fn from_str(text: &str) -> Result<Self, Errors> {
let parsed = json::parse(text)?;
let time = to_u64(&parsed, "time")?;
let id = to_u64(&parsed, "id")?;
let msg = parsed["msg"].to_string();
let data = Payload::from_raw(&msg, &parsed["data"])?;
let ret = Message {
msg, time, id, data,
};
Ok(ret)
}
}
|
use anyhow::{anyhow, Context, Result};
use serde::ser::Serializer;
use serde::ser::SerializeSeq;
use crate::config::read_config;
use crate::db::active_notes;
pub fn exec() -> Result<()> {
let cfg = read_config()
.context("Reading config")?;
let db = sqlite::open(&cfg.db_path)
.context("Opening database file")?;
let mut s = serde_yaml::Serializer::new(std::io::stdout());
let mut ss = s.serialize_seq(None)?;
for n in active_notes(&db)? {
ss.serialize_element(&n)?;
}
ss.end().map_err(|e| anyhow!(e))
}
|
use crate::effects;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Tritone {
#[serde(rename = "ix")]
pub index: i64,
#[serde(rename = "mn")]
pub match_name: String,
#[serde(rename = "nm")]
pub name: String,
#[serde(rename = "ef")]
pub effects: (
effects::Color,
effects::Color,
effects::Color,
effects::Slider,
),
}
impl Tritone {
pub const TY: u8 = 23;
}
|
use num::One;
use alga::general::{ClosedMul, ClosedSub, ClosedAdd};
use core::{Scalar, SquareMatrix};
use core::dimension::Dim;
use core::storage::Storage;
impl<N, D: Dim, S> SquareMatrix<N, D, S>
where N: Scalar + One + ClosedMul + ClosedAdd + ClosedSub,
S: Storage<N, D, D> {
/// This matrix determinant.
#[inline]
pub fn determinant(&self) -> N {
assert!(self.is_square(), "Unable to invert a non-square matrix.");
let dim = self.shape().0;
unsafe {
match dim {
0 => N::one(),
1 => {
*self.get_unchecked(0, 0)
},
2 => {
let m11 = *self.get_unchecked(0, 0); let m12 = *self.get_unchecked(0, 1);
let m21 = *self.get_unchecked(1, 0); let m22 = *self.get_unchecked(1, 1);
m11 * m22 - m21 * m12
},
3 => {
let m11 = *self.get_unchecked(0, 0);
let m12 = *self.get_unchecked(0, 1);
let m13 = *self.get_unchecked(0, 2);
let m21 = *self.get_unchecked(1, 0);
let m22 = *self.get_unchecked(1, 1);
let m23 = *self.get_unchecked(1, 2);
let m31 = *self.get_unchecked(2, 0);
let m32 = *self.get_unchecked(2, 1);
let m33 = *self.get_unchecked(2, 2);
let minor_m12_m23 = m22 * m33 - m32 * m23;
let minor_m11_m23 = m21 * m33 - m31 * m23;
let minor_m11_m22 = m21 * m32 - m31 * m22;
m11 * minor_m12_m23 - m12 * minor_m11_m23 + m13 * minor_m11_m22
},
_ => {
unimplemented!()
}
}
}
}
}
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use visitor::FmtVisitor;
use utils::*;
use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
use syntax::{ast, ptr};
use syntax::codemap::{Pos, Span};
use syntax::parse::token;
use syntax::print::pprust;
use MIN_STRING;
impl<'a> FmtVisitor<'a> {
fn rewrite_string_lit(&mut self, s: &str, span: Span, width: usize, offset: usize) -> String {
// FIXME I bet this stomps unicode escapes in the source string
// Check if there is anything to fix: we always try to fixup multi-line
// strings, or if the string is too long for the line.
let l_loc = self.codemap.lookup_char_pos(span.lo);
let r_loc = self.codemap.lookup_char_pos(span.hi);
if l_loc.line == r_loc.line && r_loc.col.to_usize() <= config!(max_width) {
return self.snippet(span);
}
// TODO if lo.col > IDEAL - 10, start a new line (need cur indent for that)
let s = s.escape_default();
let offset = offset + 1;
let indent = make_indent(offset);
let indent = &indent;
let mut cur_start = 0;
let mut result = String::with_capacity(round_up_to_power_of_two(s.len()));
result.push('"');
loop {
let max_chars = if cur_start == 0 {
// First line.
width - 2 // 2 = " + \
} else {
config!(max_width) - offset - 1 // 1 = either \ or ;
};
let mut cur_end = cur_start + max_chars;
if cur_end >= s.len() {
result.push_str(&s[cur_start..]);
break;
}
// Make sure we're on a char boundary.
cur_end = next_char(&s, cur_end);
// Push cur_end left until we reach whitespace
while !s.char_at(cur_end-1).is_whitespace() {
cur_end = prev_char(&s, cur_end);
if cur_end - cur_start < MIN_STRING {
// We can't break at whitespace, fall back to splitting
// anywhere that doesn't break an escape sequence
cur_end = next_char(&s, cur_start + max_chars);
while s.char_at(prev_char(&s, cur_end)) == '\\' {
cur_end = prev_char(&s, cur_end);
}
break;
}
}
// Make sure there is no whitespace to the right of the break.
while cur_end < s.len() && s.char_at(cur_end).is_whitespace() {
cur_end = next_char(&s, cur_end+1);
}
result.push_str(&s[cur_start..cur_end]);
result.push_str("\\\n");
result.push_str(indent);
cur_start = cur_end;
}
result.push('"');
result
}
fn rewrite_call(&mut self,
callee: &ast::Expr,
args: &[ptr::P<ast::Expr>],
width: usize,
offset: usize)
-> String
{
debug!("rewrite_call, width: {}, offset: {}", width, offset);
// TODO using byte lens instead of char lens (and probably all over the place too)
let callee_str = self.rewrite_expr(callee, width, offset);
debug!("rewrite_call, callee_str: `{}`", callee_str);
// 2 is for parens.
let remaining_width = width - callee_str.len() - 2;
let offset = callee_str.len() + 1 + offset;
let arg_count = args.len();
let args_str = if arg_count > 0 {
let args: Vec<_> = args.iter().map(|e| (self.rewrite_expr(e,
remaining_width,
offset), String::new())).collect();
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: offset,
h_width: remaining_width,
v_width: remaining_width,
};
write_list(&args, &fmt)
} else {
String::new()
};
format!("{}({})", callee_str, args_str)
}
fn rewrite_paren(&mut self, subexpr: &ast::Expr, width: usize, offset: usize) -> String {
debug!("rewrite_paren, width: {}, offset: {}", width, offset);
// 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
// paren on the same line as the subexpr
let subexpr_str = self.rewrite_expr(subexpr, width-2, offset+1);
debug!("rewrite_paren, subexpr_str: `{}`", subexpr_str);
format!("({})", subexpr_str)
}
fn rewrite_struct_lit(&mut self,
path: &ast::Path,
fields: &[ast::Field],
base: Option<&ast::Expr>,
width: usize,
offset: usize)
-> String
{
debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
assert!(fields.len() > 0 || base.is_some());
let path_str = pprust::path_to_string(path);
// Foo { a: Foo } - indent is +3, width is -5.
let indent = offset + path_str.len() + 3;
let budget = width - (path_str.len() + 5);
let mut field_strs: Vec<_> =
fields.iter().map(|f| self.rewrite_field(f, budget, indent)).collect();
if let Some(expr) = base {
// Another 2 on the width/indent for the ..
field_strs.push(format!("..{}", self.rewrite_expr(expr, budget - 2, indent + 2)))
}
// FIXME comments
let field_strs: Vec<_> = field_strs.into_iter().map(|s| (s, String::new())).collect();
let fmt = ListFormatting {
tactic: ListTactic::HorizontalVertical,
separator: ",",
trailing_separator: if base.is_some() {
SeparatorTactic::Never
} else {
config!(struct_lit_trailing_comma)
},
indent: indent,
h_width: budget,
v_width: budget,
};
let fields_str = write_list(&field_strs, &fmt);
format!("{} {{ {} }}", path_str, fields_str)
// FIXME if the usual multi-line layout is too wide, we should fall back to
// Foo {
// a: ...,
// }
}
fn rewrite_field(&mut self, field: &ast::Field, width: usize, offset: usize) -> String {
let name = &token::get_ident(field.ident.node);
let overhead = name.len() + 2;
let expr = self.rewrite_expr(&field.expr, width - overhead, offset + overhead);
format!("{}: {}", name, expr)
}
fn rewrite_tuple_lit(&mut self, items: &[ptr::P<ast::Expr>], width: usize, offset: usize)
-> String {
// opening paren
let indent = offset + 1;
// In case of length 1, need a trailing comma
if items.len() == 1 {
return format!("({},)", self.rewrite_expr(&*items[0], width - 3, indent));
}
// Only last line has width-1 as budget, other may take max_width
let item_strs: Vec<_> =
items.iter()
.enumerate()
.map(|(i, item)| self.rewrite_expr(
item,
// last line : given width (minus "("+")"), other lines : max_width
// (minus "("+","))
if i == items.len() - 1 { width - 2 } else { config!(max_width) - indent - 2 },
indent))
.collect();
let tactics = if item_strs.iter().any(|s| s.contains('\n')) {
ListTactic::Vertical
} else {
ListTactic::HorizontalVertical
};
// FIXME handle comments
let item_strs: Vec<_> = item_strs.into_iter().map(|s| (s, String::new())).collect();
let fmt = ListFormatting {
tactic: tactics,
separator: ",",
trailing_separator: SeparatorTactic::Never,
indent: indent,
h_width: width - 2,
v_width: width - 2,
};
let item_str = write_list(&item_strs, &fmt);
format!("({})", item_str)
}
pub fn rewrite_expr(&mut self, expr: &ast::Expr, width: usize, offset: usize) -> String {
match expr.node {
ast::Expr_::ExprLit(ref l) => {
match l.node {
ast::Lit_::LitStr(ref is, _) => {
let result = self.rewrite_string_lit(&is, l.span, width, offset);
debug!("string lit: `{}`", result);
return result;
}
_ => {}
}
}
ast::Expr_::ExprCall(ref callee, ref args) => {
return self.rewrite_call(callee, args, width, offset);
}
ast::Expr_::ExprParen(ref subexpr) => {
return self.rewrite_paren(subexpr, width, offset);
}
ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
return self.rewrite_struct_lit(path,
fields,
base.as_ref().map(|e| &**e),
width,
offset);
}
ast::Expr_::ExprTup(ref items) => {
return self.rewrite_tuple_lit(items, width, offset);
}
_ => {}
}
self.snippet(expr.span)
}
}
|
use support::{ decl_module, decl_storage, decl_event, dispatch::Result,
StorageValue, StorageMap, ensure, traits::{ Currency, ReservableCurrency } };
use { system::ensure_signed, timestamp };
// this is needed when you want to use Vec and Box
use rstd::prelude::*;
use runtime_primitives::traits::{ As, /*CheckedAdd, CheckedDiv, CheckedMul,*/ Hash };
use parity_codec::{ Encode, Decode };
// use runtime_io::{ self };
pub type StdResult<T> = rstd::result::Result<T, &'static str>;
/// The module's configuration trait. This is trait inheritance.
pub trait Trait: timestamp::Trait + balances::Trait {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
}
// store the 3 topmost bids, and they cannot be withdrawn
const TOPMOST_BIDS_LEN: usize = 3;
// auction duration has to be at least 3 mins
const AUCTION_MIN_DURATION: u64 = 3 * 60;
// modify the following to at least 1 min when run in production
const DISPLAY_BIDS_UPDATE_PERIOD: u64 = 1 * 60;
#[derive(Encode, Decode, Clone, PartialEq, Debug)]
pub enum AuctionStatus {
Ongoing,
Cancelled,
Closed
}
// necessary so structs depending on this enum can be en-/de-code with
// default value.
impl Default for AuctionStatus {
fn default() -> Self { AuctionStatus::Ongoing }
}
#[derive(Encode, Decode, Clone, PartialEq, Debug)]
pub enum BidStatus {
Active,
Withdrawn,
}
// necessary so structs depending on this enum can be en-/de-code with
// default value.
impl Default for BidStatus {
fn default() -> Self { BidStatus::Active }
}
// Our own Cat struct
#[derive(Encode, Decode, Default, Clone, PartialEq, Debug)]
pub struct Kitty<Hash, AccountId> {
id: Hash,
name: Option<Vec<u8>>,
owner: Option<AccountId>,
owner_pos: Option<u64>,
in_auction: bool,
}
#[derive(Encode, Decode, Default, Clone, PartialEq, Debug)]
pub struct Auction<Hash, Balance, Moment, AuctionTx> {
id: Hash,
kitty_id: Hash,
base_price: Balance,
start_time: Moment,
end_time: Moment,
status: AuctionStatus,
topmost_bids: Vec<Hash>,
price_to_topmost: Balance,
display_bids: Vec<Hash>,
display_bids_last_update: Moment,
tx: Option<AuctionTx>,
}
#[derive(Encode, Decode, Default, Clone, PartialEq, Debug)]
pub struct Bid<Hash, AccountId, Balance, Moment> {
id: Hash,
auction_id: Hash,
bidder: AccountId,
price: Balance,
last_update: Moment,
status: BidStatus,
}
#[derive(Encode, Decode, Default, Clone, PartialEq, Debug)]
pub struct AuctionTx<Moment, AccountId, Balance> {
tx_time: Moment,
winner: AccountId,
tx_price: Balance,
}
// This module's storage items.
decl_storage! {
trait Store for Module<T: Trait> as CatAuction {
Kitties get(kitties): map T::Hash => Kitty<T::Hash, T::AccountId>;
KittiesArray get(kitty_array): map u64 => T::Hash;
KittiesCount get(kitties_count): u64 = 0;
// The following two go hand-in-hand, write to one likely need to update the other two
OwnerKitties get(owner_kitties): map (T::AccountId, u64) => T::Hash;
OwnerKittiesCount get(owner_kitties_count): map T::AccountId => u64 = 0;
// On Auction
Auctions get(auctions): map T::Hash => Auction<T::Hash, T::Balance, T::Moment,
AuctionTx<T::Moment, T::AccountId, T::Balance>>;
AuctionsArray get(auction_array): map u64 => T::Hash;
AuctionsCount get(auctions_count): u64 = 0;
// `bid_id` => Bid object
Bids get(bids): map T::Hash => Bid<T::Hash, T::AccountId, T::Balance, T::Moment>;
// On auction & bid: (auction_id, index) => bid_id
AuctionBids get(auction_bids): map (T::Hash, u64) => T::Hash;
AuctionBidsCount get(auction_bids_count): map T::Hash => u64 = 0;
AuctionBidderBids get(auction_bidder_bids): map (T::Hash, T::AccountId) => T::Hash;
Nonce: u64 = 0;
}
}
decl_event!(
pub enum Event<T> where
<T as system::Trait>::AccountId,
<T as system::Trait>::Hash,
<T as balances::Trait>::Balance,
<T as timestamp::Trait>::Moment {
// Events in our runtime
KittyCreated(AccountId, Hash, Vec<u8>),
AuctionStarted(AccountId, Hash, Hash, Balance, Moment),
AuctionCancelled(Hash),
AuctionClosed(Hash),
NewBid(Hash, Balance),
UpdateDisplayedBids(Hash, Vec<Hash>),
AuctionTx(Hash, Hash, AccountId, AccountId),
}
);
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn deposit_event<T>() = default;
pub fn create_kitty(origin, kitty_name: Vec<u8>) -> Result {
let sender = ensure_signed(origin)?;
let kitty_id = Self::_gen_random_hash(&sender)?;
// ensure the kitty_id is not existed
ensure!(!<Kitties<T>>::exists(&kitty_id), "Cat with the id existed already");
let mut kitty = Kitty {
id: kitty_id,
name: Some(kitty_name.clone()),
owner: None, // to be updated in _add_kitty_to_storage
owner_pos: None, // to be updated in _add_kitty_to_storage
in_auction: false,
};
Self::_add_kitty_to_storage(&mut kitty, Some(&sender))?;
// emit an event
Self::deposit_event(RawEvent::KittyCreated(sender, kitty_id, kitty_name));
Ok(())
} // end of fn `create_kitty`
pub fn start_auction(origin, kitty_id: T::Hash, end_time: T::Moment,
base_price: T::Balance) -> Result {
let sender = ensure_signed(origin)?;
// Check:
// 1. ensure kitty exists, and the kitty.owner == sender. Currently,
// only the kitty owner can put his own kitty in auction
// 2. kitty is not already `in_auction` state
// 3. ensure end_time > current_time
// 4. base_price > 0
// check #1
ensure!(<Kitties<T>>::exists(kitty_id), "Kitty does not exist");
let kitty = Self::kitties(kitty_id);
// check #2
ensure!(!kitty.in_auction, "Kitty is already in another auction");
// check #3
let now = <timestamp::Module<T>>::get();
ensure!(end_time.clone().as_() > AUCTION_MIN_DURATION + now.clone().as_(),
"End time cannot be set less than 3 mins from current time");
// check #4
ensure!(base_price > <T::Balance as As<u64>>::sa(0),
"Base price must be set greater than 0");
// Write:
// 1. create the auction
let auction_id = Self::_gen_random_hash(&sender)?;
// check: auction_id not existed yet
ensure!(!<Auctions<T>>::exists(&auction_id), "Auction ID generated exists already");
let auction = Auction {
id: auction_id.clone(),
kitty_id,
base_price,
start_time: now.clone(),
end_time: end_time.clone(),
status: AuctionStatus::Ongoing,
topmost_bids: Vec::new(),
price_to_topmost: base_price,
display_bids: Vec::new(),
display_bids_last_update: now,
tx: None,
};
Self::_add_auction_to_storage(&auction)?;
// also set the kitty state in_auction = true
<Kitties<T>>::mutate(kitty_id, |k| k.in_auction = true);
// emit an event
Self::deposit_event(RawEvent::AuctionStarted(sender, kitty_id, auction_id,
base_price, end_time));
Ok(())
} // end of `fn start_auction(...)
pub fn cancel_auction(origin, auction_id: T::Hash) -> Result {
let sender = ensure_signed(origin)?;
// check:
// 1. only the auction_admin (which is the kitty owner) can cancel the auction
// 2. the current time is before the auction end time
// 3. No one has placed bid in the auction yet
// check #1:
ensure!(<Auctions<T>>::exists(auction_id), "Auction does not exist");
ensure!(Self::_auction_admin(auction_id) == sender, "You are not the auction admin");
let auction = Self::auctions(auction_id);
let kitty_id = auction.kitty_id;
let now = <timestamp::Module<T>>::get();
// check #2:
ensure!(auction.end_time > now, "The auction has passed its end time");
// check #3:
ensure!(Self::auction_bids_count(auction_id) == 0,
"Someone has bidded already. So this auction cannot be cancelled");
// write:
// 1. update the auction status to cancelled.
// 2. update the cat status
<Auctions<T>>::mutate(auction_id, |auction| auction.status = AuctionStatus::Cancelled);
<Kitties<T>>::mutate(kitty_id, |kitty| kitty.in_auction = false);
Self::deposit_event(RawEvent::AuctionCancelled(auction_id));
Ok(())
} // end of `fn cancel_auction(...)`
pub fn bid(origin, auction_id: T::Hash, bid_price: T::Balance) -> Result {
let bidder = ensure_signed(origin)?;
// check:
// 1. bidder is not the kitty owner
// 2. bid_price >= base_price
// 3. check the auction status is still ongoing
// 4. now < auction end_time
// check #1
ensure!(<Auctions<T>>::exists(auction_id), "Auction does not exist");
let auction = Self::auctions(auction_id);
let kitty_owner = Self::kitties(auction.kitty_id).owner.ok_or("Kitty does not have owner")?;
ensure!(bidder != kitty_owner, "The kitty owner cannot bid in this auction");
// check #2
ensure!(bid_price >= auction.base_price, "The bid price is lower than the auction base price");
// check #3
ensure!(auction.status == AuctionStatus::Ongoing, "Auction is not active");
// check #4
let now = <timestamp::Module<T>>::get();
ensure!(now < auction.end_time, "Auction has expired already");
//write #1
let to_reserve: T::Balance;
let bid = if <AuctionBidderBids<T>>::exists((auction_id, bidder.clone())) {
// Overwriting on his own previous bid
let bid = Self::bids(Self::auction_bidder_bids((auction_id, bidder.clone())));
// check the current bid is larger than its previous bid
ensure!(bid_price > bid.price, "New bid has to be larger than your previous bid");
to_reserve = bid_price - bid.price; // only reserve the difference from his previous bid
<Bids<T>>::mutate(bid.id, |bid| {
bid.price = bid_price;
bid.last_update = now;
});
bid // bid returned
} else {
// This is a new bid for this bidder
let bid = Bid {
id: Self::_gen_random_hash(&bidder)?,
auction_id,
bidder: bidder.clone(),
price: bid_price,
last_update: now,
status: BidStatus::Active
};
// check the bid ID is a new unique ID
ensure!(!<Bids<T>>::exists(&bid.id), "Generated bid ID is duplicated");
// add into storage
<Bids<T>>::insert(bid.id, bid.clone());
<AuctionBids<T>>::insert((auction_id, Self::auction_bids_count(auction_id)),
bid.id);
<AuctionBidsCount<T>>::mutate(auction_id, |cnt| *cnt += 1);
<AuctionBidderBids<T>>::insert((auction_id, bidder.clone()), bid.id);
to_reserve = bid_price;
bid // bid returned
};
// bidder money has to be locked here
<balances::Module<T>>::reserve(&bidder, to_reserve)?;
// update auction bid info inside if higher than topmost
if bid_price >= auction.price_to_topmost {
let _ = Self::_update_auction_topmost_bids(&auction_id, &bid.id);
}
// emit an event
Self::deposit_event(RawEvent::NewBid(auction_id, bid_price));
Ok(())
}
pub fn update_auction_display_bids(_origin, auction_id: T::Hash) -> Result {
// no need to verify caller, anyone can call this method
// check:
// 1. auction existed
// 2. auction is still ongoing
// 3. its last updated time passed the DISPLAY_BIDS_UPDATE_PERIOD
ensure!(<Auctions<T>>::exists(auction_id), "The auction does not exist");
let now = <timestamp::Module<T>>::get();
let auction = Self::auctions(auction_id);
let to_update = DISPLAY_BIDS_UPDATE_PERIOD + auction.display_bids_last_update.as_();
ensure!(auction.status == AuctionStatus::Ongoing, "The auction is no longer running.");
ensure!(to_update <= now.clone().as_(), "The auction display bids has just been recently updated.");
Self::_update_auction_display_bids_nocheck(auction_id, true)
}
pub fn close_auction_and_tx(_origin, auction_id: T::Hash) -> Result {
ensure!(<Auctions<T>>::exists(auction_id), "The auction does not exist");
let now = <timestamp::Module<T>>::get();
let auction = Self::auctions(auction_id);
ensure!(auction.status == AuctionStatus::Ongoing, "The auction is no longer running.");
ensure!(now >= auction.end_time, "The auction is not expired yet.");
// write
// 1. check if there is a highest bidder. If yes
// - unreserve his money,
// - transfer his money to kitty_owner
// - update kitty to the bidder
// - emit an event saying an auction with aid has a transaction, of kitty_id
// from AccountId to AccountId
// 2. unreserve all fund from the rest of the bidders
// 3. set auction status to Closed
// - emit an event saying auction closed
// #1. Transact the kitty and money between winner and kitty owner
let mut winner_opt: Option<T::AccountId> = None;
let mut auction_tx_opt: Option<AuctionTx<T::Moment, T::AccountId, T::Balance>> = None;
if auction.topmost_bids.len() > 0 {
let reward_bid = Self::bids(auction.topmost_bids[0]);
winner_opt = Some(reward_bid.bidder.clone());
let kitty_owner = Self::kitties(auction.kitty_id).owner.unwrap();
// 1) unreserve winner money,
// 2) transfer winner money to kitty_owner,
// 3) transfer kitty ownership to the winner
if let Some(ref winner_ref) = winner_opt {
<balances::Module<T>>::unreserve(winner_ref, reward_bid.price);
let _transfer = <balances::Module<T> as Currency<_>>::transfer(winner_ref, &kitty_owner, reward_bid.price);
match _transfer {
Err(_e) => Err("Fund transfer error"),
Ok(_v) => {
Self::_transfer_kitty_ownership(&auction.kitty_id, winner_ref);
// create the auction_tx here
auction_tx_opt = Some(AuctionTx {
tx_time: now,
winner: winner_ref.clone(),
tx_price: reward_bid.price
});
// emit event of the kitty is transferred
Self::deposit_event(RawEvent::AuctionTx(auction_id, auction.kitty_id, kitty_owner, winner_opt.clone().unwrap()));
Ok(())
},
}?;
}
} else {
// No one bid. So no kitty ownership transfer is made. Resume the kitty to the owner
<Kitties<T>>::mutate(Self::auctions(auction_id).kitty_id, |kitty| {
kitty.in_auction = false;
});
}
// #2. unreserve funds for other bidders
let bids_count = <AuctionBidsCount<T>>::get(auction_id);
(0..bids_count)
.map(|i| Self::bids( Self::auction_bids((auction_id, i)) ) ) // get the bids
.filter(|bid| match &winner_opt { // filter out the auction winner
Some(winner) => *winner != bid.bidder,
None => true
})
.for_each(|bid| { // unreserve funds for other bidders
<balances::Module<T>>::unreserve(&bid.bidder, bid.price);
});
// #3. close the auction and emit event
<Auctions<T>>::mutate(auction_id, |auction| {
auction.status = AuctionStatus::Closed;
auction.tx = auction_tx_opt;
});
// #4. update the display bid upon closing
let _ = Self::_update_auction_display_bids_nocheck(auction_id, false);
Self::deposit_event(RawEvent::AuctionClosed(auction_id));
Ok(())
}
} // end of `struct Module<T: Trait> for enum Call...`
} // end of `decl_module!`
impl<T: Trait> Module<T> {
// generate a random hash key
fn _gen_random_hash(sender: &T::AccountId) -> StdResult<T::Hash> {
let nonce = <Nonce<T>>::get();
let random_seed = <system::Module<T>>::random_seed();
let random_hash = (random_seed, sender, nonce).using_encoded(<T as system::Trait>::Hashing::hash);
// nonce increment by 1
<Nonce<T>>::mutate(|nonce| *nonce += 1);
Ok(random_hash)
}
// allow owner to be None
fn _add_kitty_to_storage(kitty: &mut Kitty<T::Hash, T::AccountId>, owner: Option<&T::AccountId>)
-> Result
{
let kitty_id: T::Hash = kitty.id;
// add the owner reference if `owner` is specified
if let Some(owner_id) = owner {
kitty.owner = Some(owner_id.clone());
kitty.owner_pos = Some(Self::owner_kitties_count(owner_id));
// update OwnerKitties storage...
<OwnerKitties<T>>::insert((owner_id.clone(), kitty.owner_pos.unwrap()), &kitty_id);
<OwnerKittiesCount<T>>::mutate(owner_id, |cnt| *cnt += 1);
}
// update kitty-related storages
<Kitties<T>>::insert(&kitty_id, kitty.clone());
<KittiesArray<T>>::insert(Self::kitties_count(), &kitty_id);
<KittiesCount<T>>::mutate(|cnt| *cnt += 1);
Ok(())
}
fn _add_auction_to_storage(auction: &Auction<T::Hash, T::Balance,
T::Moment, AuctionTx<T::Moment, T::AccountId, T::Balance>>) -> Result
{
<Auctions<T>>::insert(auction.id, auction);
<AuctionsArray<T>>::insert(Self::auctions_count(), auction.id);
<AuctionsCount<T>>::mutate(|cnt| *cnt += 1);
Ok(())
}
fn _auction_admin(auction_id: T::Hash) -> T::AccountId {
// we use an internal function here, so later on we can modify the logic
// how an auction admin is determined.
let auction = Self::auctions(auction_id);
let kitty = Self::kitties(auction.kitty_id);
kitty.owner.unwrap()
}
fn _update_auction_topmost_bids(auction_id: &T::Hash, bid_id: &T::Hash) -> Result {
let auction = Self::auctions(auction_id);
let bid = Self::bids(bid_id);
if bid.price < auction.price_to_topmost {
return Ok(());
}
<Auctions<T>>::mutate(auction_id, |auction| {
// it could be this bid is a topmost bid already with bid_price being updated
if !auction.topmost_bids.contains(bid_id) {
auction.topmost_bids.push(bid_id.clone());
}
// sort the bids
auction.topmost_bids.sort_by(|a, b| {
let a_bp = Self::bids(a).price;
let b_bp = Self::bids(b).price;
b_bp.partial_cmp(&a_bp).unwrap()
});
// drop the last bid if needed
auction.topmost_bids = auction.topmost_bids.clone()
.into_iter().take(TOPMOST_BIDS_LEN).collect();
// update the price_to_topmost. Only update it when the vector is filled
if auction.topmost_bids.len() >= TOPMOST_BIDS_LEN {
let bid = Self::bids(auction.topmost_bids[TOPMOST_BIDS_LEN - 1]);
auction.price_to_topmost = bid.price + <T::Balance as As<u64>>::sa(1);
}
});
Ok(())
}
fn _update_auction_display_bids_nocheck(auction_id: T::Hash, ev: bool) -> Result {
let now = <timestamp::Module<T>>::get();
<Auctions<T>>::mutate(auction_id, |auction| {
auction.display_bids = auction.topmost_bids.clone();
auction.display_bids_last_update = now.clone();
});
// emit event depends on the passed-in flag
if ev {
let auction = Self::auctions(auction_id);
Self::deposit_event(RawEvent::UpdateDisplayedBids(auction_id, auction.display_bids));
}
Ok(())
}
fn _transfer_kitty_ownership(kitty_id: &T::Hash, new_owner_ref: &T::AccountId) {
// Need to update:
// 1. update OwnerKitties, OwnerKittiesCount of original owner
// 2. update OwnerKitties, OwnerKittiesCount of new_owner
// 3. update Kitty (owner, owner_pos)
let kitty = Self::kitties(kitty_id);
// 1. update OwnerKitties, OwnerKittiesCount of original owner
let orig_kitty_owner = kitty.owner.clone().unwrap();
let kitty_cnt = Self::owner_kitties_count(&orig_kitty_owner);
let kitty_owner_pos = kitty.owner_pos.unwrap();
// Two cases: when 1) the kitty is at the last position in OwnerKitties storage, 2) or not
if kitty_owner_pos == kitty_cnt - 1 {
// transferred kitty is at the last position, just need to remove that from OwnerKitties
<OwnerKitties<T>>::remove((orig_kitty_owner.clone(), kitty_cnt - 1));
} else {
// we move the kitty in the last position to the position of the transferring kitty
let last_kitty_id = Self::owner_kitties((orig_kitty_owner.clone(), kitty_cnt - 1));
// update the kitty storage value
<Kitties<T>>::mutate(last_kitty_id, |last_kitty| last_kitty.owner_pos = Some(kitty_owner_pos));
// switch kitty position here
<OwnerKitties<T>>::remove((orig_kitty_owner.clone(), kitty_cnt - 1));
<OwnerKitties<T>>::insert(
(orig_kitty_owner.clone(), kitty_owner_pos),
last_kitty_id
);
}
<OwnerKittiesCount<T>>::mutate(&orig_kitty_owner, |cnt| *cnt -= 1);
// 2. update OwnerKitties, OwnerKittiesCount of new_owner
let kitty_new_pos = Self::owner_kitties_count(new_owner_ref);
<OwnerKitties<T>>::insert((new_owner_ref.clone(), kitty_new_pos), kitty_id);
<OwnerKittiesCount<T>>::mutate(new_owner_ref, |cnt| *cnt += 1);
// 3. update the kitty
<Kitties<T>>::mutate(kitty_id, |kitty| {
kitty.owner = Some(new_owner_ref.clone());
kitty.owner_pos = Some(kitty_new_pos);
kitty.in_auction = false;
});
}
}
#[cfg(test)]
mod tests {
// Test Codes
use super::*;
use support::{ impl_outer_origin, assert_ok };
use runtime_io::{ with_externalities, TestExternalities };
use primitives::{ H256, Blake2Hasher };
use runtime_primitives::{
BuildStorage, traits::{BlakeTwo256, IdentityLookup},
testing::{Digest, DigestItem, Header}
};
// Manually called this which is called in `contstruct_runtime`
impl_outer_origin! {
pub enum Origin for CatAuctionTest {}
}
#[derive(Clone, Eq, PartialEq)]
pub struct CatAuctionTest;
impl system::Trait for CatAuctionTest {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type Digest = Digest;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type Log = DigestItem;
}
impl balances::Trait for CatAuctionTest {
type Balance = u64;
type OnFreeBalanceZero = ();
type OnNewAccount = ();
type Event = ();
type TransactionPayment = ();
type DustRemoval = ();
type TransferPayment = ();
}
impl timestamp::Trait for CatAuctionTest {
/// A timestamp: seconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = ();
}
impl super::Trait for CatAuctionTest {
type Event = ();
}
type CatAuction = super::Module<CatAuctionTest>;
const KITTY_NAMES: [&'static str; 3] = [
"lovely-kitty01",
"lovely-kitty02",
"lovely-kitty03",
];
const ALICE: u64 = 10;
const BOB: u64 = 20;
const CHARLES: u64 = 30;
const DAVE: u64 = 40;
const EVE: u64 = 50;
const BASE_PRICE: u64 = 10000;
const INI_BALANCE: u64 = 100000;
// construct genesis storage
fn build_ext() -> TestExternalities<Blake2Hasher> {
let mut t = system::GenesisConfig::<CatAuctionTest>::default().build_storage().unwrap().0;
t.extend(balances::GenesisConfig::<CatAuctionTest> {
// this is where you specify the genesis data structure
balances: vec![
(ALICE, INI_BALANCE), (BOB, INI_BALANCE), (CHARLES, INI_BALANCE),
(DAVE, INI_BALANCE), (EVE, INI_BALANCE) ],
..Default::default()
}.build_storage().unwrap().0);
t.into()
}
#[test]
fn it_works() {
// Test case to test all test mocks are setup properly
with_externalities(&mut build_ext(), || {
assert!(true);
})
} // finish test `it_works`
#[test]
fn can_create_kitty() {
with_externalities(&mut build_ext(), || {
let kitty_name_in_hex = KITTY_NAMES[0].as_bytes().to_vec();
assert_ok!(CatAuction::create_kitty(Origin::signed(ALICE), kitty_name_in_hex));
assert_eq!(CatAuction::kitties_count(), 1);
assert_eq!(CatAuction::owner_kitties_count(ALICE), 1);
let kitty_id = CatAuction::kitty_array(0);
assert_eq!(CatAuction::owner_kitties((ALICE, 0)), kitty_id);
// test kitty object data is consistent
let kitty = CatAuction::kitties(kitty_id);
assert_eq!(kitty.in_auction, false);
assert_eq!(kitty.owner, Some(ALICE));
assert_eq!(kitty.owner_pos, Some(0));
})
} // finish test `can_start_auction`
#[test]
fn can_start_auction_n_bid_n_close() {
with_externalities(&mut build_ext(), || {
let kitty_name_in_hex = KITTY_NAMES[0].as_bytes().to_vec();
assert_ok!(CatAuction::create_kitty(Origin::signed(ALICE), kitty_name_in_hex));
let kitty_id = CatAuction::kitty_array(0);
let time_buffer = 5; // 5s for time buffer
let end_time = <timestamp::Module<CatAuctionTest>>::get() +
AUCTION_MIN_DURATION + time_buffer;
assert_ok!(CatAuction::start_auction(Origin::signed(ALICE), kitty_id, end_time, BASE_PRICE));
// Test auction:
// 1. auctions_count
assert_eq!(CatAuction::auctions_count(), 1);
let auction_id = CatAuction::auction_array(0);
let abal_b4_bid = <balances::Module<CatAuctionTest>>::free_balance(ALICE);
let bbal_b4_bid = <balances::Module<CatAuctionTest>>::free_balance(BOB);
// Bob bids in the auction
assert_ok!(CatAuction::bid(Origin::signed(BOB), auction_id, BASE_PRICE));
<timestamp::Module<CatAuctionTest>>::set_timestamp(end_time);
// Close the auction
assert_ok!(CatAuction::close_auction_and_tx(Origin::INHERENT, auction_id));
// Check
// 1. auction object
// 2. payment is transferred
// 3. kitty object
// 4. OwnerKittiesCount (A, B)
// 5. OwnerKitties (A, B)
// check #1: auction object
let auction = CatAuction::auctions(auction_id);
assert_eq!(auction.status, AuctionStatus::Closed);
let auction_tx = auction.tx.unwrap();
assert_eq!(auction_tx.winner, BOB);
assert_eq!(auction_tx.tx_price, BASE_PRICE);
// check #2: payment is transferred
let abal_after_bid = <balances::Module<CatAuctionTest>>::free_balance(ALICE);
let bbal_after_bid = <balances::Module<CatAuctionTest>>::free_balance(BOB);
assert!(abal_after_bid - abal_b4_bid >= BASE_PRICE);
assert!(bbal_b4_bid - bbal_after_bid >= BASE_PRICE);
// check #3: check kitty object
let kitty = CatAuction::kitties(kitty_id);
assert!(!kitty.in_auction);
assert_eq!(kitty.owner, Some(BOB));
assert_eq!(kitty.owner_pos, Some(0));
// check #4: check OwnerKittiesCount
assert_eq!(CatAuction::owner_kitties_count(ALICE), 0);
assert_eq!(CatAuction::owner_kitties_count(BOB), 1);
// check #5: check OwnerKitties
assert!(!<OwnerKitties<CatAuctionTest>>::exists((ALICE, 0)));
assert!(<OwnerKitties<CatAuctionTest>>::exists((BOB, 0)));
assert_eq!(CatAuction::owner_kitties((BOB, 0)), kitty_id);
});
}
// TODO: Write test cases:
// 1. with alice, bob having more than one kitten, and in auction to test
// the kitty switching logic when auction closes and tx happens
// 2. with alice starting an auction, Bob, Charles, Dave, and Eve come bid
// with each one out-bidding each others, and then auction closed.
}
|
use std::any;
use std::fmt;
use crate::number::Number;
use crate::token::Token;
//////////////////////////////////////////////////////////////////////
/// Operator
//////////////////////////////////////////////////////////////////////
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Operator {
SUM,
SUB,
MUL,
DIV,
AND,
XOR,
OR,
SHIFTL,
SHIFTR,
LPARENTHESIS,
RPARENTHESIS,
}
impl Operator {
pub fn from_bytes(input: &[u8]) -> Option<Operator> {
let mut op: Option<Operator> = None;
match input[0] {
43 => op = Some(Operator::SUM),
45 => op = Some(Operator::SUB),
42 => op = Some(Operator::MUL),
47 => op = Some(Operator::DIV),
38 => op = Some(Operator::AND),
94 => op = Some(Operator::XOR),
124 => op = Some(Operator::OR),
60 | 62 => {
if input.len() > 1 {
if input[1] == input[0] {
op = if input[1] == 60 {
Some(Operator::SHIFTL)
} else {
Some(Operator::SHIFTR)
};
}
}
}
40 => op = Some(Operator::LPARENTHESIS),
41 => op = Some(Operator::RPARENTHESIS),
_ => {}
};
return op;
}
pub fn get_precedence(&self) -> u32 {
match self {
Self::MUL => 10,
Self::DIV => 10,
Self::SUM => 9,
Self::SUB => 9,
Self::AND => 7,
Self::XOR => 6,
Self::OR => 5,
Self::SHIFTL => 8,
Self::SHIFTR => 8,
Self::LPARENTHESIS => 0,
Self::RPARENTHESIS => 0,
}
}
pub fn is_left_associative(&self) -> bool {
match self {
Self::SUM
| Self::SUB
| Self::MUL
| Self::DIV
| Self::AND
| Self::XOR
| Self::OR
| Self::SHIFTL
| Self::SHIFTR => true,
Self::LPARENTHESIS | Self::RPARENTHESIS => false,
}
}
pub fn operate(&self, a: Number, b: Number) -> Option<Number> {
match self {
Self::SUM => Some(a + b),
Self::SUB => Some(a - b),
Self::MUL => Some(a * b),
Self::DIV => Some(a / b),
Self::AND => Some(a & b),
Self::XOR => Some(a ^ b),
Self::OR => Some(a | b),
Self::SHIFTL => Some(a << b),
Self::SHIFTR => Some(a >> b),
Self::LPARENTHESIS | Self::RPARENTHESIS => None,
}
}
}
impl Token for Operator {
fn to_string(&self) -> String {
match self {
Self::SUM => String::from("+"),
Self::SUB => String::from("-"),
Self::MUL => String::from("*"),
Self::DIV => String::from("/"),
Self::AND => String::from("&"),
Self::XOR => String::from("^"),
Self::OR => String::from("|"),
Self::SHIFTL => String::from("<<"),
Self::SHIFTR => String::from(">>"),
Self::LPARENTHESIS => String::from("("),
Self::RPARENTHESIS => String::from(")"),
}
}
fn as_any(&self) -> &dyn any::Any {
self
}
}
impl fmt::Display for Operator {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", Token::to_string(self))
}
}
|
use std::collections::HashSet;
use std::fs::File;
use std::io::{BufRead, BufReader};
type Coordinate = (usize, usize);
type DumboOctopusEnergyLevels = [[u8; 10]; 10];
fn main() {
let filename = "input/input.txt";
let mut energy_levels: DumboOctopusEnergyLevels = parse_input_file(filename);
let initial_energy_levels = energy_levels;
println!("initial energy_levels: {:?}", initial_energy_levels);
println!();
// Part 1
let num_steps = 100;
let mut total_flashes: usize = 0;
for _ in 0..num_steps {
total_flashes += step(&mut energy_levels);
}
println!("num flashes after {} steps: {}", num_steps, total_flashes);
// Part 2
let mut energy_levels = initial_energy_levels;
let mut flashes = 0;
let mut steps = 0;
while flashes != 100 {
flashes = step(&mut energy_levels);
steps += 1;
}
println!("first step where all octopuses flash: {}", steps);
}
fn step(energy_levels: &mut DumboOctopusEnergyLevels) -> usize {
// First, the energy level of each octopus increases by 1.
energy_levels.iter_mut().for_each(|row| {
row.iter_mut().for_each(|energy_level| {
*energy_level += 1;
})
});
// Then, any octopus with an energy level greater than 9 flashes.
// This increases the energy level of all adjacent octopuses by 1, including octopuses that are diagonally adjacent.
// If this causes an octopus to have an energy level greater than 9, it also flashes.
// This process continues as long as new octopuses keep having their energy level increased beyond 9. (An octopus can only flash at most once per step.)
let mut flashed: HashSet<Coordinate> = HashSet::new();
let side_len = energy_levels.len();
for x in 0..side_len {
for y in 0..side_len {
let curr_coord = (x, y);
if flashed.contains(&curr_coord) {
continue;
}
let curr_energy_level = energy_levels[x][y];
if curr_energy_level > 9 {
flash(energy_levels, &mut flashed, curr_coord);
}
}
}
// Finally, any octopus that flashed during this step has its energy level set to 0, as it used all of its energy to flash.
for (x, y) in &flashed {
energy_levels[*x][*y] = 0;
}
flashed.len()
}
// Mark current octopus as flashed
// Increase energy levels of surrounding octopuses
// Trigger flash on any neighbors if energy level is greater than 9 and they haven't already flashed
fn flash(
energy_levels: &mut DumboOctopusEnergyLevels,
flashed: &mut HashSet<Coordinate>,
octo_coord: Coordinate,
) {
flashed.insert(octo_coord);
for neighbor_coord in neighboring_octopuses(octo_coord) {
let (nx, ny) = neighbor_coord;
energy_levels[nx][ny] += 1;
if energy_levels[nx][ny] > 9 && !flashed.contains(&neighbor_coord) {
flash(energy_levels, flashed, neighbor_coord);
}
}
}
fn neighboring_octopuses(c: Coordinate) -> Vec<Coordinate> {
let (x, y) = c;
let ix = isize::try_from(x).unwrap();
let iy = isize::try_from(y).unwrap();
vec![
(ix - 1, iy),
(ix + 1, iy),
(ix, iy - 1),
(ix, iy + 1),
(ix - 1, iy - 1),
(ix - 1, iy + 1),
(ix + 1, iy - 1),
(ix + 1, iy + 1),
]
.into_iter()
.filter(|c| in_bounds(c))
.map(|(nx, ny)| (usize::try_from(nx).unwrap(), usize::try_from(ny).unwrap()))
.collect()
}
fn in_bounds((x, y): &(isize, isize)) -> bool {
(0..10).contains(x) && (0..10).contains(y)
}
fn parse_input_file(filename: &str) -> DumboOctopusEnergyLevels {
// Open the file in read-only mode (ignoring errors).
let file = File::open(filename).expect("couldn't open file");
let reader = BufReader::new(file);
// Read the file line by line using the lines() iterator from std::io::BufRead.
reader
.lines()
.map(|l| {
let line = l.unwrap();
assert_eq!(line.len(), 10);
<[u8; 10]>::try_from(
line.chars()
.map(|c| c.to_string().parse().unwrap())
.collect::<Vec<u8>>(),
)
.unwrap()
})
.collect::<Vec<[u8; 10]>>()
.try_into()
.unwrap()
}
|
extern crate evdev_rs;
use evdev_rs::enums::{EventCode, EV_KEY};
use evdev_rs::Device;
use std::fs::File;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;
use crate::utils::CheckedSender;
use crate::web::http_client::*;
use crate::{env, ApplicationContext, ApplicationState, Message};
pub struct QrScanner {
path: String,
sender: Sender<Message>,
context: Arc<Mutex<ApplicationContext>>,
buffer: String,
shift: bool,
}
impl QrScanner {
fn parse(&mut self, value: i32, key: EV_KEY) -> Option<String> {
let ch = match key {
EV_KEY::KEY_1 => ('1', '!'),
EV_KEY::KEY_2 => ('2', '@'),
EV_KEY::KEY_3 => ('3', '#'),
EV_KEY::KEY_4 => ('4', '$'),
EV_KEY::KEY_5 => ('5', '%'),
EV_KEY::KEY_6 => ('6', '^'),
EV_KEY::KEY_7 => ('7', '&'),
EV_KEY::KEY_8 => ('8', '*'),
EV_KEY::KEY_9 => ('9', '('),
EV_KEY::KEY_0 => ('0', ')'),
EV_KEY::KEY_A => ('a', 'A'),
EV_KEY::KEY_B => ('b', 'B'),
EV_KEY::KEY_C => ('c', 'C'),
EV_KEY::KEY_D => ('d', 'D'),
EV_KEY::KEY_E => ('e', 'E'),
EV_KEY::KEY_F => ('f', 'F'),
EV_KEY::KEY_G => ('g', 'G'),
EV_KEY::KEY_H => ('h', 'H'),
EV_KEY::KEY_I => ('i', 'I'),
EV_KEY::KEY_J => ('j', 'J'),
EV_KEY::KEY_K => ('k', 'K'),
EV_KEY::KEY_L => ('l', 'L'),
EV_KEY::KEY_M => ('m', 'M'),
EV_KEY::KEY_N => ('n', 'N'),
EV_KEY::KEY_O => ('o', 'O'),
EV_KEY::KEY_P => ('p', 'P'),
EV_KEY::KEY_Q => ('q', 'Q'),
EV_KEY::KEY_R => ('r', 'R'),
EV_KEY::KEY_S => ('s', 'S'),
EV_KEY::KEY_T => ('t', 'T'),
EV_KEY::KEY_U => ('u', 'U'),
EV_KEY::KEY_V => ('v', 'V'),
EV_KEY::KEY_W => ('w', 'W'),
EV_KEY::KEY_X => ('x', 'X'),
EV_KEY::KEY_Y => ('y', 'Y'),
EV_KEY::KEY_Z => ('z', 'Z'),
EV_KEY::KEY_MINUS => ('-', '_'),
EV_KEY::KEY_EQUAL => ('=', '+'),
EV_KEY::KEY_LEFTBRACE => ('[', '{'),
EV_KEY::KEY_RIGHTBRACE => (']', '}'),
EV_KEY::KEY_SEMICOLON => (';', ':'),
EV_KEY::KEY_APOSTROPHE => ('\'', '"'),
EV_KEY::KEY_GRAVE => ('´', '~'),
EV_KEY::KEY_BACKSLASH => ('\\', '|'),
EV_KEY::KEY_COMMA => (',', '<'),
EV_KEY::KEY_DOT => ('.', '>'),
EV_KEY::KEY_SLASH => ('/', '?'),
EV_KEY::KEY_SPACE => (' ', ' '),
EV_KEY::KEY_LEFTSHIFT | EV_KEY::KEY_RIGHTSHIFT => {
self.shift = value == 1;
return None;
}
EV_KEY::KEY_ENTER => {
if value != 1 {
return None;
}
let result = self.buffer.clone();
self.buffer = String::new();
return Some(result);
}
_ => {
println!("Unknown: {:?}", key);
return None;
}
};
if value != 1 {
return None;
}
let ch = if self.shift { ch.1 } else { ch.0 };
self.buffer.push(ch);
None
}
fn run(&mut self) -> bool {
let f = match File::open(&self.path) {
Ok(f) => f,
Err(_) => return false,
};
let mut d = match Device::new() {
Some(d) => d,
None => return false,
};
if d.set_fd(f).is_err() {
return false;
}
println!("Connect qr scanner {}", self.path);
loop {
let a = d.next_event(evdev_rs::ReadFlag::NORMAL | evdev_rs::ReadFlag::BLOCKING);
if let Ok(k) = a {
let k1 = k.1.clone();
if let EventCode::EV_KEY(key) = k.1.event_code {
if let Some(code) = self.parse(k1.value, key) {
self.communicate(&code);
}
}
} else {
break;
}
}
true
}
fn communicate(&self, code: &str) {
let mut c = self.context.lock().expect("Mutex deadlock!");
let state = c.get_state();
self.communicate_identify(code);
if let ApplicationState::Payment { amount, .. } = state {
c.consume_state();
self.communicate_payment(code, amount);
}
}
fn communicate_identify(&self, code: &str) {
let req = IdentificationRequest::Barcode {
code: code.to_owned(),
};
if let Ok(res) = send_identify(req) {
match res {
IdentificationResponse::Account { account } => {
if self.sender.send(Message::Account { account }).is_ok() {
return;
}
}
IdentificationResponse::Product { product } => {
if self.sender.send(Message::Product { product }).is_ok() {
return;
}
}
IdentificationResponse::NotFound => {
if self
.sender
.send(Message::QrCode {
code: code.to_owned(),
})
.is_ok()
{
return;
}
}
_ => {
// Unexpected response
}
}
}
self.sender.send_checked(Message::Error);
}
fn communicate_payment(&self, code: &str, amount: i32) {
let req = TokenRequest {
amount,
method: Authentication::Barcode {
code: code.to_owned(),
},
};
if let Ok(TokenResponse::Authorized { token }) = send_token_request(req) {
if self.sender.send(Message::PaymentToken { token }).is_ok() {
return;
}
}
self.sender.send_checked(Message::Error);
}
fn thread_loop(&mut self) {
if self.run() {
println!("Disconnect qr scanner {}!", self.path);
} else {
println!("Cannot connect to qr scanner {}!", self.path);
}
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
if self.run() {
println!("Disconnect qr scanner {}!", self.path);
}
}
}
pub fn create(sender: Sender<Message>, context: Arc<Mutex<ApplicationContext>>, file: &str) {
let mut qr = QrScanner {
path: file.to_owned(),
sender,
context,
buffer: String::new(),
shift: false,
};
thread::spawn(move || qr.thread_loop());
}
pub fn find_files() -> Vec<String> {
env::QR_SCANNER
.as_str()
.split(';')
.map(|s| s.trim().to_owned())
.collect()
}
}
|
use crate::error::ServerError;
use crate::service::multipart::MultipartFile;
use handlebars::{Handlebars, TemplateRenderError as HandlebarTemplateRenderError};
use lettre::SendableEmail;
use lettre_email::{error::Error as LetterError, EmailBuilder};
use mrml;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::string::ToString;
#[derive(Clone, Debug)]
pub enum TemplateError {
InterpolationError(String),
RenderingError(String),
SendingError(String),
}
impl From<HandlebarTemplateRenderError> for TemplateError {
fn from(err: HandlebarTemplateRenderError) -> Self {
TemplateError::InterpolationError(err.to_string())
}
}
impl From<LetterError> for TemplateError {
fn from(err: LetterError) -> Self {
TemplateError::SendingError(err.to_string())
}
}
impl From<TemplateError> for ServerError {
fn from(err: TemplateError) -> Self {
match err {
TemplateError::InterpolationError(msg) => ServerError::BadRequest(msg),
TemplateError::RenderingError(msg) => ServerError::InternalServerError(msg),
TemplateError::SendingError(msg) => ServerError::InternalServerError(msg),
}
}
}
impl From<mrml::Error> for TemplateError {
fn from(err: mrml::Error) -> Self {
let msg = match err {
mrml::Error::MJMLError(mjml_error) => format!("MJML Error: {:?}", mjml_error),
mrml::Error::ParserError(parser_error) => format!("Parser Error: {:?}", parser_error),
};
TemplateError::RenderingError(msg)
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Template {
pub name: String,
#[serde(default = "String::new")]
pub description: String,
pub content: String,
pub attributes: JsonValue,
}
pub fn default_attachments() -> Vec<MultipartFile> {
vec![]
}
#[derive(Debug, Deserialize)]
pub struct TemplateOptions {
to: String,
from: String,
params: JsonValue,
#[serde(default = "default_attachments", skip_deserializing, skip_serializing)]
attachments: Vec<MultipartFile>,
}
impl TemplateOptions {
pub fn new(
from: String,
to: String,
params: JsonValue,
attachments: Vec<MultipartFile>,
) -> Self {
Self {
from,
to,
params,
attachments,
}
}
}
impl Template {
fn render(&self, opts: &TemplateOptions) -> Result<mrml::Email, TemplateError> {
let reg = Handlebars::new();
let mjml = reg.render_template(self.content.as_str(), &opts.params)?;
let email = mrml::to_email(mjml.as_str(), mrml::Options::default())?;
Ok(email)
}
pub fn to_email(&self, opts: &TemplateOptions) -> Result<SendableEmail, TemplateError> {
debug!("rendering template: {} ({})", self.name, self.description);
let email = self.render(opts)?;
let mut builder = EmailBuilder::new()
.from(opts.from.clone())
.to(opts.to.clone())
.subject(email.subject)
.text(email.text)
.html(email.html);
for item in opts.attachments.iter() {
builder = builder.attachment_from_file(
item.filepath.as_path(),
item.filename.as_ref().map(|value| value.as_str()),
&item.content_type,
)?;
}
let email = builder.build()?;
Ok(email.into())
}
}
// LCOV_EXCL_START
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn render_success() {
let tmpl = Template {
name: "hello".into(),
description: "world".into(),
content: "<mjml></mjml>".into(),
attributes: json!({
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
}),
};
let opts = TemplateOptions::new(
"sender@example.com".into(),
"recipient@example.com".into(),
json!({"name": "Alice"}),
vec![],
);
let result = tmpl.render(&opts);
assert!(result.is_ok());
}
#[test]
fn to_email_success() {
let tmpl = Template {
name: "hello".into(),
description: "world".into(),
content: "<mjml></mjml>".into(),
attributes: json!({
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
}),
};
let opts = TemplateOptions::new(
"sender@example.com".into(),
"recipient@example.com".into(),
json!({"name": "Alice"}),
vec![],
);
let result = tmpl.to_email(&opts);
assert!(result.is_ok());
}
}
// LCOV_EXCL_END
|
fn rebind(){
let sum = 0;
println!("sum : {}",sum);
for i in 0..10 {
// 新しい束縛を作っているので上の束縛には影響がない。
let sum = sum + i;
}
println!("rebind sum : {}", sum); // => 0
}
fn reassign() {
let mut sum = 0;
println!("sum : {}", sum);
for i in 0..10 {
// 上の束縛の値を書き換える。
sum = sum + i;
}
println!("reassign sum : {}", sum);
}
fn rebind2(){
let y = 0;
println!("let y : {}", y);
let i = 10;
let y = y + i;
// let y = y + 1;
println!("letyで新しい束縛を作った結果\ny : {}", y);
}
fn reassign2(){
let mut y = 0;
println!("let mut y : {}", y);
y = y + 1;
println!("y=y+1でyを再代入した結果\ny : {}", y);
}
fn main(){
rebind();
reassign();
rebind2();
reassign2();
} |
use crate::geometry;
use crate::multivector::*;
use web_sys::console::dir;
/// Given two points `p0` and `p1`, there is a unique fold that passes through both of them.
pub fn axiom_1(p0: &Multivector, p1: &Multivector) -> Multivector {
let mut crease = p0.join(p1);
crease.normalized()
}
/// Given two points `p0` and `p1`, there is a unique fold that places `p0` onto `p1`.
pub fn axiom_2(p0: &Multivector, p1: &Multivector) -> Multivector {
let l = p0.join(p1);
let midpoint = geometry::midpoint(p0, p1);
let crease = geometry::orthogonal(&midpoint, &l);
crease.normalized()
}
/// Given two lines `l0` and `l1`, there is a fold that places `l0` onto `l1`.
pub fn axiom_3(l0: &Multivector, l1: &Multivector) -> Multivector {
let crease = geometry::bisector(l0, l1);
crease.normalized()
// There are two possible solutions (two angle bisectors) - the one above or:
// let crease = geometry::orthogonal(l0.meet(l1), crease);
}
/// Given a point `p` and a line `l`, there is a unique fold perpendicular to `l` that passes
/// through point `p`.
pub fn axiom_4(p: &Multivector, l: &Multivector) -> Multivector {
// Simply take the inner product between l and p to construct the perpendicular that passes
// through p
let crease = geometry::orthogonal(p, l);
crease.normalized()
}
/// Given two points `p0` and `p1` and a line `l`, there is a fold that places `p0` onto `l` and
/// passes through `p1`.
pub fn axiom_5(p0: &Multivector, p1: &Multivector, l: &Multivector) -> Option<Multivector> {
// Calculate. the radius of the circle centered on `p1` that is tangent to `p0`
let r = geometry::dist_point_to_point(p0, p1);
// Then, calculate the (shortest) distance from the line to the center of the circle
let dist_from_line_to_center = geometry::dist_point_to_line(p1, &l);
// Exit early if no intersection is possible
if dist_from_line_to_center > r {
return None;
}
// Constructs a line perpendicular to `l` that passes through `p1`
let orthogonal = geometry::orthogonal(p1, &l);
// Then, "meet" this line with the original line to calculate the point of intersection
let mut perpendicular = geometry::intersect_lines(&orthogonal, &l).normalized();
// "Flip" x/y if e12 is negative
perpendicular = perpendicular * perpendicular.e12();
// Pythagoras' theorem: find the length of the third side of the triangle
// whose hypotenuse is `r` and other side is `dist_from_line_to_center`
//
// We don't need to take the absolute value of the value inside of the sqrt operation
// (as in enki's ray tracing code) since we check above that `dist_from_line_to_center`
// is less than (or equal to) the radius `r`
let d = (r * r - dist_from_line_to_center * dist_from_line_to_center).sqrt();
// Multiplying a line by e012 has the effect of "pulling out" its direction vector,
// represented by an ideal point (i.e. a point at infinity) - this is also known as
// metric polarity
let mut direction = (*l) * e012;
direction /= direction.ideal_norm();
// If l isn't normalized, we have to do the above or just:
// direction = l.normalize() * e012;
// If there are 2 intersections (i.e., the line "pierces through" the circle), then you
// can choose either point of intersection (both are valid) - simply change the `+` to a
// `-` (or vice-versa)
//
// The point of intersection can be found by translating the point `perp` along the line
// `l` by an amount `d` (in either direction, in the case of 2 intersections)
direction *= d;
let intersection = geometry::translate(&perpendicular, direction.e20(), direction.e01());
// A new line joining the point of intersection and p0
let m = intersection.join(p0);
// A line perpendicular to m that passes through p1: note that this line should always
// pass through the midpoint of the line segment `intersection - p0`
let crease = geometry::orthogonal(p1, &m);
Some(crease.normalized())
}
/// Given two points `p0` and `p1` and two lines `l0` and `l1`, there is a fold that places `p0` onto
/// `l0` and `p1` onto `l1`.
pub fn axiom_6(
p0: &Multivector,
p1: &Multivector,
l0: &Multivector,
l1: &Multivector,
) -> Multivector {
unimplemented!();
}
/// Given one point `p` and two lines `l0` and `l1`, there is a fold that places `p` onto `l0`
/// and is perpendicular to `l1`.
pub fn axiom_7(p: &Multivector, l0: &Multivector, l1: &Multivector) -> Option<Multivector> {
let angle_between = geometry::angle(l0, l1);
// Lines are parallel - no solution (at least, a solution that does not involve
// infinite elements)
if (angle_between.abs() - std::f32::consts::PI).abs() <= 0.001 {
return None;
}
// Project line `l1` onto the point `p`
let shifted = geometry::project(&l1, p);
// Intersect this line with `l0` - normalize and invert e12 if necessary, since
// the input lines will, in general, not be normalized or oriented in the same
// direction
let mut intersect = shifted.meet(&l0);
intersect = intersect.normalized();
intersect *= intersect.e12();
// Find the midpoint between this new point of intersection and `p` -
// drop a perpendicular from `l1` to this point
let midpoint = geometry::midpoint(p, &intersect);
let crease = geometry::orthogonal(&midpoint, l1);
Some(crease.normalized())
}
|
#[doc = "Reader of register OA0_COMP_TRIM"]
pub type R = crate::R<u32, super::OA0_COMP_TRIM>;
#[doc = "Writer for register OA0_COMP_TRIM"]
pub type W = crate::W<u32, super::OA0_COMP_TRIM>;
#[doc = "Register OA0_COMP_TRIM `reset()`'s with value 0"]
impl crate::ResetValue for super::OA0_COMP_TRIM {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `OA0_COMP_TRIM`"]
pub type OA0_COMP_TRIM_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `OA0_COMP_TRIM`"]
pub struct OA0_COMP_TRIM_W<'a> {
w: &'a mut W,
}
impl<'a> OA0_COMP_TRIM_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 & !0x03) | ((value as u32) & 0x03);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - Opamp0 Compensation Capacitor Trim. Value depends on the drive strength setting - 1x mode: set to 01; 10x mode: set to 11"]
#[inline(always)]
pub fn oa0_comp_trim(&self) -> OA0_COMP_TRIM_R {
OA0_COMP_TRIM_R::new((self.bits & 0x03) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - Opamp0 Compensation Capacitor Trim. Value depends on the drive strength setting - 1x mode: set to 01; 10x mode: set to 11"]
#[inline(always)]
pub fn oa0_comp_trim(&mut self) -> OA0_COMP_TRIM_W {
OA0_COMP_TRIM_W { w: self }
}
}
|
use std::collections::HashMap;
fn read_line() -> String {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().to_owned()
}
fn main() {
let solver = Solver::new(read_line());
let stdout = solver.solve();
stdout.iter().for_each(|s| {
println!("{}", s);
})
}
struct Solver {
s: String,
}
impl Solver {
fn new(s: String) -> Solver {
Solver { s: s }
}
fn solve(&self) -> Vec<String> {
let mut buf = Vec::new();
if self.s.len() == 1 {
let ans = if self.s == "8" { "Yes" } else { "No" };
buf.push(format!("{}", ans));
return buf;
}
if self.s.len() == 2 {
let c0 = self.s.chars().nth(0).unwrap();
let c1 = self.s.chars().nth(1).unwrap();
let n1: u32 = format!("{}{}", c0, c1).parse().unwrap();
let n2: u32 = format!("{}{}", c1, c0).parse().unwrap();
let ans = if n1 % 8 == 0 || n2 % 8 == 0 {
"Yes"
} else {
"No"
};
buf.push(format!("{}", ans));
return buf;
}
let mut char_counts: HashMap<u32, u32> = HashMap::new();
self.s.chars().for_each(|c| {
let key: u32 = format!("{}", c).parse().unwrap();
char_counts.insert(
key,
match char_counts.get(&key) {
Some(count) => count + 1,
None => 1,
},
);
});
let mut can_make = false;
let mut i = 112;
while i < 10000 {
let mut counts: HashMap<u32, u32> = HashMap::new();
let mut num = i;
while num != 0 {
let key: u32 = num % 10;
counts.insert(
key,
match counts.get(&key) {
Some(cnt) => cnt + 1,
None => 1,
},
);
num = num / 10;
}
can_make = counts.iter().all(|(num, cnt)| {
if !char_counts.contains_key(&num) {
false
} else if char_counts.get(&num).unwrap() < cnt {
false
} else {
true
}
});
if can_make {
break;
}
i += 8;
}
buf.push(format!("{}", if can_make { "Yes" } else { "No" }));
buf
}
}
#[test]
fn test_solve_1() {
let solver = Solver::new("1".to_owned());
assert_eq!(solver.solve(), vec!("No"));
}
#[test]
fn test_solve_2() {
let solver = Solver::new("8".to_owned());
assert_eq!(solver.solve(), vec!("Yes"));
}
#[test]
fn test_solve_3() {
let solver = Solver::new("17".to_owned());
assert_eq!(solver.solve(), vec!("No"));
}
#[test]
fn test_solve_4() {
let solver = Solver::new("69".to_owned());
assert_eq!(solver.solve(), vec!("Yes"));
}
#[test]
fn test_solve_5() {
let solver = Solver::new("131".to_owned());
assert_eq!(solver.solve(), vec!("No"));
}
#[test]
fn test_solve_6() {
let solver = Solver::new("823".to_owned());
assert_eq!(solver.solve(), vec!("Yes"));
}
|
//! # The Roku OS Kernel
//!
// ===============================================================================================
// Configuration
// ===============================================================================================
#![feature(
asm,
alloc,
collections,
const_fn,
lang_items,
unique,
)]
#![no_std]
#![allow(dead_code)]
// ===============================================================================================
// Crates
// ===============================================================================================
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate collections;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate once;
#[macro_use]
extern crate system;
#[macro_use]
extern crate x86;
extern crate alloc;
extern crate allocator;
extern crate multiboot;
extern crate rlibc;
extern crate spin;
// ===============================================================================================
// Modules
// ===============================================================================================
#[macro_use]
mod macros;
pub mod handler;
mod device;
mod memory;
mod panic;
mod sys;
// ===============================================================================================
// Constants
// ===============================================================================================
const KERNEL_VERSION: &'static str = env!("CARGO_PKG_VERSION");
// ===============================================================================================
// Kernel Main
// ===============================================================================================
#[no_mangle]
pub extern "C" fn kmain() {
println!("\n------------------------------------------------------------------------------");
println!(" Roku - Version: {}", KERNEL_VERSION);
println!("------------------------------------------------------------------------------\n");
loop {}
}
// ===============================================================================================
// Kernel Init
// ===============================================================================================
#[no_mangle]
pub extern "C" fn kinit(mboot_ptr: multiboot::PAddr) {
// Get multiboot
let mboot = unsafe { multiboot::Multiboot::new(mboot_ptr, paddr_to_slice).expect("No MBoot") };
// Initialize Memory
if mboot.memory_regions().is_some() {
memory::init(mboot.memory_regions().unwrap());
} else {
panic!("No memory sections in multiboot");
}
// Initialize Exceptions/Interrupts
unsafe {
sys::idt::setup_idt();
x86::shared::irq::enable();
};
}
// ===============================================================================================
// Multiboot Conversion
// ===============================================================================================
unsafe fn paddr_to_slice<'a>(p: multiboot::PAddr, sz: usize) -> Option<&'a [u8]> {
let ptr = core::mem::transmute(p);
Some(core::slice::from_raw_parts(ptr, sz))
}
|
// Here it goes all the stuff related to the UI part of the "Update Checker" and the future "Autoupdater".
extern crate serde_json;
extern crate gtk;
extern crate restson;
use self::restson::RestClient;
use gtk::prelude::*;
use gtk::{ApplicationWindow, MessageDialog, Statusbar, DialogFlags, MessageType, ButtonsType};
use std::cell::RefCell;
use std::rc::Rc;
use std::path::PathBuf;
use std::fs::File;
use std::io::BufReader;
use ui;
use settings::GameSelected;
use settings::GameInfo;
use packedfile::db::schemas::Schema;
use updater::*;
/// This enum controls the posible responses from the server.
enum APIResponse {
SuccessNewUpdate(LastestRelease),
SuccessNewUpdateHotfix(LastestRelease),
SuccessNoUpdate,
SuccessUnknownVersion,
Error,
}
/// This enum controls the posible responses from the server. The (Versions, Versions) is local, current.
enum APIResponseSchema {
SuccessNewUpdate(Versions, Versions),
SuccessNoUpdate,
Error,
}
/// This function checks if there is any newer version of RPFM released. If the `use_dialog` is false,
/// we show the results of the check in the `Statusbar`.
pub fn check_updates(current_version: &str, use_dialog: Option<&ApplicationWindow>, status_bar: Option<&Statusbar>) {
// Create new client with API base URL
let mut client = RestClient::new("https://api.github.com").unwrap();
client.set_header_raw("User-Agent", &format!("RPFM/{}", current_version));
// Get `https://api.github.com/repos/frodo45127/rpfm/releases/latest` and deserialize the result automatically
let apiresponse = match client.get(()) {
// If we received a response from the server...
Ok(last_release) => {
// We get `last_release` into our `last_release`. Redundant, but the compiler doesn't know his type otherwise.
let last_release: LastestRelease = last_release;
// Get the last version released. This depends on the fact that the releases are called "vX.X.Xwhatever".
// We only compare the numbers here (X.X.X), so we have to remove everything else.
let mut last_version = last_release.name.to_owned();
last_version.remove(0);
last_version.split_off(5);
// Get the version numbers from our version and from the lastest released version, so we can compare them.
let first = (last_version.chars().nth(0).unwrap_or('0').to_digit(10).unwrap_or(0), current_version.chars().nth(0).unwrap_or('0').to_digit(10).unwrap_or(0));
let second = (last_version.chars().nth(2).unwrap_or('0').to_digit(10).unwrap_or(0), current_version.chars().nth(2).unwrap_or('0').to_digit(10).unwrap_or(0));
let third = (last_version.chars().nth(4).unwrap_or('0').to_digit(10).unwrap_or(0), current_version.chars().nth(4).unwrap_or('0').to_digit(10).unwrap_or(0));
// If this is triggered, there has been a problem parsing the current version or the last version released.
if first.0 == 0 && second.0 == 0 && third.0 == 0 || first.1 == 0 && second.1 == 0 && third.1 == 0 {
APIResponse::SuccessUnknownVersion
}
// If the current version is different than the last released version...
else if last_version != current_version {
// If the lastest released version is lesser than the current version...
if first.0 < first.1 {
// No update. We are using a newer build than the last build released (dev?).
APIResponse::SuccessNoUpdate
}
// If the lastest released version is greater than the current version...
else if first.0 > first.1 {
// New major update. No more checks needed.
APIResponse::SuccessNewUpdate(last_release)
}
// If the lastest released version the same than the current version...
// We check the second number in the versions, and repeat.
else if second.0 < second.1 {
// No update. We are using a newer build than the last build released (dev?).
APIResponse::SuccessNoUpdate
}
else if second.0 > second.1 {
// New major update. No more checks needed.
APIResponse::SuccessNewUpdate(last_release)
}
// If the lastest released version the same than the current version...
// We check the last number in the versions, and repeat.
else if third.0 < third.1 {
// No update. We are using a newer build than the last build released (dev?).
APIResponse::SuccessNoUpdate
}
// If the lastest released version only has the last number higher, is a hotfix.
else if third.0 > third.1 {
// New major update. No more checks needed.
APIResponse::SuccessNewUpdateHotfix(last_release)
}
// If both versions are the same, it's a tie. We should never be able to reach this,
// thanks to the else a few lines below, but better safe than sorry.
else {
APIResponse::SuccessNoUpdate
}
}
// If both versions are the same, there is no update.
else {
APIResponse::SuccessNoUpdate
}
}
// If there has been no response from the server, or it has responded with an error...
Err(_) => APIResponse::Error,
};
// If we want to use a `MessageDialog`...
if let Some(parent_window) = use_dialog {
// Get the message we want to show, depending on the result of the "Update Check" from before.
let message: (String, String) = match apiresponse {
APIResponse::SuccessNewUpdate(last_release) => (format!("New mayor update found: \"{}\"", last_release.name), format!("Download available here:\n<a href=\"{}\">{}</a>\n\nChanges:\n{}", last_release.html_url, last_release.html_url, last_release.body)),
APIResponse::SuccessNewUpdateHotfix(last_release) => (format!("New minor update/hotfix found: \"{}\"", last_release.name), format!("Download available here:\n<a href=\"{}\">{}</a>\n\nChanges:\n{}", last_release.html_url, last_release.html_url, last_release.body)),
APIResponse::SuccessNoUpdate => ("No new updates available".to_owned(), "More luck next time :)".to_owned()),
APIResponse::SuccessUnknownVersion => ("Error while checking new updates".to_owned(), "There has been a problem when getting the lastest released version number, or the current version number.\n\nThat means I fucked up the last release title. If you see this, please report it here:\n<a href=\"https://github.com/Frodo45127/rpfm/issues\">https://github.com/Frodo45127/rpfm/issues</a>".to_owned()),
APIResponse::Error => ("Error while checking new updates :(".to_owned(), "If you see this message, there has been a problem with your connection to the Github.com server.\n\nPlease, make sure you can access to <a href=\"https:\\\\api.github.com\">https:\\\\api.github.com</a> and try again.".to_owned()),
};
// Create the `MessageDialog` to hold the messages.
let check_updates_dialog = MessageDialog::new(
Some(parent_window),
DialogFlags::from_bits(1).unwrap(),
MessageType::Info,
ButtonsType::Close,
&message.0
);
// Show the "Changes" of the release in the `MessageDialog`.
check_updates_dialog.set_title("Checking for updates...");
check_updates_dialog.set_property_secondary_use_markup(true);
check_updates_dialog.set_property_secondary_text(Some(&message.1));
// Run & Destroy.
check_updates_dialog.run();
check_updates_dialog.destroy();
}
// If we want to use the `Statusbar`...
else if let Some(status_bar) = status_bar {
// Get the message we want to show, depending on the result of the "Update Check" from before.
let message: String = match apiresponse {
APIResponse::SuccessNewUpdate(last_release) => format!("New mayor update found: \"{}\".", last_release.name),
APIResponse::SuccessNewUpdateHotfix(last_release) => format!("New minor update/hotfix found: \"{}\".", last_release.name),
APIResponse::SuccessNoUpdate => String::from("No new updates available."),
APIResponse::SuccessUnknownVersion |
APIResponse::Error => String::from("Error while checking new updates :("),
};
ui::show_message_in_statusbar(status_bar, &message);
}
// If we reach this place, no valid methods to show the result of the "Update Check" has been provided.
// So... we do nothing.
else {}
}
/// This function checks if there is any newer version of RPFM's schemas released. If the `use_dialog`
/// is false, we show the results of the check in the `Statusbar`.
pub fn check_schema_updates(
current_version: &str,
rpfm_path: &PathBuf,
supported_games: &[GameInfo],
game_selected: &Rc<RefCell<GameSelected>>,
loaded_schema: &Rc<RefCell<Option<Schema>>>,
use_dialog: Option<&ApplicationWindow>,
status_bar: Option<&Statusbar>
) {
// Create new client with API base URL
let mut client = RestClient::new("https://raw.githubusercontent.com").unwrap();
client.set_header_raw("User-Agent", &format!("RPFM/{}", current_version));
// Get `https://raw.githubusercontent.com/Frodo45127/rpfm/master/schemas/versions.json` and deserialize the result automatically.
let apiresponse = match client.get(()) {
// If we received a response from the server...
Ok(current_versions) => {
// We get `current_versions` into our `current_versions`. Redundant, but the compiler doesn't know his type otherwise.
let current_versions: Versions = current_versions;
// Get the local versions.
let local_versions: Versions = serde_json::from_reader(BufReader::new(File::open(PathBuf::from("schemas/versions.json")).unwrap())).unwrap();
// If both versions are equal, we have no updates.
if current_versions == local_versions { APIResponseSchema::SuccessNoUpdate }
// In any other sisuation, there is an update (or I broke something).
else { APIResponseSchema::SuccessNewUpdate(local_versions, current_versions) }
}
// If there has been no response from the server, or it has responded with an error...
Err(_) => APIResponseSchema::Error,
};
// If we want to use a `MessageDialog`...
if let Some(parent_window) = use_dialog {
// Get the message we want to show, depending on the result of the "Update Check" from before.
let message: (String, String) = match &apiresponse {
APIResponseSchema::SuccessNewUpdate(local_versions, current_versions) => {
// Set the title and the message.
let title = "New schema update available".to_owned();
let mut message = String::new();
// For each schema supported...
for (index, schema) in current_versions.schemas.iter().enumerate() {
// Add the name of the game, aligned to the left, with 20 characters.
message.push_str(&format!("{:width$}", schema.schema_file, width = 20));
// If the game exist in the local version, show both versions.
if let Some(local_schema) = local_versions.schemas.get(index) {
message.push_str(&format!(": {} => {}\n", local_schema.version, schema.version))
}
// Otherwise, it's a new game. Use 0 as his initial version.
else { message.push_str(&format!(": 0 => {}\n", schema.version))}
}
// Ask if you want to update.
message.push_str("\nDo you want to update the schemas?\n\nPlease note that the net code is far from optimal, and the program will hang while updating.");
// Return the title and the message.
(title, message)
}
APIResponseSchema::SuccessNoUpdate => ("No new schema updates available".to_owned(), "More luck next time :)".to_owned()),
APIResponseSchema::Error => ("Error while checking new schema updates :(".to_owned(), "If you see this message, there has been a problem with your connection to the Github.com server.\n\nPlease, make sure you can access to <a href=\"https:\\\\api.github.com\">https:\\\\api.github.com</a> and try again.".to_owned()),
};
// Depending on what we got, we use one button type or another.
let buttons = match apiresponse {
APIResponseSchema::SuccessNewUpdate(_, _) => ButtonsType::YesNo,
_ => ButtonsType::Close
};
// Create the `MessageDialog` to hold the messages.
let check_updates_dialog = MessageDialog::new(
Some(parent_window),
DialogFlags::from_bits(1).unwrap(),
MessageType::Info,
buttons,
&message.0
);
// Show the "Changes" of the release in the `MessageDialog`.
check_updates_dialog.set_title("Checking for schema updates...");
check_updates_dialog.set_property_secondary_use_markup(true);
check_updates_dialog.set_property_secondary_text(Some(&message.1));
// Match the response we have from running the dialog. "Yes" is -8. Anything else is close the dialog.
match check_updates_dialog.run() {
-8 => {
// Useless if, but easiest way I know to get local and current version at this point.
if let APIResponseSchema::SuccessNewUpdate(local_versions, current_versions) = apiresponse {
// Try to update the schemas.
let result = update_schemas(local_versions, current_versions, rpfm_path);
// After that, destroy the dialog.
check_updates_dialog.destroy();
// And now, we show a message of success or error, depending on what was the result of the update.
match result {
Ok(_) => {
// Reload the currently in-use schema, just in case it got updated.
*loaded_schema.borrow_mut() = Schema::load(rpfm_path, &supported_games.iter().filter(|x| x.folder_name == *game_selected.borrow().game).map(|x| x.schema.to_owned()).collect::<String>()).ok();
// Report success.
ui::show_dialog(parent_window, true, "Schemas successfully updated.");
}
Err(_) => ui::show_dialog(parent_window, false, "Error while trying to update the schemas."),
}
}
}
// In any other case, destroy it.
_ => check_updates_dialog.destroy(),
}
}
// If we want to use the `Statusbar`...
else if let Some(status_bar) = status_bar {
// Get the message we want to show, depending on the result of the "Update Check" from before.
let message: String = match apiresponse {
APIResponseSchema::SuccessNewUpdate(_,_) => String::from("New schema update found. Go to \"About/Check Schema Updates\" to download it."),
APIResponseSchema::SuccessNoUpdate => String::from("No new schema updates available."),
APIResponseSchema::Error => String::from("Error while checking new schema updates :("),
};
ui::show_message_in_statusbar(status_bar, &message);
}
// If we reach this place, no valid methods to show the result of the "Update Check" has been provided.
// So... we do nothing.
else {}
}
|
use dbus;
use dbus::tree::{MTFn, Method};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::atomic::Ordering;
use crate::daemon::{dbus_helper::DbusFactory, Daemon, DaemonStatus};
// Methods supported by the daemon.
pub const FETCH_UPDATES: &str = "FetchUpdates";
pub fn fetch_updates(
daemon: Rc<RefCell<Daemon>>,
dbus_factory: &DbusFactory,
) -> Method<MTFn<()>, ()> {
let method = dbus_factory.method(FETCH_UPDATES, move |message| {
let mut daemon = daemon.borrow_mut();
daemon.set_status(DaemonStatus::FetchingPackages, move |daemon, already_active| {
if already_active {
let (completed, total) = daemon.fetching_state.load(Ordering::SeqCst);
let completed = completed as u32;
let total = total as u32;
Ok(vec![true.into(), completed.into(), total.into()])
} else {
let (value, download_only): (Vec<String>, bool) =
message.read2().map_err(|why| format!("{}", why))?;
daemon
.fetch_updates(&value, download_only)
.map(|(x, t)| vec![x.into(), 0u32.into(), t.into()])
}
})
});
method
.inarg::<Vec<String>>("additional_packages")
.inarg::<bool>("download_only")
.outarg::<bool>("updates_available")
.outarg::<u32>("completed")
.outarg::<u32>("total")
.consume()
}
pub const RECOVERY_UPGRADE_FILE: &str = "RecoveryUpgradeFile";
pub fn recovery_upgrade_file(
daemon: Rc<RefCell<Daemon>>,
dbus_factory: &DbusFactory,
) -> Method<MTFn<()>, ()> {
let daemon = daemon.clone();
let method = dbus_factory.method::<_, String>(RECOVERY_UPGRADE_FILE, move |message| {
let mut daemon = daemon.borrow_mut();
daemon.set_status(DaemonStatus::RecoveryUpgrade, move |daemon, active| {
if !active {
let path = message.read1().map_err(|why| format!("{}", why))?;
daemon.recovery_upgrade_file(path)?;
}
Ok(Vec::new())
})
});
method.inarg::<&str>("path").outarg::<u8>("result").consume()
}
pub const RECOVERY_UPGRADE_RELEASE: &str = "RecoveryUpgradeRelease";
pub fn recovery_upgrade_release(
daemon: Rc<RefCell<Daemon>>,
dbus_factory: &DbusFactory,
) -> Method<MTFn<()>, ()> {
let daemon = daemon.clone();
let method = dbus_factory.method::<_, String>(RECOVERY_UPGRADE_RELEASE, move |message| {
let mut daemon = daemon.borrow_mut();
daemon.set_status(DaemonStatus::RecoveryUpgrade, move |daemon, active| {
if !active {
let (version, arch, flags) = message.read3().map_err(|why| format!("{}", why))?;
daemon.recovery_upgrade_release(version, arch, flags)?;
}
Ok(Vec::new())
})
});
method
.inarg::<&str>("version")
.inarg::<&str>("arch")
.inarg::<u8>("flags")
.outarg::<u8>("result")
.consume()
}
pub const RELEASE_CHECK: &str = "ReleaseCheck";
pub fn release_check(
daemon: Rc<RefCell<Daemon>>,
dbus_factory: &DbusFactory,
) -> Method<MTFn<()>, ()> {
let daemon = daemon.clone();
let method = dbus_factory.method(RELEASE_CHECK, move |_message| {
daemon.borrow_mut().release_check().map(|(current, next, available)| {
vec![current.into(), next.into(), available.map_or(-1, |a| a as i16).into()]
})
});
method.outarg::<&str>("current").outarg::<&str>("next").outarg::<i16>("build").consume()
}
pub const RELEASE_UPGRADE: &str = "ReleaseUpgrade";
pub fn release_upgrade(
daemon: Rc<RefCell<Daemon>>,
dbus_factory: &DbusFactory,
) -> Method<MTFn<()>, ()> {
let daemon = daemon.clone();
let method = dbus_factory.method::<_, String>(RELEASE_UPGRADE, move |message| {
let mut daemon = daemon.borrow_mut();
daemon.set_status(DaemonStatus::ReleaseUpgrade, move |daemon, active| {
if !active {
let (how, from, to) = message.read3().map_err(|why| format!("{}", why))?;
daemon.release_upgrade(how, from, to)?;
}
Ok(Vec::new())
})
});
method.inarg::<u8>("how").inarg::<&str>("from").inarg::<&str>("to").consume()
}
pub const RELEASE_REPAIR: &str = "ReleaseRepair";
pub fn release_repair(
daemon: Rc<RefCell<Daemon>>,
dbus_factory: &DbusFactory,
) -> Method<MTFn<()>, ()> {
let daemon = daemon.clone();
let method = dbus_factory.method::<_, String>(RELEASE_REPAIR, move |_message| {
let mut daemon = daemon.borrow_mut();
daemon.release_repair()?;
Ok(Vec::new())
});
method.consume()
}
pub const STATUS: &str = "Status";
pub fn status(daemon: Rc<RefCell<Daemon>>, dbus_factory: &DbusFactory) -> Method<MTFn<()>, ()> {
let daemon = daemon.clone();
let method = dbus_factory.method::<_, String>(STATUS, move |_| {
let daemon = daemon.borrow_mut();
let status = daemon.status.load(Ordering::SeqCst) as u8;
let sub_status = daemon.sub_status.load(Ordering::SeqCst) as u8;
Ok(vec![status.into(), sub_status.into()])
});
method.outarg::<u8>("status").outarg::<u8>("sub_status").consume()
}
pub const PACKAGE_UPGRADE: &str = "UpgradePackages";
pub fn package_upgrade(
daemon: Rc<RefCell<Daemon>>,
dbus_factory: &DbusFactory,
) -> Method<MTFn<()>, ()> {
let daemon = daemon.clone();
let method = dbus_factory.method::<_, String>(PACKAGE_UPGRADE, move |_| {
daemon.borrow_mut().set_status(DaemonStatus::PackageUpgrade, move |daemon, active| {
if !active {
daemon.package_upgrade()?;
}
Ok(Vec::new())
})
});
method.consume()
}
|
use bellperson::bls::Engine;
use bellperson::{Circuit, ConstraintSystem, SynthesisError};
use fff::Field;
pub const MIMC_ROUNDS: usize = 322;
pub fn mimc<E: Engine>(mut xl: E::Fr, mut xr: E::Fr, constants: &[E::Fr]) -> E::Fr {
assert_eq!(constants.len(), MIMC_ROUNDS);
for i in 0..MIMC_ROUNDS {
let mut tmp1 = xl;
tmp1.add_assign(&constants[i]);
let mut tmp2 = tmp1;
tmp2.square();
tmp2.mul_assign(&tmp1);
tmp2.add_assign(&xr);
xr = xl;
xl = tmp2;
}
xl
}
pub struct MiMCDemo<'a, E: Engine> {
pub xl: Option<E::Fr>,
pub xr: Option<E::Fr>,
pub constants: &'a [E::Fr],
}
impl<'a, E: Engine> Circuit<E> for MiMCDemo<'a, E> {
fn synthesize<CS: ConstraintSystem<E>>(self, cs: &mut CS) -> Result<(), SynthesisError> {
assert_eq!(self.constants.len(), MIMC_ROUNDS);
// Allocate the first component of the preimage.
let mut xl_value = self.xl;
let mut xl = cs.alloc(
|| "preimage xl",
|| xl_value.ok_or(SynthesisError::AssignmentMissing),
)?;
// Allocate the second component of the preimage.
let mut xr_value = self.xr;
let mut xr = cs.alloc(
|| "preimage xr",
|| xr_value.ok_or(SynthesisError::AssignmentMissing),
)?;
for i in 0..MIMC_ROUNDS {
// xL, xR := xR + (xL + Ci)^3, xL
let cs = &mut cs.namespace(|| format!("round {}", i));
// tmp = (xL + Ci)^2
let tmp_value = xl_value.map(|mut e| {
e.add_assign(&self.constants[i]);
e.square();
e
});
let tmp = cs.alloc(
|| "tmp",
|| tmp_value.ok_or(SynthesisError::AssignmentMissing),
)?;
cs.enforce(
|| "tmp = (xL + Ci)^2",
|lc| lc + xl + (self.constants[i], CS::one()),
|lc| lc + xl + (self.constants[i], CS::one()),
|lc| lc + tmp,
);
// new_xL = xR + (xL + Ci)^3
// new_xL = xR + tmp * (xL + Ci)
// new_xL - xR = tmp * (xL + Ci)
let new_xl_value = xl_value.map(|mut e| {
e.add_assign(&self.constants[i]);
e.mul_assign(&tmp_value.unwrap());
e.add_assign(&xr_value.unwrap());
e
});
let new_xl = if i == (MIMC_ROUNDS - 1) {
// This is the last round, xL is our image and so
// we allocate a public input.
cs.alloc_input(
|| "image",
|| new_xl_value.ok_or(SynthesisError::AssignmentMissing),
)?
} else {
cs.alloc(
|| "new_xl",
|| new_xl_value.ok_or(SynthesisError::AssignmentMissing),
)?
};
cs.enforce(
|| "new_xL = xR + (xL + Ci)^3",
|lc| lc + tmp,
|lc| lc + xl + (self.constants[i], CS::one()),
|lc| lc + new_xl - xr,
);
// xR = xL
xr = xl;
xr_value = xl_value;
// xL = new_xL
xl = new_xl;
xl_value = new_xl_value;
}
Ok(())
}
}
|
use crate::objects::hittable::HitRecord;
use crate::utils::util::random_double;
use crate::vec::vec3::{Color, Ray, Vec3};
pub trait Material: Sync + Send {
fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Vec3)>;
}
// ----------------------------------------------------------------------
// ----- METAL -----
// ----------------------------------------------------------------------
pub struct Metal {
pub(crate) albedo: Color,
pub(crate) fuzz: f64,
}
impl Metal {
pub fn new(albedo: Color, fuzz: f64) -> Metal {
Metal { albedo, fuzz }
}
}
impl Material for Metal {
fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Vec3)> {
let reflected = Vec3::reflect(&r_in.dir.unit(), &rec.normal);
let scattered = Ray::new(rec.p, reflected + self.fuzz * Vec3::random_in_unit_sphere());
let attenuation = self.albedo;
Some((scattered, attenuation))
}
}
// ----------------------------------------------------------------------
// ----- LAMBERTIAN -----
// ----------------------------------------------------------------------
pub struct Lambertian {
pub(crate) albedo: Color,
}
impl Lambertian {
pub fn new(albedo: Color) -> Lambertian {
Lambertian { albedo }
}
}
impl Material for Lambertian {
fn scatter(&self, _r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Vec3)> {
let scatter_direction = rec.normal + Vec3::random_unit_vector();
let scattered = Ray::new(rec.p, scatter_direction);
let attenuation = self.albedo;
Some((scattered, attenuation))
}
}
// ----------------------------------------------------------------------
// ----- DIELECTRIC -----
// ----------------------------------------------------------------------
#[derive(Clone, Copy)]
pub struct Dielectric {
pub(crate) reflection_index: f64,
}
impl Dielectric {
pub fn new(reflection_index: f64) -> Dielectric {
Dielectric { reflection_index }
}
fn reflectance(cosine: f64, ref_idx: f64) -> f64 {
// Use Schlick's approximation for reflectance.
let mut r0: f64 = (1.0 - ref_idx) / (1.0 + ref_idx);
r0 = r0 * r0;
r0 + (1.0 - r0) * (1.0 - cosine).powi(5)
}
}
impl Material for Dielectric {
fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Vec3)> {
let attenuation = Color::new(1.0, 1.0, 1.0);
let reflection_ratio = match rec.front_face {
true => 1.0 / self.reflection_index,
false => self.reflection_index,
};
let unit_direction = r_in.dir.unit();
// No min function for f64 apparently...
let mut cos_theta = -unit_direction.dot(&rec.normal);
if cos_theta > 1.0 {
cos_theta = 1.0;
}
let sin_theta = (1.0 - cos_theta * cos_theta).sqrt();
let direction = match reflection_ratio * sin_theta > 1.0
|| Dielectric::reflectance(cos_theta, reflection_ratio) > random_double()
{
true => Vec3::reflect(&unit_direction, &rec.normal),
false => Vec3::refract(&unit_direction, &rec.normal, reflection_ratio),
};
let scattered = Ray::new(rec.p, direction);
Some((scattered, attenuation))
}
}
|
use super::component::*;
use super::event::{Event, Events};
use crate::ui::rectangles::Rectangles;
use crate::api::{Client, Downloads, UpdateChecker};
use crate::cache::Cache;
use crate::config::Config;
use crate::ui::*;
use crate::Messages;
use std::error::Error;
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use signal_hook::consts::signal::*;
use signal_hook_tokio::Signals;
use termion::event::Key;
use tokio::sync::RwLock;
use tokio::task;
pub struct MainUI<'a> {
cache: Cache,
downloads: Downloads,
events: Events,
rectangles: Rectangles,
focused: FocusedWidget<'a>,
top_bar: Arc<RwLock<TopBar<'a>>>,
files_view: Arc<RwLock<FileTable<'a>>>,
download_view: Arc<RwLock<DownloadTable<'a>>>,
msg_view: Arc<RwLock<MessageList<'a>>>,
bottom_bar: Arc<RwLock<BottomBar<'a>>>,
redraw_terminal: Arc<AtomicBool>,
updater: UpdateChecker,
msgs: Messages,
}
impl<'a> MainUI<'static> {
pub fn new(cache: Cache, client: Client, config: Config, downloads: Downloads, msgs: Messages) -> Self {
// TODO use Tokio events?
let events = Events::new();
let updater = UpdateChecker::new(cache.clone(), client.clone(), config, msgs.clone());
let top_bar = RwLock::new(TopBar::new()).into();
let redraw_terminal = Arc::new(AtomicBool::new(true));
let files_view = Arc::new(RwLock::new(FileTable::new(redraw_terminal.clone(), cache.file_index.clone())));
let download_view = RwLock::new(DownloadTable::new(redraw_terminal.clone(), downloads.clone())).into();
let msg_view = RwLock::new(MessageList::new(redraw_terminal.clone(), msgs.clone())).into();
let bottom_bar = RwLock::new(BottomBar::new(redraw_terminal.clone(), client.request_counter)).into();
let focused = FocusedWidget::FileTable(files_view.clone());
Self {
cache,
downloads,
events,
rectangles: Rectangles::new(),
focused,
top_bar,
files_view,
download_view,
msg_view,
bottom_bar,
redraw_terminal,
updater,
msgs,
}
}
/* This is the main UI loop.
* Redrawing the terminal is quite CPU intensive, so we use a bunch of locks and atomics to make sure it only
* happens when necessary. */
pub async fn run(&mut self) -> Result<(), Box<dyn Error>> {
self.files_view.write().await.focus().await;
/* X11 (and maybe Wayland?) sends SIGWINCH when the window is resized, so we can listen to that. Otherwise we
* redraw when something has changed.
* We set this to true so that all widgets are rendered in the first loop. */
let got_sigwinch = Arc::new(AtomicBool::new(true));
let signals = Signals::new([SIGWINCH])?;
let handle = signals.handle();
let _sigwinch_task = task::spawn(handle_sigwinch(signals, got_sigwinch.clone()));
let mut terminal = term_setup().unwrap();
loop {
self.files_view.write().await.refresh().await;
// TODO make sure we don't redraw too often during downloads
self.download_view.write().await.refresh().await;
self.msg_view.write().await.refresh().await;
self.top_bar.write().await.refresh().await;
self.bottom_bar.write().await.refresh().await;
let recalculate_rects = got_sigwinch.swap(false, Ordering::Relaxed);
if self.redraw_terminal.swap(false, Ordering::Relaxed) || recalculate_rects {
let mut files_view = self.files_view.write().await;
let mut downloads_view = self.download_view.write().await;
let mut msgs_view = self.msg_view.write().await;
let topbar = self.top_bar.read().await;
let botbar = self.bottom_bar.read().await;
// TODO should this be done in a blocking thread?
terminal.draw(|f| {
if recalculate_rects {
self.rectangles.recalculate(f.size());
}
f.render_stateful_widget(
files_view.widget.clone(),
self.rectangles.rect_main[0],
&mut files_view.state,
);
f.render_stateful_widget(
downloads_view.widget.clone(),
self.rectangles.rect_main[1],
&mut downloads_view.state,
);
f.render_stateful_widget(
msgs_view.widget.clone(),
self.rectangles.rect_root[1],
&mut msgs_view.state,
);
f.render_widget(topbar.widget.clone(), self.rectangles.rect_topbar[0]);
f.render_widget(botbar.widget.clone(), self.rectangles.rect_botbar[1]);
})?;
}
if let Ok(Event::Input(key)) = self.events.next() {
if let Key::Char('q') | Key::Ctrl('c') = key {
handle.close();
return Ok(());
} else {
self.handle_keypress(key).await;
}
}
}
}
async fn handle_keypress(&mut self, key: Key) {
match key {
Key::Char('q') | Key::Ctrl('c') => {
//handle.close();
//return Ok(());
}
Key::Down | Key::Char('j') => {
self.focused.next().await;
}
Key::Up | Key::Char('k') => {
self.focused.previous().await;
}
Key::Left | Key::Char('h') => match self.focused {
FocusedWidget::MessageList(_) | FocusedWidget::DownloadTable(_) => {
self.focused.change_to(FocusedWidget::FileTable(self.files_view.clone())).await;
}
FocusedWidget::FileTable(_) => {
self.focused.change_to(FocusedWidget::MessageList(self.msg_view.clone())).await;
}
},
Key::Right | Key::Char('l') => match self.focused {
FocusedWidget::MessageList(_) | FocusedWidget::FileTable(_) => {
self.focused.change_to(FocusedWidget::DownloadTable(self.download_view.clone())).await;
}
FocusedWidget::DownloadTable(_) => {
self.focused.change_to(FocusedWidget::MessageList(self.msg_view.clone())).await;
}
},
Key::Char('i') => {
if let FocusedWidget::FileTable(fv) = &self.focused {
let ftable_lock = fv.read().await;
if let Some(i) = ftable_lock.state.selected() {
self.updater.ignore_file(i).await;
}
}
}
Key::Char('p') => {
if let FocusedWidget::DownloadTable(_) = &self.focused {
let dls_table = self.download_view.read().await;
if let Some(i) = dls_table.state.selected() {
self.downloads.toggle_pause_for(i).await;
}
}
}
Key::Char('U') => {
if let FocusedWidget::FileTable(fv) = &self.focused {
let game: String;
let mod_id: u32;
{
let ftable_lock = fv.read().await;
if let Some(i) = ftable_lock.state.selected() {
let files_lock = ftable_lock.file_index.files_sorted.read().await;
let fdata = files_lock.get(i).unwrap();
let lf_lock = fdata.local_file.read().await;
game = lf_lock.game.clone();
mod_id = lf_lock.mod_id;
} else {
return;
}
}
self.updater.update_mod(game, mod_id).await;
}
}
Key::Char('u') => {
if let FocusedWidget::FileTable(_fv) = &self.focused {
self.updater.update_all().await;
}
}
Key::Char('v') => {
if let FocusedWidget::FileTable(fv) = &self.focused {
let ftable_lock = fv.read().await;
if let Some(i) = ftable_lock.state.selected() {
let files_lock = ftable_lock.file_index.files_sorted.read().await;
let fdata = files_lock.get(i).unwrap();
let lf_lock = fdata.local_file.read().await;
let url = format!("https://www.nexusmods.com/{}/mods/{}", &lf_lock.game, &lf_lock.mod_id);
if let Err(_) = Command::new("xdg-open").arg(url).status() {
self.msgs.push(format!("xdg-open is needed to open URLs in browser.")).await;
}
}
}
}
Key::Delete => match &self.focused.clone() {
FocusedWidget::FileTable(ft) => {
let mut ft_lock = ft.write().await;
if let Some(i) = ft_lock.state.selected() {
if let Err(e) = self.cache.delete_by_index(i).await {
self.msgs.push(format!("Unable to delete file: {}", e)).await;
} else {
if i == 0 {
ft_lock.state.select(None);
}
drop(ft_lock);
self.focused.previous().await;
}
}
}
FocusedWidget::DownloadTable(dt) => {
let mut dt_lock = dt.write().await;
if let Some(i) = dt_lock.state.selected() {
dt_lock.downloads.delete(i).await;
if i == 0 {
dt_lock.state.select(None);
}
drop(dt_lock);
self.focused.previous().await;
}
}
FocusedWidget::MessageList(ml) => {
let mut ml_lock = ml.write().await;
if let Some(i) = ml_lock.state.selected() {
ml_lock.msgs.remove(i).await;
if i == 0 {
ml_lock.state.select(None);
}
drop(ml_lock);
self.focused.previous().await;
}
}
},
_ => {
// Uncomment to log keypresses
// self.msgs.push(format!("{:?}", key)).await;
}
}
}
}
|
use crossterm::tty::IsTty;
mod custom_commands;
mod git_actions;
mod hg_actions;
mod input;
mod repositories;
mod revision_shortcut;
mod scroll_view;
mod select;
mod tui;
mod tui_util;
mod version_control_actions;
fn main() {
if !std::io::stdin().is_tty() {
eprintln!("not tty");
return;
}
ctrlc::set_handler(|| {}).unwrap();
if let Some(version_control) = repositories::get_current_version_control() {
let custom_commands =
custom_commands::CustomCommand::load_custom_commands();
tui::show_tui(version_control, custom_commands);
} else {
eprintln!("no repository found");
}
}
|
use std::{
rc::Rc,
sync::{
Mutex,
Arc,
},
cell::RefCell,
};
use crate::{
renderer::{
RenderPassStatistics,
framework::{
gl,
geometry_buffer::{
ElementKind,
GeometryBuffer,
AttributeDefinition,
AttributeKind,
GeometryBufferKind,
},
gpu_texture::GpuTexture,
gpu_program::{
UniformValue,
GpuProgram,
UniformLocation,
},
state::{
State,
ColorMask,
StencilFunc,
StencilOp,
},
framebuffer::{
BackBuffer,
FrameBufferTrait,
DrawParameters,
CullFace,
},
},
error::RendererError,
TextureCache,
},
gui::{
brush::Brush,
draw::{
DrawingContext,
CommandKind,
CommandTexture,
},
self,
},
resource::texture::{
Texture,
TextureKind,
},
core::{
scope_profile,
math::{
Rect,
mat4::Mat4,
vec4::Vec4,
vec2::Vec2,
},
color::Color,
},
};
use crate::renderer::framework::framebuffer::DrawPartContext;
struct UiShader {
program: GpuProgram,
wvp_matrix: UniformLocation,
diffuse_texture: UniformLocation,
is_font: UniformLocation,
solid_color: UniformLocation,
brush_type: UniformLocation,
gradient_point_count: UniformLocation,
gradient_colors: UniformLocation,
gradient_stops: UniformLocation,
gradient_origin: UniformLocation,
gradient_end: UniformLocation,
resolution: UniformLocation,
bounds_min: UniformLocation,
bounds_max: UniformLocation,
}
impl UiShader {
pub fn new() -> Result<Self, RendererError> {
let fragment_source = include_str!("shaders/ui_fs.glsl");
let vertex_source = include_str!("shaders/ui_vs.glsl");
let program = GpuProgram::from_source("UIShader", vertex_source, fragment_source)?;
Ok(Self {
wvp_matrix: program.uniform_location("worldViewProjection")?,
diffuse_texture: program.uniform_location("diffuseTexture")?,
is_font: program.uniform_location("isFont")?,
solid_color: program.uniform_location("solidColor")?,
brush_type: program.uniform_location("brushType")?,
gradient_point_count: program.uniform_location("gradientPointCount")?,
gradient_colors: program.uniform_location("gradientColors")?,
gradient_stops: program.uniform_location("gradientStops")?,
gradient_origin: program.uniform_location("gradientOrigin")?,
gradient_end: program.uniform_location("gradientEnd")?,
bounds_min: program.uniform_location("boundsMin")?,
bounds_max: program.uniform_location("boundsMax")?,
resolution: program.uniform_location("resolution")?,
program,
})
}
}
pub struct UiRenderer {
shader: UiShader,
geometry_buffer: GeometryBuffer<gui::draw::Vertex>,
}
pub struct UiRenderContext<'a, 'b, 'c> {
pub state: &'a mut State,
pub viewport: Rect<i32>,
pub backbuffer: &'b mut BackBuffer,
pub frame_width: f32,
pub frame_height: f32,
pub drawing_context: &'c DrawingContext,
pub white_dummy: Rc<RefCell<GpuTexture>>,
pub texture_cache: &'a mut TextureCache,
}
impl UiRenderer {
pub(in crate::renderer) fn new(state: &mut State) -> Result<Self, RendererError> {
let geometry_buffer = GeometryBuffer::new(GeometryBufferKind::DynamicDraw, ElementKind::Triangle);
geometry_buffer.bind(state)
.describe_attributes(vec![
AttributeDefinition { kind: AttributeKind::Float2, normalized: false },
AttributeDefinition { kind: AttributeKind::Float2, normalized: false },
])?;
Ok(Self {
geometry_buffer,
shader: UiShader::new()?,
})
}
pub(in crate::renderer) fn render(&mut self, args: UiRenderContext) -> Result<RenderPassStatistics, RendererError> {
scope_profile!();
let UiRenderContext {
state, viewport, backbuffer,
frame_width, frame_height, drawing_context, white_dummy
, texture_cache
} = args;
let mut statistics = RenderPassStatistics::default();
state.set_blend_func(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
let geometry_buffer = self.geometry_buffer.bind(state);
geometry_buffer
.set_triangles(drawing_context.get_triangles())
.set_vertices(drawing_context.get_vertices());
let ortho = Mat4::ortho(0.0, frame_width, frame_height,
0.0, -1.0, 1.0);
for cmd in drawing_context.get_commands() {
let mut diffuse_texture = white_dummy.clone();
let mut is_font_texture = false;
let mut color_write = true;
match cmd.get_kind() {
CommandKind::Clip => {
if cmd.get_nesting() == 1 {
backbuffer.clear(state, viewport, None, None, Some(0));
}
state.set_stencil_op(StencilOp { zpass: gl::INCR, ..Default::default() });
// Make sure that clipping rect will be drawn at previous nesting level only (clip to parent)
state.set_stencil_func(StencilFunc { func: gl::EQUAL, ref_value: i32::from(cmd.get_nesting() - 1), ..Default::default() });
// Draw clipping geometry to stencil buffers
state.set_stencil_mask(0xFF);
color_write = false;
}
CommandKind::Geometry => {
// Make sure to draw geometry only on clipping geometry with current nesting level
state.set_stencil_func(StencilFunc { func: gl::EQUAL, ref_value: i32::from(cmd.get_nesting()), ..Default::default() });
match cmd.texture() {
CommandTexture::Font(font_arc) => {
let mut font = font_arc.lock().unwrap();
if font.texture.is_none() {
let tex = Texture::from_bytes(
font.get_atlas_size() as u32,
font.get_atlas_size() as u32,
TextureKind::R8,
font.get_atlas_pixels().to_vec(),
);
font.texture = Some(Arc::new(Mutex::new(tex)));
}
if let Some(texture) = texture_cache.get(state, font.texture.clone().unwrap().downcast::<Mutex<Texture>>().unwrap()) {
diffuse_texture = texture;
}
is_font_texture = true;
}
CommandTexture::Texture(texture) => {
if let Ok(texture) = texture.clone().downcast::<Mutex<Texture>>() {
if let Some(texture) = texture_cache.get(state, texture) {
diffuse_texture = texture;
}
}
}
_ => ()
}
// Do not draw geometry to stencil buffer
state.set_stencil_mask(0);
}
}
let mut raw_stops = [0.0; 16];
let mut raw_colors = [Vec4::default(); 16];
let uniforms = [
(self.shader.diffuse_texture, UniformValue::Sampler { index: 0, texture: diffuse_texture }),
(self.shader.wvp_matrix, UniformValue::Mat4(ortho)),
(self.shader.resolution, UniformValue::Vec2(Vec2::new(frame_width, frame_height))),
(self.shader.bounds_min, UniformValue::Vec2(cmd.min())),
(self.shader.bounds_max, UniformValue::Vec2(cmd.max())),
(self.shader.is_font, UniformValue::Bool(is_font_texture)),
(self.shader.brush_type, UniformValue::Integer({
match cmd.brush() {
Brush::Solid(_) => 0,
Brush::LinearGradient { .. } => 1,
Brush::RadialGradient { .. } => 2,
}
})),
(self.shader.solid_color, UniformValue::Color({
match cmd.brush() {
Brush::Solid(color) => *color,
_ => Color::WHITE,
}
})),
(self.shader.gradient_origin, UniformValue::Vec2({
match cmd.brush() {
Brush::Solid(_) => Vec2::ZERO,
Brush::LinearGradient { from, .. } => *from,
Brush::RadialGradient { center, .. } => *center,
}
})),
(self.shader.gradient_end, UniformValue::Vec2({
match cmd.brush() {
Brush::Solid(_) => Vec2::ZERO,
Brush::LinearGradient { to, .. } => *to,
Brush::RadialGradient { .. } => Vec2::ZERO,
}
})),
(self.shader.gradient_point_count, UniformValue::Integer({
match cmd.brush() {
Brush::Solid(_) => 0,
Brush::LinearGradient { stops, .. } | Brush::RadialGradient { stops, .. } => stops.len() as i32,
}
})),
(self.shader.gradient_stops, UniformValue::FloatArray({
match cmd.brush() {
Brush::Solid(_) => &[],
Brush::LinearGradient { stops, .. } | Brush::RadialGradient { stops, .. } => {
for (i, point) in stops.iter().enumerate() {
raw_stops[i] = point.stop;
}
&raw_stops
}
}
})),
(self.shader.gradient_colors, UniformValue::Vec4Array({
match cmd.brush() {
Brush::Solid(_) => &[],
Brush::LinearGradient { stops, .. } | Brush::RadialGradient { stops, .. } => {
for (i, point) in stops.iter().enumerate() {
raw_colors[i] = point.color.as_frgba();
}
&raw_colors
}
}
}))
];
let params = DrawParameters {
cull_face: CullFace::Back,
culling: false,
color_write: ColorMask::all(color_write),
depth_write: false,
stencil_test: cmd.get_nesting() != 0,
depth_test: false,
blend: true,
};
statistics += backbuffer.draw_part(
DrawPartContext {
state,
viewport,
geometry: &mut self.geometry_buffer,
program: &mut self.shader.program,
params,
uniforms: &uniforms,
offset: cmd.get_start_triangle(),
count: cmd.get_triangle_count(),
}
)?;
}
Ok(statistics)
}
} |
use std::io::{self, BufWriter, Write};
use std::path::Path;
use crossterm::{
queue,
style::{Attribute, Color, ContentStyle, Print, SetAttribute, SetForegroundColor, SetStyle},
};
use super::{Error, VestiErr};
use crate::location::Span;
const BOLD_TEXT: SetAttribute = SetAttribute(Attribute::Bold);
const ERR_COLOR: SetForegroundColor = SetForegroundColor(Color::Red);
const BLUE_COLOR: SetForegroundColor = SetForegroundColor(Color::DarkBlue);
const RESET_STYLE: SetAttribute = SetAttribute(Attribute::Reset);
pub fn pretty_print(
source: Option<&str>,
vesti_error: VestiErr,
filepath: Option<&Path>,
) -> io::Result<()> {
let mut stdout = BufWriter::new(io::stdout());
let err_title_color: SetStyle = SetStyle(ContentStyle {
foreground_color: Some(Color::White),
attributes: Attribute::Bold.into(),
..Default::default()
});
let lines = source.map(|inner| inner.lines());
let err_code = vesti_error.err_code();
let err_str = vesti_error.err_str();
queue!(
stdout,
BOLD_TEXT,
ERR_COLOR,
Print(format!(" error[E{0:04X}]", err_code)),
err_title_color,
Print(format!(": {}\n", err_str)),
RESET_STYLE,
)?;
if let VestiErr::ParseErr {
location: Span { start, end },
..
} = &vesti_error
{
let start_row_num = format!("{} ", start.row());
// If the filepath of the given input one is found, print it with error location
if let Some(m_filepath) = filepath {
queue!(
stdout,
Print(" ".repeat(start_row_num.len())),
BOLD_TEXT,
BLUE_COLOR,
Print("--> "),
RESET_STYLE,
Print(m_filepath.to_str().unwrap()),
Print(format!(":{}:{}\n", start.row(), start.column())),
)?;
}
queue!(
stdout,
BOLD_TEXT,
BLUE_COLOR,
Print(" ".repeat(start_row_num.len().saturating_add(1))),
Print("|\n "),
Print(&start_row_num),
Print("| "),
RESET_STYLE,
)?;
if let Some(mut inner) = lines {
queue!(stdout, Print(inner.nth(start.row() - 1).unwrap()))?;
}
queue!(stdout, Print("\n"))?;
// Print an error message with multiple lines
let padding_space = end.column().saturating_sub(start.column()) + 1;
queue!(
stdout,
BOLD_TEXT,
BLUE_COLOR,
Print(" ".repeat(start_row_num.len().saturating_add(1))),
Print("| "),
Print(" ".repeat(start.column().saturating_sub(1))),
ERR_COLOR,
Print("^".repeat(end.column().saturating_sub(start.column()))),
Print(" "),
)?;
for (i, msg) in vesti_error.err_detail_str().iter().enumerate() {
if i == 0 {
queue!(stdout, Print(msg), Print("\n"))?;
} else {
queue!(
stdout,
BOLD_TEXT,
BLUE_COLOR,
Print(" ".repeat(start_row_num.len().saturating_add(1))),
Print("| "),
Print(" ".repeat(start.column().saturating_sub(1))),
ERR_COLOR,
Print(" ".repeat(padding_space)),
Print(msg),
Print("\n"),
)?;
}
}
}
queue!(stdout, RESET_STYLE)?;
stdout.flush()?;
Ok(())
}
|
use poker::Hand;
use std::str::FromStr;
fn main() {
let hand = Hand::deal(5);
println!("hand = {}", hand);
println!("{}", hand.evaluate());
let hand = Hand::from_str("A♥ K♥ Q♥ J♥ 10♥").unwrap();
println!("\nhand = {}", hand);
println!("{}", hand.evaluate());
}
|
pub fn fraction_to_decimal(mut numerator: i32, mut denominator: i32) -> String {
if numerator == 0 {
return "0".to_string()
}
let mut result = vec![];
if (numerator as i64) * (denominator as i64) < 0 {
result.push("-".to_string());
}
let mut numerator = (numerator as i64).abs();
let mut denominator = (denominator as i64).abs();
result.push(format!("{}", numerator / denominator));
let mut occ = std::collections::HashMap::<i64, usize>::new();
if numerator % denominator != 0 {
result.push(".".to_string());
numerator %= denominator;
while !occ.contains_key(&numerator) {
occ.insert(numerator, result.len());
numerator *= 10;
result.push(format!("{}", numerator / denominator));
numerator %= denominator;
if numerator == 0 {
break
}
}
if numerator != 0 {
let index = occ.get(&numerator).unwrap();
result.insert(*index, "(".to_string());
result.push(")".to_string());
}
}
result.iter().fold("".to_string(), |acc, x| acc + x.as_str())
} |
use std::future::Future;
use std::io;
use std::marker::PhantomData;
pub(crate) mod time;
pub(crate) fn get_default_runtime_size() -> usize {
0
}
static NO_RUNTIME_NOTICE: &str = r#"No runtime configured for this platform, \
features that requires a runtime can't be used. \
Either compile with `target_arch = "wasm32", or enable the `tokio` feature."#;
fn panic_no_runtime() -> ! {
panic!("{}", NO_RUNTIME_NOTICE);
}
#[inline(always)]
pub(super) fn spawn_local<F>(_f: F)
where
F: Future<Output = ()> + 'static,
{
panic_no_runtime();
}
#[derive(Debug, Clone)]
pub(crate) struct Runtime {}
impl Default for Runtime {
fn default() -> Self {
panic_no_runtime();
}
}
impl Runtime {
pub fn new(_size: usize) -> io::Result<Self> {
panic_no_runtime();
}
pub fn spawn_pinned<F, Fut>(&self, _create_task: F)
where
F: FnOnce() -> Fut,
F: Send + 'static,
Fut: Future<Output = ()> + 'static,
{
panic_no_runtime();
}
}
#[derive(Debug, Clone)]
pub(crate) struct LocalHandle {
// This type is not send or sync.
_marker: PhantomData<*const ()>,
}
impl LocalHandle {
pub fn try_current() -> Option<Self> {
panic_no_runtime();
}
pub fn current() -> Self {
panic_no_runtime();
}
pub fn spawn_local<F>(&self, _f: F)
where
F: Future<Output = ()> + 'static,
{
panic_no_runtime();
}
}
|
pub mod builtins;
pub mod utils;
pub mod read_line;
pub mod exec;
use std::env;
use std::path::{Path, PathBuf};
use std::fmt;
use std::io;
use std::io::Write;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
#[derive(Clone)]
pub struct State {
cwd: PathBuf,
aliases: HashMap<String, String>,
argv: Vec<String>,
argc: usize,
exit_status: i32,
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"State {{
\tcwd: {},
\taliases: {:?},
\targv: {:?}
\targc: {}
\texit_status: {}
}}
",
self.cwd.display(),
self.aliases,
self.argv,
self.argc,
self.exit_status)
}
}
impl State {
pub fn new(cwd: String) -> State {
State {
cwd: utils::make_absolute(PathBuf::from(cwd)).unwrap(),
aliases: HashMap::new(),
argv: Vec::new(),
argc: 0,
exit_status: 0,
}
}
pub fn default() -> State {
match env::home_dir() {
Some(cwd) => {
State {
cwd: cwd,
aliases: HashMap::new(),
argv: Vec::new(),
argc: 0,
exit_status: 0,
}
}
None => panic!("Unable to determine home directory."),
}
}
#[cfg(any(unix))]
pub fn exec_paths(&self) -> Vec<PathBuf> {
let path = if let Ok(s) = env::var("PATH") {
s.clone()
} else {
"".to_string()
};
path.split(":")
.map(|x| Path::new(x).to_path_buf())
.collect()
}
#[cfg(windows)]
pub fn exec_paths(&self) -> Vec<PathBuf> {
let path = if let Ok(s) = env::var("PATH") {
s.clone()
} else {
"".to_string()
};
path.split(";")
.map(|x| Path::new(x).to_path_buf())
.collect()
}
}
pub fn run(initial_state: State) {
let mut s = initial_state.clone();
let mut builtins = builtins::load();
let i = read_line::Input::from(&s);
println!("Welcome to rsh! {:?}", s);
loop {
let input = i.prompt(format!("{} -> ", s.cwd.display()));
s.argv = parse_args(&input);
s.argc = s.argv.len();
print!("\n");
println!("Input: {} {:?}", input, s);
let first_arg = s.argv.get(0).unwrap().clone();
if let Entry::Occupied(f) = builtins.entry(String::from(first_arg)) {
let bn = f.get();
s.exit_status = bn(&mut s);
// prompt for input again.
continue;
}
// else try to run the command
exec::exec(&s);
}
}
#[derive(PartialEq)]
enum BuildType {
None,
Single,
Double,
}
struct ParseResult {
result: Vec<String>,
completed: bool,
build_string: String,
build_type: BuildType,
}
fn parse_args(args: &String) -> Vec<String> {
if args.len() == 0 {
return Vec::new();
}
let mut parse_result: ParseResult = ParseResult {
result: Vec::new(),
completed: false,
build_string: String::from(""),
build_type: BuildType::None,
};
let mut argstr = args.clone();
parse_string_into_vec(&argstr, &mut parse_result);
while !parse_result.completed {
// prompt for the rest of input
print!(">");
io::stdout().flush();
argstr = String::from("");
io::stdin().read_line(&mut argstr).unwrap();
parse_string_into_vec(&argstr, &mut parse_result);
}
let result: Vec<String> = parse_result.result
.into_iter()
.filter(|s| s.len() > 0)
.collect();
result
}
fn parse_string_into_vec(string: &String, parse_result: &mut ParseResult) {
let &mut ParseResult { ref mut build_string,
ref mut build_type,
ref mut completed,
ref mut result } = parse_result;
let mut iter = string.chars().peekable();
while let Some(c) = iter.next() {
match c {
'\'' => {
match *build_type {
BuildType::Single => {
*build_type = BuildType::None;
if iter.peek() == Some(&' ') {
result.push(build_string.clone());
*build_string = String::from("");
}
}
BuildType::None => {
*build_type = BuildType::Single;
}
_ => {
build_string.push(c);
}
}
}
'\"' => {
match *build_type {
BuildType::Double => {
*build_type = BuildType::None;
if iter.peek() == Some(&' ') {
result.push(build_string.clone());
*build_string = String::from("");
}
}
BuildType::None => {
*build_type = BuildType::Double;
}
_ => {
build_string.push(c);
}
}
}
' ' => {
match *build_type {
BuildType::None => {
result.push(build_string.clone());
*build_string = String::from("");
}
_ => {
build_string.push(c);
}
}
}
'\n' => {
match *build_type {
BuildType::None => {
match iter.peek() {
Some(_) => {
build_string.push(c);
}
None => {}
}
}
_ => {
build_string.push(c);
}
}
}
_ => {
build_string.push(c);
}
}
}
if *build_type == BuildType::None {
*completed = true;
if build_string.len() > 0 {
result.push(build_string.clone());
}
}
}
#[test]
fn parse_args_test() {
// parse empty string
{
let expected: Vec<String> = Vec::new();
let result = parse_args(&String::from(""));
assert_eq!(result, expected);
}
// parse single-word string
{
let expected: Vec<String> = vec!["echo".to_string()];
let result = parse_args(&String::from("echo"));
assert_eq!(result, expected);
}
// parse single-word string inside quotes
{
let expected = vec!["echo".to_string()];
let result = parse_args(&String::from("\"echo\""));
assert_eq!(result, expected);
}
// parse multi-word string with closed quotes section
{
let expected = vec!["echo".to_string(), "-n".into(), "Hello Dear World".into()];
let result = parse_args(&String::from("echo -n \"Hello Dear World\""));
assert_eq!(result, expected);
}
// parse multi-word string with multiple closed quotes sections
{
let expected = vec!["echo".to_string(), "Hello".into(), "Dear World".into()];
let result = parse_args(&String::from("echo \"Hello\" \"Dear World\""));
assert_eq!(result, expected);
}
// parse multi-word string with no spaces around single quotes
{
let expected = vec!["echo".to_string(), "helloworld".into()];
let result = parse_args(&String::from("echo 'hello'world"));
assert_eq!(result, expected);
}
// parse multi-word string with no spaces around double quotes
{
let expected = vec!["echo".to_string(), "helloworld".into()];
let result = parse_args(&String::from("echo \"hello\"world"));
assert_eq!(result, expected);
}
// allow double quotes inside single quotes
{
let expected = vec!["\"".to_string()];
let result = parse_args(&String::from("'\"'"));
assert_eq!(result, expected);
}
// allow single quotes inside double quotes
{
let expected = vec!["\'".to_string()];
let result = parse_args(&String::from("\"\'\""));
assert_eq!(result, expected);
}
// handle multiple quote sections in succession
{
let expected = vec!["echo".to_string(), "hello world how are you".into()];
let result = parse_args(&String::from("echo \"hello world\"\' how are you\'"));
assert_eq!(result, expected);
}
// preserve newlines
{
let expected = vec!["echo".to_string(), "hello\nworld".into()];
let result = parse_args(&String::from("echo \"hello\nworld\""));
assert_eq!(result, expected);
}
// remove final newline
{
let expected = vec!["echo".to_string()];
let result = parse_args(&String::from("echo\n"));
assert_eq!(result, expected);
}
}
|
use emu8080::Cpu;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::Canvas;
use sdl2::video::Window;
use sdl2::EventPump;
use std::fs::File;
use std::io::prelude::*;
use std::time::Duration;
use std::time::Instant;
const HEIGHT: u32 = 224;
const WIDTH: u32 = 256;
struct Cabinet {
p0: u8,
p1: u8,
p2: u8,
p3: u8,
p4: u8,
p5: u8,
p6: u8,
p7: u8,
shift: u16,
offset: u8,
}
// move game stuff inside of the impl Cabinet block. The game runs as part of the full cabinet implementation.
impl Cabinet {
fn new() -> Self {
Cabinet {
// p0: 0xE,
p0: 0,
p1: 1,
// p1: 0x8,
p2: 0,
p3: 0,
p4: 0,
p5: 0,
p6: 0,
p7: 0,
shift: 0,
offset: 0,
}
}
fn input(&mut self, port: u8) -> u8 {
match port {
0 => self.p0,
1 => self.p1,
2 => self.p2,
3 => ((self.shift >> (8 - self.offset)) & 0xFF) as u8,
_ => panic!("Invalid port selection"),
}
}
fn output(&mut self, port: u8, value: u8) {
match port {
2 => self.offset = value & 0x7,
3 => {
// sound stuff
}
4 => self.shift = (self.shift >> 8) | ((value as u16) << 8),
_ => {
// do nothing
}
}
}
fn key_down(&mut self, key: Keycode) {
match key {
Keycode::A => self.p1 |= 0x20,
Keycode::Kp4 => self.p2 |= 0x20,
Keycode::D => self.p1 |= 0x40,
Keycode::Kp6 => self.p2 |= 0x40,
Keycode::Space => self.p1 |= 0x10,
Keycode::Kp0 => self.p2 |= 0x10,
_ => {
// do nothing
}
}
}
fn key_up(&mut self, key: Keycode) {
match key {
Keycode::A => self.p1 &= 0xDF,
Keycode::Kp4 => self.p2 &= 0xDF,
Keycode::D => self.p1 &= 0xBF,
Keycode::Kp6 => self.p2 &= 0xBF,
Keycode::Space => self.p1 &= 0xEF,
Keycode::Kp0 => self.p2 &= 0xEF,
_ => {
// do nothing
}
}
}
}
fn main() {
const NANOS_PER_SECOND: u64 = 1_000_000_000;
const CPU_SPEED: u64 = 2_000_000;
const NANOS_PER_CYCLE: u64 = NANOS_PER_SECOND / CPU_SPEED;
const VIDEO_INTERRUPT_TIMER: Duration = Duration::from_nanos(16667);
env_logger::init();
let sdl = sdl2::init().expect("Sdl failed to init. Big mistake.");
let mut cabinet = Cabinet::new();
let mut cpu = Cpu::new();
read_space_invaders_into_memory(&mut cpu);
let mut event_pump = sdl
.event_pump()
.expect("Event pump failed. Possibly another is running?");
let audio = sdl.audio().unwrap();
let video = sdl.video().unwrap();
let window = video
.window("Invaders from Space", HEIGHT, WIDTH)
.build()
.unwrap();
let mut canvas = window
.into_canvas()
.accelerated()
.present_vsync()
.build()
.expect("window failed to init to canvas");
let mut last_interrupt = Instant::now();
let mut last_cycle = Instant::now();
let mut cycles_elapsed: u64 = 0;
let mut count = 0;
'running: loop {
handle_events(&cpu, &mut cabinet, &mut event_pump);
// if Instant::now().duration_since(last_interrupt) >= VIDEO_INTERRUPT_TIMER {
// if cpu.interrupts_enabled() {
// last_interrupt = Instant::now();
// }
// } else {
// let nanos_elapsed = Duration::from_nanos(cycles_elapsed * NANOS_PER_CYCLE);
// if Instant::now().duration_since(last_cycle) > nanos_elapsed {
let op = cpu.get_current_opcode();
match op.code {
0xD3 => {
let (byte, register) = cpu.output();
cabinet.output(byte, register.into());
cpu.increment_pc(1);
}
0xDB => {
let input = cabinet.input(cpu.get_next_byte());
cpu.input(input);
cpu.increment_pc(1);
}
_ => {
cycles_elapsed += cpu.execute_opcode(&count) as u64;
last_cycle = Instant::now();
}
}
// }
// }
if count > 50000 {
draw_to_screen(&mut cpu, &mut canvas);
}
count += 1;
}
}
fn read_space_invaders_into_memory(cpu: &mut Cpu) {
let path1 = String::from("src/roms/invaders.h");
let path2 = String::from("src/roms/invaders.g");
let path3 = String::from("src/roms/invaders.f");
let path4 = String::from("src/roms/invaders.e");
let path_list = vec![path1, path2, path3, path4];
for (i, path) in path_list.iter().enumerate() {
let mut file = File::open(&path).expect("File not found");
let mut buffer = [0u8; 0x7FF];
file.read(&mut buffer).expect("Error reading file.");
cpu.load_rom_into_memory(0x7FF * i + i, &buffer);
}
}
fn handle_events(cpu: &Cpu, cabinet: &mut Cabinet, event_pump: &mut EventPump) {
for event in event_pump.poll_iter() {
match event {
Event::Quit { .. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => ::std::process::exit(0),
Event::KeyDown {
keycode: Some(key), ..
} => cabinet.key_down(key),
Event::KeyUp {
keycode: Some(key), ..
} => cabinet.key_up(key),
_ => {
// do nothing
}
}
}
}
fn draw_to_screen(cpu: &mut Cpu, canvas: &mut Canvas<Window>) {
let white = Color::RGB(255, 255, 255);
let black = Color::RGB(0, 0, 0);
canvas.clear();
let display_buffer = cpu.get_video_memory();
let shift_end = 7u8;
for (i, byte) in display_buffer.iter().enumerate() {
let y = (i * 8) / (WIDTH as usize + 1);
for shift in 0..shift_end {
let x = ((i * 8) % WIDTH as usize) + shift as usize;
if (byte >> shift) & 1 == 0 {
canvas.set_draw_color(black);
} else {
canvas.set_draw_color(white);
}
let rect = Rect::new(x as i32, y as i32, 10, 10);
canvas.fill_rect(rect).unwrap();
}
}
canvas.present()
}
|
extern crate log;
use mio::{Events, Poll, Ready, PollOpt, Token};
use mio::tcp::{TcpListener, TcpStream};
use std::net::{SocketAddr};
use std::collections::{HashMap};
use std::{thread, time};
use std::io::{self, Read, Write};
use super::peer::{PeerContext, PeerDirection};
use super::MSG_BUF_SIZE;
use super::message::{Message, ServerSignal, ConnectResult, ConnectHandle, TaskRequest};
use super::peer::{self, ReadResult, WriteResult};
use mio_extras::channel::{self, Receiver};
use std::sync::mpsc;
use crossbeam::channel as cbchannel;
use mio::{self, net};
use log::{info, warn};
// refer to https://sergey-melnychuk.github.io/2019/08/01/rust-mio-tcp-server/
// for context
const LISTENER: Token = Token(0);
const CONTROL: Token = Token(1);
const NETWORK_TOKEN: usize = 0;
const LOCAL_TOKEN: usize = 1;
const EVENT_CAP: usize = 1024;
pub struct Context {
poll: mio::Poll,
peers: HashMap<Token, PeerContext>,
token_counter: usize,
task_sender: cbchannel::Sender<TaskRequest>,
response_receiver: HashMap<Token, channel::Receiver<Vec<u8>>>,
api_receiver: channel::Receiver<ServerSignal>,
local_addr: SocketAddr,
is_scale_node: bool,
}
pub struct Handle {
pub control_tx: channel::Sender<ServerSignal>,
}
impl Handle{
pub fn connect(&mut self, addr: SocketAddr) -> std::io::Result<mpsc::Receiver<ConnectResult>> {
let (sender, receiver) = mpsc::channel();
let connect_handle = ConnectHandle {
result_sender: sender,
dest_addr: addr ,
};
self.control_tx.send(ServerSignal::ServerConnect(connect_handle.clone()));
Ok(receiver)
}
pub fn broadcast(
&mut self,
msg: Message
) { // -> std::io::Result<mpsc::Receiver<ConnectResult>> {
self.control_tx.send(
ServerSignal::ServerBroadcast(msg));
}
}
impl Context {
pub fn new(
task_sender: cbchannel::Sender<TaskRequest>,
addr: SocketAddr,
is_scale_node: bool,
) -> (Context, Handle) {
let (control_tx, control_rx) = channel::channel();
let handle = Handle {
control_tx: control_tx,
};
let context = Context{
poll: Poll::new().unwrap(),
peers: HashMap::new(),
token_counter: 2, // 0, 1 token are reserved
task_sender: task_sender,
response_receiver: HashMap::new(),
api_receiver: control_rx,
local_addr: addr,
is_scale_node: is_scale_node,
};
(context, handle)
}
// start a server, spawn a process
pub fn start(mut self) {
let _handler = thread::spawn(move || {
self.listen();
});
}
// register tcp in the event loop
// network read token i
// local event token i + 1
// token starts at 2
pub fn register_peer(&mut self, socket: TcpStream, direction: PeerDirection) -> io::Result<Token> {
let peer_addr = socket.peer_addr().unwrap();
let network_token = Token(self.token_counter);
self.token_counter += 1;
self.poll.register(
&socket,
network_token.clone(),
Ready::readable(),
PollOpt::edge()
).unwrap();
// create a peer context
let (peer_context, handle) = PeerContext::new(socket, direction).unwrap();
let local_token = Token(self.token_counter);
self.token_counter += 1;
self.poll.register(
&peer_context.writer.queue,
local_token,
Ready::readable(),
PollOpt::edge() | mio::PollOpt::oneshot(),
).unwrap();
self.peers.insert(network_token, peer_context);
Ok(network_token)
}
// create tcp stream for each peer
pub fn connect(&mut self, connect_handle: ConnectHandle) -> io::Result<()> {
let addr: SocketAddr = connect_handle.dest_addr;
let timeout = time::Duration::from_millis(3000);
let tcp_stream = match std::net::TcpStream::connect_timeout(&addr, timeout) {
Ok(s) => s,
Err(e) => {
connect_handle.result_sender.send(ConnectResult::Fail);
return Ok(());
}
};
let stream = TcpStream::from_stream(tcp_stream)?;
let network_token = self.register_peer(stream, PeerDirection::Outgoing).unwrap();
connect_handle.result_sender.send(ConnectResult::Success);
Ok(())
}
pub fn process_control(&mut self, msg: ServerSignal) -> std::io::Result<()> {
match msg {
ServerSignal::ServerConnect(connect_handle) => {
self.connect(connect_handle);
},
ServerSignal::ServerBroadcast(network_message) => {
for (token, peer) in self.peers.iter() {
match peer.direction {
PeerDirection::Incoming => (),
PeerDirection::Outgoing => {
peer.peer_handle.write(network_message.clone());
},
}
}
},
ServerSignal::ServerUnicast((socket, network_message)) => {
for (token, peer) in self.peers.iter() {
if peer.addr == socket {
match peer.direction {
PeerDirection::Incoming => (),
PeerDirection::Outgoing => {
peer.peer_handle.write(network_message.clone());
},
}
}
}
},
ServerSignal::ServerStart => {
},
ServerSignal::ServerStop => {
},
ServerSignal::ServerDisconnect => {
},
}
Ok(())
}
pub fn process_writable(&mut self, token: mio::Token) -> std::io::Result<()> {
let peer = self.peers.get_mut(&token).expect("writable cannot get peer");
match peer.writer.write() {
Ok(WriteResult::Complete) => {
let writer_token = mio::Token(token.0 + 1);
let socket_token = token;
self.poll.reregister(
&peer.stream,
socket_token,
mio::Ready::readable(),
mio::PollOpt::edge(),
)?;
// we're interested in write queue again.
self.poll.reregister(
&peer.writer.queue,
writer_token,
mio::Ready::readable(),
mio::PollOpt::edge() | mio::PollOpt::oneshot(),
)?;
},
Ok(WriteResult::EOF) => {
info!("Peer {} dropped connection", peer.addr);
self.peers.remove(&token);
},
Ok(WriteResult::ChanClosed) => {
warn!("Peer {} outgoing queue closed", peer.addr);
let socket_token = token;
self.poll.reregister(
&peer.stream,
socket_token,
mio::Ready::readable(),
mio::PollOpt::edge(),
)?;
self.poll.deregister(&peer.writer.queue)?;
},
Err(e) => {
if e.kind() == std::io::ErrorKind::WouldBlock {
trace!("Peer {} finished writing", peer.addr);
// socket is not ready anymore, stop reading
} else {
warn!("Error writing peer {}, disconnecting: {}", peer.addr, e);
self.peers.remove(&token);
}
}
}
Ok(())
}
pub fn process_readable(&mut self, token: mio::Token) {
let mut peer = self.peers.get_mut(&token).expect("get peer fail");
loop {
match peer.reader.read() {
Ok(ReadResult::EOF) => {
info!("Peer {} dropped connection", peer.addr);
self.peers.remove(&token);
//let index = self.peer_list.iter().position(|&x| x == peer_id).unwrap();
//self.peer_list.swap_remove(index);
break;
}
Ok(ReadResult::Continue) => {
trace!("Peer {:?} reading continue", token);
continue;
},
Ok(ReadResult::Message(m)) => {
// send task request to performer
let msg = bincode::deserialize(&m).unwrap();
let performer_task = TaskRequest{
peer: Some(peer.peer_handle.clone()),
msg: msg,
};
self.task_sender.send(performer_task).expect("send request to performer");
},
Err(ref e) => {
if e.kind() == std::io::ErrorKind::WouldBlock {
trace!("Peer {:?} finished reading", token);
// socket is not ready anymore, stop reading
break;
} else {
warn!("Error reading peer {}, disconnecting: {}", peer.addr, e);
self.peers.remove(&token);
//let index = self.peer_list.iter().position(|&x| x == peer_id).unwrap();
//self.peer_list.swap_remove(index);
break;
}
}
}
}
}
// polling events
pub fn listen(&mut self) -> std::io::Result<()> {
let listener = TcpListener::bind(&self.local_addr).unwrap();
self.poll.register(
&listener,
LISTENER,
Ready::readable(),
PollOpt::edge()
).unwrap();
self.poll.register(
&self.api_receiver,
CONTROL,
Ready::readable(),
PollOpt::edge()
).unwrap();
let mut events = Events::with_capacity(EVENT_CAP);
loop {
self.poll.poll(&mut events, None).expect("unable to poll events");
for event in &events {
let token = event.token();
match token {
LISTENER => {
loop {
match listener.accept() {
Ok((socket, socket_addr)) => {
match self.register_peer(socket, PeerDirection::Incoming) {
Ok(_) => (),
Err(e) => {
error!("Error initializaing incoming peer {}: {}", socket_addr, e);
}
}
},
Err(e) => {
if e.kind() == std::io::ErrorKind::WouldBlock {
break;
} else {
return Err(e);
}
}
}
}
},
CONTROL => {
// process until queue is empty
loop {
match self.api_receiver.try_recv() {
Ok(msg) => self.process_control(msg).unwrap(),
Err(e) => match e {
mpsc::TryRecvError::Empty => break,
mpsc::TryRecvError::Disconnected => {
warn!("P2P server dropped, disconnecting all peers");
self.poll.deregister(&self.api_receiver)?;
break;
}
}
}
}
},
mio::Token(token_id) => {
let token_type: usize = token_id % 2;
match token_type {
NETWORK_TOKEN => {
let readiness = event.readiness();
if readiness.is_readable() {
//if !self.peers.contains(token) {
//continue;
//}
self.process_readable(token);
}
if readiness.is_writable() {
//if !self.peers.contains(token) {
//continue;
//}
self.process_writable(token);
}
},
LOCAL_TOKEN => {
let peer_token = Token(token_id - 1);
let peer = self.peers.get(&peer_token).expect("cannot get peer with local token");
self.poll.reregister(
&peer.stream,
peer_token,
mio::Ready::readable() | mio::Ready::writable(),
mio::PollOpt::edge(),
).unwrap();
},
_ => unreachable!(),
}
}
}
}
}
}
}
|
//! The rrpcore crate contains all the building blocks to run a reverse proxy.
//! RRP is heavily based off of Netflix's Zuul framework. HTTP requests are run
//! through a series of user defined Filter's, which process the request and can
//! take several actions including validating the request, routing the request, etc.
//! Once routed other filters can then process the response and forward the upstream
//! response to the client. Note that RRP simply provides the building blocks -
//! an implementation need not have the same functionality (or even be a reverse proxy).
//!
//! # Examples
//! TODO
extern crate hyper;
extern crate lazysort;
#[macro_use]
extern crate log;
use hyper::server::{Handler, Request, Response};
pub mod filters;
pub struct RRPHandler {
}
impl Handler for RRPHandler {
fn handle(&self, req: Request, res: Response) {
filters::FilterRegistry::new();
res.send(b"Hello World!").unwrap();
}
} |
pub mod create_table;
pub mod delete_query;
pub mod insert_query;
pub mod select_query;
use std::fmt;
use self::create_table::CreateTableQuery;
use self::delete_query::DeleteQuery;
use self::insert_query::InsertQuery;
use self::select_query::SelectQuery;
#[derive(Debug, PartialEq)]
pub enum ValidatedStatement {
Create(CreateTableQuery),
Insert(InsertQuery<TypedColumn>),
Select(SelectQuery<TypedColumn>),
Delete
}
#[derive(PartialEq)]
pub enum TypedStatement {
Create(CreateTableQuery),
Insert(InsertQuery<TypedColumn>),
Select(SelectQuery<TypedColumn>),
Delelte
}
impl fmt::Debug for TypedStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
TypedStatement::Create(ref create_table_query) => write!(f, "{:?}", create_table_query),
TypedStatement::Insert(ref insert_query) => write!(f, "{:?}", insert_query),
TypedStatement::Select(ref select_query) => write!(f, "{:?}", select_query),
_ => panic!("unimplemented debug formatting")
}
}
}
#[derive(PartialEq, Clone)]
pub struct TypedColumn {
pub name: String,
pub col_type: Type
}
impl TypedColumn {
pub fn new<I: Into<String>>(name: I, col_type: Type) -> TypedColumn {
TypedColumn {
name: name.into(),
col_type: col_type
}
}
}
impl fmt::Debug for TypedColumn {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<name: '{}', type: '{:?}'>", self.name, self.col_type)
}
}
#[derive(PartialEq, Clone)]
pub enum RawStatement {
Create(CreateTableQuery),
Delete(DeleteQuery),
Insert(InsertQuery<RawColumn>),
Select(SelectQuery<RawColumn>)
}
impl fmt::Debug for RawStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RawStatement::Create(ref query) => write!(f, "{:?}", query),
RawStatement::Delete(ref query) => write!(f, "{:?}", query),
RawStatement::Insert(ref query) => write!(f, "{:?}", query),
RawStatement::Select(ref query) => write!(f, "{:?}", query),
}
}
}
#[derive(PartialEq, Clone)]
pub struct RawColumn {
pub name: String
}
impl RawColumn {
pub fn new<I: Into<String>>(name: I) -> RawColumn {
RawColumn {
name: name.into()
}
}
}
impl fmt::Debug for RawColumn {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<name: '{}'>", self.name)
}
}
#[derive(PartialEq, Clone, Copy, Hash, Eq)]
pub enum Type {
Integer,
Character(Option<u8>),
}
impl fmt::Debug for Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Type::Integer => write!(f, "integer"),
Type::Character(Some(v)) => write!(f, "character[{}]", v),
Type::Character(None) => write!(f, "character")
}
}
}
pub fn debug_predicates(predicates: &Option<Condition>) -> String {
match *predicates {
Some(ref cond) => cond.to_string(),
None => "no predicate".into()
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct Condition {
pub left: CondArg,
pub right: CondArg,
pub cond_type: CondType
}
impl Condition {
pub fn new(left: CondArg, right: CondArg, cond_type: CondType) -> Condition {
Condition {
left: left,
right: right,
cond_type: cond_type
}
}
pub fn equals(left: CondArg, right: CondArg) -> Condition {
Condition::new(left, right, CondType::Eq)
}
pub fn not_equals(left: CondArg, right: CondArg) -> Condition {
Condition::new(left, right, CondType::NotEq)
}
}
impl ToString for Condition {
fn to_string(&self) -> String {
match (&self.left, &self.cond_type, &self.right) {
(&CondArg::ColumnName(ref name), &CondType::Eq, &CondArg::NumConst(ref c)) => format!("predicate <{} equals to {}>", name, c),
(&CondArg::StringConstant(ref c), &CondType::Eq, &CondArg::ColumnName(ref name)) => format!("predicate <'{}' equals to {}>", c, name),
(&CondArg::Limit, &CondType::Eq, &CondArg::NumConst(ref c)) => format!("predicate <limit equals to {}>", c),
(&CondArg::ColumnName(ref name), &CondType::NotEq, &CondArg::StringConstant(ref c)) => format!("predicate <{} not equals to '{}'>", name, c),
_ => "unimlemented condition formatting".into()
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum CondType {
Eq,
NotEq
}
#[derive(Debug, PartialEq, Clone)]
pub enum CondArg {
ColumnName(String),
StringConstant(String),
NumConst(String),
Limit
}
impl CondArg {
pub fn column<I: Into<String>>(column_name: I) -> CondArg {
CondArg::ColumnName(column_name.into())
}
pub fn str<I: Into<String>>(const_str: I) -> CondArg {
CondArg::StringConstant(const_str.into())
}
pub fn num<I: Into<String>>(const_num: I) -> CondArg {
CondArg::NumConst(const_num.into())
}
}
|
//! Support for streaming objects from a Parquet file.
use std::fs::File;
use std::path::Path;
use std::thread::spawn;
use crossbeam::channel::{bounded, Receiver};
use anyhow::Result;
use arrow2::chunk::Chunk;
use log::*;
use arrow2::array::{Array, StructArray};
use arrow2::io::parquet::read::{infer_schema, read_metadata, FileReader};
use arrow2_convert::deserialize::*;
/// Iterator over deserialized records from a Parquet file.
pub struct RecordIter<R>
where
R: ArrowDeserialize + Send + Sync + 'static,
for<'a> &'a R::ArrayType: IntoIterator,
{
remaining: usize,
channel: Receiver<Result<Vec<R>>>,
batch: Option<std::vec::IntoIter<R>>,
}
impl<R> RecordIter<R>
where
R: ArrowDeserialize + Send + Sync + 'static,
for<'a> &'a R::ArrayType: IntoIterator,
{
pub fn remaining(&self) -> usize {
self.remaining
}
}
fn decode_chunk<R, E>(chunk: Result<Chunk<Box<dyn Array>>, E>) -> Result<Vec<R>>
where
R: ArrowDeserialize<Type = R> + Send + Sync + 'static,
for<'a> &'a R::ArrayType: IntoIterator<Item = Option<R>>,
E: std::error::Error + Send + Sync + 'static,
{
let chunk = chunk?;
let chunk_size = chunk.len();
let sa = StructArray::try_new(R::data_type(), chunk.into_arrays(), None).map_err(|e| {
error!("error decoding struct array: {:?}", e);
e
})?;
let sa: Box<dyn Array> = Box::new(sa);
let sadt = sa.data_type().clone();
let recs: Vec<R> = sa.try_into_collection().map_err(|e| {
error!("error deserializing batch: {:?}", e);
info!("chunk schema: {:?}", sadt);
info!("target schema: {:?}", R::data_type());
e
})?;
assert_eq!(recs.len(), chunk_size);
Ok(recs)
}
/// Scan a Parquet file in a background thread and deserialize records.
pub fn scan_parquet_file<R, P>(path: P) -> Result<RecordIter<R>>
where
P: AsRef<Path>,
R: ArrowDeserialize<Type = R> + Send + Sync + 'static,
for<'a> &'a R::ArrayType: IntoIterator<Item = Option<R>>,
{
let path = path.as_ref();
let mut reader = File::open(path)?;
let meta = read_metadata(&mut reader)?;
let schema = infer_schema(&meta)?;
let row_count = meta.num_rows;
let row_groups = meta.row_groups;
let reader = FileReader::new(reader, row_groups, schema, None, None, None);
info!("scanning {:?} with {} rows", path, row_count);
debug!("file schema: {:?}", meta.schema_descr);
// use a small bound since we're sending whole batches
let (send, receive) = bounded(5);
spawn(move || {
let send = send;
let reader = reader;
for chunk in reader {
let recs = decode_chunk(chunk);
let recs = match recs {
Ok(v) => v,
Err(e) => {
debug!("routing backend error {:?}", e);
send.send(Err(e)).expect("channel send error");
return;
}
};
send.send(Ok(recs)).expect("channel send error");
}
});
Ok(RecordIter {
remaining: row_count,
channel: receive,
batch: None,
})
}
impl<R> Iterator for RecordIter<R>
where
R: ArrowDeserialize + Send + Sync + 'static,
for<'a> &'a R::ArrayType: IntoIterator,
{
type Item = Result<R>;
fn next(&mut self) -> Option<Self::Item> {
loop {
// try to get another item from the current batch
let next = self.batch.as_mut().map(|i| i.next()).flatten();
if let Some(row) = next {
// we got something! return it
self.remaining -= 1;
return Some(Ok(row));
} else if let Ok(br) = self.channel.recv() {
// fetch a new batch and try again
match br {
Ok(batch) => {
self.batch = Some(batch.into_iter());
// loop around and use the batch
}
Err(e) => {
// error on the channel
return Some(Err(e));
}
}
} else {
// we're done
return None;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.