text stringlengths 8 4.13M |
|---|
mod number;
mod operator;
mod token;
extern crate clap;
use std::collections::VecDeque;
use clap::{App, Arg, value_t};
use number::{Number, NumberBase};
use operator::Operator;
use token::Token;
//////////////////////////////////////////////////////////////////////
/// Utils Common
//////////////////////////////////////////////////////////////////////
fn is_valid_binary_number(ch: u8) -> bool {
ch == 48 || ch == 49
}
fn is_valid_octal_number(ch: u8) -> bool {
ch >= 48 && ch <= 55
}
fn is_valid_decimal_number(ch: u8) -> bool {
ch >= 48 && ch <= 57
}
fn is_valid_hexadecimal_number(ch: u8) -> bool {
is_valid_decimal_number(ch) || (ch >= 65 && ch <= 70) || (ch >= 97 && ch <= 102)
}
//////////////////////////////////////////////////////////////////////
/// Shunting Yard
//////////////////////////////////////////////////////////////////////
fn shunting_yard(input: Vec<u8>) -> Result<VecDeque<Box<dyn Token>>, String> {
let mut error_msg = String::new();
let mut start;
let mut end = 0;
let mut tokens = VecDeque::<Box<dyn Token>>::new();
let mut operator_stack = Vec::<Operator>::new();
loop {
start = end;
if !error_msg.is_empty() {
println!("Error parsing in column {}: {}", end, error_msg);
println!("{}", String::from_utf8(input).unwrap());
println!("{0}^\n{0}Error here", " ".repeat(end - 1));
return Err("Parsing Error".to_owned());
}
if start >= input.len() {
break;
}
end = start + 1;
// Check for space
if input[start] == 32 {
continue;
}
// Check for UTF-8 non breaking space
if input[start] == 194 && end < input.len() && input[end] == 160 {
end += 1;
continue;
}
// Check for number
if is_valid_decimal_number(input[start]) {
let mut num_base: NumberBase = NumberBase::DEC;
// Check if input[start] == "0"
if input[start] == 48 && end < input.len() {
let next: u8 = input[end];
// Check for b and B
if next == 98 || next == 66 {
num_base = NumberBase::BIN;
}
// Check for o and O
else if next == 111 || next == 79 {
num_base = NumberBase::OCT;
}
// Check for x and X
else if next == 120 || next == 88 {
num_base = NumberBase::HEX;
}
if num_base != NumberBase::DEC {
end += 1;
}
}
loop {
if end >= input.len() {
break;
}
let next = input[end];
let is_valid;
match num_base {
NumberBase::BIN => is_valid = is_valid_binary_number(next),
NumberBase::OCT => is_valid = is_valid_octal_number(next),
NumberBase::DEC => is_valid = is_valid_decimal_number(next),
NumberBase::HEX => is_valid = is_valid_hexadecimal_number(next),
}
if !is_valid {
if is_valid_hexadecimal_number(next) {
error_msg = "Invalid ".to_owned() + num_base.to_string() + " number";
end += 1;
}
break;
}
end += 1;
}
if error_msg.is_empty() {
let num_start = if num_base != NumberBase::DEC {
start + 2
} else {
start
};
if let Ok(number) = Number::from_slice(&input[num_start..end], &num_base) {
tokens.push_back(Box::new(number));
}
}
continue;
}
// Check function: TODO
// Get the next operator
let op = Operator::from_bytes(&input[start..input.len()]);
if op == Some(Operator::SHIFTL) || op == Some(Operator::SHIFTR) {
end += 1;
}
// Check operator
if let Some(operator) = op {
if operator == Operator::LPARENTHESIS {
operator_stack.push(operator);
continue;
} else if operator == Operator::RPARENTHESIS {
let mut lparenth_found = false;
while let Some(top_operator) = operator_stack.last() {
if *top_operator != Operator::LPARENTHESIS {
tokens.push_back(Box::new(operator_stack.pop().unwrap()));
} else {
operator_stack.pop();
lparenth_found = true;
break;
}
}
if !lparenth_found {
error_msg = "Error mismatched parenthesis".to_owned();
}
continue;
} else {
while let Some(top_operator) = operator_stack.last() {
if (
// there is a function at the top of the operator stack: TODO
// there is an operator at the top of the operator stack with greater precedence
(top_operator.get_precedence() > operator.get_precedence()) ||
// the operator at the top of the operator stack has equal precedence and the token is left associative
(top_operator.get_precedence() == operator.get_precedence() && operator.is_left_associative())
) && *top_operator != Operator::LPARENTHESIS
{
tokens.push_back(Box::new(operator_stack.pop().unwrap()));
} else {
break;
}
}
operator_stack.push(operator);
continue;
}
} else {
error_msg = "Invalid operator".to_owned();
continue;
}
}
while operator_stack.len() > 0 {
// Check for mismatched parenthesis
let op = operator_stack.pop().unwrap();
if op == Operator::LPARENTHESIS || op == Operator::RPARENTHESIS {
println!("Error mismatched parenthesis");
return Err("Parsing Error".to_owned());
}
tokens.push_back(Box::new(op));
}
return Ok(tokens);
}
fn postfix_eval(tokens: &VecDeque<Box<dyn Token>>) -> Option<Vec::<(Number, Operator, Number, Number)>> {
let mut stack = Vec::<Number>::new();
let mut operations = Vec::<(Number, Operator, Number, Number)>::new();
for i in 0..tokens.len() {
let token = tokens[i].as_any();
if let Some(number) = token.downcast_ref::<Number>() {
stack.push(number.clone());
}
if let Some(operator) = token.downcast_ref::<Operator>() {
if stack.len() >= 2 {
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
if let Some(result) = operator.operate(a.clone(), b.clone()) {
operations.push((a, *operator, b, result.clone()));
stack.push(result);
} else {
println!(
"Error evaluating expression: {0:#b} ({0:#?}) {1} {2:#b} ({2:#?})",
a, operator, b
);
return None;
}
} else {
println!("Error malformed expression");
return None;
}
}
}
if !operations.is_empty() {
return Some(operations);
}
return None;
}
fn main() {
let matches = App::new("Developer Calculator")
.version("1.0")
.author("Manuel Sabogal <mfer32@gmail.com>")
.about("Developer step by step calculator")
.arg(
Arg::with_name("EXPRESSION")
.help("The expression to evaluate")
.required(true)
.index(1),
)
.arg(
Arg::with_name("base")
.short("b")
.long("base")
.value_name("BASE")
.help("Set the base for the output")
.possible_values(&["bin", "2", "oct", "8", "dec", "10", "hex", "16"])
.default_value("dec")
.takes_value(true),
)
.get_matches();
let operation = value_t!(matches.value_of("EXPRESSION"), String).unwrap_or_else(|e| e.exit());
let output_base = value_t!(matches.value_of("base"), NumberBase).unwrap_or_else(|e| e.exit());
if let Ok(tokens) = shunting_yard(operation.clone().into_bytes()) {
if tokens.len() == 1 {
if let Some(number) = tokens[0].as_any().downcast_ref::<Number>() {
println!("Binary: {:#}", number.clone().set_base(&NumberBase::BIN));
println!("Octal: {:#}", number.clone().set_base(&NumberBase::OCT));
println!("Decimal: {:#}", number.clone().set_base(&NumberBase::DEC));
println!("Hexadecimal: {:#}", number.clone().set_base(&NumberBase::HEX));
return;
}
}
println!("Executing: {}\n", operation);
if let Some(mut operations) = postfix_eval(&tokens) {
for operation in &mut operations {
let (a, operator, b, result) = operation;
let line = format!(
"{0:#b} {1} {2:#b} = {3:#b} ({0:#} {1} {2:#} = {3:#})",
a, operator, b, result.set_base(&output_base)
);
println!("{}", line);
}
let mut result = operations.last().unwrap().3.clone();
println!();
println!("Result: {:#}", result.set_base(&output_base));
}
}
}
|
use super::schema::{grades, users};
#[derive(Queryable, Debug, PartialEq, Eq)]
pub struct User {
pub id: i32,
pub username: String,
pub password: String,
pub role: String,
}
impl User {
/// Only exists for the unit tests
pub fn new(username: &str, passwd: &str, role: &str) -> Self {
Self {
id: 1,
username: username.to_string(),
password: passwd.to_string(),
role: role.to_string(),
}
}
}
#[derive(Queryable, Debug, Associations, PartialEq)]
#[belongs_to(User foreign_key = "student_id")]
pub struct Grade {
pub id: i32,
pub grade: f32,
pub student_id: i32,
}
#[derive(Insertable)]
#[table_name = "users"]
pub struct NewUser<'a> {
pub username: &'a str,
pub password: &'a str,
pub role: &'a str,
}
#[derive(Insertable)]
#[table_name = "grades"]
pub struct NewGrade {
pub grade: f32,
pub student_id: i32,
}
|
use std::net::SocketAddr;
use chrono::prelude::*;
use hydroflow::hydroflow_syntax;
use hydroflow::scheduled::graph::Hydroflow;
use hydroflow::util::{UdpLinesSink, UdpLinesStream};
use crate::helpers::{deserialize_json, serialize_json};
use crate::protocol::EchoMsg;
pub(crate) async fn run_server(outbound: UdpLinesSink, inbound: UdpLinesStream) {
println!("Server live!");
let mut flow: Hydroflow = hydroflow_syntax! {
// Inbound channel sharing
inbound_chan = source_stream(inbound) -> map(deserialize_json) -> tee();
// Logic
inbound_chan[0] -> for_each(|(m, a): (EchoMsg, SocketAddr)| println!("Got {:?} from {:?}", m, a));
inbound_chan[1] -> map(|(EchoMsg { payload, .. }, addr)| (EchoMsg { payload, ts: Utc::now() }, addr))
-> map(|(m, a)| (serialize_json(m), a))
-> dest_sink(outbound);
};
// run the server
flow.run_async().await;
}
|
#![allow(unused)]
#[macro_use]
extern crate rayon;
extern crate roots;
extern crate extendr_api;
use extendr_api::prelude::*;
mod filter;
use filter::FilteringResult;
//Wrapping functions for R
#[extendr]
fn perform_filtering_for_r(update_type: String, q: Vec<f64>, alpha: f64, delta_t: f64, first_aprils: Vec<f64>) -> Vec<f64> {
let first_aprils_usize: Vec<usize> = first_aprils.iter().map(|x| *x as usize).collect();
let rust_result: FilteringResult = filter::perform_filtering(&update_type[..], &q, alpha, delta_t, &first_aprils_usize[..]);
rust_result.to_vec_for_r()
}
#[extendr]
fn bfi_for_r(update_type: String, q: Vec<f64>, alpha: f64, delta_t: f64, first_aprils: Vec<f64>) -> f64 {
let first_aprils_usize: Vec<usize> = first_aprils.iter().map(|x| *x as usize).collect();
let rust_result: FilteringResult = filter::perform_filtering(&update_type[..], &q, alpha, delta_t, &first_aprils_usize[..]);
rust_result.bfi()
}
#[extendr]
fn criteria_for_r(update_type: String, q: Vec<f64>, alpha: f64, delta_t: f64, p: Vec<f64>, pet: Vec<f64>, tau: f64, first_aprils: Vec<f64>) -> f64 {
let first_aprils_usize: Vec<usize> = first_aprils.iter().map(|x| *x as usize).collect();
filter::criteria_computation(&update_type[..], &q, alpha, delta_t, &p, &pet, tau, &first_aprils_usize[..])
}
#[extendr]
fn criteria_vector_for_r(update_type: String, q: Vec<f64>, alphas: Vec<f64>, delta_t: f64, p: Vec<f64>, pet: Vec<f64>, taus: Vec<f64>, first_aprils: Vec<f64>) -> Vec<f64> {
let first_aprils_usize: Vec<usize> = first_aprils.iter().map(|x| *x as usize).collect();
filter::criteria_computation_vector(&update_type[..], &q, alphas, delta_t, &p, &pet, taus, &first_aprils_usize[..])
}
extendr_module! {
mod baseflow;
fn perform_filtering_for_r;
fn bfi_for_r;
fn criteria_for_r;
fn criteria_vector_for_r;
}
|
mod actions;
mod audio;
mod base;
mod digger;
mod loading;
mod map;
mod menu;
mod ui;
use crate::actions::ActionsPlugin;
use crate::audio::InternalAudioPlugin;
use crate::base::BasePlugin;
use crate::digger::DiggerPlugin;
use crate::loading::LoadingPlugin;
use crate::map::MapPlugin;
use crate::menu::MenuPlugin;
use crate::ui::UiPlugin;
use bevy::app::AppBuilder;
// use bevy::diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin};
use bevy::ecs::schedule::SystemSet;
use bevy::prelude::*;
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
enum GameState {
Restart,
Loading,
Playing,
Menu,
}
pub struct GamePlugin;
impl Plugin for GamePlugin {
fn build(&self, app: &mut AppBuilder) {
app.add_state(GameState::Loading)
.add_plugin(LoadingPlugin)
.add_plugin(UiPlugin)
.add_plugin(MapPlugin)
.add_plugin(MenuPlugin)
.add_plugin(DiggerPlugin)
.add_plugin(ActionsPlugin)
.add_plugin(BasePlugin)
.add_plugin(InternalAudioPlugin)
// .add_plugin(FrameTimeDiagnosticsPlugin::default())
// .add_plugin(LogDiagnosticsPlugin::default())
.add_system_set(
SystemSet::on_enter(GameState::Restart).with_system(switch_to_game.system()),
);
}
}
fn switch_to_game(mut state: ResMut<State<GameState>>) {
state.set(GameState::Playing).unwrap();
}
|
#[doc = "Register `APB2SMENR` reader"]
pub type R = crate::R<APB2SMENR_SPEC>;
#[doc = "Register `APB2SMENR` writer"]
pub type W = crate::W<APB2SMENR_SPEC>;
#[doc = "Field `SYSCFGSMEN` reader - SYSCFG clocks enable during Sleep and Stop modes"]
pub type SYSCFGSMEN_R = crate::BitReader<SYSCFGSMEN_A>;
#[doc = "SYSCFG clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SYSCFGSMEN_A {
#[doc = "0: SYSCFG + COMP + VREFBUF clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: SYSCFG + COMP + VREFBUF clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<SYSCFGSMEN_A> for bool {
#[inline(always)]
fn from(variant: SYSCFGSMEN_A) -> Self {
variant as u8 != 0
}
}
impl SYSCFGSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SYSCFGSMEN_A {
match self.bits {
false => SYSCFGSMEN_A::Disabled,
true => SYSCFGSMEN_A::Enabled,
}
}
#[doc = "SYSCFG + COMP + VREFBUF clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SYSCFGSMEN_A::Disabled
}
#[doc = "SYSCFG + COMP + VREFBUF clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SYSCFGSMEN_A::Enabled
}
}
#[doc = "Field `SYSCFGSMEN` writer - SYSCFG clocks enable during Sleep and Stop modes"]
pub type SYSCFGSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SYSCFGSMEN_A>;
impl<'a, REG, const O: u8> SYSCFGSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "SYSCFG + COMP + VREFBUF clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SYSCFGSMEN_A::Disabled)
}
#[doc = "SYSCFG + COMP + VREFBUF clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SYSCFGSMEN_A::Enabled)
}
}
#[doc = "Field `TIM1SMEN` reader - TIM1 timer clocks enable during Sleep and Stop modes"]
pub type TIM1SMEN_R = crate::BitReader<TIM1SMEN_A>;
#[doc = "TIM1 timer clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TIM1SMEN_A {
#[doc = "0: TIMx clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: TIMx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<TIM1SMEN_A> for bool {
#[inline(always)]
fn from(variant: TIM1SMEN_A) -> Self {
variant as u8 != 0
}
}
impl TIM1SMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TIM1SMEN_A {
match self.bits {
false => TIM1SMEN_A::Disabled,
true => TIM1SMEN_A::Enabled,
}
}
#[doc = "TIMx clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == TIM1SMEN_A::Disabled
}
#[doc = "TIMx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == TIM1SMEN_A::Enabled
}
}
#[doc = "Field `TIM1SMEN` writer - TIM1 timer clocks enable during Sleep and Stop modes"]
pub type TIM1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIM1SMEN_A>;
impl<'a, REG, const O: u8> TIM1SMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "TIMx clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(TIM1SMEN_A::Disabled)
}
#[doc = "TIMx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(TIM1SMEN_A::Enabled)
}
}
#[doc = "Field `SPI1SMEN` reader - SPI1 clocks enable during Sleep and Stop modes"]
pub type SPI1SMEN_R = crate::BitReader<SPI1SMEN_A>;
#[doc = "SPI1 clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SPI1SMEN_A {
#[doc = "0: SPI1 clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: SPI1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<SPI1SMEN_A> for bool {
#[inline(always)]
fn from(variant: SPI1SMEN_A) -> Self {
variant as u8 != 0
}
}
impl SPI1SMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SPI1SMEN_A {
match self.bits {
false => SPI1SMEN_A::Disabled,
true => SPI1SMEN_A::Enabled,
}
}
#[doc = "SPI1 clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SPI1SMEN_A::Disabled
}
#[doc = "SPI1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SPI1SMEN_A::Enabled
}
}
#[doc = "Field `SPI1SMEN` writer - SPI1 clocks enable during Sleep and Stop modes"]
pub type SPI1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SPI1SMEN_A>;
impl<'a, REG, const O: u8> SPI1SMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "SPI1 clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SPI1SMEN_A::Disabled)
}
#[doc = "SPI1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SPI1SMEN_A::Enabled)
}
}
#[doc = "Field `TIM8SMEN` reader - TIM8 timer clocks enable during Sleep and Stop modes"]
pub use TIM1SMEN_R as TIM8SMEN_R;
#[doc = "Field `TIM8SMEN` writer - TIM8 timer clocks enable during Sleep and Stop modes"]
pub use TIM1SMEN_W as TIM8SMEN_W;
#[doc = "Field `USART1SMEN` reader - USART1clocks enable during Sleep and Stop modes"]
pub type USART1SMEN_R = crate::BitReader<USART1SMEN_A>;
#[doc = "USART1clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum USART1SMEN_A {
#[doc = "0: USART1 clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: USART1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<USART1SMEN_A> for bool {
#[inline(always)]
fn from(variant: USART1SMEN_A) -> Self {
variant as u8 != 0
}
}
impl USART1SMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> USART1SMEN_A {
match self.bits {
false => USART1SMEN_A::Disabled,
true => USART1SMEN_A::Enabled,
}
}
#[doc = "USART1 clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == USART1SMEN_A::Disabled
}
#[doc = "USART1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == USART1SMEN_A::Enabled
}
}
#[doc = "Field `USART1SMEN` writer - USART1clocks enable during Sleep and Stop modes"]
pub type USART1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, USART1SMEN_A>;
impl<'a, REG, const O: u8> USART1SMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "USART1 clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(USART1SMEN_A::Disabled)
}
#[doc = "USART1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(USART1SMEN_A::Enabled)
}
}
#[doc = "Field `TIM15SMEN` reader - TIM15 timer clocks enable during Sleep and Stop modes"]
pub use TIM1SMEN_R as TIM15SMEN_R;
#[doc = "Field `TIM16SMEN` reader - TIM16 timer clocks enable during Sleep and Stop modes"]
pub use TIM1SMEN_R as TIM16SMEN_R;
#[doc = "Field `TIM17SMEN` reader - TIM17 timer clocks enable during Sleep and Stop modes"]
pub use TIM1SMEN_R as TIM17SMEN_R;
#[doc = "Field `TIM15SMEN` writer - TIM15 timer clocks enable during Sleep and Stop modes"]
pub use TIM1SMEN_W as TIM15SMEN_W;
#[doc = "Field `TIM16SMEN` writer - TIM16 timer clocks enable during Sleep and Stop modes"]
pub use TIM1SMEN_W as TIM16SMEN_W;
#[doc = "Field `TIM17SMEN` writer - TIM17 timer clocks enable during Sleep and Stop modes"]
pub use TIM1SMEN_W as TIM17SMEN_W;
#[doc = "Field `SAI1SMEN` reader - SAI1 clocks enable during Sleep and Stop modes"]
pub type SAI1SMEN_R = crate::BitReader<SAI1SMEN_A>;
#[doc = "SAI1 clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SAI1SMEN_A {
#[doc = "0: SAIx clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: SAIx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<SAI1SMEN_A> for bool {
#[inline(always)]
fn from(variant: SAI1SMEN_A) -> Self {
variant as u8 != 0
}
}
impl SAI1SMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SAI1SMEN_A {
match self.bits {
false => SAI1SMEN_A::Disabled,
true => SAI1SMEN_A::Enabled,
}
}
#[doc = "SAIx clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SAI1SMEN_A::Disabled
}
#[doc = "SAIx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SAI1SMEN_A::Enabled
}
}
#[doc = "Field `SAI1SMEN` writer - SAI1 clocks enable during Sleep and Stop modes"]
pub type SAI1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SAI1SMEN_A>;
impl<'a, REG, const O: u8> SAI1SMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "SAIx clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(SAI1SMEN_A::Disabled)
}
#[doc = "SAIx clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(SAI1SMEN_A::Enabled)
}
}
#[doc = "Field `SAI2SMEN` reader - SAI2 clocks enable during Sleep and Stop modes"]
pub use SAI1SMEN_R as SAI2SMEN_R;
#[doc = "Field `SAI2SMEN` writer - SAI2 clocks enable during Sleep and Stop modes"]
pub use SAI1SMEN_W as SAI2SMEN_W;
#[doc = "Field `DFSDM1SMEN` reader - DFSDM timer clocks enable during Sleep and Stop modes"]
pub type DFSDM1SMEN_R = crate::BitReader<DFSDM1SMEN_A>;
#[doc = "DFSDM timer clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DFSDM1SMEN_A {
#[doc = "0: DFSDM1 clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: DFSDM1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<DFSDM1SMEN_A> for bool {
#[inline(always)]
fn from(variant: DFSDM1SMEN_A) -> Self {
variant as u8 != 0
}
}
impl DFSDM1SMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DFSDM1SMEN_A {
match self.bits {
false => DFSDM1SMEN_A::Disabled,
true => DFSDM1SMEN_A::Enabled,
}
}
#[doc = "DFSDM1 clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DFSDM1SMEN_A::Disabled
}
#[doc = "DFSDM1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DFSDM1SMEN_A::Enabled
}
}
#[doc = "Field `DFSDM1SMEN` writer - DFSDM timer clocks enable during Sleep and Stop modes"]
pub type DFSDM1SMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DFSDM1SMEN_A>;
impl<'a, REG, const O: u8> DFSDM1SMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "DFSDM1 clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(DFSDM1SMEN_A::Disabled)
}
#[doc = "DFSDM1 clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(DFSDM1SMEN_A::Enabled)
}
}
#[doc = "Field `LTDCSMEN` reader - LCD-TFT timer clocks enable during Sleep and Stop modes"]
pub type LTDCSMEN_R = crate::BitReader<LTDCSMEN_A>;
#[doc = "LCD-TFT timer clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LTDCSMEN_A {
#[doc = "0: LCD-TFT clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: LCD-TFT clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<LTDCSMEN_A> for bool {
#[inline(always)]
fn from(variant: LTDCSMEN_A) -> Self {
variant as u8 != 0
}
}
impl LTDCSMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LTDCSMEN_A {
match self.bits {
false => LTDCSMEN_A::Disabled,
true => LTDCSMEN_A::Enabled,
}
}
#[doc = "LCD-TFT clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == LTDCSMEN_A::Disabled
}
#[doc = "LCD-TFT clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == LTDCSMEN_A::Enabled
}
}
#[doc = "Field `LTDCSMEN` writer - LCD-TFT timer clocks enable during Sleep and Stop modes"]
pub type LTDCSMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LTDCSMEN_A>;
impl<'a, REG, const O: u8> LTDCSMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "LCD-TFT clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(LTDCSMEN_A::Disabled)
}
#[doc = "LCD-TFT clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(LTDCSMEN_A::Enabled)
}
}
#[doc = "Field `DSISMEN` reader - DSI clocks enable during Sleep and Stop modes"]
pub type DSISMEN_R = crate::BitReader<DSISMEN_A>;
#[doc = "DSI clocks enable during Sleep and Stop modes\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DSISMEN_A {
#[doc = "0: DSI clocks disabled by the clock gating during Sleep and Stop modes"]
Disabled = 0,
#[doc = "1: DSI clocks enabled by the clock gating(1) during Sleep and Stop modes"]
Enabled = 1,
}
impl From<DSISMEN_A> for bool {
#[inline(always)]
fn from(variant: DSISMEN_A) -> Self {
variant as u8 != 0
}
}
impl DSISMEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DSISMEN_A {
match self.bits {
false => DSISMEN_A::Disabled,
true => DSISMEN_A::Enabled,
}
}
#[doc = "DSI clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DSISMEN_A::Disabled
}
#[doc = "DSI clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DSISMEN_A::Enabled
}
}
#[doc = "Field `DSISMEN` writer - DSI clocks enable during Sleep and Stop modes"]
pub type DSISMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DSISMEN_A>;
impl<'a, REG, const O: u8> DSISMEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "DSI clocks disabled by the clock gating during Sleep and Stop modes"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(DSISMEN_A::Disabled)
}
#[doc = "DSI clocks enabled by the clock gating(1) during Sleep and Stop modes"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(DSISMEN_A::Enabled)
}
}
impl R {
#[doc = "Bit 0 - SYSCFG clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn syscfgsmen(&self) -> SYSCFGSMEN_R {
SYSCFGSMEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 11 - TIM1 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tim1smen(&self) -> TIM1SMEN_R {
TIM1SMEN_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - SPI1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn spi1smen(&self) -> SPI1SMEN_R {
SPI1SMEN_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - TIM8 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tim8smen(&self) -> TIM8SMEN_R {
TIM8SMEN_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - USART1clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn usart1smen(&self) -> USART1SMEN_R {
USART1SMEN_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 16 - TIM15 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tim15smen(&self) -> TIM15SMEN_R {
TIM15SMEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - TIM16 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tim16smen(&self) -> TIM16SMEN_R {
TIM16SMEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - TIM17 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn tim17smen(&self) -> TIM17SMEN_R {
TIM17SMEN_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 21 - SAI1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sai1smen(&self) -> SAI1SMEN_R {
SAI1SMEN_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - SAI2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn sai2smen(&self) -> SAI2SMEN_R {
SAI2SMEN_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 24 - DFSDM timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn dfsdm1smen(&self) -> DFSDM1SMEN_R {
DFSDM1SMEN_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 26 - LCD-TFT timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn ltdcsmen(&self) -> LTDCSMEN_R {
LTDCSMEN_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - DSI clocks enable during Sleep and Stop modes"]
#[inline(always)]
pub fn dsismen(&self) -> DSISMEN_R {
DSISMEN_R::new(((self.bits >> 27) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - SYSCFG clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn syscfgsmen(&mut self) -> SYSCFGSMEN_W<APB2SMENR_SPEC, 0> {
SYSCFGSMEN_W::new(self)
}
#[doc = "Bit 11 - TIM1 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tim1smen(&mut self) -> TIM1SMEN_W<APB2SMENR_SPEC, 11> {
TIM1SMEN_W::new(self)
}
#[doc = "Bit 12 - SPI1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn spi1smen(&mut self) -> SPI1SMEN_W<APB2SMENR_SPEC, 12> {
SPI1SMEN_W::new(self)
}
#[doc = "Bit 13 - TIM8 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tim8smen(&mut self) -> TIM8SMEN_W<APB2SMENR_SPEC, 13> {
TIM8SMEN_W::new(self)
}
#[doc = "Bit 14 - USART1clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn usart1smen(&mut self) -> USART1SMEN_W<APB2SMENR_SPEC, 14> {
USART1SMEN_W::new(self)
}
#[doc = "Bit 16 - TIM15 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tim15smen(&mut self) -> TIM15SMEN_W<APB2SMENR_SPEC, 16> {
TIM15SMEN_W::new(self)
}
#[doc = "Bit 17 - TIM16 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tim16smen(&mut self) -> TIM16SMEN_W<APB2SMENR_SPEC, 17> {
TIM16SMEN_W::new(self)
}
#[doc = "Bit 18 - TIM17 timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn tim17smen(&mut self) -> TIM17SMEN_W<APB2SMENR_SPEC, 18> {
TIM17SMEN_W::new(self)
}
#[doc = "Bit 21 - SAI1 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sai1smen(&mut self) -> SAI1SMEN_W<APB2SMENR_SPEC, 21> {
SAI1SMEN_W::new(self)
}
#[doc = "Bit 22 - SAI2 clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn sai2smen(&mut self) -> SAI2SMEN_W<APB2SMENR_SPEC, 22> {
SAI2SMEN_W::new(self)
}
#[doc = "Bit 24 - DFSDM timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn dfsdm1smen(&mut self) -> DFSDM1SMEN_W<APB2SMENR_SPEC, 24> {
DFSDM1SMEN_W::new(self)
}
#[doc = "Bit 26 - LCD-TFT timer clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn ltdcsmen(&mut self) -> LTDCSMEN_W<APB2SMENR_SPEC, 26> {
LTDCSMEN_W::new(self)
}
#[doc = "Bit 27 - DSI clocks enable during Sleep and Stop modes"]
#[inline(always)]
#[must_use]
pub fn dsismen(&mut self) -> DSISMEN_W<APB2SMENR_SPEC, 27> {
DSISMEN_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 = "APB2SMENR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2smenr::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 [`apb2smenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB2SMENR_SPEC;
impl crate::RegisterSpec for APB2SMENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb2smenr::R`](R) reader structure"]
impl crate::Readable for APB2SMENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb2smenr::W`](W) writer structure"]
impl crate::Writable for APB2SMENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB2SMENR to value 0x0d67_7801"]
impl crate::Resettable for APB2SMENR_SPEC {
const RESET_VALUE: Self::Ux = 0x0d67_7801;
}
|
use serde::Deserialize;
use serde::Serialize;
pub type Score=u32;
pub type Id=u32;
#[derive(Debug)]
pub struct Date(pub u16, pub u8, pub u8);
#[derive(Debug, Serialize, Deserialize)]
pub struct Thread {
pub listing: Listing,
pub comments: Vec<Comment>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Listing {
pub title: String,
pub id: Id,
pub score: Option<Score>,
pub user: Option<String>,
// comments: u32,
pub url: String,
pub text: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Comment {
pub user: String,
pub id: Id,
pub text: Option<String>,
pub indent: u32,
pub dead: bool,
pub children: Vec<Comment>,
}
pub mod firebase {
use super::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct User {
/// The user's unique username. Case-sensitive.
id: Option<String>,
/// Delay in minutes between a comment's creation and its visibility to other users.
delay: Option<u32>,
/// Creation date of the user, in Unix Time.
created: u32,
/// The user's karma.
karma: Score,
/// The user's optional self-description. HTML.
about: Option<String>,
/// List of the user's stories, polls and comments.
submitted: Option<Vec<Id>>,
}
// TODO: This is essentially a Listing, at least with respect to what it represents in the data
// model. There should be some sort of unification in the API.
#[derive(Serialize, Deserialize, Debug)]
pub struct Job {
/// The item's unique id.
pub id: Id,
/// true if the item is deleted.
pub deleted: Option<bool>,
/// The username of the item's author.
pub by: Option<String>,
/// Creation date of the item, in Unix Time.
pub time: u64,
/// true if the item is dead.
pub dead: Option<bool>,
/// The ids of the item's comments, in ranked display order.
pub kids: Option<Vec<Id>>,
/// The comment, story or poll text. HTML.
pub text: Option<String>,
/// The URL of the story.
pub url: Option<String>,
/// The title of the story, poll or job.
pub title: String,
}
// TODO: This is essentially a Listing, at least with respect to what it represents in the data
// model. There should be some sort of unification in the API.
#[derive(Serialize, Deserialize, Debug)]
pub struct Story {
/// The item's unique id.
pub id: Id,
/// True if the item is deleted.
pub deleted: Option<bool>,
/// The type of item. One of "job", "story", "comment", "poll", or "pollopt".
pub by: Option<String>,
/// Creation date of the item, in Unix Time.
pub time: u64,
/// True if the item is dead.
pub dead: Option<bool>,
/// The ids of the item's comments, in ranked display order.
pub kids: Option<Vec<Id>>,
/// In the case of stories or polls, the total comment count.
pub descendants: Option<u32>,
/// The story's score, or the votes for a pollopt.
pub score: Option<Score>,
/// The title of the story, poll or job.
pub title: Option<String>,
/// The URL of the story.
pub url: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Comment {
// Fields directly obtained from the response payload
/// The item's unique id.
pub id: Id,
/// true if the item is deleted.
pub deleted: Option<bool>,
/// The type of item. One of "job", "story", "comment", "poll", or "pollopt".
pub by: Option<String>,
/// Creation date of the item, in Unix Time.
pub time: u64,
/// true if the item is dead.
pub dead: Option<bool>,
/// The ids of the item's comments, in ranked display order.
pub kids: Option<Vec<Id>>,
/// The comment's parent: either another comment or the relevant story.
pub parent: Option<Id>,
/// The comment, story or poll text. HTML.
pub text: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Poll {
/// The item's unique id.
pub id: Id,
/// true if the item is deleted.
pub deleted: Option<bool>,
/// The type of item. One of "job", "story", "comment", "poll", or "pollopt".
pub by: Option<String>,
/// Creation date of the item, in Unix Time.
pub time: u64,
/// true if the item is dead.
pub dead: Option<bool>,
/// The ids of the item's comments, in ranked display order.
pub kids: Option<Vec<Id>>,
/// A list of related pollopts, in display order.
pub parts: Option<Vec<Id>>,
/// In the case of stories or polls, the total comment count.
pub descendants: Option<u32>,
/// The story's score, or the votes for a pollopt.
pub score: Option<Score>,
/// The title of the story, poll or job.
pub title: Option<String>,
/// The comment, story or poll text. HTML.
pub text: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PollOption {
/// The item's unique id.
pub id: Id,
/// true if the item is deleted.
pub deleted: Option<bool>,
/// The type of item. One of "job", "story", "comment", "poll", or "pollopt".
pub by: Option<String>,
/// Creation date of the item, in Unix Time.
pub time: u64,
/// true if the item is dead.
pub dead: Option<bool>,
/// The ids of the item's comments, in ranked display order.
pub kids: Option<Vec<Id>>,
/// The comment's parent: either another comment or the relevant story.
pub parent: Option<Id>,
/// The story's score, or the votes for a pollopt.
pub score: Option<Score>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Item {
#[serde(rename = "job")]
Job(Job),
#[serde(rename = "story")]
Story(Story),
#[serde(rename = "comment")]
Comment(Comment),
#[serde(rename = "poll")]
Poll(Poll),
#[serde(rename = "pollopt")]
PollOption(PollOption),
}
#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct ItemsAndProfiles {
pub items: Vec<Id>,
pub profiles: Vec<String>,
}
impl Item {
pub fn is_job(&self) -> bool {
matches!(self, Self::Job(_job))
}
pub fn is_story(&self) -> bool {
matches!(self, Self::Story(_story))
}
pub fn is_comment(&self) -> bool {
matches!(self, Self::Comment(_comment))
}
pub fn is_poll(&self) -> bool {
matches!(self, Self::Poll(_poll))
}
pub fn is_poll_option(&self) -> bool {
matches!(self, Self::PollOption(_poll_opt))
}
}
}
#[cfg(test)]
mod tests {
use super::firebase::Story;
use super::firebase::Item;
#[test]
fn test_item_type() {
let story = Item::Story(Story { id: 27476206,
deleted: None,
by: Some("what_ever".to_string()),
time: 1623432780,
dead: None,
kids: Some(vec![27488169, 27478163, 27488195, 27477211, 27488706, 27477425, 27477221, 27489125, 27490162, 27489280, 27487982, 27479605, 27490009, 27488234, 27491642, 27489141, 27477380, 27489264]),
descendants: Some(314),
score: Some(529),
title: Some("Apple admits it ranked its Files app ahead of competitor Dropbox".to_string()),
url: Some("https://www.theverge.com/2021/6/11/22528701/apple-rank-own-app-over-competitor-files-dropbox-wwdc-2017".to_string())
});
assert!(story.is_story());
}
}
|
//! Most basic explorable structure: a sequence of values.
//!
//! # Remarks
//!
//! With the ``prelude`` module, we can easily convert ``IntoIterator``s
//! into ``Sequence`` for ease of use. The same can be achieved with the
//! ``new`` method.
//!
//! # Examples
//!
//! Quick plot.
//! ```no_run
//! use preexplorer::prelude::*;
//! (0..10).preexplore().plot("my_identifier").unwrap();
//! ```
//!
//! Compare ``Sequence``s.
//! ```no_run
//! use preexplorer::prelude::*;
//! pre::Sequences::new(vec![
//! (0..10).preexplore(),
//! (0..10).preexplore(),
//! ])
//! .plot("my_identifier").unwrap();
//! ```
// Traits
// use core::ops::Add;
pub use crate::traits::{Configurable, Plotable, Saveable};
use core::fmt::Display;
// /// Compare various ``Sequence``s.
// pub mod comparison;
// pub use comparison::Sequences;
/// Sequence of values.
#[derive(Debug, PartialEq, Clone)]
pub struct ProcessViolin<T, S>
where
T: Display + Clone,
S: Display + Clone,
{
domain: Vec<T>,
image: Vec<Vec<S>>,
config: crate::configuration::Configuration,
}
impl<T, S> ProcessViolin<T, S>
where
T: Display + Clone,
S: Display + Clone,
{
/// Create a new ``ProcessViolin``.
///
/// # Examples
///
/// From a complicated computation.
/// ```
/// use preexplorer::prelude::*;
/// let data = (0..10).map(|i| (i..10 + i));
/// let pro_vio = pre::ProcessViolin::new((0..10), data);
/// ```
pub fn new<I, J, K>(domain: I, image: J) -> ProcessViolin<T, S>
where
I: IntoIterator<Item = T>,
J: IntoIterator<Item = K>,
K: IntoIterator<Item = S>,
{
let domain: Vec<T> = domain.into_iter().collect();
let image: Vec<Vec<S>> = image.into_iter().map(|j| j.into_iter().collect()).collect();
let config = crate::configuration::Configuration::default();
ProcessViolin {
domain,
image,
config,
}
}
}
// impl<T, S> Add for ProcessViolin<T, S>
// where
// T: Display + Clone,
// S: Display + Clone,
// {
// type Output = crate::ProcessViolines<T, S>;
// fn add(self, other: crate::ProcessViolin<T, S>) -> crate::ProcessViolines<T, S> {
// let mut cmp = self.into();
// cmp += other;
// cmp
// }
// }
impl<T, S> Configurable for ProcessViolin<T, S>
where
T: Display + Clone,
S: Display + Clone,
{
fn configuration_mut(&mut self) -> &mut crate::configuration::Configuration {
&mut self.config
}
fn configuration(&self) -> &crate::configuration::Configuration {
&self.config
}
}
impl<T, S> Saveable for ProcessViolin<T, S>
where
T: Display + Clone,
S: Display + Clone,
{
fn plotable_data(&self) -> String {
let mut plotable_data = String::new();
for (time, values) in self.domain.clone().into_iter().zip(self.image.clone()) {
for value in values {
plotable_data.push_str(&format!("{}\t{}\n", time, value));
}
// Separate datasets
plotable_data.push_str("\n\n");
}
plotable_data
}
}
impl<T, S> Plotable for ProcessViolin<T, S>
where
T: Display + Clone,
S: Display + Clone,
{
fn plot_script(&self) -> String {
let mut gnuplot_script = self.opening_plot_script();
gnuplot_script += &format!("array TIMES[{}] = [", self.domain.len());
for i in 0..self.domain.len() - 1 {
gnuplot_script += &format!("{}, ", self.domain[i]);
}
gnuplot_script += &format!("{}]\n", self.domain[self.domain.len() - 1]); // Last time
// gnuplot_script += &format!("array DataPoints[{}] = [", self.image.len());
// for i in 0..self.image.len() - 1 {
// gnuplot_script += &format!("{}, ", self.image[i].len());
// }
// gnuplot_script += &format!("{}]\n", self.image[self.image.len() - 1].len()); // Last time
gnuplot_script += &format!("\
renormalize = 2
do for [i=0:{}] {{
# Computing some values
set table $_
plot {:?} index i using 2:(1) smooth kdensity
unset table
renormalize = (renormalize < 2 * GPVAL_Y_MAX) ? 2 * GPVAL_Y_MAX : renormalize
# Plotting a greater domain
set table '{}'.'_partial_plot'.i
x_min = (GPVAL_X_MIN < GPVAL_X_MIN - 5 * GPVAL_KDENSITY_BANDWIDTH)? GPVAL_X_MIN : GPVAL_X_MIN - 5 * GPVAL_KDENSITY_BANDWIDTH
x_max = (GPVAL_X_MAX > GPVAL_X_MAX + 5 * GPVAL_KDENSITY_BANDWIDTH)? GPVAL_X_MAX : GPVAL_X_MAX + 5 * GPVAL_KDENSITY_BANDWIDTH
set xrange [x_min:x_max]
plot {:?} index i using 2:(1) smooth kdensity
unset table
# Clean the plotting
unset xrange
unset yrange
}}
# Plotting the violins
set style fill transparent solid 0.5
# Right side
plot for [i=0:{}] '{}'.'_partial_plot'.i using (TIMES[i+1] + $2/renormalize):1 with filledcurve x=TIMES[i+1] linecolor i
# Left side
replot for [i=0:{}] '{}'.'_partial_plot'.i using (TIMES[i+1] - $2/renormalize):1 with filledcurve x=TIMES[i+1] linecolor i
",
self.image.len() - 1,
self.data_path(),
self.data_path().display(),
self.data_path(),
self.image.len() - 1,
self.data_path().display(),
self.image.len() - 1,
self.data_path().display(),
);
gnuplot_script += &self.ending_plot_script();
gnuplot_script
}
}
///////////////////////////////////////////////
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn set_style() {
let domain = 0..2;
let image = (0..2).map(|i| -> Vec<u64> { (0..4).map(|j| j + i).collect() });
let mut seq = ProcessViolin::new(domain, image);
seq.set_style("points");
assert_eq!(
&crate::configuration::plot::style::Style::Points,
seq.style()
);
}
}
|
use itertools::Either;
use super::HalfJoinState;
pub struct SymmetricHashJoin<'a, Key, I1, V1, I2, V2, LhsState, RhsState>
where
Key: Eq + std::hash::Hash + Clone,
V1: Clone,
V2: Clone,
I1: Iterator<Item = (Key, V1)>,
I2: Iterator<Item = (Key, V2)>,
LhsState: HalfJoinState<Key, V1, V2>,
RhsState: HalfJoinState<Key, V2, V1>,
{
lhs: I1,
rhs: I2,
lhs_state: &'a mut LhsState,
rhs_state: &'a mut RhsState,
}
impl<'a, Key, I1, V1, I2, V2, LhsState, RhsState> Iterator
for SymmetricHashJoin<'a, Key, I1, V1, I2, V2, LhsState, RhsState>
where
Key: Eq + std::hash::Hash + Clone,
V1: Clone,
V2: Clone,
I1: Iterator<Item = (Key, V1)>,
I2: Iterator<Item = (Key, V2)>,
LhsState: HalfJoinState<Key, V1, V2>,
RhsState: HalfJoinState<Key, V2, V1>,
{
type Item = (Key, (V1, V2));
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some((k, v2, v1)) = self.lhs_state.pop_match() {
return Some((k, (v1, v2)));
}
if let Some((k, v1, v2)) = self.rhs_state.pop_match() {
return Some((k, (v1, v2)));
}
if let Some((k, v1)) = self.lhs.next() {
if self.lhs_state.build(k.clone(), &v1) {
if let Some((k, v1, v2)) = self.rhs_state.probe(&k, &v1) {
return Some((k, (v1, v2)));
}
}
continue;
}
if let Some((k, v2)) = self.rhs.next() {
if self.rhs_state.build(k.clone(), &v2) {
if let Some((k, v2, v1)) = self.lhs_state.probe(&k, &v2) {
return Some((k, (v1, v2)));
}
}
continue;
}
return None;
}
}
}
pub fn symmetric_hash_join_into_iter<'a, Key, I1, V1, I2, V2, LhsState, RhsState>(
mut lhs: I1,
mut rhs: I2,
lhs_state: &'a mut LhsState,
rhs_state: &'a mut RhsState,
is_new_tick: bool,
) -> impl 'a + Iterator<Item = (Key, (V1, V2))>
where
Key: 'a + Eq + std::hash::Hash + Clone,
V1: 'a + Clone,
V2: 'a + Clone,
I1: 'a + Iterator<Item = (Key, V1)>,
I2: 'a + Iterator<Item = (Key, V2)>,
LhsState: HalfJoinState<Key, V1, V2>,
RhsState: HalfJoinState<Key, V2, V1>,
{
if is_new_tick {
for (k, v1) in lhs.by_ref() {
lhs_state.build(k.clone(), &v1);
}
for (k, v2) in rhs.by_ref() {
rhs_state.build(k.clone(), &v2);
}
Either::Left(if lhs_state.len() < rhs_state.len() {
Either::Left(lhs_state.iter().flat_map(|(k, sv)| {
sv.iter().flat_map(|v1| {
rhs_state
.full_probe(k)
.map(|v2| (k.clone(), (v1.clone(), v2.clone())))
})
}))
} else {
Either::Right(rhs_state.iter().flat_map(|(k, sv)| {
sv.iter().flat_map(|v2| {
lhs_state
.full_probe(k)
.map(|v1| (k.clone(), (v1.clone(), v2.clone())))
})
}))
})
} else {
Either::Right(SymmetricHashJoin {
lhs,
rhs,
lhs_state,
rhs_state,
})
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use crate::compiled::pull::{symmetric_hash_join_into_iter, HalfSetJoinState};
#[test]
fn hash_join() {
let lhs = (0..10).map(|x| (x, format!("left {}", x)));
let rhs = (6..15).map(|x| (x / 2, format!("right {} / 2", x)));
let (mut lhs_state, mut rhs_state) =
(HalfSetJoinState::default(), HalfSetJoinState::default());
let join = symmetric_hash_join_into_iter(lhs, rhs, &mut lhs_state, &mut rhs_state, true);
let joined = join.collect::<HashSet<_>>();
assert!(joined.contains(&(3, ("left 3".into(), "right 6 / 2".into()))));
assert!(joined.contains(&(3, ("left 3".into(), "right 7 / 2".into()))));
assert!(joined.contains(&(4, ("left 4".into(), "right 8 / 2".into()))));
assert!(joined.contains(&(4, ("left 4".into(), "right 9 / 2".into()))));
assert!(joined.contains(&(5, ("left 5".into(), "right 10 / 2".into()))));
assert!(joined.contains(&(5, ("left 5".into(), "right 11 / 2".into()))));
assert!(joined.contains(&(6, ("left 6".into(), "right 12 / 2".into()))));
assert!(joined.contains(&(7, ("left 7".into(), "right 14 / 2".into()))));
}
#[test]
fn hash_join_subsequent_ticks_do_produce_even_if_nothing_is_changed() {
let (lhs_tx, lhs_rx) = std::sync::mpsc::channel::<(usize, usize)>();
let (rhs_tx, rhs_rx) = std::sync::mpsc::channel::<(usize, usize)>();
lhs_tx.send((7, 3)).unwrap();
rhs_tx.send((7, 3)).unwrap();
let (mut lhs_state, mut rhs_state) =
(HalfSetJoinState::default(), HalfSetJoinState::default());
let mut join = symmetric_hash_join_into_iter(
lhs_rx.try_iter(),
rhs_rx.try_iter(),
&mut lhs_state,
&mut rhs_state,
true,
);
assert_eq!(join.next(), Some((7, (3, 3))));
assert_eq!(join.next(), None);
lhs_tx.send((7, 3)).unwrap();
rhs_tx.send((7, 3)).unwrap();
assert_eq!(join.next(), None);
}
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LocalizableString {
pub value: String,
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Unit {
Count,
Bytes,
Seconds,
CountPerSecond,
BytesPerSecond,
Percent,
MilliSeconds,
ByteSeconds,
Unspecified,
Cores,
MilliCores,
NanoCores,
BitsPerSecond,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricValue {
#[serde(rename = "timeStamp")]
pub time_stamp: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub average: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub minimum: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maximum: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Metric {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
pub name: LocalizableString,
pub unit: Unit,
pub data: Vec<MetricValue>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricCollection {
pub value: Vec<Metric>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RetentionPolicy {
pub enabled: bool,
pub days: i32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricSettings {
#[serde(rename = "timeGrain")]
pub time_grain: String,
pub enabled: bool,
#[serde(rename = "retentionPolicy", default, skip_serializing_if = "Option::is_none")]
pub retention_policy: Option<RetentionPolicy>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogSettings {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
pub enabled: bool,
#[serde(rename = "retentionPolicy", default, skip_serializing_if = "Option::is_none")]
pub retention_policy: Option<RetentionPolicy>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServiceDiagnosticSettings {
#[serde(rename = "storageAccountId", default, skip_serializing_if = "Option::is_none")]
pub storage_account_id: Option<String>,
#[serde(rename = "serviceBusRuleId", default, skip_serializing_if = "Option::is_none")]
pub service_bus_rule_id: Option<String>,
#[serde(rename = "eventHubAuthorizationRuleId", default, skip_serializing_if = "Option::is_none")]
pub event_hub_authorization_rule_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub metrics: Vec<MetricSettings>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub logs: Vec<LogSettings>,
#[serde(rename = "workspaceId", default, skip_serializing_if = "Option::is_none")]
pub workspace_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServiceDiagnosticSettingsResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ServiceDiagnosticSettings>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServiceDiagnosticSettingsResourcePatch {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ServiceDiagnosticSettings>,
}
|
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet, BinaryHeap};
use super::types::SiteId;
use super::map::{Map, River};
#[derive(Serialize, Deserialize)]
pub struct Graph {
neighs: HashMap<SiteId, HashSet<SiteId>>,
}
enum Visit {
Visited,
NotYetVisited(usize),
}
#[derive(Default)]
pub struct GraphCache<S = ()> {
pqueue: BinaryHeap<PQNode<S>>,
visited: HashMap<SiteId, Visit>,
path_buf: Vec<(SiteId, usize)>,
path: Vec<SiteId>,
}
impl<S> GraphCache<S> {
fn clear(&mut self) {
self.pqueue.clear();
self.visited.clear();
self.path_buf.clear();
self.path.clear();
}
}
pub enum EdgeAttr {
Blocked,
Accessible { edge_cost: usize, },
}
impl EdgeAttr {
pub fn standard(_: (SiteId, SiteId)) -> EdgeAttr {
EdgeAttr::Accessible { edge_cost: 1, }
}
}
pub enum StepCommand<S> {
Continue(S),
Stop,
Terminate,
}
impl Graph {
pub fn from_map(map: &Map) -> Graph {
Graph::from_iter(map.rivers.iter().map(|r| (r.source, r.target)))
}
pub fn from_iter<I>(iter: I) -> Graph where I: Iterator<Item = (SiteId, SiteId)> {
let mut neighs = HashMap::new();
{
let mut add = |k, v| neighs
.entry(k)
.or_insert_with(HashSet::new)
.insert(v);
for (src, dst) in iter {
add(src, dst);
add(dst, src);
}
}
Graph {
neighs: neighs,
}
}
pub fn shortest_path_only<'a, S>(&self, source: SiteId, target: SiteId, cache: &'a mut GraphCache<S>) -> Option<&'a [SiteId]>
where S: Default + Clone
{
self.shortest_path(source, target, cache, EdgeAttr::standard)
}
pub fn shortest_path<'a, E, S>(
&self,
source: SiteId,
target: SiteId,
cache: &'a mut GraphCache<S>,
probe_edge: E
)
-> Option<&'a [SiteId]>
where E: Fn((SiteId, SiteId)) -> EdgeAttr,
S: Default + Clone,
{
self.generic_bfs(source, Default::default(), |path, _cost, _seed| {
if let Some(&pt) = path.last() {
if pt == target {
StepCommand::Terminate
} else {
StepCommand::Continue(Default::default())
}
} else {
StepCommand::Stop
}
}, probe_edge, cache)
}
pub fn longest_jouney_from<S>(&self, source: SiteId, cache: &mut GraphCache<S>) -> Option<Vec<SiteId>> where S: Default + Clone {
let mut best = None;
self.generic_bfs(source, Default::default(), |path, cost, _seed| {
best = Some(if let Some((best_cost, best_path)) = best.take() {
if best_cost < cost {
(cost, path.to_owned())
} else {
(best_cost, best_path)
}
} else {
(cost, path.to_owned())
});
StepCommand::Continue(Default::default())
}, EdgeAttr::standard, cache);
best.map(|v| v.1)
}
pub fn generic_bfs<'a, S, F, E>(
&self,
source: SiteId,
source_seed: S,
mut step_fn: F,
probe_edge: E,
cache: &'a mut GraphCache<S>
)
-> Option<&'a [SiteId]>
where F: FnMut(&[SiteId], usize, &S) -> StepCommand<S>,
E: Fn((SiteId, SiteId)) -> EdgeAttr,
S: Clone,
{
cache.clear();
cache.path_buf.push((source, 0));
cache.pqueue.push(PQNode { site: source, cost: 0, phead: 1, seed: source_seed, });
while let Some(PQNode { site, cost: current_cost, phead: current_phead, seed, }) = cache.pqueue.pop() {
// check if node is visited
match cache.visited.get(&site) {
Some(&Visit::NotYetVisited(prev_cost)) if current_cost > prev_cost =>
continue,
_ =>
(),
}
cache.visited.insert(site, Visit::Visited);
// restore full path
cache.path.clear();
let mut phead = current_phead;
while phead != 0 {
let (site_hop, next_phead) = cache.path_buf[phead - 1];
cache.path.push(site_hop);
phead = next_phead;
}
cache.path.reverse();
// check if we should stop here
let next_seed = match step_fn(&cache.path, current_cost, &seed) {
StepCommand::Terminate =>
return Some(&cache.path),
StepCommand::Stop =>
continue,
StepCommand::Continue(next_seed) =>
next_seed,
};
// proceed with neighbours
if let Some(neighs) = self.neighs.get(&site) {
let next_cost = current_cost + 1;
for &reachable_site in neighs.iter() {
match cache.visited.get(&reachable_site) {
None =>
(),
Some(&Visit::NotYetVisited(prev_cost)) if next_cost < prev_cost =>
(),
_ =>
continue,
}
match probe_edge((site, reachable_site)) {
EdgeAttr::Blocked =>
continue,
EdgeAttr::Accessible { edge_cost, } => {
cache.visited.insert(reachable_site, Visit::NotYetVisited(next_cost));
cache.path_buf.push((reachable_site, current_phead));
cache.pqueue.push(PQNode {
site: reachable_site,
cost: current_cost + edge_cost,
phead: cache.path_buf.len(),
seed: next_seed.clone(),
});
},
}
}
}
}
None
}
// The Girvan-Newman Algorithm
pub fn rivers_betweenness<S>(&self, cache: &mut GraphCache<S>) -> HashMap<River, f64> where S: Default {
let mut rivers = HashMap::new();
let mut visit_cache = HashMap::new();
let mut visit_rev = BinaryHeap::new();
for (&node, _) in self.neighs.iter() {
self.rivers_betweenness_pass(node, &mut rivers, &mut visit_cache, &mut visit_rev, cache);
}
for betweenness2 in rivers.values_mut() {
*betweenness2 /= 2.0;
}
rivers
}
fn rivers_betweenness_pass<S>(
&self,
start_node: SiteId,
rivers: &mut HashMap<River, f64>,
visit_cache: &mut HashMap<SiteId, BssVisit>,
visit_rev: &mut BinaryHeap<(usize, SiteId)>,
cache: &mut GraphCache<S>)
where S: Default
{
visit_cache.clear();
visit_rev.clear();
cache.clear();
cache.pqueue.push(PQNode { site: start_node, cost: 0, phead: 0, ..Default::default() });
// forward pass
while let Some(PQNode { site, cost: parent_cost, .. }) = cache.pqueue.pop() {
let parent_count = {
let site_visit = visit_cache.entry(site)
.or_insert_with(|| BssVisit {
visited: false,
cost: parent_cost,
paths_count: 1,
credits: 1.0,
});
if site_visit.visited {
continue;
} else {
site_visit.visited = true;
visit_rev.push((parent_cost, site));
site_visit.paths_count
}
};
if let Some(neighs) = self.neighs.get(&site) {
let children_cost = parent_cost + 1;
for &reachable_site in neighs.iter() {
let visit = visit_cache.entry(reachable_site)
.or_insert_with(|| BssVisit {
visited: false,
cost: children_cost,
paths_count: 0,
credits: 1.0,
});
if visit.cost > parent_cost {
visit.paths_count += parent_count;
}
if !visit.visited {
cache.pqueue.push(PQNode {
site: reachable_site,
cost: children_cost,
phead: 0,
..Default::default()
})
}
}
}
}
// backward pass
while let Some((cost, node)) = visit_rev.pop() {
let credits = if let Some(visit) = visit_cache.get(&node) {
visit.credits
} else {
continue;
};
if let Some(neighs) = self.neighs.get(&node) {
let mut parents_paths_sum = 0;
for neigh in neighs.iter() {
if let Some(parent) = visit_cache.get(neigh) {
if parent.cost >= cost {
// skip non DAG nodes
continue;
}
parents_paths_sum += parent.paths_count;
}
}
if parents_paths_sum == 0 {
continue;
}
for &neigh in neighs.iter() {
if let Some(parent) = visit_cache.get_mut(&neigh) {
if parent.cost >= cost {
// skip non DAG nodes
continue;
}
let river = River::new(node, neigh);
let river_credit = credits * parent.paths_count as f64 / parents_paths_sum as f64;
*rivers.entry(river).or_insert(0.0) += river_credit;
parent.credits += river_credit;
}
}
}
}
}
}
#[derive(Default)]
struct PQNode<S = ()> {
site: SiteId,
cost: usize,
phead: usize,
seed: S,
}
impl<S> PartialEq for PQNode<S> {
fn eq(&self, other: &PQNode<S>) -> bool {
self.site == other.site && self.cost == other.cost && self.phead == other.phead
}
}
impl<S> Eq for PQNode<S> {}
impl<S> Ord for PQNode<S> {
fn cmp(&self, other: &PQNode<S>) -> Ordering {
other.cost.cmp(&self.cost)
.then_with(|| self.site.cmp(&other.site))
.then_with(|| self.phead.cmp(&other.phead))
}
}
impl<S> PartialOrd for PQNode<S> {
fn partial_cmp(&self, other: &PQNode<S>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug)]
struct BssVisit {
visited: bool,
cost: usize,
paths_count: usize,
credits: f64,
}
#[cfg(test)]
mod test {
use super::super::types::SiteId;
use super::super::test_common::*;
use super::{Graph, EdgeAttr};
#[test]
fn shortest_path() {
let mut cache = Default::default();
let graph = sample_map_graph();
let path14: &[_] = &[1, 3, 4]; assert_eq!(graph.shortest_path_only::<()>(1, 4, &mut cache), Some(path14));
let path15: &[_] = &[1, 7, 5]; assert_eq!(graph.shortest_path_only::<()>(1, 5, &mut cache), Some(path15));
let path04: &[_] = &[0, 7, 5, 4]; assert_eq!(graph.shortest_path_only::<()>(0, 4, &mut cache), Some(path04));
}
#[test]
fn shortest_path_with_custom_costs() {
let mut cache = Default::default();
let graph = Graph::from_iter(
[(3, 4), (0, 1), (2, 3), (1, 3), (5, 6), (4, 5), (3, 5), (6, 7), (5, 7), (1, 7), (0, 7), (1, 2)]
.iter()
.cloned());
fn edge_probe((s, t): (SiteId, SiteId)) -> EdgeAttr {
if ((s == 1) && (t == 3)) || ((s == 3) && (t == 1)) {
EdgeAttr::Accessible { edge_cost: 3, }
} else if ((s == 0) && (t == 1)) || ((s == 1) && (t == 0)) {
EdgeAttr::Blocked
} else {
EdgeAttr::Accessible { edge_cost: 1, }
}
}
let path14: &[_] = &[1, 7, 5, 4]; assert_eq!(graph.shortest_path::<_, ()>(1, 4, &mut cache, edge_probe), Some(path14));
let path15: &[_] = &[1, 7, 5]; assert_eq!(graph.shortest_path::<_, ()>(1, 5, &mut cache, edge_probe), Some(path15));
let path04: &[_] = &[0, 7, 5, 4]; assert_eq!(graph.shortest_path::<_, ()>(0, 4, &mut cache, edge_probe), Some(path04));
}
#[test]
fn betweenness_mmds() {
let mut cache = Default::default();
let graph = Graph::from_iter(
[(0, 1), (0, 2), (1, 2), (1, 3), (3, 4), (3, 5), (3, 6), (4, 5), (5, 6)]
.iter()
.cloned());
let b_rivers = graph.rivers_betweenness::<()>(&mut cache);
let mut vb_rivers: Vec<_> = b_rivers
.into_iter()
.map(|(r, v)| ((r.source, r.target), v))
.collect();
vb_rivers.sort_by_key(|p| p.0);
assert_eq!(vb_rivers, vec![((0, 1), 5.0),
((0, 2), 1.0),
((1, 2), 5.0),
((1, 3), 12.0),
((3, 4), 4.5),
((3, 5), 4.0),
((3, 6), 4.5),
((4, 5), 1.5),
((5, 6), 1.5)]);
}
#[test]
fn longest_jouney() {
let mut cache = Default::default();
let graph = sample_map_graph();
assert_eq!(graph.longest_jouney_from::<()>(6, &mut cache).and_then(|p| p.last().cloned()), Some(2));
}
#[test]
fn betweenness_sample_map() {
let mut cache = Default::default();
let graph = sample_map_graph();
let b_rivers = graph.rivers_betweenness::<()>(&mut cache);
let mut vb_rivers: Vec<_> = b_rivers
.into_iter()
.map(|(r, v)| ((r.source, r.target), v))
.collect();
vb_rivers.sort_by_key(|p| p.0);
assert_eq!(vb_rivers, vec![((0, 1), 3.5),
((0, 7), 3.5),
((1, 2), 3.5),
((1, 3), 4.5),
((1, 7), 4.5),
((2, 3), 3.5),
((3, 4), 3.5),
((3, 5), 4.5),
((4, 5), 3.5),
((5, 6), 3.5),
((5, 7), 4.5),
((6, 7), 3.5)]);
}
#[test]
fn betweenness_random_medium_map() {
let mut cache = Default::default();
let graph = random_medium_map_graph();
let b_rivers = graph.rivers_betweenness::<()>(&mut cache);
let mut vb_rivers: Vec<_> = b_rivers
.into_iter()
.map(|(r, v)| ((r.source, r.target), (v * 1000.0) as usize))
.collect();
vb_rivers.sort_by_key(|p| p.0);
assert_eq!(vb_rivers, vec![
((0, 21), 36484),
((0, 34), 220904),
((0, 39), 131120),
((0, 49), 27579),
((0, 56), 13938),
((0, 96), 37109),
((1, 30), 247739),
((1, 65), 70850),
((1, 67), 253536),
((1, 82), 363584),
((2, 24), 234571),
((2, 88), 121565),
((2, 89), 89020),
((3, 30), 154325),
((3, 67), 50923),
((3, 78), 77506),
((4, 24), 186155),
((4, 27), 408135),
((4, 55), 23583),
((4, 87), 243576),
((5, 32), 343580),
((5, 49), 92094),
((5, 74), 366297),
((6, 14), 352342),
((6, 45), 201604),
((6, 88), 168611),
((7, 10), 11644),
((7, 15), 25176),
((7, 47), 44170),
((7, 73), 20695),
((8, 20), 158732),
((8, 35), 78532),
((9, 18), 152409),
((9, 57), 223853),
((10, 15), 158058),
((10, 26), 117106),
((10, 47), 103208),
((10, 52), 306768),
((10, 73), 7524),
((10, 94), 35535),
((11, 12), 114871),
((11, 29), 114871),
((11, 75), 374451),
((11, 95), 545349),
((12, 29), 1000),
((12, 58), 146438),
((12, 75), 31233),
((13, 31), 75666),
((13, 41), 2833),
((13, 66), 77666),
((13, 80), 8333),
((13, 84), 64833),
((14, 23), 332733),
((14, 60), 163663),
((14, 64), 356754),
((14, 70), 478481),
((15, 26), 46740),
((15, 47), 415391),
((15, 59), 529230),
((15, 94), 24509),
((16, 38), 100946),
((16, 54), 149813),
((17, 50), 2000),
((17, 82), 94000),
((18, 38), 105446),
((19, 58), 65357),
((19, 64), 30642),
((20, 71), 393307),
((20, 77), 474785),
((21, 39), 8682),
((21, 49), 43567),
((21, 56), 168164),
((21, 85), 259352),
((21, 96), 1625),
((22, 51), 123267),
((22, 53), 210670),
((22, 72), 64984),
((22, 79), 81586),
((23, 58), 177929),
((23, 60), 12246),
((23, 64), 79156),
((23, 86), 279922),
((24, 55), 10700),
((24, 87), 96474),
((25, 40), 223333),
((25, 44), 137666),
((26, 46), 72406),
((26, 62), 33146),
((26, 94), 3873),
((27, 40), 407335),
((28, 72), 167759),
((28, 88), 118896),
((28, 89), 83062),
((29, 58), 146438),
((29, 75), 31233),
((30, 85), 434026),
((31, 36), 328166),
((31, 41), 122333),
((31, 66), 2500),
((31, 80), 50333),
((32, 52), 204834),
((32, 68), 161405),
((33, 39), 106951),
((33, 43), 85101),
((33, 76), 85101),
((33, 83), 84069),
((33, 85), 302056),
((33, 92), 84069),
((34, 37), 174896),
((34, 47), 162959),
((34, 56), 125378),
((34, 73), 122607),
((35, 51), 87432),
((36, 40), 575333),
((36, 66), 164166),
((37, 47), 479266),
((37, 86), 647162),
((39, 49), 53561),
((39, 85), 116609),
((39, 96), 9613),
((40, 61), 282805),
((40, 95), 482773),
((41, 84), 31166),
((42, 45), 72491),
((42, 53), 90480),
((42, 72), 16817),
((43, 48), 11070),
((43, 74), 67383),
((43, 76), 1000),
((43, 83), 7000),
((43, 92), 7000),
((44, 80), 54666),
((45, 69), 111613),
((46, 62), 9494),
((46, 63), 12449),
((46, 91), 16751),
((47, 73), 55975),
((48, 74), 63717),
((48, 76), 11070),
((48, 83), 17071),
((48, 92), 17071),
((49, 56), 46262),
((50, 82), 188000),
((50, 93), 96000),
((52, 56), 325566),
((52, 68), 238386),
((52, 73), 103641),
((53, 70), 438481),
((53, 71), 417654),
((53, 72), 144711),
((54, 77), 236146),
((55, 87), 61716),
((56, 96), 169289),
((57, 68), 336958),
((57, 81), 130477),
((58, 60), 192591),
((58, 64), 351216),
((58, 75), 669602),
((58, 86), 396573),
((59, 62), 54557),
((59, 63), 70334),
((59, 77), 511867),
((59, 90), 80895),
((59, 91), 139196),
((60, 64), 9642),
((61, 67), 268406),
((61, 78), 40399),
((62, 63), 19979),
((62, 91), 20587),
((62, 94), 84211),
((63, 90), 2559),
((63, 91), 7695),
((64, 87), 443934),
((65, 67), 25150),
((69, 79), 46780),
((73, 94), 96727),
((74, 76), 67383),
((74, 82), 323584),
((75, 85), 886139),
((76, 83), 7000),
((76, 92), 7000),
((78, 95), 65425),
((81, 91), 127210),
((83, 92), 1000),
((85, 96), 224326),
((88, 89), 36375),
((90, 91), 12545)]);
}
}
|
//! This module defines various utilities that do not belong in other modules.
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::*;
use std::mem;
use alloc::raw_vec::RawVec;
use string_interner::StringInterner;
/// Defines an interned string, which can be cheaply cloned.
pub struct InternedString<'cx> {
interner: &'cx StringInterner<usize>,
symbol: usize
}
impl<'cx> InternedString<'cx> {
/// Creates an interned string, given its interner and symbol.
pub fn new(interner: &'cx StringInterner<usize>, symbol: usize) -> Self {
InternedString { interner, symbol }
}
}
impl<'cx> Clone for InternedString<'cx> {
fn clone(&self) -> InternedString<'cx> {
InternedString { interner: dup!(self.interner), symbol: self.symbol }
}
}
impl<'cx> Display for InternedString<'cx> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
unsafe {
f.write_str(self.interner.resolve_unchecked(self.symbol))
}
}
}
impl<'cx> Debug for InternedString<'cx> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
unsafe {
f.write_str(self.interner.resolve_unchecked(self.symbol))
}
}
}
/// Defines a data structure that can be interned.
pub trait Internable: Into<String> + AsRef<str> {
fn intern(self, interner: &mut StringInterner<usize>) -> InternedString {
let symbol = interner.get_or_intern(self);
InternedString::new(interner, symbol)
}
}
/// Defines a structure that can be displayed, provided a `StringInterner`.
pub trait InternedDisplay {
/// Creates a human-readable representation of the structure, optionally
/// retrieving data in a `StringInterner`.
fn fmt(&self, f: &mut Formatter, interner: &StringInterner<usize>) -> fmt::Result;
/// Returns a string representation of the structure.
fn display(&self, interner: &StringInterner<usize>) -> String where Self: Sized {
let fmt = {
#[allow(dead_code)]
struct ManualDisplay<'a>(&'a InternedDisplay, &'a StringInterner<usize>);
impl<'a> Display for ManualDisplay<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.0.fmt(f, self.1)
}
}
ManualDisplay(self, interner)
};
format!("{}", fmt)
}
}
impl<T: Display> InternedDisplay for T {
fn fmt(&self, f: &mut Formatter, _: &StringInterner<usize>) -> fmt::Result {
Display::fmt(self, f)
}
}
/// A map of generic types.
pub struct Generics<T> {
vec: RawVec<*const T>,
len: usize
}
impl<T> Default for Generics<T> {
fn default() -> Self {
Generics { vec: RawVec::with_capacity(28), len: 0 }
}
}
impl<T> Drop for Generics<T> {
fn drop(&mut self) {
let size = mem::size_of::<*const T>();
let ptr = self.vec.ptr() as usize;
for i in 0..self.len {
unsafe {
Box::from_raw((ptr + i * size + 8) as *mut T);
}
}
}
}
impl<T: Hash> Generics<T> {
/// If the given type already exists in the generic map; returns a reference to it.
/// Else, inserts it and returns a reference to the inserted value.
pub fn get_or_insert<'vm>(&mut self, ty: T) -> &'vm T {
use fnv::FnvHasher;
let size = mem::size_of::<*const T>() + 8;
let vec = &mut self.vec;
let len = self.len;
let mut addr = vec.ptr() as usize;
let hash = {
let mut hasher = FnvHasher::default();
ty.hash(&mut hasher);
hasher.finish()
};
unsafe {
for i in 0..len {
let addr = addr + (size * i);
let item_hash = *(addr as *mut u64);
if item_hash == hash {
let addr = *((addr + 8) as *const usize) as *const _;
return &*addr
}
}
if vec.cap() == len {
vec.double();
addr = vec.ptr() as usize;
}
let boxed = Box::into_raw(box ty);
*((addr + len * size) as *mut _) = hash;
*((addr + len * size + 8) as *mut _) = boxed;
&*boxed
}
}
}
/// A structure similar to a `HashMap`, but that uses references for lookups.
#[derive(Clone, Debug)]
pub struct RefMap<'k, K: 'k, V> {
keys: Vec<&'k K>,
values: Vec<V>
}
impl<'k, K, V> Default for RefMap<'k, K, V> {
fn default() -> Self {
RefMap { keys: Vec::default(), values: Vec::default() }
}
}
impl<'k, K, V> RefMap<'k, K, V> {
/// Creates a new RefMap, given its capacity.
pub fn with_capacity(cap: usize) -> Self {
RefMap { keys: Vec::with_capacity(cap), values: Vec::with_capacity(cap) }
}
/// Returns the keys of this map.
pub fn keys(&self) -> &[&'k K] {
&self.keys
}
/// Returns the values of this map.
pub fn values(&self) -> &[V] {
&self.values
}
/// Gets the value related to the specified reference.
pub fn get(&self, key: &K) -> Option<&V> {
let key = key as *const K;
for (i, k) in self.keys.iter().enumerate() {
if *k as *const K == key {
return unsafe {
Some(self.values.get_unchecked(i))
}
}
}
None
}
/// Returns a `bool` that represents whether the reference map contains
/// a value matching the specified key.
pub fn contains(&self, key: &K) -> bool {
let key = key as *const K;
for k in &self.keys {
if *k as *const K == key {
return true
}
}
false
}
/// Takes the value matching the specified key.
pub fn take(&mut self, key: &K) -> Option<V> {
let key = key as *const K;
let mut i = 0;
while i < self.keys.len() {
let is_match = unsafe {
*self.keys.get_unchecked(i) as *const K == key
};
if is_match {
self.keys.swap_remove(i);
return Some(self.values.swap_remove(i));
} else {
i += 1;
}
}
None
}
/// Inserts the given value in the reference map;
/// if it already exists, its old value will be returned.
pub fn insert(&mut self, key: &'k K, value: V) -> Option<V> {
let result = self.take(key);
self.keys.push(key);
self.values.push(value);
result
}
}
|
//! This is a small procedural macro to load your `.env` file at compile time. That way you can use
//! [`std::env!`][] to load environment variables and fail the build if a variable is missing.
//!
//! All it does is call the [dotenv](https://crates.io/crates/dotenv) crate.
//!
//! # Example
//!
//! `.env` file:
//!
//! ```text
//! KEY=value
//! ```
//!
//! Rust:
//!
//! ```
//! use load_dotenv::load_dotenv;
//!
//! load_dotenv!();
//!
//! fn main() {
//! assert_eq!("value", env!("KEY"));
//! }
//! ```
//!
//! [`std::env!`]: https://doc.rust-lang.org/std/macro.env.html
#![doc(html_root_url = "https://docs.rs/load-dotenv/0.1.1")]
extern crate proc_macro;
use quote::quote;
/// Load the `.env` file and panic if the file is missing.
#[proc_macro]
pub fn load_dotenv(_: proc_macro::TokenStream) -> proc_macro::TokenStream {
dotenv::dotenv().expect("Failed to load .env file");
(quote! {}).into()
}
/// Load the `.env.xxx` file and panic if the file is missing.
#[proc_macro]
pub fn load_dotenv_from_filename(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let _input: String = input.to_string();
let _input: &str = _input.trim_matches('"');
dotenv::from_filename(_input).expect(format!("Failed to load {} file", _input).as_str());
(quote! {}).into()
}
/// Load the `.env` file but don't panic if the file is missing.
#[proc_macro]
pub fn try_load_dotenv(_: proc_macro::TokenStream) -> proc_macro::TokenStream {
dotenv::dotenv().ok();
(quote! {}).into()
}
|
/**
* 对目录下的文件进行自动分类到类型目录
* by shaipe 20190726
*/
use std::env;
use std::path::Path;
use std::fs::{read_dir, create_dir, copy, remove_file};
use std::io;
use std::io::prelude::*;
use std::fs::OpenOptions;
fn main(){
// 获取输入的参,参数为待处理的路径
let args: Vec<String>= env::args().collect();
let dir_str = if args.len() > 1 {
&args[1]
}
else {
"./"
};
// test_write_file();
// 获取当前目录下的所有文件或目录
for entry in read_dir(dir_str).unwrap(){
let path = entry.unwrap().path();
// 只对当前目录下的文件进行分类处理
if path.is_file() {
let ext = path.extension();
// 判断文件是否有扩展名,只对有扩展名的文件进行分类
if !ext.is_none() {
let ext_str = ext.unwrap().to_str().unwrap();
// println!("{}", ext_str);
// 测试时使用,只移动txt文件
// if ext_str.to_lowercase() != "txt"{
// continue;
// }
// 获取扩展类型对应的目录串
let t_dir_str = dir_str.to_owned() + ext_str;
let t_path = Path::new(&t_dir_str);
// println!("{:?}", t_dir_str);
// 判断目录是否存在,如果不存在就创建目录
if !t_path.exists() {
let _ = create_dir(t_dir_str.clone());
}
let tf_str = t_dir_str + "/" + path.file_name().unwrap().to_str().unwrap();
// 复制文件
match copy(path.clone(), tf_str.clone()){
Ok(_)=>{
// 复制文件成功后删除源文件
match remove_file(path.clone()){
Ok(_)=>{},
Err(ex) => println!("{:?}", ex)
}
},
Err(ex) => println!("{:?}", ex)
}
println!("move file {:?}, to {:?} successfully!", path.display(), tf_str.clone());
}
else{
println!("file {:?} not extension!", path.display());
}
}
}
}
/// 创建文件并写入值,用于测试使用
fn test_write_file() -> io::Result<()> {
let filename = "foo.txt";
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
//.create_new(true)
.append(true)
.open(filename);
match file {
Ok(mut stream) => {
stream.write_all(b"hello, world!\n")?;
}
Err(err) => {
println!("{:?}", err);
}
}
Ok(())
} |
use anyhow::{anyhow, Result};
use clap::{self, Clap, ValueHint};
use frodobuf::{
codegen::rust,
render::{OutputLanguage, RenderConfig, Renderer},
};
use frodobuf_schema::model::Schema;
use midl_parser::parse_string;
use std::{fs, path::PathBuf};
#[derive(Clap, Debug)]
#[clap(name = "midl", about, version)]
struct Opt {
// The number of occurrences of the `v/verbose` flag
/// Verbose mode (-v, -vv, -vvv, etc.)
#[clap(short, long, parse(from_occurrences))]
verbose: u8,
/// Subcommand
#[clap(subcommand)]
command: Command,
}
#[derive(Debug, Clap)]
pub enum Command {
/// Parse idl into json
#[clap(name = "json", alias = "schema")]
Json(JsonOpt),
/// Update source files after change in idl source
#[clap(name = "update")]
Update(UpdateOpt),
/// create new source project from idl file
#[clap(name = "create")]
Create(CreateOpt),
}
#[derive(Clap, Debug)]
pub struct JsonOpt {
/// Output file
#[clap(short, long)]
output: PathBuf,
/// Write output in prettified format
#[clap(long)]
pretty: bool,
/// Input files to process
#[clap(short, long)]
input: PathBuf,
}
#[derive(Clap, Debug)]
pub struct CreateOpt {
/// Input idl file
#[clap(short, long)]
input: PathBuf,
/// Output language. Multiple languages may be specified as `-l lang1 -l lang2 ...`
#[clap(short, long, alias = "lang")]
language: Vec<OutputLanguage>,
/// Existing output directory where files will be generated. Defaults to current directory.
#[clap(short, long, parse(from_os_str), value_hint = ValueHint::FilePath)]
output_dir: Option<PathBuf>,
/// Rust edition (default 2018)
#[clap(long, default_value = "2018")]
edition: String,
/// Package name for Cargo.toml.
/// Default value is "X-interface", where X is the base name of the midl file.
#[clap(long)]
package: Option<String>,
}
#[derive(Clap, Debug)]
pub struct UpdateOpt {
/// Input schema
#[clap(short, long, parse(from_os_str), value_hint = ValueHint::AnyPath)]
input: PathBuf,
/// Output language.
#[clap(short, long, alias = "lang")]
language: OutputLanguage,
/// Existing output directory where file will be generated. Defaults to current directory.
#[clap(short, long, parse(from_os_str), value_hint = ValueHint::FilePath)]
output_dir: Option<PathBuf>,
}
fn current_dir() -> PathBuf {
match std::env::current_dir() {
Ok(d) => d,
Err(_) => PathBuf::from("."),
}
}
fn main() {
let opt = Opt::parse();
if opt.verbose > 2 {
println!("{:#?}", &opt);
}
if let Err(e) = run(opt) {
eprintln!("Error: {}", e.to_string());
}
}
fn run(opt: Opt) -> Result<()> {
match &opt.command {
Command::Json(json_opt) => to_json(json_opt)?,
Command::Update(gen_opt) => update(gen_opt)?,
Command::Create(create_opt) => create(create_opt)?,
}
Ok(())
}
// parse idl and save schema json
fn to_json(opt: &JsonOpt) -> Result<()> {
let schema = parse_idl(&opt.input)?;
let schema_json = if opt.pretty {
serde_json::to_string_pretty(&schema)?
} else {
serde_json::to_string(&schema)?
};
fs::write(&opt.output, &schema_json.as_bytes())
.map_err(|e| anyhow!("writing output file '{}': {}", &opt.output.display(), e))?;
Ok(())
}
/// Create a project (only rust currently supported)
fn create(opt: &CreateOpt) -> Result<()> {
// first ensure we can read the schema
let schema = parse_idl(&opt.input)?;
let schema_json = serde_json::to_value(&schema)?;
let package = if let Some(package) = opt.package.as_ref() {
package.clone()
} else {
schema.namespace.name.clone()
};
let output = match opt.output_dir.as_ref() {
Some(o) => o.clone(),
None => current_dir(),
};
if !output.is_dir() {
return Err(anyhow!(
"output-dir parameter must be an existing directory"
));
}
for language in opt.language.iter() {
let mut renderer = Renderer::init(&RenderConfig {
language: *language,
..Default::default()
})?;
renderer.set("schema", schema_json.clone());
match language {
OutputLanguage::Rust => {
rust::create_project(
&mut renderer,
&schema,
rust::CreateProject {
input: &opt.input,
output: &output,
package: &package,
edition: &opt.edition,
},
)?;
}
}
}
Ok(())
}
fn update(opt: &UpdateOpt) -> Result<()> {
let schema = parse_idl(&opt.input)?;
let schema_json = serde_json::to_value(&schema)?;
let output = match opt.output_dir.as_ref() {
Some(o) => o.clone(),
None => current_dir(),
};
if !output.is_dir() {
return Err(anyhow!(
"output-dir parameter must be an existing directory"
));
}
let mut renderer = Renderer::init(&RenderConfig {
language: opt.language,
..Default::default()
})?;
renderer.set("schema", schema_json);
renderer.codegen_for_schema(&schema, &output)?;
Ok(())
}
/// Read idl file and convert to Schema
fn parse_idl(input: &std::path::Path) -> Result<Schema> {
let text = fs::read_to_string(input)
.map_err(|e| anyhow!("reading input file '{}': {}", &input.to_string_lossy(), e))?;
let descriptor = parse_string(&text)?;
// set package name to the file base if not otherwise set
Ok(descriptor.schema)
}
|
use std::{
convert::{TryFrom, TryInto},
fmt,
ops::Deref,
};
use thiserror::Error;
use crate::Error;
use librespot_protocol as protocol;
// re-export FileId for historic reasons, when it was part of this mod
pub use crate::FileId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SpotifyItemType {
Album,
Artist,
Episode,
Playlist,
Show,
Track,
Local,
Unknown,
}
impl From<&str> for SpotifyItemType {
fn from(v: &str) -> Self {
match v {
"album" => Self::Album,
"artist" => Self::Artist,
"episode" => Self::Episode,
"playlist" => Self::Playlist,
"show" => Self::Show,
"track" => Self::Track,
"local" => Self::Local,
_ => Self::Unknown,
}
}
}
impl From<SpotifyItemType> for &str {
fn from(item_type: SpotifyItemType) -> &'static str {
match item_type {
SpotifyItemType::Album => "album",
SpotifyItemType::Artist => "artist",
SpotifyItemType::Episode => "episode",
SpotifyItemType::Playlist => "playlist",
SpotifyItemType::Show => "show",
SpotifyItemType::Track => "track",
SpotifyItemType::Local => "local",
_ => "unknown",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct SpotifyId {
pub id: u128,
pub item_type: SpotifyItemType,
}
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
pub enum SpotifyIdError {
#[error("ID cannot be parsed")]
InvalidId,
#[error("not a valid Spotify URI")]
InvalidFormat,
#[error("URI does not belong to Spotify")]
InvalidRoot,
}
impl From<SpotifyIdError> for Error {
fn from(err: SpotifyIdError) -> Self {
Error::invalid_argument(err)
}
}
pub type SpotifyIdResult = Result<SpotifyId, Error>;
pub type NamedSpotifyIdResult = Result<NamedSpotifyId, Error>;
const BASE62_DIGITS: &[u8; 62] = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const BASE16_DIGITS: &[u8; 16] = b"0123456789abcdef";
impl SpotifyId {
const SIZE: usize = 16;
const SIZE_BASE16: usize = 32;
const SIZE_BASE62: usize = 22;
/// Returns whether this `SpotifyId` is for a playable audio item, if known.
pub fn is_playable(&self) -> bool {
matches!(
self.item_type,
SpotifyItemType::Episode | SpotifyItemType::Track
)
}
/// Parses a base16 (hex) encoded [Spotify ID] into a `SpotifyId`.
///
/// `src` is expected to be 32 bytes long and encoded using valid characters.
///
/// [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids
pub fn from_base16(src: &str) -> SpotifyIdResult {
let mut dst: u128 = 0;
for c in src.as_bytes() {
let p = match c {
b'0'..=b'9' => c - b'0',
b'a'..=b'f' => c - b'a' + 10,
_ => return Err(SpotifyIdError::InvalidId.into()),
} as u128;
dst <<= 4;
dst += p;
}
Ok(Self {
id: dst,
item_type: SpotifyItemType::Unknown,
})
}
/// Parses a base62 encoded [Spotify ID] into a `u128`.
///
/// `src` is expected to be 22 bytes long and encoded using valid characters.
///
/// [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids
pub fn from_base62(src: &str) -> SpotifyIdResult {
let mut dst: u128 = 0;
for c in src.as_bytes() {
let p = match c {
b'0'..=b'9' => c - b'0',
b'a'..=b'z' => c - b'a' + 10,
b'A'..=b'Z' => c - b'A' + 36,
_ => return Err(SpotifyIdError::InvalidId.into()),
} as u128;
dst *= 62;
dst += p;
}
Ok(Self {
id: dst,
item_type: SpotifyItemType::Unknown,
})
}
/// Creates a `u128` from a copy of `SpotifyId::SIZE` (16) bytes in big-endian order.
///
/// The resulting `SpotifyId` will default to a `SpotifyItemType::Unknown`.
pub fn from_raw(src: &[u8]) -> SpotifyIdResult {
match src.try_into() {
Ok(dst) => Ok(Self {
id: u128::from_be_bytes(dst),
item_type: SpotifyItemType::Unknown,
}),
Err(_) => Err(SpotifyIdError::InvalidId.into()),
}
}
/// Parses a [Spotify URI] into a `SpotifyId`.
///
/// `uri` is expected to be in the canonical form `spotify:{type}:{id}`, where `{type}`
/// can be arbitrary while `{id}` is a 22-character long, base62 encoded Spotify ID.
///
/// Note that this should not be used for playlists, which have the form of
/// `spotify:playlist:{id}`.
///
/// [Spotify URI]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids
pub fn from_uri(src: &str) -> SpotifyIdResult {
// Basic: `spotify:{type}:{id}`
// Named: `spotify:user:{user}:{type}:{id}`
// Local: `spotify:local:{artist}:{album_title}:{track_title}:{duration_in_seconds}`
let mut parts = src.split(':');
let scheme = parts.next().ok_or(SpotifyIdError::InvalidFormat)?;
let item_type = {
let next = parts.next().ok_or(SpotifyIdError::InvalidFormat)?;
if next == "user" {
let _username = parts.next().ok_or(SpotifyIdError::InvalidFormat)?;
parts.next().ok_or(SpotifyIdError::InvalidFormat)?
} else {
next
}
};
let id = parts.next().ok_or(SpotifyIdError::InvalidFormat)?;
if scheme != "spotify" {
return Err(SpotifyIdError::InvalidRoot.into());
}
let item_type = item_type.into();
// Local files have a variable-length ID: https://developer.spotify.com/documentation/general/guides/local-files-spotify-playlists/
// TODO: find a way to add this local file ID to SpotifyId.
// One possible solution would be to copy the contents of `id` to a new String field in SpotifyId,
// but then we would need to remove the derived Copy trait, which would be a breaking change.
if item_type == SpotifyItemType::Local {
return Ok(Self { item_type, id: 0 });
}
if id.len() != Self::SIZE_BASE62 {
return Err(SpotifyIdError::InvalidId.into());
}
Ok(Self {
item_type,
..Self::from_base62(id)?
})
}
/// Returns the `SpotifyId` as a base16 (hex) encoded, `SpotifyId::SIZE_BASE16` (32)
/// character long `String`.
#[allow(clippy::wrong_self_convention)]
pub fn to_base16(&self) -> Result<String, Error> {
to_base16(&self.to_raw(), &mut [0u8; Self::SIZE_BASE16])
}
/// Returns the `SpotifyId` as a [canonically] base62 encoded, `SpotifyId::SIZE_BASE62` (22)
/// character long `String`.
///
/// [canonically]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids
#[allow(clippy::wrong_self_convention)]
pub fn to_base62(&self) -> Result<String, Error> {
let mut dst = [0u8; 22];
let mut i = 0;
let n = self.id;
// The algorithm is based on:
// https://github.com/trezor/trezor-crypto/blob/c316e775a2152db255ace96b6b65ac0f20525ec0/base58.c
//
// We are not using naive division of self.id as it is an u128 and div + mod are software
// emulated at runtime (and unoptimized into mul + shift) on non-128bit platforms,
// making them very expensive.
//
// Trezor's algorithm allows us to stick to arithmetic on native registers making this
// an order of magnitude faster. Additionally, as our sizes are known, instead of
// dealing with the ID on a byte by byte basis, we decompose it into four u32s and
// use 64-bit arithmetic on them for an additional speedup.
for shift in &[96, 64, 32, 0] {
let mut carry = (n >> shift) as u32 as u64;
for b in &mut dst[..i] {
carry += (*b as u64) << 32;
*b = (carry % 62) as u8;
carry /= 62;
}
while carry > 0 {
dst[i] = (carry % 62) as u8;
carry /= 62;
i += 1;
}
}
for b in &mut dst {
*b = BASE62_DIGITS[*b as usize];
}
dst.reverse();
String::from_utf8(dst.to_vec()).map_err(|_| SpotifyIdError::InvalidId.into())
}
/// Returns a copy of the `SpotifyId` as an array of `SpotifyId::SIZE` (16) bytes in
/// big-endian order.
#[allow(clippy::wrong_self_convention)]
pub fn to_raw(&self) -> [u8; Self::SIZE] {
self.id.to_be_bytes()
}
/// Returns the `SpotifyId` as a [Spotify URI] in the canonical form `spotify:{type}:{id}`,
/// where `{type}` is an arbitrary string and `{id}` is a 22-character long, base62 encoded
/// Spotify ID.
///
/// If the `SpotifyId` has an associated type unrecognized by the library, `{type}` will
/// be encoded as `unknown`.
///
/// [Spotify URI]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids
#[allow(clippy::wrong_self_convention)]
pub fn to_uri(&self) -> Result<String, Error> {
// 8 chars for the "spotify:" prefix + 1 colon + 22 chars base62 encoded ID = 31
// + unknown size item_type.
let item_type: &str = self.item_type.into();
let mut dst = String::with_capacity(31 + item_type.len());
dst.push_str("spotify:");
dst.push_str(item_type);
dst.push(':');
let base_62 = self.to_base62()?;
dst.push_str(&base_62);
Ok(dst)
}
}
impl fmt::Debug for SpotifyId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("SpotifyId")
.field(&self.to_uri().unwrap_or_else(|_| "invalid uri".into()))
.finish()
}
}
impl fmt::Display for SpotifyId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_uri().unwrap_or_else(|_| "invalid uri".into()))
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct NamedSpotifyId {
pub inner_id: SpotifyId,
pub username: String,
}
impl NamedSpotifyId {
pub fn from_uri(src: &str) -> NamedSpotifyIdResult {
let uri_parts: Vec<&str> = src.split(':').collect();
// At minimum, should be `spotify:user:{username}:{type}:{id}`
if uri_parts.len() < 5 {
return Err(SpotifyIdError::InvalidFormat.into());
}
if uri_parts[0] != "spotify" {
return Err(SpotifyIdError::InvalidRoot.into());
}
if uri_parts[1] != "user" {
return Err(SpotifyIdError::InvalidFormat.into());
}
Ok(Self {
inner_id: SpotifyId::from_uri(src)?,
username: uri_parts[2].to_owned(),
})
}
pub fn to_uri(&self) -> Result<String, Error> {
let item_type: &str = self.inner_id.item_type.into();
let mut dst = String::with_capacity(37 + self.username.len() + item_type.len());
dst.push_str("spotify:user:");
dst.push_str(&self.username);
dst.push(':');
dst.push_str(item_type);
dst.push(':');
let base_62 = self.to_base62()?;
dst.push_str(&base_62);
Ok(dst)
}
pub fn from_spotify_id(id: SpotifyId, username: &str) -> Self {
Self {
inner_id: id,
username: username.to_owned(),
}
}
}
impl Deref for NamedSpotifyId {
type Target = SpotifyId;
fn deref(&self) -> &Self::Target {
&self.inner_id
}
}
impl fmt::Debug for NamedSpotifyId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("NamedSpotifyId")
.field(
&self
.inner_id
.to_uri()
.unwrap_or_else(|_| "invalid id".into()),
)
.finish()
}
}
impl fmt::Display for NamedSpotifyId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(
&self
.inner_id
.to_uri()
.unwrap_or_else(|_| "invalid id".into()),
)
}
}
impl TryFrom<&[u8]> for SpotifyId {
type Error = crate::Error;
fn try_from(src: &[u8]) -> Result<Self, Self::Error> {
Self::from_raw(src)
}
}
impl TryFrom<&str> for SpotifyId {
type Error = crate::Error;
fn try_from(src: &str) -> Result<Self, Self::Error> {
Self::from_base62(src)
}
}
impl TryFrom<String> for SpotifyId {
type Error = crate::Error;
fn try_from(src: String) -> Result<Self, Self::Error> {
Self::try_from(src.as_str())
}
}
impl TryFrom<&Vec<u8>> for SpotifyId {
type Error = crate::Error;
fn try_from(src: &Vec<u8>) -> Result<Self, Self::Error> {
Self::try_from(src.as_slice())
}
}
impl TryFrom<&protocol::spirc::TrackRef> for SpotifyId {
type Error = crate::Error;
fn try_from(track: &protocol::spirc::TrackRef) -> Result<Self, Self::Error> {
match SpotifyId::from_raw(track.gid()) {
Ok(mut id) => {
id.item_type = SpotifyItemType::Track;
Ok(id)
}
Err(_) => SpotifyId::from_uri(track.uri()),
}
}
}
impl TryFrom<&protocol::metadata::Album> for SpotifyId {
type Error = crate::Error;
fn try_from(album: &protocol::metadata::Album) -> Result<Self, Self::Error> {
Ok(Self {
item_type: SpotifyItemType::Album,
..Self::from_raw(album.gid())?
})
}
}
impl TryFrom<&protocol::metadata::Artist> for SpotifyId {
type Error = crate::Error;
fn try_from(artist: &protocol::metadata::Artist) -> Result<Self, Self::Error> {
Ok(Self {
item_type: SpotifyItemType::Artist,
..Self::from_raw(artist.gid())?
})
}
}
impl TryFrom<&protocol::metadata::Episode> for SpotifyId {
type Error = crate::Error;
fn try_from(episode: &protocol::metadata::Episode) -> Result<Self, Self::Error> {
Ok(Self {
item_type: SpotifyItemType::Episode,
..Self::from_raw(episode.gid())?
})
}
}
impl TryFrom<&protocol::metadata::Track> for SpotifyId {
type Error = crate::Error;
fn try_from(track: &protocol::metadata::Track) -> Result<Self, Self::Error> {
Ok(Self {
item_type: SpotifyItemType::Track,
..Self::from_raw(track.gid())?
})
}
}
impl TryFrom<&protocol::metadata::Show> for SpotifyId {
type Error = crate::Error;
fn try_from(show: &protocol::metadata::Show) -> Result<Self, Self::Error> {
Ok(Self {
item_type: SpotifyItemType::Show,
..Self::from_raw(show.gid())?
})
}
}
impl TryFrom<&protocol::metadata::ArtistWithRole> for SpotifyId {
type Error = crate::Error;
fn try_from(artist: &protocol::metadata::ArtistWithRole) -> Result<Self, Self::Error> {
Ok(Self {
item_type: SpotifyItemType::Artist,
..Self::from_raw(artist.artist_gid())?
})
}
}
impl TryFrom<&protocol::playlist4_external::Item> for SpotifyId {
type Error = crate::Error;
fn try_from(item: &protocol::playlist4_external::Item) -> Result<Self, Self::Error> {
Ok(Self {
item_type: SpotifyItemType::Track,
..Self::from_uri(item.uri())?
})
}
}
// Note that this is the unique revision of an item's metadata on a playlist,
// not the ID of that item or playlist.
impl TryFrom<&protocol::playlist4_external::MetaItem> for SpotifyId {
type Error = crate::Error;
fn try_from(item: &protocol::playlist4_external::MetaItem) -> Result<Self, Self::Error> {
Self::try_from(item.revision())
}
}
// Note that this is the unique revision of a playlist, not the ID of that playlist.
impl TryFrom<&protocol::playlist4_external::SelectedListContent> for SpotifyId {
type Error = crate::Error;
fn try_from(
playlist: &protocol::playlist4_external::SelectedListContent,
) -> Result<Self, Self::Error> {
Self::try_from(playlist.revision())
}
}
// TODO: check meaning and format of this field in the wild. This might be a FileId,
// which is why we now don't create a separate `Playlist` enum value yet and choose
// to discard any item type.
impl TryFrom<&protocol::playlist_annotate3::TranscodedPicture> for SpotifyId {
type Error = crate::Error;
fn try_from(
picture: &protocol::playlist_annotate3::TranscodedPicture,
) -> Result<Self, Self::Error> {
Self::from_base62(picture.uri())
}
}
pub fn to_base16(src: &[u8], buf: &mut [u8]) -> Result<String, Error> {
let mut i = 0;
for v in src {
buf[i] = BASE16_DIGITS[(v >> 4) as usize];
buf[i + 1] = BASE16_DIGITS[(v & 0x0f) as usize];
i += 2;
}
String::from_utf8(buf.to_vec()).map_err(|_| SpotifyIdError::InvalidId.into())
}
#[cfg(test)]
mod tests {
use super::*;
struct ConversionCase {
id: u128,
kind: SpotifyItemType,
uri: &'static str,
base16: &'static str,
base62: &'static str,
raw: &'static [u8],
}
static CONV_VALID: [ConversionCase; 5] = [
ConversionCase {
id: 238762092608182713602505436543891614649,
kind: SpotifyItemType::Track,
uri: "spotify:track:5sWHDYs0csV6RS48xBl0tH",
base16: "b39fe8081e1f4c54be38e8d6f9f12bb9",
base62: "5sWHDYs0csV6RS48xBl0tH",
raw: &[
179, 159, 232, 8, 30, 31, 76, 84, 190, 56, 232, 214, 249, 241, 43, 185,
],
},
ConversionCase {
id: 204841891221366092811751085145916697048,
kind: SpotifyItemType::Track,
uri: "spotify:track:4GNcXTGWmnZ3ySrqvol3o4",
base16: "9a1b1cfbc6f244569ae0356c77bbe9d8",
base62: "4GNcXTGWmnZ3ySrqvol3o4",
raw: &[
154, 27, 28, 251, 198, 242, 68, 86, 154, 224, 53, 108, 119, 187, 233, 216,
],
},
ConversionCase {
id: 204841891221366092811751085145916697048,
kind: SpotifyItemType::Episode,
uri: "spotify:episode:4GNcXTGWmnZ3ySrqvol3o4",
base16: "9a1b1cfbc6f244569ae0356c77bbe9d8",
base62: "4GNcXTGWmnZ3ySrqvol3o4",
raw: &[
154, 27, 28, 251, 198, 242, 68, 86, 154, 224, 53, 108, 119, 187, 233, 216,
],
},
ConversionCase {
id: 204841891221366092811751085145916697048,
kind: SpotifyItemType::Show,
uri: "spotify:show:4GNcXTGWmnZ3ySrqvol3o4",
base16: "9a1b1cfbc6f244569ae0356c77bbe9d8",
base62: "4GNcXTGWmnZ3ySrqvol3o4",
raw: &[
154, 27, 28, 251, 198, 242, 68, 86, 154, 224, 53, 108, 119, 187, 233, 216,
],
},
ConversionCase {
id: 0,
kind: SpotifyItemType::Local,
uri: "spotify:local:0000000000000000000000",
base16: "00000000000000000000000000000000",
base62: "0000000000000000000000",
raw: &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
},
];
static CONV_INVALID: [ConversionCase; 3] = [
ConversionCase {
id: 0,
kind: SpotifyItemType::Unknown,
// Invalid ID in the URI.
uri: "spotify:arbitrarywhatever:5sWHDYs0Bl0tH",
base16: "ZZZZZ8081e1f4c54be38e8d6f9f12bb9",
base62: "!!!!!Ys0csV6RS48xBl0tH",
raw: &[
// Invalid length.
154, 27, 28, 251, 198, 242, 68, 86, 154, 224, 5, 3, 108, 119, 187, 233, 216, 255,
],
},
ConversionCase {
id: 0,
kind: SpotifyItemType::Unknown,
// Missing colon between ID and type.
uri: "spotify:arbitrarywhatever5sWHDYs0csV6RS48xBl0tH",
base16: "--------------------",
base62: "....................",
raw: &[
// Invalid length.
154, 27, 28, 251,
],
},
ConversionCase {
id: 0,
kind: SpotifyItemType::Unknown,
// Uri too short
uri: "spotify:azb:aRS48xBl0tH",
base16: "--------------------",
base62: "....................",
raw: &[
// Invalid length.
154, 27, 28, 251,
],
},
];
#[test]
fn from_base62() {
for c in &CONV_VALID {
assert_eq!(SpotifyId::from_base62(c.base62).unwrap().id, c.id);
}
for c in &CONV_INVALID {
assert!(SpotifyId::from_base62(c.base62).is_err(),);
}
}
#[test]
fn to_base62() {
for c in &CONV_VALID {
let id = SpotifyId {
id: c.id,
item_type: c.kind,
};
assert_eq!(id.to_base62().unwrap(), c.base62);
}
}
#[test]
fn from_base16() {
for c in &CONV_VALID {
assert_eq!(SpotifyId::from_base16(c.base16).unwrap().id, c.id);
}
for c in &CONV_INVALID {
assert!(SpotifyId::from_base16(c.base16).is_err(),);
}
}
#[test]
fn to_base16() {
for c in &CONV_VALID {
let id = SpotifyId {
id: c.id,
item_type: c.kind,
};
assert_eq!(id.to_base16().unwrap(), c.base16);
}
}
#[test]
fn from_uri() {
for c in &CONV_VALID {
let actual = SpotifyId::from_uri(c.uri).unwrap();
assert_eq!(actual.id, c.id);
assert_eq!(actual.item_type, c.kind);
}
for c in &CONV_INVALID {
assert!(SpotifyId::from_uri(c.uri).is_err());
}
}
#[test]
fn from_local_uri() {
let actual = SpotifyId::from_uri("spotify:local:xyz:123").unwrap();
assert_eq!(actual.id, 0);
assert_eq!(actual.item_type, SpotifyItemType::Local);
}
#[test]
fn from_named_uri() {
let actual =
NamedSpotifyId::from_uri("spotify:user:spotify:playlist:37i9dQZF1DWSw8liJZcPOI")
.unwrap();
assert_eq!(actual.id, 136159921382084734723401526672209703396);
assert_eq!(actual.item_type, SpotifyItemType::Playlist);
assert_eq!(actual.username, "spotify");
}
#[test]
fn to_uri() {
for c in &CONV_VALID {
let id = SpotifyId {
id: c.id,
item_type: c.kind,
};
assert_eq!(id.to_uri().unwrap(), c.uri);
}
}
#[test]
fn from_raw() {
for c in &CONV_VALID {
assert_eq!(SpotifyId::from_raw(c.raw).unwrap().id, c.id);
}
for c in &CONV_INVALID {
assert!(SpotifyId::from_raw(c.raw).is_err());
}
}
}
|
use naming;
use std::path::PathBuf;
pub struct Options {
pub out_path: PathBuf,
pub package_prefix: Option<String>,
pub id_converter: Option<Box<naming::Naming>>,
pub modules: Vec<String>,
}
|
use criterion::{black_box, criterion_group, criterion_main, Criterion};
#[path = "../src/char_offset.rs"]
mod char_offset;
use char_offset::char_offset_impl;
pub fn char_offset_impl_original(c: char) -> usize {
match c {
' '..='~' => c as usize,
'\u{0000}' => 0x00,
'☺' => 0x01,
'☻' => 0x02,
'♥' => 0x03,
'♦' => 0x04,
'♣' => 0x05,
'♠' => 0x06,
'•' => 0x07,
'◘' => 0x08,
'○' => 0x09,
'◙' => 0x0A,
'♂' => 0x0B,
'♀' => 0x0C,
'♪' => 0x0D,
'♫' => 0x0E,
'☼' => 0x0F,
'►' => 0x10,
'◄' => 0x11,
'↕' => 0x12,
'‼' => 0x13,
'¶' => 0x14,
'§' => 0x15,
'▬' => 0x16,
'↨' => 0x17,
'↑' => 0x18,
'↓' => 0x19,
'→' => 0x1A,
'←' => 0x1B,
'∟' => 0x1C,
'↔' => 0x1D,
'▲' => 0x1E,
'▼' => 0x1F,
'⌂' => 0x7F,
'Ç' => 0x80,
'ü' => 0x81,
'é' => 0x82,
'â' => 0x83,
'ä' => 0x84,
'à' => 0x85,
'å' => 0x86,
'ç' => 0x87,
'ê' => 0x88,
'ë' => 0x89,
'è' => 0x8A,
'ï' => 0x8B,
'î' => 0x8C,
'ì' => 0x8D,
'Ä' => 0x8E,
'Å' => 0x8F,
'É' => 0x90,
'æ' => 0x91,
'Æ' => 0x92,
'ô' => 0x93,
'ö' => 0x94,
'ò' => 0x95,
'û' => 0x96,
'ù' => 0x97,
'ÿ' => 0x98,
'Ö' => 0x99,
'Ü' => 0x9A,
'¢' => 0x9B,
'£' => 0x9C,
'¥' => 0x9D,
'₧' => 0x9E,
'ƒ' => 0x9F,
'á' => 0xA0,
'í' => 0xA1,
'ó' => 0xA2,
'ú' => 0xA3,
'ñ' => 0xA4,
'Ñ' => 0xA5,
'ª' => 0xA6,
'º' => 0xA7,
'¿' => 0xA8,
'⌐' => 0xA9,
'¬' => 0xAA,
'½' => 0xAB,
'¼' => 0xAC,
'¡' => 0xAD,
'«' => 0xAE,
'»' => 0xAF,
'░' => 0xB0,
'▒' => 0xB1,
'▓' => 0xB2,
'│' => 0xB3,
'┤' => 0xB4,
'╡' => 0xB5,
'╢' => 0xB6,
'╖' => 0xB7,
'╕' => 0xB8,
'╣' => 0xB9,
'║' => 0xBA,
'╗' => 0xBB,
'╝' => 0xBC,
'╜' => 0xBD,
'╛' => 0xBE,
'┐' => 0xBF,
'└' => 0xC0,
'┴' => 0xC1,
'┬' => 0xC2,
'├' => 0xC3,
'─' => 0xC4,
'┼' => 0xC5,
'╞' => 0xC6,
'╟' => 0xC7,
'╚' => 0xC8,
'╔' => 0xC9,
'╩' => 0xCA,
'╦' => 0xCB,
'╠' => 0xCC,
'═' => 0xCD,
'╬' => 0xCE,
'╧' => 0xCF,
'╨' => 0xD0,
'╤' => 0xD1,
'╥' => 0xD2,
'╙' => 0xD3,
'╘' => 0xD4,
'╒' => 0xD5,
'╓' => 0xD6,
'╫' => 0xD7,
'╪' => 0xD8,
'┘' => 0xD9,
'┌' => 0xDA,
'█' => 0xDB,
'▄' => 0xDC,
'▌' => 0xDD,
'▐' => 0xDE,
'▀' => 0xDF,
'α' => 0xE0,
'ß' => 0xE1,
'Γ' => 0xE2,
'π' => 0xE3,
'Σ' => 0xE4,
'σ' => 0xE5,
'µ' => 0xE6,
'τ' => 0xE7,
'Φ' => 0xE8,
'Θ' => 0xE9,
'Ω' => 0xEA,
'δ' => 0xEB,
'∞' => 0xEC,
'φ' => 0xED,
'ε' => 0xEE,
'∩' => 0xEF,
'≡' => 0xF0,
'±' => 0xF1,
'≥' => 0xF2,
'≤' => 0xF3,
'⌠' => 0xF4,
'⌡' => 0xF5,
'÷' => 0xF6,
'≈' => 0xF7,
'°' => 0xF8,
'∙' => 0xF9,
'·' => 0xFA,
'√' => 0xFB,
'ⁿ' => 0xFC,
'²' => 0xFD,
'■' => 0xFE,
'\u{00A0}' => 0xFF,
_ => '?' as usize,
}
}
fn benchmark_original_ascii(c: &mut Criterion) {
let chars = "The quick brown fox jumps over the lazy dog".chars();
c.bench_function("Original mapping, ASCII characters", |b| {
b.iter(|| {
for c in chars.clone() {
let _ = char_offset_impl_original(black_box(c));
}
})
});
}
fn benchmark_current_ascii(c: &mut Criterion) {
let chars = "The quick brown fox jumps over the lazy dog".chars();
c.bench_function("Remapped, ASCII characters", |b| {
b.iter(|| {
for c in chars.clone() {
let _ = char_offset_impl(black_box(c));
}
})
});
}
fn benchmark_original_all_chars(c: &mut Criterion) {
let chars = include_str!("../src/Characters_src.txt")
.lines()
.map(|l| l.chars())
.flatten()
.collect::<Vec<char>>();
c.bench_function("Original mapping", |b| {
b.iter(|| {
for c in chars.iter() {
let _ = char_offset_impl_original(black_box(*c));
}
})
});
}
fn benchmark_current_all_chars(c: &mut Criterion) {
let chars = include_str!("../doc/Characters.txt")
.lines()
.map(|l| l.chars())
.flatten()
.collect::<Vec<char>>();
c.bench_function("Remapped", |b| {
b.iter(|| {
for c in chars.iter() {
let _ = char_offset_impl(black_box(*c));
}
})
});
}
criterion_group!(
char_offset_bench,
benchmark_original_ascii,
benchmark_current_ascii,
benchmark_original_all_chars,
benchmark_current_all_chars
);
criterion_main!(char_offset_bench);
|
//! Command processor
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use unicode_segmentation::UnicodeSegmentation;
use super::history::{Direction, History};
use super::keymap::{Anchor, At, CharSearch, RepeatCount, Word};
use super::keymap::{InputState, Refresher};
use super::line_buffer::{LineBuffer, WordAction, MAX_LINE};
use super::undo::Changeset;
use super::Offset as Position;
/// Represent the state during line editing.
/// Implement rendering.
pub struct State {
pub line: LineBuffer, // Edited line buffer
pub cursor: Position, /* Cursor position (relative to the start of the prompt
* for `row`) */
history_index: usize, // The history index we are currently editing
saved_line_for_history: LineBuffer, // Current edited line before history browsing
byte_buffer: [u8; 4],
pub changes: Rc<RefCell<Changeset>>, // changes to line, for undo/redo
pub width: usize,
pub rows: usize,
}
impl State {
pub fn new(history_index: usize) -> State {
let capacity = MAX_LINE;
State {
line: LineBuffer::with_capacity(capacity),
cursor: Default::default(),
history_index,
saved_line_for_history: LineBuffer::with_capacity(capacity),
byte_buffer: [0; 4],
changes: Rc::new(RefCell::new(Changeset::new())),
width: 80,
rows: 1,
}
}
pub fn backup(&mut self) {
self.saved_line_for_history
.update(self.line.as_str(), self.line.pos());
}
pub fn restore(&mut self) {
self.line.update(
self.saved_line_for_history.as_str(),
self.saved_line_for_history.pos(),
);
}
pub fn refresh(&mut self) {
let focuspos = self.line.pos();
let mut focus = Position::new(0, 0);
let mut idx = 0;
let lines = self.render_width(self.width);
self.rows = lines.len();
'outer: for (row, line) in lines.into_iter().enumerate() {
if idx == focuspos {
focus = Position::new(0, row);
break 'outer;
}
for (col, _ch) in UnicodeSegmentation::graphemes(line.as_str(), true).enumerate() {
idx += 1;
if idx == focuspos {
focus = Position::new(col + 1, row);
break 'outer;
}
}
idx += 1;
}
self.cursor = focus;
}
pub fn render_width(&self, width: usize) -> Vec<String> {
let lines: Vec<String> = self
.line
.as_str()
.split('\n')
.flat_map(|l| {
let letters: Vec<&str> = UnicodeSegmentation::graphemes(l, true).collect();
let mut split_lines = letters
.chunks(width)
.map(|ls| ls.concat())
.collect::<Vec<String>>();
if split_lines.len() == 0 {
split_lines.push("".to_string());
}
split_lines.into_iter()
})
.collect();
lines
}
pub fn finalize(&mut self) -> String {
let rv = self.line.as_str().to_owned();
self.line = LineBuffer::with_capacity(MAX_LINE);
self.refresh();
rv
}
pub fn set_line(&mut self, text: &str) {
self.line.update(text, text.len());
self.refresh();
}
}
impl Refresher for State {
fn refresh_line(&mut self) {
self.refresh()
}
fn doing_insert(&mut self) {
self.changes.borrow_mut().begin();
}
fn doing_replace(&mut self) {
self.changes.borrow_mut().begin();
}
fn done_inserting(&mut self) {
self.changes.borrow_mut().end();
}
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("State")
.field("buf", &self.line)
.field("cursor", &self.cursor)
.field("rows", &self.rows)
.field("width", &self.width)
.field("history_index", &self.history_index)
.field("saved_line_for_history", &self.saved_line_for_history)
.finish()
}
}
impl State {
/// Insert the character `ch` at cursor current position.
pub fn edit_insert(&mut self, ch: char, n: RepeatCount) {
if let Some(_) = self.line.insert(ch, n) {
self.refresh_line()
};
}
/// Replace a single (or n) character(s) under the cursor (Vi mode)
pub fn edit_replace_char(&mut self, ch: char, n: RepeatCount) {
self.changes.borrow_mut().begin();
let succeed = if let Some(chars) = self.line.delete(n) {
let count = chars.graphemes(true).count();
self.line.insert(ch, count);
self.line.move_backward(1);
true
} else {
false
};
self.changes.borrow_mut().end();
if succeed {
self.refresh_line()
}
}
/// Overwrite the character under the cursor (Vi mode)
pub fn edit_overwrite_char(&mut self, ch: char) {
if let Some(end) = self.line.next_pos(1) {
{
let text = ch.encode_utf8(&mut self.byte_buffer);
let start = self.line.pos();
self.line.replace(start..end, text);
}
self.refresh_line()
}
}
// Yank/paste `text` at current position.
pub fn edit_yank(
&mut self,
input_state: &InputState,
text: &str,
anchor: Anchor,
n: RepeatCount,
) {
if let Anchor::After = anchor {
self.line.move_forward(1);
}
if self.line.yank(text, n).is_some() {
if !input_state.is_emacs_mode() {
self.line.move_backward(1);
}
self.refresh_line()
}
}
// Delete previously yanked text and yank/paste `text` at current position.
pub fn edit_yank_pop(&mut self, yank_size: usize, text: &str) {
self.changes.borrow_mut().begin();
if self.line.yank_pop(yank_size, text).is_some() {
self.refresh_line()
};
self.changes.borrow_mut().end();
}
/// Move cursor on the left.
pub fn edit_move_backward(&mut self, n: RepeatCount) {
if self.line.move_backward(n) {
self.refresh()
}
}
/// Move cursor on the right.
pub fn edit_move_forward(&mut self, n: RepeatCount) {
if self.line.move_forward(n) {
self.refresh()
}
}
/// Move cursor to the start of the line.
pub fn edit_move_home(&mut self) {
if self.line.move_home() {
self.refresh()
}
}
/// Move cursor to the end of the line.
pub fn edit_move_end(&mut self) {
if self.line.move_end() {
self.refresh()
}
}
/// Delete the character at the right of the cursor without altering the
/// cursor position. Basically this is what happens with the "Delete"
/// keyboard key.
pub fn edit_delete(&mut self, n: RepeatCount) {
if self.line.delete(n).is_some() {
self.refresh_line()
}
}
/// Backspace implementation.
pub fn edit_backspace(&mut self, n: RepeatCount) {
if self.line.backspace(n) {
self.refresh_line()
}
}
/// Kill the text from point to the end of the line.
pub fn edit_kill_line(&mut self) {
if self.line.kill_line() {
self.refresh_line()
}
}
/// Kill backward from point to the beginning of the line.
pub fn edit_discard_line(&mut self) {
if self.line.discard_line() {
self.refresh_line()
}
}
/// Exchange the char before cursor with the character at cursor.
pub fn edit_transpose_chars(&mut self) {
self.changes.borrow_mut().begin();
let succeed = self.line.transpose_chars();
self.changes.borrow_mut().end();
if succeed {
self.refresh_line()
}
}
pub fn edit_move_to_prev_word(&mut self, word_def: Word, n: RepeatCount) {
if self.line.move_to_prev_word(word_def, n) {
self.refresh()
}
}
/// Delete the previous word, maintaining the cursor at the start of the
/// current word.
pub fn edit_delete_prev_word(&mut self, word_def: Word, n: RepeatCount) {
if self.line.delete_prev_word(word_def, n) {
self.refresh_line()
}
}
pub fn edit_move_to_next_word(&mut self, at: At, word_def: Word, n: RepeatCount) {
if self.line.move_to_next_word(at, word_def, n) {
self.refresh()
}
}
pub fn edit_move_to(&mut self, cs: CharSearch, n: RepeatCount) {
if self.line.move_to(cs, n) {
self.refresh()
}
}
/// Kill from the cursor to the end of the current word, or, if between
/// words, to the end of the next word.
pub fn edit_delete_word(&mut self, at: At, word_def: Word, n: RepeatCount) {
if self.line.delete_word(at, word_def, n) {
self.refresh_line()
}
}
pub fn edit_delete_to(&mut self, cs: CharSearch, n: RepeatCount) {
if self.line.delete_to(cs, n) {
self.refresh_line()
}
}
pub fn edit_word(&mut self, a: WordAction) {
self.changes.borrow_mut().begin();
let succeed = self.line.edit_word(a);
self.changes.borrow_mut().end();
if succeed {
self.refresh_line()
}
}
pub fn edit_transpose_words(&mut self, n: RepeatCount) {
self.changes.borrow_mut().begin();
let succeed = self.line.transpose_words(n);
self.changes.borrow_mut().end();
if succeed {
self.refresh_line()
}
}
/// Substitute the currently edited line with the next or previous history
/// entry.
pub fn edit_history_next(&mut self, history: &History, prev: bool) {
if history.is_empty() {
return;
}
if self.history_index == history.len() {
if prev {
// Save the current edited line before overwriting it
self.backup();
} else {
return;
}
} else if self.history_index == 0 && prev {
return;
}
if prev {
self.history_index -= 1;
} else {
self.history_index += 1;
}
if self.history_index < history.len() {
let buf = history.get(self.history_index).unwrap();
self.changes.borrow_mut().begin();
self.line.update(buf, buf.len());
self.changes.borrow_mut().end();
} else {
// Restore current edited line
self.restore();
}
self.refresh_line()
}
// Non-incremental, anchored search
pub fn edit_history_search(&mut self, history: &History, dir: Direction) {
if history.is_empty() {
return;
}
if self.history_index == history.len() && dir == Direction::Forward {
return;
} else if self.history_index == 0 && dir == Direction::Reverse {
return;
}
if dir == Direction::Reverse {
self.history_index -= 1;
} else {
self.history_index += 1;
}
if let Some(history_index) = history.starts_with(
&self.line.as_str()[..self.line.pos()],
self.history_index,
dir,
) {
self.history_index = history_index;
let buf = history.get(history_index).unwrap();
self.changes.borrow_mut().begin();
self.line.update(buf, buf.len());
self.changes.borrow_mut().end();
self.refresh_line()
}
}
/// Substitute the currently edited line with the first/last history entry.
pub fn edit_history(&mut self, history: &History, first: bool) {
if history.is_empty() {
return;
}
if self.history_index == history.len() {
if first {
// Save the current edited line before overwriting it
self.backup();
} else {
return;
}
} else if self.history_index == 0 && first {
return;
}
if first {
self.history_index = 0;
let buf = history.get(self.history_index).unwrap();
self.changes.borrow_mut().begin();
self.line.update(buf, buf.len());
self.changes.borrow_mut().end();
} else {
self.history_index = history.len();
// Restore current edited line
self.restore();
}
self.refresh_line()
}
}
#[cfg(test)]
pub fn init_state(line: &str, pos: usize) -> State {
State {
rows: 1,
width: line.len(),
line: LineBuffer::init(line, pos, None),
cursor: Position::default(),
history_index: 0,
saved_line_for_history: LineBuffer::with_capacity(100),
byte_buffer: [0; 4],
changes: Rc::new(RefCell::new(Changeset::new())),
}
}
#[cfg(test)]
mod test {
use super::super::history::History;
use super::init_state;
#[test]
fn edit_history_next() {
let line = "current edited line";
let mut s = init_state(line, 6);
let mut history = History::new();
history.add("line0");
history.add("line1");
s.history_index = history.len();
for _ in 0..2 {
s.edit_history_next(&history, false);
assert_eq!(line, s.line.as_str());
}
s.edit_history_next(&history, true);
assert_eq!(line, s.saved_line_for_history.as_str());
assert_eq!(1, s.history_index);
assert_eq!("line1", s.line.as_str());
for _ in 0..2 {
s.edit_history_next(&history, true);
assert_eq!(line, s.saved_line_for_history.as_str());
assert_eq!(0, s.history_index);
assert_eq!("line0", s.line.as_str());
}
s.edit_history_next(&history, false);
assert_eq!(line, s.saved_line_for_history.as_str());
assert_eq!(1, s.history_index);
assert_eq!("line1", s.line.as_str());
s.edit_history_next(&history, false);
// assert_eq!(line, s.saved_line_for_history);
assert_eq!(2, s.history_index);
assert_eq!(line, s.line.as_str());
}
}
|
use config::{ConfigError, Config, File, Environment};
/// Settings managing the data collection process
#[derive(Debug, Deserialize)]
pub struct DataCollectionSettings {
/// How many samples to take from the sensor for each data collection. These samples will be
/// averaged together, and that average will be used as the data point
pub samples_per_collection: u8,
/// A calibration value to account for any constant delay, such as long wires and propagation delay
pub calibration_microsec: f64,
/// Whether to simulate a sensor or use an actual ultrasonic sensor attached via GPIO
pub simulate_sensor: bool,
/// Number of milliseconds to wait in between taking data collections
pub millisec_between_readings: u64,
/// Filename of the SQLite database to use to store data
pub db_filename: String
}
#[derive(Debug, Deserialize)]
pub struct Settings {
pub data_collection: DataCollectionSettings
}
impl Settings {
pub fn new() -> Result<Self, ConfigError> {
let mut settings = Config::new();
settings.merge(File::with_name("Settings")).expect("Could not merge in settings file");
settings.merge(Environment::with_prefix("app")).expect("Could not merge in environment variables");
settings.try_into()
}
} |
// This file is part of Substrate.
// Copyright (C) 2017-2021 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.
//! Tests for the module.
use super::*;
use frame_support::{
assert_err, assert_noop, assert_ok,
traits::{Currency, Hooks, ReservableCurrency},
};
use frame_system::RawOrigin;
use mock::*;
use node_primitives::{
credit::{CreditData, CreditInterface, CreditLevel, CreditSetting, H160},
DPR,
};
use pallet_balances::Error as BalancesError;
use sp_runtime::traits::{BadOrigin, UniqueSaturatedFrom};
use sp_staking::offence::OffenceDetails;
use sp_std::convert::TryFrom;
use std::collections::HashMap;
macro_rules! assert_eq_uvec {
( $x:expr, $y:expr $(,)? ) => {
if $x.len() != $y.len() {
panic!("vectors not equal: {:?} != {:?}", $x, $y);
}
$x.iter().for_each(|e| {
if !$y.contains(e) {
panic!("vectors not equal: {:?} != {:?}", $x, $y);
}
});
};
}
#[test]
fn kill_stash_works() {
ExtBuilder::default().build_and_execute(|| {
// Account 11 is stashed and locked, and account 10 is the controller
assert_eq!(Staking::bonded(&11), Some(10));
// Adds 2 slashing spans
add_slash(&11);
// Only can kill a stash account
assert_noop!(Staking::kill_stash(&12, 0), Error::<Test>::NotStash);
// Respects slashing span count
assert_noop!(
Staking::kill_stash(&11, 0),
Error::<Test>::IncorrectSlashingSpans
);
// Correct inputs, everything works
assert_ok!(Staking::kill_stash(&11, 2));
// No longer bonded.
assert_eq!(Staking::bonded(&11), None);
});
}
#[test]
fn basic_setup_works() {
// Verifies initial conditions of mock
ExtBuilder::default().build_and_execute(|| {
// Account 11 is stashed and locked, and account 10 is the controller
assert_eq!(Staking::bonded(&11), Some(10));
// Account 21 is stashed and locked, and account 20 is the controller
assert_eq!(Staking::bonded(&21), Some(20));
// Account 1 is not a stashed
assert_eq!(Staking::bonded(&1), None);
// Account 10 controls the stash from account 11, which is 100 * balance_factor units
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![]
})
);
// Account 20 controls the stash from account 21, which is 200 * balance_factor units
assert_eq!(
Staking::ledger(&20),
Some(StakingLedger {
stash: 21,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![]
})
);
// Account 1 does not control any stash
assert_eq!(Staking::ledger(&1), None);
// ValidatorPrefs are default
assert_eq_uvec!(
<Validators<Test>>::iter().collect::<Vec<_>>(),
vec![
(31, ValidatorPrefs::default()),
(21, ValidatorPrefs::default()),
(11, ValidatorPrefs::default())
]
);
assert_eq!(
Staking::ledger(100),
Some(StakingLedger {
stash: 101,
total: 500,
active: 500,
unlocking: vec![],
claimed_rewards: vec![]
})
);
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
Exposure {
total: 1000,
own: 1000,
others: vec![1001]
},
);
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 21),
Exposure {
total: 1000,
own: 1000,
others: vec![1001]
},
);
// initial total stake = 1125 + 1375
assert_eq!(
Staking::eras_total_stake(Staking::active_era().unwrap().index),
2000
);
// The number of validators required.
assert_eq!(Staking::validator_count(), 2);
// Initial Era and session
assert_eq!(Staking::active_era().unwrap().index, 0);
// Account 10 has `balance_factor` free balance
assert_eq!(Balances::free_balance(10), 1);
assert_eq!(Balances::free_balance(10), 1);
// New era is not being forced
assert_eq!(Staking::force_era(), Forcing::NotForcing);
});
}
#[test]
fn difference_compensation() {
ExtBuilder::default().build_and_execute(|| {
let reward_data_before = RewardData::<BalanceOf<Test>> {
total_referee_reward: 0,
received_referee_reward: 0,
referee_reward: 0,
received_pocr_reward: 100,
poc_reward: 10,
};
Reward::<Test>::insert(&1, &reward_data_before);
assert_eq!(Staking::reward(&1), Some(reward_data_before.clone()));
let reward_data_after = RewardData::<BalanceOf<Test>> {
total_referee_reward: 0,
received_referee_reward: 0,
referee_reward: 0,
received_pocr_reward: 120,
poc_reward: 20,
};
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
1001,
Privilege::ReleaseSetter
));
assert_ok!(Operation::set_release_limit_parameter(
RuntimeOrigin::root(),
20,
100
));
// If you are a non-authorized user, the call will fail
assert_noop!(
Staking::difference_compensation(RuntimeOrigin::signed(1002), 1, 0, 20),
Error::<Test>::UnauthorizedAccounts
);
assert_eq!(Staking::reward(&1), Some(reward_data_before.clone()));
// If you are the authorized user, the call should succeed
assert_ok!(Staking::difference_compensation(
RuntimeOrigin::signed(1001),
1,
0,
20
));
assert_eq!(Staking::reward(&1), Some(reward_data_after));
});
}
#[test]
fn change_controller_works() {
ExtBuilder::default().build_and_execute(|| {
// 10 and 11 are bonded as stash controller.
assert_eq!(Staking::bonded(&11), Some(10));
// 10 can control 11 who is initially a validator.
assert_ok!(Staking::chill(RuntimeOrigin::signed(10)));
// change controller
assert_ok!(Staking::set_controller(RuntimeOrigin::signed(11), 5));
assert_eq!(Staking::bonded(&11), Some(5));
mock::start_active_era(1);
// 10 is no longer in control.
assert_noop!(
Staking::validate(RuntimeOrigin::signed(10), ValidatorPrefs::default()),
Error::<Test>::NotController,
);
assert_ok!(Staking::validate(
RuntimeOrigin::signed(5),
ValidatorPrefs::default()
));
})
}
#[test]
fn rewards_should_work() {
ExtBuilder::default()
.session_per_era(6)
.num_delegators(3)
.build_and_execute(|| {
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1002), vec![11, 21]));
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1003), vec![11, 21]));
let init_balance_10 = Balances::total_balance(&10);
let init_balance_11 = Balances::total_balance(&11);
let init_balance_20 = Balances::total_balance(&20);
let init_balance_21 = Balances::total_balance(&21);
let init_balance_1001 = Balances::total_balance(&1001);
let init_balance_1002 = Balances::total_balance(&1002);
let init_balance_1003 = Balances::total_balance(&1003);
// Set payees
Payee::<Test>::insert(11, RewardDestination::Controller);
Payee::<Test>::insert(21, RewardDestination::Controller);
<Pallet<Test>>::reward_by_ids(vec![(11, 50)]);
<Pallet<Test>>::reward_by_ids(vec![(11, 50)]);
// This is the second validator of the current elected set.
<Pallet<Test>>::reward_by_ids(vec![(21, 50)]);
start_session(1);
assert_eq!(Balances::total_balance(&10), init_balance_10);
assert_eq!(Balances::total_balance(&11), init_balance_11);
assert_eq!(Balances::total_balance(&20), init_balance_20);
assert_eq!(Balances::total_balance(&21), init_balance_21);
assert_eq!(Balances::total_balance(&1001), init_balance_1001);
assert_eq!(Balances::total_balance(&1002), init_balance_1002);
assert_eq!(Balances::total_balance(&1003), init_balance_1003);
assert_eq_uvec!(Session::validators(), vec![11, 21]);
start_session(2);
start_session(3);
start_session(4);
start_session(5);
start_session(6);
assert_eq!(Staking::active_era().unwrap().index, 1);
assert_eq!(
Balances::total_balance(&10),
init_balance_10 + 39999999960000000000
);
assert_eq!(Balances::total_balance(&11), init_balance_11);
assert_eq!(
Balances::total_balance(&20),
init_balance_20 + 19999999980000000000
);
assert_eq!(Balances::total_balance(&21), init_balance_21);
// delegator not paid yet
assert_eq!(Balances::total_balance(&1001), init_balance_1001);
assert_eq!(Balances::total_balance(&1002), init_balance_1002);
assert_eq!(Balances::total_balance(&1003), init_balance_1003);
let mut remainder = TOTAL_MINING_REWARD - 39999999960000000000 - 19999999980000000000;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
run_to_block(BLOCKS_PER_ERA + 1); // pay delegator from the second block of the second era
assert_eq!(
Balances::total_balance(&1002),
init_balance_1001 + 21369858941948251800
);
remainder = remainder - 21369858941948251800;
assert_eq!(
Balances::total_balance(&1001),
init_balance_1001 + 21369858941948251800
); // 1001 is paid
remainder = remainder - 21369858941948251800;
assert_eq!(Balances::total_balance(&1003), init_balance_1003); // 1003 is not paid yet
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
run_to_block(BLOCKS_PER_ERA + 2);
// since 1001 is paid already, it should not pay it again
assert_eq!(
Balances::total_balance(&1001),
init_balance_1001 + 21369858941948251800
);
// since 1002 is paid already, it should not pay it again
assert_eq!(
Balances::total_balance(&1002),
init_balance_1002 + 21369858941948251800
);
// 1003 is paid now
assert_eq!(
Balances::total_balance(&1003),
init_balance_1003 + 21369858941948251800
);
remainder = remainder - 21369858941948251800;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
});
}
#[test]
fn many_delegators_rewards_should_work() {
ExtBuilder::default()
.session_per_era(6)
.num_delegators(u32::try_from(BLOCKS_PER_ERA).ok().unwrap() - 1)
.build_and_execute(|| {
let mut init_balances = HashMap::<AccountId, Balance>::new();
for i in 1001..1001 + BLOCKS_PER_ERA - 1 {
assert_ok!(Staking::delegate(RuntimeOrigin::signed(i), vec![11, 21]));
init_balances.insert(i, Balances::total_balance(&i));
}
assert_eq!(Staking::delegator_count() as u64, BLOCKS_PER_ERA - 1);
assert_eq!(Staking::active_delegator_count() as u64, BLOCKS_PER_ERA - 1);
run_to_block(BLOCKS_PER_ERA); // the first block of the second era
for i in 1001..1001 + BLOCKS_PER_ERA - 1 {
// no delegators are paid yet
assert_eq!(Balances::total_balance(&i), *init_balances.get(&i).unwrap());
}
// since we need to pay BLOCKS_PER_ERA delegators in (BLOCKS_PER_ERA - 2) blocks
// 1 each block is not enough,for some edge case,instead we pay 3 delegators each block
assert_eq!(Staking::delegator_payouts_per_block(), 3);
assert!(!Staking::delegators_key_prefix().is_empty());
assert_eq!(
Staking::delegators_key_prefix(),
Staking::delegators_last_key()
);
let mut remainder = TOTAL_MINING_REWARD;
let mut i = 1u64;
while i < BLOCKS_PER_ERA / 3 {
run_to_block(BLOCKS_PER_ERA + i);
// it should pay 3 delegators each block
remainder = remainder - 21369858941948251800 * 3;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
i += 1;
}
run_to_block(BLOCKS_PER_ERA + BLOCKS_PER_ERA / 3);
// 2 delegators last been paid
remainder = remainder - 21369858941948251800 - 21369858941948251800;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
i = BLOCKS_PER_ERA / 3 + 1;
while i < BLOCKS_PER_ERA {
run_to_block(BLOCKS_PER_ERA + i);
// all the delegators are paid, so no new payment should be made
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
i += 1;
}
for i in 1002..1001 + BLOCKS_PER_ERA - 1 {
assert_eq!(Balances::total_balance(&1001), Balances::total_balance(&i));
}
});
}
#[test]
fn no_rewards_if_undelegating_in_the_same_era() {
ExtBuilder::default()
.session_per_era(6)
.build_and_execute(|| {
// 1001 is the default delegator
assert_eq!(Staking::delegator_count() as u64, 1);
assert_eq!(Staking::active_delegator_count() as u64, 1);
assert_ok!(Staking::undelegate(RuntimeOrigin::signed(1001)));
assert_eq!(Staking::active_delegator_count() as u64, 0);
assert_eq!(Staking::delegator_count() as u64, 0);
run_to_block(BLOCKS_PER_ERA + 1);
assert_eq!(
Staking::remainder_mining_reward().unwrap(),
TOTAL_MINING_REWARD
);
});
}
#[test]
fn rewards_if_undelegating_in_next_era() {
ExtBuilder::default()
.session_per_era(6)
.build_and_execute(|| {
// 1001 is the default delegator
assert_eq!(Staking::delegator_count() as u64, 1);
assert_eq!(Staking::active_delegator_count() as u64, 1);
run_to_block(BLOCKS_PER_ERA);
assert_eq!(
Staking::remainder_mining_reward().unwrap(),
TOTAL_MINING_REWARD
);
run_to_block(BLOCKS_PER_ERA + 1);
assert!(Staking::remainder_mining_reward().unwrap() < TOTAL_MINING_REWARD);
assert_ok!(Staking::undelegate(RuntimeOrigin::signed(1001)));
assert_eq!(Staking::active_delegator_count() as u64, 0);
assert_eq!(Staking::delegator_count() as u64, 0);
});
}
#[test]
fn rewards_continue_each_era() {
ExtBuilder::default()
.session_per_era(6)
.build_and_execute(|| {
// 1001 is the default delegator
assert_eq!(Staking::delegator_count() as u64, 1);
assert_eq!(Staking::active_delegator_count() as u64, 1);
let init_balance_1001 = Balances::total_balance(&1001);
run_to_block(BLOCKS_PER_ERA);
assert_eq!(
Staking::remainder_mining_reward().unwrap(),
TOTAL_MINING_REWARD
);
run_to_block(BLOCKS_PER_ERA + 1);
// 1001 is paid
assert_eq!(
Balances::total_balance(&1001),
init_balance_1001 + 21369858941948251800
);
let mut remainder = TOTAL_MINING_REWARD - 21369858941948251800;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
run_to_block(BLOCKS_PER_ERA * 2 + 1);
// 1001 is paid
assert_eq!(
Balances::total_balance(&1001),
init_balance_1001 + 21369858941948251800 * 2
);
remainder = TOTAL_MINING_REWARD - 21369858941948251800 * 2;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
});
}
#[test]
fn rewards_always_paid_in_next_era() {
ExtBuilder::default()
.session_per_era(6)
.num_delegators(2)
.build_and_execute(|| {
// 1001 is the default delegator
assert_eq!(Staking::delegator_count() as u64, 1);
assert_eq!(Staking::active_delegator_count() as u64, 1);
let init_balance_1001 = Balances::total_balance(&1001);
let init_balance_1002 = Balances::total_balance(&1002);
run_to_block(BLOCKS_PER_ERA);
assert_eq!(
Staking::remainder_mining_reward().unwrap(),
TOTAL_MINING_REWARD
);
run_to_block(BLOCKS_PER_ERA + 1);
// 1001 is paid
assert_eq!(
Balances::total_balance(&1001),
init_balance_1001 + 21369858941948251800
);
let mut remainder = TOTAL_MINING_REWARD - 21369858941948251800;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
// 1001 undelegates so that it won't be paid next era
assert_ok!(Staking::undelegate(RuntimeOrigin::signed(1001)));
// 1002 becomes delegator in the new era
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1002), vec![11, 21]));
assert_eq!(Staking::active_delegator_count() as u64, 1);
assert_eq!(Staking::delegator_count() as u64, 1);
run_to_block(BLOCKS_PER_ERA * 2 + 2);
// 1001 balance is the same as the last era
assert_eq!(
Balances::total_balance(&1001),
init_balance_1001 + 21369858941948251800
);
// 1002 is paid now
assert_eq!(
Balances::total_balance(&1002),
init_balance_1002 + 21369858941948251800
);
remainder = remainder - 21369858941948251800;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
});
}
#[test]
fn rewards_not_affected_by_others_undelegating() {
ExtBuilder::default()
.session_per_era(6)
.num_delegators(4)
.build_and_execute(|| {
// 1001 is the default delegator
assert_eq!(Staking::delegator_count() as u64, 1);
assert_eq!(Staking::active_delegator_count() as u64, 1);
let init_balance_1001 = Balances::total_balance(&1001);
let init_balance_1002 = Balances::total_balance(&1002);
let init_balance_1003 = Balances::total_balance(&1003);
let init_balance_1004 = Balances::total_balance(&1004);
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1002), vec![11, 21]));
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1003), vec![11, 21]));
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1004), vec![11, 21]));
assert_eq!(Staking::active_delegator_count() as u64, 4);
assert_eq!(Staking::delegator_count() as u64, 4);
run_to_block(BLOCKS_PER_ERA);
assert_eq!(
Staking::remainder_mining_reward().unwrap(),
TOTAL_MINING_REWARD
);
run_to_block(BLOCKS_PER_ERA + 1);
// 1004 is paid
assert_eq!(
Balances::total_balance(&1004),
init_balance_1004 + 21369858941948251800
);
// 1002 is paid
assert_eq!(
Balances::total_balance(&1002),
init_balance_1002 + 21369858941948251800
);
assert_eq!(Balances::total_balance(&1001), init_balance_1001);
assert_eq!(Balances::total_balance(&1003), init_balance_1003);
let mut remainder = TOTAL_MINING_REWARD - 21369858941948251800 - 21369858941948251800;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
// 1004 undelegates now
assert_ok!(Staking::undelegate(RuntimeOrigin::signed(1004)));
// 1004 is removed from delegators
assert!(!Delegators::<Test>::contains_key(&1004));
assert_eq!(Staking::active_delegator_count() as u64, 3);
assert_eq!(Staking::delegator_count() as u64, 3);
run_to_block(BLOCKS_PER_ERA + 2);
// 1001 is paid now
assert_eq!(
Balances::total_balance(&1001),
init_balance_1001 + 21369858941948251800
);
remainder = remainder - 21369858941948251800;
// 1003 is paid now
assert_eq!(
Balances::total_balance(&1003),
init_balance_1003 + 21369858941948251800
);
remainder = remainder - 21369858941948251800;
// 1004 balance does not increase this round as it's already paid
assert_eq!(
Balances::total_balance(&1004),
init_balance_1004 + 21369858941948251800
);
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
});
}
#[test]
fn less_than_needed_candidates_works() {
ExtBuilder::default()
.minimum_validator_count(1)
.validator_count(4)
.num_validators(3)
.build()
.execute_with(|| {
assert_eq!(Staking::validator_count(), 4);
assert_eq!(Staking::minimum_validator_count(), 1);
assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]);
mock::start_active_era(1);
// Previous set is selected. NO election algorithm is even executed.
assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]);
// But the exposure is updated in a simple way. No external votes exists.
// This is purely self-vote.
assert!(
ErasStakers::<Test>::iter_prefix_values(Staking::active_era().unwrap().index)
.all(|exposure| exposure.others.is_empty())
);
});
}
#[test]
fn no_candidate_emergency_condition() {
ExtBuilder::default()
.minimum_validator_count(1)
.validator_count(15)
.num_validators(4)
.validator_pool(true) // 11, 21, 31, 41
.build()
.execute_with(|| {
// initial validators
assert_eq_uvec!(validator_controllers(), vec![10, 20, 30, 40]);
let prefs = ValidatorPrefs {
commission: Perbill::one(),
..Default::default()
};
<Staking as crate::Store>::Validators::insert(11, prefs.clone());
// set the minimum validator count.
<Staking as crate::Store>::MinimumValidatorCount::put(10);
// try to chill
let _ = Staking::chill(RuntimeOrigin::signed(10));
// trigger era
mock::start_active_era(1);
// Previous ones are elected. chill is invalidates. TODO: #2494
assert_eq_uvec!(validator_controllers(), vec![10, 20, 30, 40]);
// Though the validator preferences has been removed.
assert!(Staking::validators(11) != prefs);
});
}
#[test]
fn delegators_also_get_slashed() {
ExtBuilder::default().build_and_execute(|| {
let slash_percent = Perbill::from_percent(5);
let initial_exposure = Staking::eras_stakers(active_era(), 11);
// 1001 is a delegator for 11
assert_eq!(initial_exposure.others.first().unwrap(), &1001);
let initial_credit = Credit::get_credit_score(&1001).unwrap_or(0);
assert_eq!(initial_credit, INITIAL_CREDIT + CREDIT_ATTENUATION_STEP);
// staked values;
let validator_stake = Staking::ledger(10).unwrap().active;
let validator_balance = balances(&11).0;
let exposed_stake = initial_exposure.total;
let exposed_validator = initial_exposure.own;
// 11 goes offline
on_offence_now(
&[OffenceDetails {
offender: (11, initial_exposure.clone()),
reporters: vec![],
}],
&[slash_percent],
);
// validator stake must have been decreased.
assert!(Staking::ledger(10).unwrap().active < validator_stake);
let slash_amount = slash_percent * exposed_stake;
let validator_share =
Perbill::from_rational(exposed_validator, exposed_stake) * slash_amount;
// slash amount need to be positive for the test to make sense.
assert!(validator_share > 0);
// validator stake must have been decreased pro-rata.
assert_eq!(
Staking::ledger(10).unwrap().active,
validator_stake - validator_share,
);
assert_eq!(
balances(&11).0, // free balance
validator_balance - validator_share,
);
// Because slashing happened.
assert!(is_disabled(10));
// delegator credit is slashed
let credit_after_slashing = Credit::get_credit_score(&1001).unwrap_or(0);
assert!(credit_after_slashing < initial_credit);
});
}
#[test]
fn double_controlling_should_fail() {
// should test (in the same order):
// * an account already bonded as controller CANNOT be reused as the controller of another account.
ExtBuilder::default().build_and_execute(|| {
let arbitrary_value = 5;
// 2 = controller, 1 stashed => ok
assert_ok!(Staking::bond(
RuntimeOrigin::signed(1),
2,
arbitrary_value,
RewardDestination::default(),
));
// 2 = controller, 3 stashed (Note that 2 is reused.) => no-op
assert_noop!(
Staking::bond(
RuntimeOrigin::signed(3),
2,
arbitrary_value,
RewardDestination::default()
),
Error::<Test>::AlreadyPaired,
);
});
}
#[test]
fn bond_lower_than_existential_should_fail() {
ExtBuilder::default().build_and_execute(|| {
assert_ok!(Staking::set_existential_deposit(RuntimeOrigin::root(), 100));
assert_noop!(
Staking::bond(RuntimeOrigin::signed(3), 2, 5, RewardDestination::default()),
Error::<Test>::InsufficientValue,
);
});
}
#[test]
fn session_and_eras_work_simple() {
ExtBuilder::default().period(1).build_and_execute(|| {
assert_eq!(active_era(), 0);
assert_eq!(current_era(), 0);
assert_eq!(Session::current_index(), 1);
assert_eq!(System::block_number(), 1);
// Session 1: this is basically a noop. This has already been started.
start_session(1);
assert_eq!(Session::current_index(), 1);
assert_eq!(active_era(), 0);
assert_eq!(System::block_number(), 1);
// Session 2: No change.
start_session(2);
assert_eq!(Session::current_index(), 2);
assert_eq!(active_era(), 0);
assert_eq!(System::block_number(), 2);
// Session 3: Era increment.
start_session(3);
assert_eq!(Session::current_index(), 3);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 3);
// Session 4: No change.
start_session(4);
assert_eq!(Session::current_index(), 4);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 4);
// Session 5: No change.
start_session(5);
assert_eq!(Session::current_index(), 5);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 5);
// Session 6: Era increment.
start_session(6);
assert_eq!(Session::current_index(), 6);
assert_eq!(active_era(), 2);
assert_eq!(System::block_number(), 6);
});
}
#[test]
fn session_and_eras_work_complex() {
ExtBuilder::default().period(5).build_and_execute(|| {
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 0);
assert_eq!(System::block_number(), 1);
start_session(1);
assert_eq!(Session::current_index(), 1);
assert_eq!(active_era(), 0);
assert_eq!(System::block_number(), 5);
start_session(2);
assert_eq!(Session::current_index(), 2);
assert_eq!(active_era(), 0);
assert_eq!(System::block_number(), 10);
start_session(3);
assert_eq!(Session::current_index(), 3);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 15);
start_session(4);
assert_eq!(Session::current_index(), 4);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 20);
start_session(5);
assert_eq!(Session::current_index(), 5);
assert_eq!(active_era(), 1);
assert_eq!(System::block_number(), 25);
start_session(6);
assert_eq!(Session::current_index(), 6);
assert_eq!(active_era(), 2);
assert_eq!(System::block_number(), 30);
});
}
#[test]
fn update_account_in_blacklist() {
ExtBuilder::default().build_and_execute(|| {
let era = current_era();
let account: u64 = 1000;
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
2,
Privilege::BlackListAdmin
));
assert_ok!(Staking::add_account_to_blacklist(
RuntimeOrigin::signed(2),
account,
era
));
assert_eq!(Staking::black_list(&account), Some(era));
assert_ok!(Staking::remove_account_from_blacklist(
RuntimeOrigin::signed(2),
account
));
assert_eq!(Staking::black_list(&account), None);
});
}
#[test]
fn no_rewards_in_blacklist() {
ExtBuilder::default()
.session_per_era(6)
.num_delegators(3)
.build_and_execute(|| {
let era = current_era();
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
2,
Privilege::BlackListAdmin
));
assert_ok!(Staking::add_account_to_blacklist(
RuntimeOrigin::signed(2),
1002,
era + 10
));
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1002), vec![11, 21]));
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1003), vec![11, 21]));
let init_balance_1002 = Balances::total_balance(&1002);
Payee::<Test>::insert(11, RewardDestination::Controller);
Payee::<Test>::insert(21, RewardDestination::Controller);
start_session(1);
start_session(2);
start_session(3);
start_session(4);
start_session(5);
start_session(6);
run_to_block(BLOCKS_PER_ERA + 1);
assert_eq!(Balances::total_balance(&1002), init_balance_1002);
});
}
#[test]
fn forcing_new_era_works() {
ExtBuilder::default().build_and_execute(|| {
// normal flow of session.
start_session(1);
assert_eq!(active_era(), 0);
start_session(2);
assert_eq!(active_era(), 0);
start_session(3);
assert_eq!(active_era(), 1);
// no era change.
ForceEra::<Test>::put(Forcing::ForceNone);
start_session(4);
assert_eq!(active_era(), 1);
start_session(5);
assert_eq!(active_era(), 1);
start_session(6);
assert_eq!(active_era(), 1);
start_session(7);
assert_eq!(active_era(), 1);
// back to normal.
// this immediately starts a new session.
ForceEra::<Test>::put(Forcing::NotForcing);
start_session(8);
assert_eq!(active_era(), 1);
start_session(9);
assert_eq!(active_era(), 2);
// forceful change
ForceEra::<Test>::put(Forcing::ForceAlways);
start_session(10);
assert_eq!(active_era(), 2);
start_session(11);
assert_eq!(active_era(), 3);
start_session(12);
assert_eq!(active_era(), 4);
// just one forceful change
ForceEra::<Test>::put(Forcing::ForceNew);
start_session(13);
assert_eq!(active_era(), 5);
assert_eq!(ForceEra::<Test>::get(), Forcing::NotForcing);
start_session(14);
assert_eq!(active_era(), 6);
start_session(15);
assert_eq!(active_era(), 6);
});
}
#[test]
fn cannot_transfer_staked_balance() {
// Tests that a stash account cannot transfer funds
ExtBuilder::default().build_and_execute(|| {
// Confirm account 11 is stashed
assert_eq!(Staking::bonded(&11), Some(10));
// Confirm account 11 has some free balance
assert_eq!(Balances::free_balance(11), 1000);
// Confirm account 11 (via controller 10) is totally staked
assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000);
// Confirm account 11 cannot transfer as a result
assert_noop!(
Balances::transfer(RuntimeOrigin::signed(11), 20, 1),
BalancesError::<Test, _>::LiquidityRestrictions
);
// Give account 11 extra free balance
let _ = Balances::make_free_balance_be(&11, 10000);
// Confirm that account 11 can now transfer some balance
assert_ok!(Balances::transfer(RuntimeOrigin::signed(11), 20, 1));
});
}
#[test]
fn cannot_transfer_staked_balance_2() {
// Tests that a stash account cannot transfer funds
// Same test as above but with 20, and more accurate.
// 21 has 2000 free balance but 1000 at stake
ExtBuilder::default().fair(true).build_and_execute(|| {
// Confirm account 21 is stashed
assert_eq!(Staking::bonded(&21), Some(20));
// Confirm account 21 has some free balance
assert_eq!(Balances::free_balance(21), 2000);
// Confirm account 21 (via controller 20) is totally staked
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 21).total,
1000
);
// Confirm account 21 can transfer at most 1000
assert_noop!(
Balances::transfer(RuntimeOrigin::signed(21), 20, 1001),
BalancesError::<Test, _>::LiquidityRestrictions
);
assert_ok!(Balances::transfer(RuntimeOrigin::signed(21), 20, 1000));
});
}
#[test]
fn cannot_reserve_staked_balance() {
// Checks that a bonded account cannot reserve balance from free balance
ExtBuilder::default().build_and_execute(|| {
// Confirm account 11 is stashed
assert_eq!(Staking::bonded(&11), Some(10));
// Confirm account 11 has some free balance
assert_eq!(Balances::free_balance(11), 1000);
// Confirm account 11 (via controller 10) is totally staked
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 11).own,
1000
);
// Confirm account 11 cannot reserve as a result
assert_noop!(
Balances::reserve(&11, 1),
BalancesError::<Test, _>::LiquidityRestrictions,
);
// Give account 11 extra free balance
let _ = Balances::make_free_balance_be(&11, 10000);
// Confirm account 11 can now reserve balance
assert_ok!(Balances::reserve(&11, 1));
});
}
#[test]
fn bond_extra_works() {
// Tests that extra `free_balance` in the stash can be added to stake
// NOTE: this tests only verifies `StakingLedger` for correct updates
// See `bond_extra_and_withdraw_unbonded_works` for more details and updates on `Exposure`.
ExtBuilder::default().build_and_execute(|| {
// Check that account 10 is a validator
assert!(<Validators<Test>>::contains_key(11));
// Check that account 10 is bonded to account 11
assert_eq!(Staking::bonded(&11), Some(10));
// Check how much is at stake
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![],
})
);
// Give account 11 some large free balance greater than total
let _ = Balances::make_free_balance_be(&11, 1000000);
// Call the bond_extra function from controller, add only 100
assert_ok!(Staking::bond_extra(RuntimeOrigin::signed(11), 100));
// There should be 100 more `total` and `active` in the ledger
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000 + 100,
active: 1000 + 100,
unlocking: vec![],
claimed_rewards: vec![],
})
);
// Call the bond_extra function with a large number, should handle it
assert_ok!(Staking::bond_extra(
RuntimeOrigin::signed(11),
Balance::max_value()
));
// The full amount of the funds should now be in the total and active
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000000,
active: 1000000,
unlocking: vec![],
claimed_rewards: vec![],
})
);
});
}
#[test]
fn bond_extra_and_withdraw_unbonded_works() {
// * Should test
// * Given an account being bonded [and chosen as a validator](not mandatory)
// * It can add extra funds to the bonded account.
// * it can unbond a portion of its funds from the stash account.
// * Once the unbonding period is done, it can actually take the funds out of the stash.
ExtBuilder::default().build_and_execute(|| {
// Set payee to controller. avoids confusion
assert_ok!(Staking::set_payee(
RuntimeOrigin::signed(10),
RewardDestination::Controller
));
// Give account 11 some large free balance greater than total
let _ = Balances::make_free_balance_be(&11, 1000000);
// Initial config should be correct
assert_eq!(Staking::active_era().unwrap().index, 0);
// check the balance of a validator accounts.
assert_eq!(Balances::total_balance(&10), 1);
// confirm that 10 is a normal validator and gets paid at the end of the era.
mock::start_active_era(1);
// Initial state of 10
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![],
})
);
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 21),
Exposure {
total: 1000,
own: 1000,
others: vec![1001]
}
);
// deposit the extra 100 units
Staking::bond_extra(RuntimeOrigin::signed(11), 100).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000 + 100,
active: 1000 + 100,
unlocking: vec![],
claimed_rewards: vec![],
})
);
assert_ne!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
Exposure {
total: 1000 + 100,
own: 1000 + 100,
others: vec![]
}
);
// trigger next era.
mock::start_active_era(2);
assert_eq!(Staking::active_era().unwrap().index, 2);
// ledger should be the same.
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000 + 100,
active: 1000 + 100,
unlocking: vec![],
claimed_rewards: vec![],
})
);
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
Exposure {
total: 1000 + 100,
own: 1000 + 100,
others: vec![1001]
}
);
// Unbond almost all of the funds in stash.
Staking::unbond(RuntimeOrigin::signed(10), 1000).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000 + 100,
active: 100,
unlocking: vec![UnlockChunk {
value: 1000,
era: 2 + 3
}],
claimed_rewards: vec![]
}),
);
// Attempting to free the balances now will fail. 2 eras need to pass.
assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0));
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000 + 100,
active: 100,
unlocking: vec![UnlockChunk {
value: 1000,
era: 2 + 3
}],
claimed_rewards: vec![]
}),
);
// trigger next era.
mock::start_active_era(3);
// nothing yet
assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0));
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000 + 100,
active: 100,
unlocking: vec![UnlockChunk {
value: 1000,
era: 2 + 3
}],
claimed_rewards: vec![]
}),
);
// trigger next era.
mock::start_active_era(5);
assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0));
// Now the value is free and the staking ledger is updated.
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 100,
active: 100,
unlocking: vec![],
claimed_rewards: vec![]
}),
);
})
}
#[test]
fn too_many_unbond_calls_should_not_work() {
ExtBuilder::default().build_and_execute(|| {
// locked at era 0 until 3
for _ in 0..MAX_UNLOCKING_CHUNKS - 1 {
assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1));
}
mock::start_active_era(1);
// locked at era 1 until 4
assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1));
// can't do more.
assert_noop!(
Staking::unbond(RuntimeOrigin::signed(10), 1),
Error::<Test>::NoMoreChunks
);
mock::start_active_era(3);
assert_noop!(
Staking::unbond(RuntimeOrigin::signed(10), 1),
Error::<Test>::NoMoreChunks
);
// free up.
assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(10), 0));
// Can add again.
assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 1));
assert_eq!(Staking::ledger(&10).unwrap().unlocking.len(), 2);
})
}
#[test]
fn rebond_works() {
// * Should test
// * Given an account being bonded [and chosen as a validator](not mandatory)
// * it can unbond a portion of its funds from the stash account.
// * it can re-bond a portion of the funds scheduled to unlock.
ExtBuilder::default().build().execute_with(|| {
// Set payee to controller. avoids confusion
assert_ok!(Staking::set_payee(
RuntimeOrigin::signed(10),
RewardDestination::Controller
));
// Give account 11 some large free balance greater than total
let _ = Balances::make_free_balance_be(&11, 1000000);
// confirm that 10 is a normal validator and gets paid at the end of the era.
mock::start_active_era(1);
// Initial state of 10
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![],
})
);
mock::start_active_era(2);
assert_eq!(Staking::active_era().unwrap().index, 2);
// Try to rebond some funds. We get an error since no fund is unbonded.
assert_noop!(
Staking::rebond(RuntimeOrigin::signed(10), 500),
Error::<Test>::NoUnlockChunk,
);
// Unbond almost all of the funds in stash.
Staking::unbond(RuntimeOrigin::signed(10), 900).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 100,
unlocking: vec![UnlockChunk {
value: 900,
era: 2 + 3,
}],
claimed_rewards: vec![],
})
);
// Re-bond all the funds unbonded.
Staking::rebond(RuntimeOrigin::signed(10), 900).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![],
})
);
// Unbond almost all of the funds in stash.
Staking::unbond(RuntimeOrigin::signed(10), 900).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 100,
unlocking: vec![UnlockChunk { value: 900, era: 5 }],
claimed_rewards: vec![],
})
);
// Re-bond part of the funds unbonded.
Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 600,
unlocking: vec![UnlockChunk { value: 400, era: 5 }],
claimed_rewards: vec![],
})
);
// Re-bond the remainder of the funds unbonded.
Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![],
})
);
// Unbond parts of the funds in stash.
Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap();
Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap();
Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 100,
unlocking: vec![
UnlockChunk { value: 300, era: 5 },
UnlockChunk { value: 300, era: 5 },
UnlockChunk { value: 300, era: 5 },
],
claimed_rewards: vec![],
})
);
// Re-bond part of the funds unbonded.
Staking::rebond(RuntimeOrigin::signed(10), 500).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 600,
unlocking: vec![
UnlockChunk { value: 300, era: 5 },
UnlockChunk { value: 100, era: 5 },
],
claimed_rewards: vec![],
})
);
})
}
#[test]
fn rebond_is_fifo() {
// Rebond should proceed by reversing the most recent bond operations.
ExtBuilder::default().build().execute_with(|| {
// Set payee to controller. avoids confusion
assert_ok!(Staking::set_payee(
RuntimeOrigin::signed(10),
RewardDestination::Controller
));
// Give account 11 some large free balance greater than total
let _ = Balances::make_free_balance_be(&11, 1000000);
// confirm that 10 is a normal validator and gets paid at the end of the era.
mock::start_active_era(1);
// Initial state of 10
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![],
})
);
mock::start_active_era(2);
// Unbond some of the funds in stash.
Staking::unbond(RuntimeOrigin::signed(10), 400).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 600,
unlocking: vec![UnlockChunk {
value: 400,
era: 2 + 3
},],
claimed_rewards: vec![],
})
);
mock::start_active_era(3);
// Unbond more of the funds in stash.
Staking::unbond(RuntimeOrigin::signed(10), 300).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 300,
unlocking: vec![
UnlockChunk {
value: 400,
era: 2 + 3
},
UnlockChunk {
value: 300,
era: 3 + 3
},
],
claimed_rewards: vec![],
})
);
mock::start_active_era(4);
// Unbond yet more of the funds in stash.
Staking::unbond(RuntimeOrigin::signed(10), 200).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 100,
unlocking: vec![
UnlockChunk {
value: 400,
era: 2 + 3
},
UnlockChunk {
value: 300,
era: 3 + 3
},
UnlockChunk {
value: 200,
era: 4 + 3
},
],
claimed_rewards: vec![],
})
);
// Re-bond half of the unbonding funds.
Staking::rebond(RuntimeOrigin::signed(10), 400).unwrap();
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 500,
unlocking: vec![
UnlockChunk {
value: 400,
era: 2 + 3
},
UnlockChunk {
value: 100,
era: 3 + 3
},
],
claimed_rewards: vec![],
})
);
})
}
#[test]
fn on_free_balance_zero_stash_removes_validator() {
// Tests that validator storage items are cleaned up when stash is empty
// Tests that storage items are untouched when controller is empty
ExtBuilder::default()
.existential_deposit(10)
.build_and_execute(|| {
// Check the balance of the validator account
assert_eq!(Balances::free_balance(10), 256);
// Check the balance of the stash account
assert_eq!(Balances::free_balance(11), 256000);
// Check these two accounts are bonded
assert_eq!(Staking::bonded(&11), Some(10));
// Set some storage items which we expect to be cleaned up
// Set payee information
assert_ok!(Staking::set_payee(
RuntimeOrigin::signed(10),
RewardDestination::Stash
));
// Check storage items that should be cleaned up
assert!(<Ledger<Test>>::contains_key(&10));
assert!(<Bonded<Test>>::contains_key(&11));
assert!(<Validators<Test>>::contains_key(&11));
assert!(<Payee<Test>>::contains_key(&11));
// Reduce free_balance of controller to 0
let _ = Balances::slash(&10, Balance::max_value());
// Check the balance of the stash account has not been touched
assert_eq!(Balances::free_balance(11), 256000);
// Check these two accounts are still bonded
assert_eq!(Staking::bonded(&11), Some(10));
// Check storage items have not changed
assert!(<Ledger<Test>>::contains_key(&10));
assert!(<Bonded<Test>>::contains_key(&11));
assert!(<Validators<Test>>::contains_key(&11));
assert!(<Payee<Test>>::contains_key(&11));
// Reduce free_balance of stash to 0
let _ = Balances::slash(&11, Balance::max_value());
// Check total balance of stash
assert_eq!(Balances::total_balance(&11), 10);
// Reap the stash
assert_ok!(Staking::reap_stash(RuntimeOrigin::none(), 11, 0));
// Check storage items do not exist
assert!(!<Ledger<Test>>::contains_key(&10));
assert!(!<Bonded<Test>>::contains_key(&11));
assert!(!<Validators<Test>>::contains_key(&11));
assert!(!<Payee<Test>>::contains_key(&11));
});
}
#[test]
fn on_low_credit_score_removes_delegator() {
// Tests that delegator storage items are not cleaned up if credit is not too low
// Tests that delegator storage items are cleaned up if credit is too low
ExtBuilder::default().build_and_execute(|| {
// The setup is delegator 1001 delegates credit to validator 11 and 21
let initial_exposure = Staking::eras_stakers(active_era(), 11);
// 11 goes offline
on_offence_now(
&[OffenceDetails {
offender: (11, initial_exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(5)],
);
// delegator credit is slashed
let mut credit_after_slashing = Credit::get_credit_score(&1001).unwrap_or(0);
assert!(credit_after_slashing >= 100);
assert!(<Delegators<Test>>::contains_key(&1001));
assert!(Staking::candidate_validators(&11)
.delegators
.contains(&1001));
assert!(Staking::candidate_validators(&21)
.delegators
.contains(&1001));
// 21 goes offline
on_offence_now(
&[OffenceDetails {
offender: (21, initial_exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(5)],
);
credit_after_slashing = Credit::get_credit_score(&1001).unwrap_or(0);
assert!(credit_after_slashing < 100);
// it's removed since there is no pending reward
assert!(!<Delegators<Test>>::contains_key(&1001));
assert!(!Staking::candidate_validators(&11)
.delegators
.contains(&1001));
assert!(!Staking::candidate_validators(&21)
.delegators
.contains(&1001));
});
}
#[test]
fn election_works() {
ExtBuilder::default()
.validator_pool(true) // 11, 21, 31, 41
.num_delegators(4) // 1001, 1002, 1003, 1004
.build_and_execute(|| {
// 1001 delegate 11 and 21 in default setup
assert_eq_uvec!(validator_controllers(), vec![10, 20]);
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1002), vec![31, 41]));
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1003), vec![31, 41]));
// new block
mock::start_active_era(1);
assert_eq_uvec!(validator_controllers(), vec![30, 40]);
});
}
#[test]
fn bond_with_no_staked_value() {
// Behavior when someone bonds with no staked value.
// Particularly when she votes and the candidate is elected.
ExtBuilder::default()
.validator_count(3)
.existential_deposit(5)
.minimum_validator_count(1)
.build()
.execute_with(|| {
// Can't bond with 1
assert_noop!(
Staking::bond(
RuntimeOrigin::signed(1),
2,
1,
RewardDestination::Controller
),
Error::<Test>::InsufficientValue,
);
// bonded with absolute minimum value possible.
assert_ok!(Staking::bond(
RuntimeOrigin::signed(1),
2,
5,
RewardDestination::Controller
));
assert_eq!(Balances::locks(&1)[0].amount, 5);
// unbonding even 1 will cause all to be unbonded.
assert_ok!(Staking::unbond(RuntimeOrigin::signed(2), 1));
assert_eq!(
Staking::ledger(2),
Some(StakingLedger {
stash: 1,
active: 0,
total: 5,
unlocking: vec![UnlockChunk { value: 5, era: 3 }],
claimed_rewards: vec![],
})
);
mock::start_active_era(1);
mock::start_active_era(2);
// not yet removed.
assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(2), 0));
assert!(Staking::ledger(2).is_some());
assert_eq!(Balances::locks(&1)[0].amount, 5);
mock::start_active_era(3);
// poof. Account 1 is removed from the staking system.
assert_ok!(Staking::withdraw_unbonded(RuntimeOrigin::signed(2), 0));
assert!(Staking::ledger(2).is_none());
assert_eq!(Balances::locks(&1).len(), 0);
});
}
#[test]
fn new_era_elects_correct_number_of_validators() {
ExtBuilder::default()
.validator_pool(true)
.fair(true)
.validator_count(1)
.build()
.execute_with(|| {
assert_eq!(Staking::validator_count(), 1);
assert_eq!(validator_controllers().len(), 1);
Session::on_initialize(System::block_number());
assert_eq!(validator_controllers().len(), 1);
})
}
#[test]
fn reward_from_authorship_event_handler_works() {
ExtBuilder::default().build_and_execute(|| {
use pallet_authorship::EventHandler;
assert_eq!(<pallet_authorship::Pallet<Test>>::author(), Some(11));
<Pallet<Test>>::note_author(11);
<Pallet<Test>>::note_uncle(21, 1);
// Rewarding the same two times works.
<Pallet<Test>>::note_uncle(11, 1);
// Not mandatory but must be coherent with rewards
assert_eq_uvec!(Session::validators(), vec![11, 21]);
// 21 is rewarded as an uncle producer
// 11 is rewarded as a block producer and uncle referencer and uncle producer
assert_eq!(
ErasRewardPoints::<Test>::get(Staking::active_era().unwrap().index),
EraRewardPoints {
individual: vec![(11, 20 + 2 * 2 + 1), (21, 1)].into_iter().collect(),
total: 26,
},
);
})
}
#[test]
fn add_reward_points_fns_works() {
ExtBuilder::default().build_and_execute(|| {
// Not mandatory but must be coherent with rewards
assert_eq_uvec!(Session::validators(), vec![21, 11]);
<Pallet<Test>>::reward_by_ids(vec![(21, 1), (11, 1), (11, 1)]);
<Pallet<Test>>::reward_by_ids(vec![(21, 1), (11, 1), (11, 1)]);
assert_eq!(
ErasRewardPoints::<Test>::get(Staking::active_era().unwrap().index),
EraRewardPoints {
individual: vec![(11, 4), (21, 2)].into_iter().collect(),
total: 6,
},
);
})
}
#[test]
fn unbonded_balance_is_not_slashable() {
ExtBuilder::default().build_and_execute(|| {
// total amount staked is slashable.
assert_eq!(Staking::slashable_balance_of(&11), 1000);
assert_ok!(Staking::unbond(RuntimeOrigin::signed(10), 800));
// only the active portion.
assert_eq!(Staking::slashable_balance_of(&11), 200);
})
}
#[test]
fn era_is_always_same_length() {
// This ensures that the sessions is always of the same length if there is no forcing no
// session changes.
ExtBuilder::default().build_and_execute(|| {
let session_per_era = <SessionsPerEra as Get<SessionIndex>>::get();
mock::start_active_era(1);
assert_eq!(
Staking::eras_start_session_index(current_era()).unwrap(),
session_per_era
);
mock::start_active_era(2);
assert_eq!(
Staking::eras_start_session_index(current_era()).unwrap(),
session_per_era * 2u32
);
let session = Session::current_index();
ForceEra::<Test>::put(Forcing::ForceNew);
advance_session();
advance_session();
assert_eq!(current_era(), 3);
assert_eq!(
Staking::eras_start_session_index(current_era()).unwrap(),
session + 2
);
mock::start_active_era(4);
assert_eq!(
Staking::eras_start_session_index(current_era()).unwrap(),
session + 2u32 + session_per_era
);
});
}
#[test]
fn offence_forces_new_era() {
ExtBuilder::default().build_and_execute(|| {
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(5)],
);
assert_eq!(Staking::force_era(), Forcing::ForceNew);
});
}
#[test]
fn offence_ensures_new_era_without_clobbering() {
ExtBuilder::default().build_and_execute(|| {
assert_ok!(Staking::force_new_era_always(RuntimeOrigin::root()));
assert_eq!(Staking::force_era(), Forcing::ForceAlways);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(5)],
);
assert_eq!(Staking::force_era(), Forcing::ForceAlways);
});
}
#[test]
fn offence_deselects_validator_even_when_slash_is_zero() {
ExtBuilder::default().build_and_execute(|| {
assert!(Session::validators().contains(&11));
assert!(<Validators<Test>>::contains_key(11));
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(0)],
);
assert_eq!(Staking::force_era(), Forcing::ForceNew);
assert!(!<Validators<Test>>::contains_key(11));
mock::start_active_era(1);
assert!(!Session::validators().contains(&11));
assert!(!<Validators<Test>>::contains_key(11));
});
}
#[test]
fn slashing_performed_according_exposure() {
// This test checks that slashing is performed according the exposure (or more precisely,
// historical exposure), not the current balance.
ExtBuilder::default().build_and_execute(|| {
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 11).own,
1000
);
// Handle an offence with a historical exposure.
on_offence_now(
&[OffenceDetails {
offender: (
11,
Exposure {
total: 500,
own: 500,
others: vec![],
},
),
reporters: vec![],
}],
&[Perbill::from_percent(50)],
);
// The stash account should be slashed for 250 (50% of 500).
assert_eq!(Balances::free_balance(11), 1000 - 250);
});
}
#[test]
fn slash_in_old_span_does_not_deselect() {
ExtBuilder::default().build_and_execute(|| {
mock::start_active_era(1);
assert!(<Validators<Test>>::contains_key(21));
assert!(Session::validators().contains(&21));
on_offence_now(
&[OffenceDetails {
offender: (
21,
Staking::eras_stakers(Staking::active_era().unwrap().index, 21),
),
reporters: vec![],
}],
&[Perbill::from_percent(0)],
);
assert_eq!(Staking::force_era(), Forcing::ForceNew);
assert!(!<Validators<Test>>::contains_key(21));
mock::start_active_era(2);
Staking::validate(RuntimeOrigin::signed(20), Default::default()).unwrap();
Staking::delegate(RuntimeOrigin::signed(1001), vec![11]).unwrap();
assert_eq!(Staking::force_era(), Forcing::NotForcing);
assert!(<Validators<Test>>::contains_key(21));
assert!(!Session::validators().contains(&21));
mock::start_active_era(3);
// this staker is in a new slashing span now, having re-registered after
// their prior slash.
on_offence_in_era(
&[OffenceDetails {
offender: (
21,
Staking::eras_stakers(Staking::active_era().unwrap().index, 21),
),
reporters: vec![],
}],
&[Perbill::from_percent(0)],
1,
DisableStrategy::WhenSlashed,
);
// not forcing for zero-slash and previous span.
assert_eq!(Staking::force_era(), Forcing::NotForcing);
assert!(<Validators<Test>>::contains_key(21));
assert!(Session::validators().contains(&21));
on_offence_in_era(
&[OffenceDetails {
offender: (
21,
Staking::eras_stakers(Staking::active_era().unwrap().index, 21),
),
reporters: vec![],
}],
// NOTE: A 100% slash here would clean up the account, causing de-registration.
&[Perbill::from_percent(95)],
1,
DisableStrategy::WhenSlashed,
);
// or non-zero.
assert_eq!(Staking::force_era(), Forcing::NotForcing);
assert!(<Validators<Test>>::contains_key(21));
assert!(Session::validators().contains(&21));
});
}
#[test]
fn reporters_receive_their_slice() {
// This test verifies that the reporters of the offence receive their slice from the slashed
// amount.
ExtBuilder::default().build_and_execute(|| {
// The reporters' reward is calculated from the total exposure.
let initial_balance = 1000;
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total,
initial_balance
);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![1, 2],
}],
&[Perbill::from_percent(50)],
);
// F1 * (reward_proportion * slash - 0)
// 50% * (10% * initial_balance / 2)
let reward = (initial_balance / 20) / 2;
let reward_each = reward / 2; // split into two pieces.
assert_eq!(Balances::free_balance(1), 10 + reward_each);
assert_eq!(Balances::free_balance(2), 20 + reward_each);
});
}
#[test]
fn subsequent_reports_in_same_span_pay_out_less() {
// This test verifies that the reporters of the offence receive their slice from the slashed
// amount, but less and less if they submit multiple reports in one span.
ExtBuilder::default().build_and_execute(|| {
// The reporters' reward is calculated from the total exposure.
let initial_balance = 1000;
assert_eq!(
Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total,
initial_balance
);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![1],
}],
&[Perbill::from_percent(20)],
);
// F1 * (reward_proportion * slash - 0)
// 50% * (10% * initial_balance * 20%)
let reward = (initial_balance / 5) / 20;
assert_eq!(Balances::free_balance(1), 10 + reward);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![1],
}],
&[Perbill::from_percent(50)],
);
let prior_payout = reward;
// F1 * (reward_proportion * slash - prior_payout)
// 50% * (10% * (initial_balance / 2) - prior_payout)
let reward = ((initial_balance / 20) - prior_payout) / 2;
assert_eq!(Balances::free_balance(1), 10 + prior_payout + reward);
});
}
#[test]
fn invulnerables_are_not_slashed() {
// For invulnerable validators no slashing is performed.
ExtBuilder::default()
.invulnerables(vec![11])
.build_and_execute(|| {
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(21), 2000);
let _exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 21);
let initial_balance = Staking::slashable_balance_of(&21);
on_offence_now(
&[
OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
},
OffenceDetails {
offender: (
21,
Staking::eras_stakers(Staking::active_era().unwrap().index, 21),
),
reporters: vec![],
},
],
&[Perbill::from_percent(50), Perbill::from_percent(20)],
);
// The validator 11 hasn't been slashed, but 21 has been.
assert_eq!(Balances::free_balance(11), 1000);
// 2000 - (0.2 * initial_balance)
assert_eq!(
Balances::free_balance(21),
2000 - (2 * initial_balance / 10)
);
});
}
#[test]
fn dont_slash_if_fraction_is_zero() {
// Don't slash if the fraction is zero.
ExtBuilder::default().build_and_execute(|| {
assert_eq!(Balances::free_balance(11), 1000);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(0)],
);
// The validator hasn't been slashed. The new era is not forced.
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Staking::force_era(), Forcing::ForceNew);
});
}
#[test]
fn only_slash_for_max_in_era() {
// multiple slashes within one era are only applied if it is more than any previous slash in the
// same era.
ExtBuilder::default().build_and_execute(|| {
assert_eq!(Balances::free_balance(11), 1000);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(50)],
);
// The validator has been slashed and has been force-chilled.
assert_eq!(Balances::free_balance(11), 500);
assert_eq!(Staking::force_era(), Forcing::ForceNew);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(25)],
);
// The validator has not been slashed additionally.
assert_eq!(Balances::free_balance(11), 500);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(60)],
);
// The validator got slashed 10% more.
assert_eq!(Balances::free_balance(11), 400);
})
}
#[test]
fn garbage_collection_after_slashing() {
// ensures that `SlashingSpans` and `SpanSlash` of an account is removed after reaping.
ExtBuilder::default()
.existential_deposit(2)
.build_and_execute(|| {
assert_eq!(Balances::free_balance(11), 256_000);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
assert_eq!(Balances::free_balance(11), 256_000 - 25_600);
assert!(<Staking as crate::Store>::SlashingSpans::get(&11).is_some());
assert_eq!(
<Staking as crate::Store>::SpanSlash::get(&(11, 0)).amount_slashed(),
&25_600
);
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(100)],
);
// validator and nominator slash in era are garbage-collected by era change,
// so we don't test those here.
assert_eq!(Balances::free_balance(11), 2);
assert_eq!(Balances::total_balance(&11), 2);
let slashing_spans = <Staking as crate::Store>::SlashingSpans::get(&11).unwrap();
assert_eq!(slashing_spans.iter().count(), 2);
// reap_stash respects num_slashing_spans so that weight is accurate
assert_noop!(
Staking::reap_stash(RuntimeOrigin::none(), 11, 0),
Error::<Test>::IncorrectSlashingSpans
);
assert_ok!(Staking::reap_stash(RuntimeOrigin::none(), 11, 2));
assert!(<Staking as crate::Store>::SlashingSpans::get(&11).is_none());
assert_eq!(
<Staking as crate::Store>::SpanSlash::get(&(11, 0)).amount_slashed(),
&0
);
})
}
#[test]
fn garbage_collection_on_window_pruning() {
// ensures that `ValidatorSlashInEra` are cleared after `BondingDuration`.
ExtBuilder::default().build_and_execute(|| {
assert_eq!(Balances::free_balance(11), 1000);
let now = Staking::active_era().unwrap().index;
assert_eq!(Balances::free_balance(101), 2000);
on_offence_now(
&[OffenceDetails {
offender: (11, Staking::eras_stakers(now, 11)),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
assert_eq!(Balances::free_balance(11), 900);
assert!(<Staking as crate::Store>::ValidatorSlashInEra::get(&now, &11).is_some());
// + 1 because we have to exit the bonding window.
for era in (0..(BondingDuration::get() + 1)).map(|offset| offset + now + 1) {
assert!(<Staking as crate::Store>::ValidatorSlashInEra::get(&now, &11).is_some());
mock::start_active_era(era);
}
assert!(<Staking as crate::Store>::ValidatorSlashInEra::get(&now, &11).is_none());
})
}
#[test]
fn slashes_are_summed_across_spans() {
ExtBuilder::default().build_and_execute(|| {
mock::start_active_era(1);
mock::start_active_era(2);
mock::start_active_era(3);
assert_eq!(Balances::free_balance(21), 2000);
assert_eq!(Staking::slashable_balance_of(&21), 1000);
let get_span = |account| <Staking as crate::Store>::SlashingSpans::get(&account).unwrap();
on_offence_now(
&[OffenceDetails {
offender: (
21,
Staking::eras_stakers(Staking::active_era().unwrap().index, 21),
),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
let expected_spans = vec![
slashing::SlashingSpan {
index: 1,
start: 4,
length: None,
},
slashing::SlashingSpan {
index: 0,
start: 0,
length: Some(4),
},
];
assert_eq!(get_span(21).iter().collect::<Vec<_>>(), expected_spans);
assert_eq!(Balances::free_balance(21), 1900);
// 21 has been force-chilled. re-signal intent to validate.
Staking::validate(RuntimeOrigin::signed(20), Default::default()).unwrap();
mock::start_active_era(4);
assert_eq!(Staking::slashable_balance_of(&21), 900);
on_offence_now(
&[OffenceDetails {
offender: (
21,
Staking::eras_stakers(Staking::active_era().unwrap().index, 21),
),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
let expected_spans = vec![
slashing::SlashingSpan {
index: 2,
start: 5,
length: None,
},
slashing::SlashingSpan {
index: 1,
start: 4,
length: Some(1),
},
slashing::SlashingSpan {
index: 0,
start: 0,
length: Some(4),
},
];
assert_eq!(get_span(21).iter().collect::<Vec<_>>(), expected_spans);
assert_eq!(Balances::free_balance(21), 1810);
});
}
#[test]
fn deferred_slashes_are_deferred() {
ExtBuilder::default()
.slash_defer_duration(2)
.build_and_execute(|| {
on_offence_now(
&[OffenceDetails {
offender: (
11,
Staking::eras_stakers(Staking::active_era().unwrap().index, 11),
),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
mock::start_active_era(1);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
mock::start_active_era(2);
assert_eq!(Balances::free_balance(11), 1000);
assert_eq!(Balances::free_balance(101), 2000);
mock::start_active_era(3);
// at the start of era 4, slashes from era 1 are processed,
// after being deferred for at least 2 full eras.
assert_eq!(Balances::free_balance(11), 900);
assert_eq!(Balances::free_balance(101), 2000);
})
}
#[test]
fn remove_deferred() {
ExtBuilder::default()
.slash_defer_duration(2)
.build_and_execute(|| {
mock::start_active_era(1);
assert_eq!(Balances::free_balance(21), 2000);
let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 21);
assert_eq!(Balances::free_balance(101), 2000);
on_offence_now(
&[OffenceDetails {
offender: (21, exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
assert_eq!(Balances::free_balance(21), 2000);
assert_eq!(Balances::free_balance(101), 2000);
mock::start_active_era(2);
on_offence_in_era(
&[OffenceDetails {
offender: (21, exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(15)],
1,
DisableStrategy::WhenSlashed,
);
// fails if empty
assert_noop!(
Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![]),
Error::<Test>::EmptyTargets
);
assert_ok!(Staking::cancel_deferred_slash(
RuntimeOrigin::root(),
1,
vec![0]
));
assert_eq!(Balances::free_balance(21), 2000);
assert_eq!(Balances::free_balance(101), 2000);
mock::start_active_era(3);
assert_eq!(Balances::free_balance(21), 2000);
assert_eq!(Balances::free_balance(101), 2000);
// at the start of era 4, slashes from era 1 are processed,
// after being deferred for at least 2 full eras.
mock::start_active_era(4);
// the first slash for 10% was cancelled, so no effect.
assert_eq!(Balances::free_balance(21), 2000);
assert_eq!(Balances::free_balance(101), 2000);
mock::start_active_era(5);
// 5% slash (15% - 10%) of the active bond 1000 processed now.
assert_eq!(Balances::free_balance(21), 1950);
})
}
#[test]
fn remove_multi_deferred() {
ExtBuilder::default()
.slash_defer_duration(2)
.build_and_execute(|| {
mock::start_active_era(1);
assert_eq!(Balances::free_balance(11), 1000);
let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 21);
assert_eq!(Balances::free_balance(101), 2000);
on_offence_now(
&[OffenceDetails {
offender: (21, exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
on_offence_now(
&[OffenceDetails {
offender: (31, exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(10)],
);
on_offence_now(
&[OffenceDetails {
offender: (21, exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(25)],
);
on_offence_now(
&[OffenceDetails {
offender: (42, exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(25)],
);
on_offence_now(
&[OffenceDetails {
offender: (69, exposure.clone()),
reporters: vec![],
}],
&[Perbill::from_percent(25)],
);
assert_eq!(<Staking as Store>::UnappliedSlashes::get(&1).len(), 5);
// fails if list is not sorted
assert_noop!(
Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![2, 0, 4]),
Error::<Test>::NotSortedAndUnique
);
// fails if list is not unique
assert_noop!(
Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![0, 2, 2]),
Error::<Test>::NotSortedAndUnique
);
// fails if bad index
assert_noop!(
Staking::cancel_deferred_slash(RuntimeOrigin::root(), 1, vec![1, 2, 3, 4, 5]),
Error::<Test>::InvalidSlashIndex
);
assert_ok!(Staking::cancel_deferred_slash(
RuntimeOrigin::root(),
1,
vec![0, 2, 4]
));
let slashes = <Staking as Store>::UnappliedSlashes::get(&1);
assert_eq!(slashes.len(), 2);
assert_eq!(slashes[0].validator, 31);
assert_eq!(slashes[1].validator, 42);
})
}
#[test]
fn six_session_delay() {
ExtBuilder::default()
.initialize_first_session(false)
.build_and_execute(|| {
use pallet_session::SessionManager;
let val_set = Session::validators();
let init_session = Session::current_index();
let init_active_era = Staking::active_era().unwrap().index;
// pallet-session is delaying session by one, thus the next session to plan is +2.
assert_eq!(
<Staking as SessionManager<_>>::new_session(init_session + 2),
None
);
assert_ne!(
<Staking as SessionManager<_>>::new_session(init_session + 3),
Some(val_set.clone())
);
assert_eq!(
<Staking as SessionManager<_>>::new_session(init_session + 4),
None
);
assert_eq!(
<Staking as SessionManager<_>>::new_session(init_session + 5),
None
);
assert_ne!(
<Staking as SessionManager<_>>::new_session(init_session + 6),
Some(val_set.clone())
);
<Staking as SessionManager<_>>::end_session(init_session);
<Staking as SessionManager<_>>::start_session(init_session + 1);
assert_eq!(active_era(), init_active_era);
<Staking as SessionManager<_>>::end_session(init_session + 1);
<Staking as SessionManager<_>>::start_session(init_session + 2);
assert_eq!(active_era(), init_active_era);
// Reward current era
Staking::reward_by_ids(vec![(11, 1)]);
// New active era is triggered here.
<Staking as SessionManager<_>>::end_session(init_session + 2);
<Staking as SessionManager<_>>::start_session(init_session + 3);
assert_eq!(active_era(), init_active_era + 1);
<Staking as SessionManager<_>>::end_session(init_session + 3);
<Staking as SessionManager<_>>::start_session(init_session + 4);
assert_eq!(active_era(), init_active_era + 1);
<Staking as SessionManager<_>>::end_session(init_session + 4);
<Staking as SessionManager<_>>::start_session(init_session + 5);
assert_eq!(active_era(), init_active_era + 1);
// Reward current era
Staking::reward_by_ids(vec![(21, 2)]);
// New active era is triggered here.
<Staking as SessionManager<_>>::end_session(init_session + 5);
<Staking as SessionManager<_>>::start_session(init_session + 6);
assert_eq!(active_era(), init_active_era + 2);
// That reward are correct
assert_eq!(Staking::eras_reward_points(init_active_era).total, 1);
assert_eq!(Staking::eras_reward_points(init_active_era + 1).total, 2);
});
}
#[test]
fn bond_during_era_correctly_populates_claimed_rewards() {
ExtBuilder::default()
.has_stakers(false)
.build_and_execute(|| {
// Era = None
bond_validator(21, 20, 1000);
assert_eq!(
Staking::ledger(&20),
Some(StakingLedger {
stash: 21,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![],
})
);
mock::start_active_era(5);
bond_validator(11, 10, 1000);
assert_eq!(
Staking::ledger(&10),
Some(StakingLedger {
stash: 11,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: (0..5).collect(),
})
);
mock::start_active_era(99);
bond_validator(31, 30, 1000);
assert_eq!(
Staking::ledger(&30),
Some(StakingLedger {
stash: 31,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: (15..99).collect(),
})
);
});
}
#[test]
fn on_initialize_weight_is_correct() {
ExtBuilder::default()
.has_stakers(false)
.build_and_execute(|| {
assert_eq!(Validators::<Test>::iter().count(), 0);
// When this pallet has nothing, we do 2 reads and 1 write
let base_weight = <Test as frame_system::Config>::DbWeight::get().reads_writes(2, 1);
assert_eq!(base_weight, Staking::on_initialize(0));
});
}
#[test]
fn session_buffering_with_offset() {
// similar to live-chains, have some offset for the first session
ExtBuilder::default()
.offset(2)
.period(5)
.session_per_era(5)
.build_and_execute(|| {
assert_eq!(current_era(), 0);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 0);
start_session(1);
assert_eq!(current_era(), 0);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 1);
assert_eq!(System::block_number(), 2);
start_session(2);
assert_eq!(current_era(), 0);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 2);
assert_eq!(System::block_number(), 7);
start_session(3);
assert_eq!(current_era(), 0);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 3);
assert_eq!(System::block_number(), 12);
// active era is lagging behind by one session, because of how session module works.
start_session(4);
assert_eq!(current_era(), 1);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 4);
assert_eq!(System::block_number(), 17);
start_session(5);
assert_eq!(current_era(), 1);
assert_eq!(active_era(), 1);
assert_eq!(Session::current_index(), 5);
assert_eq!(System::block_number(), 22);
// go all the way to active 2.
start_active_era(2);
assert_eq!(current_era(), 2);
assert_eq!(active_era(), 2);
assert_eq!(Session::current_index(), 10);
});
}
#[test]
fn session_buffering_no_offset() {
// no offset, first session starts immediately
ExtBuilder::default()
.offset(0)
.period(5)
.session_per_era(5)
.build_and_execute(|| {
assert_eq!(current_era(), 0);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 0);
start_session(1);
assert_eq!(current_era(), 0);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 1);
assert_eq!(System::block_number(), 5);
start_session(2);
assert_eq!(current_era(), 0);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 2);
assert_eq!(System::block_number(), 10);
start_session(3);
assert_eq!(current_era(), 0);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 3);
assert_eq!(System::block_number(), 15);
// active era is lagging behind by one session, because of how session module works.
start_session(4);
assert_eq!(current_era(), 1);
assert_eq!(active_era(), 0);
assert_eq!(Session::current_index(), 4);
assert_eq!(System::block_number(), 20);
start_session(5);
assert_eq!(current_era(), 1);
assert_eq!(active_era(), 1);
assert_eq!(Session::current_index(), 5);
assert_eq!(System::block_number(), 25);
// go all the way to active 2.
start_active_era(2);
assert_eq!(current_era(), 2);
assert_eq!(active_era(), 2);
assert_eq!(Session::current_index(), 10);
});
}
#[test]
fn cannot_rebond_to_lower_than_ed() {
ExtBuilder::default()
.existential_deposit(10)
.build_and_execute(|| {
// stash must have more balance than bonded for this to work.
assert_eq!(Balances::free_balance(&21), 512_000);
// initial stuff.
assert_eq!(
Staking::ledger(&20).unwrap(),
StakingLedger {
stash: 21,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![]
}
);
// unbond all of it.
assert_ok!(Staking::unbond(RuntimeOrigin::signed(20), 1000));
assert_eq!(
Staking::ledger(&20).unwrap(),
StakingLedger {
stash: 21,
total: 1000,
active: 0,
unlocking: vec![UnlockChunk {
value: 1000,
era: 3
}],
claimed_rewards: vec![]
}
);
// now bond a wee bit more
assert_noop!(
Staking::rebond(RuntimeOrigin::signed(20), 5),
Error::<Test>::InsufficientValue,
);
})
}
#[test]
fn cannot_bond_extra_to_lower_than_ed() {
ExtBuilder::default()
.existential_deposit(10)
.build_and_execute(|| {
// stash must have more balance than bonded for this to work.
assert_eq!(Balances::free_balance(&21), 512_000);
// initial stuff.
assert_eq!(
Staking::ledger(&20).unwrap(),
StakingLedger {
stash: 21,
total: 1000,
active: 1000,
unlocking: vec![],
claimed_rewards: vec![]
}
);
// unbond all of it.
assert_ok!(Staking::unbond(RuntimeOrigin::signed(20), 1000));
assert_eq!(
Staking::ledger(&20).unwrap(),
StakingLedger {
stash: 21,
total: 1000,
active: 0,
unlocking: vec![UnlockChunk {
value: 1000,
era: 3
}],
claimed_rewards: vec![]
}
);
// now bond a wee bit more
assert_noop!(
Staking::bond_extra(RuntimeOrigin::signed(21), 5),
Error::<Test>::InsufficientValue,
);
})
}
#[test]
fn delegate() {
ExtBuilder::default()
.existential_deposit(10)
.validator_pool(true) // 11, 21, 31, 41
.num_delegators(10) // 1001, 1002, ..., 1010
.build_and_execute(|| {
// TEST0: delegate with low score
assert_noop!(
Staking::delegate(RuntimeOrigin::signed(1000), vec![4, 6]),
Error::<Test>::NotValidator
);
// 1001 is the only delegator
assert_eq!(Staking::delegator_count(), 1);
assert_eq!(Staking::active_delegator_count(), 1);
// TEST1: delegate to one validator
// delegate credit score
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1001), vec![11]));
// delegator count does not change since 1001 is the existing one
assert_eq!(Staking::delegator_count(), 1);
assert_eq!(Staking::active_delegator_count(), 1);
// check delegated info
let delegator_data = Staking::delegators(1001);
assert_eq!(delegator_data.delegated_validators, vec![11]);
assert_eq!(Staking::candidate_validators(11).delegators.len(), 1);
assert!(Staking::candidate_validators(11).delegators.contains(&1001));
// TEST2: delegate to many validators
// delegate credit score
assert_ok!(Staking::delegate(
RuntimeOrigin::signed(1002),
vec![11, 21, 31, 41]
));
// 1001 and 1002 are both delegators now
assert_eq!(Staking::delegator_count(), 2);
assert_eq!(Staking::active_delegator_count(), 2);
// check delegator data
let delegator_data = Staking::delegators(1002);
assert_eq!(delegator_data.delegated_validators, vec![11, 21, 31, 41]);
assert_eq!(Staking::candidate_validators(11).delegators.len(), 2);
assert!(Staking::candidate_validators(11).delegators.contains(&1002));
assert_eq!(Staking::candidate_validators(21).delegators.len(), 1);
assert!(Staking::candidate_validators(21).delegators.contains(&1002));
assert_eq!(Staking::candidate_validators(31).delegators.len(), 1);
assert!(Staking::candidate_validators(31).delegators.contains(&1002));
assert_eq!(Staking::candidate_validators(41).delegators.len(), 1);
assert!(Staking::candidate_validators(41).delegators.contains(&1002));
// TEST3: delegate with invalid validator
assert_noop!(
Staking::delegate(RuntimeOrigin::signed(1002), vec![5]),
Error::<Test>::NotValidator
);
// TEST4: delegate with invalid validator
assert_noop!(
Staking::delegate(RuntimeOrigin::signed(1002), vec![11, 5]),
Error::<Test>::NotValidator
);
// TEST5: delegate after having called delegate() is allowed
assert_ok!(Staking::delegate(
RuntimeOrigin::signed(1003),
vec![11, 21, 31, 41]
));
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1003), vec![11]));
// 1001, 1002 and 1003 are all delegators now
assert_eq!(Staking::delegator_count(), 3);
assert_eq!(Staking::active_delegator_count(), 3);
assert_eq!(Staking::delegators(1003).delegated_validators, vec![11]);
assert!(Staking::candidate_validators(11).delegators.contains(&1003));
assert!(!Staking::candidate_validators(21).delegators.contains(&1003));
assert!(!Staking::candidate_validators(31).delegators.contains(&1003));
assert!(!Staking::candidate_validators(41).delegators.contains(&1003));
});
}
#[test]
fn undelegate() {
ExtBuilder::default()
.existential_deposit(10)
.validator_pool(true) // 11, 21, 31, 41
.build_and_execute(|| {
// TEST1: undelegate
// delegate credit score
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1001), vec![11]));
assert!(Delegators::<Test>::contains_key(&1001));
assert_eq!(Staking::delegator_count(), 1);
assert_eq!(Staking::active_delegator_count(), 1);
// undelegate after calling delegate()
assert_ok!(Staking::undelegate(RuntimeOrigin::signed(1001)));
assert!(!Delegators::<Test>::contains_key(&1001));
assert_eq!(Staking::delegator_count(), 0);
assert_eq!(Staking::active_delegator_count(), 0);
assert_eq!(
Staking::candidate_validators(11).delegators.is_empty(),
true
);
// TEST2: undelegate before calling delegate()
assert_noop!(
Staking::undelegate(RuntimeOrigin::signed(12)),
Error::<Test>::NotDelegator
);
assert!(!Delegators::<Test>::contains_key(&12));
// TEST3: delegate in era 0 and undelegate in era 1
assert_ok!(Staking::delegate(RuntimeOrigin::signed(1001), vec![11]));
assert!(Delegators::<Test>::contains_key(&1001));
assert_eq!(Staking::delegator_count(), 1);
assert_eq!(Staking::active_delegator_count(), 1);
run_to_block(BLOCKS_PER_ERA);
assert_ok!(Staking::undelegate(RuntimeOrigin::signed(1001)));
// reward not paid yet, hence not deleted yet
assert!(Delegators::<Test>::contains_key(&1001));
let delegator_data = Staking::delegators(&1001);
assert_eq!(delegator_data.unrewarded_since.unwrap(), 0);
assert!(!delegator_data.delegating);
assert_eq!(Staking::delegator_count(), 1);
assert_eq!(Staking::active_delegator_count(), 0);
});
}
#[test]
fn increase_mining_reward() {
ExtBuilder::default().build().execute_with(|| {
assert_noop!(
Staking::increase_mining_reward(RuntimeOrigin::signed(1), 10000),
BadOrigin
);
assert_ok!(Staking::increase_mining_reward(
RawOrigin::Root.into(),
10000
));
assert_eq!(
Staking::remainder_mining_reward().unwrap(),
TOTAL_MINING_REWARD + 10000
);
});
}
#[test]
fn set_era_validator_reward() {
ExtBuilder::default().build().execute_with(|| {
assert_noop!(
Staking::set_era_validator_reward(RuntimeOrigin::signed(1), 10000),
BadOrigin
);
assert_ok!(Staking::set_era_validator_reward(
RawOrigin::Root.into(),
10000
));
assert_eq!(Staking::era_validator_reward(), 10000);
});
}
#[test]
fn elected_validators_should_rotate() {
ExtBuilder::default()
.validator_pool(true)
.build_and_execute(|| {
assert_eq_uvec!(Session::validators(), vec![11, 21]);
mock::start_active_era(1);
assert_eq_uvec!(Session::validators(), vec![31, 41]);
mock::start_active_era(2);
assert_eq_uvec!(Session::validators(), vec![11, 21]);
mock::start_active_era(3);
assert_eq_uvec!(Session::validators(), vec![31, 41]);
mock::start_active_era(4);
assert_eq_uvec!(Session::validators(), vec![11, 21]);
});
}
#[test]
fn staking_delegate() {
ExtBuilder::default()
.validator_pool(true)
.build_and_execute(|| {
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
51,
Privilege::CreditAdmin
));
assert_ok!(Credit::set_credit_balances(
RuntimeOrigin::signed(51),
vec![
0u32.into(),
10u32.into(),
100u32.into(),
1000u32.into(),
10000u32.into(),
100000u32.into(),
1000000u32.into(),
10000000u32.into()
]
));
let new_credit_data = CreditData {
campaign_id: 4,
credit: 0,
initial_credit_level: CreditLevel::Zero,
rank_in_initial_credit_level: 0u32,
number_of_referees: 0,
current_credit_level: CreditLevel::Zero,
reward_eras: 3650,
};
assert_ok!(Credit::add_or_update_credit_data(
RuntimeOrigin::root(),
51,
new_credit_data
));
assert_eq!(Balances::free_balance(&51), 2000);
assert_ok!(Staking::_do_staking_delegate(51, 1));
let credit_balances = Credit::get_credit_balance(&51, Some(4));
let pay = credit_balances[1];
assert_eq!(Balances::free_balance(&51), 2000 - pay);
assert_eq!(Credit::user_credit(&51).unwrap().credit, 100);
assert_eq!(
Credit::user_credit(&51).unwrap().current_credit_level,
CreditLevel::One
);
assert_eq!(
Credit::user_credit(&51).unwrap().initial_credit_level,
CreditLevel::Zero
);
assert_eq!(Credit::user_credit(&51).unwrap().reward_eras, 10 * 365);
assert_ok!(Staking::_do_staking_delegate(51, 3));
let sec_pay = credit_balances[3] - credit_balances[1];
assert_eq!(Balances::free_balance(&51), 2000 - pay - sec_pay);
assert_eq!(Credit::user_credit(&51).unwrap().credit, 300);
assert_eq!(
Credit::user_credit(&51).unwrap().current_credit_level,
CreditLevel::Three
);
assert_eq!(Staking::delegators(&51).delegator, 51);
assert_eq!(Staking::delegators(&51).delegating, true);
});
}
#[test]
fn force_unstaking_delegate() {
ExtBuilder::default()
.validator_pool(true)
.build_and_execute(|| {
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
51,
Privilege::CreditAdmin
));
let new_credit_data = CreditData {
campaign_id: 4,
credit: 210,
initial_credit_level: CreditLevel::Zero,
rank_in_initial_credit_level: 0u32,
number_of_referees: 0,
current_credit_level: CreditLevel::Two,
reward_eras: 3650,
};
assert_ok!(Credit::add_or_update_credit_data(
RuntimeOrigin::root(),
1,
new_credit_data
));
Credit::init_delegator_history(&1, 250);
assert!(!Credit::user_credit(&1).is_none());
assert!(!Credit::user_credit_history(&1).is_empty());
assert_ok!(Staking::force_unstaking_delegate(
RuntimeOrigin::signed(51),
1
));
assert!(Credit::user_credit(&1).is_none());
assert!(Credit::user_credit_history(&1).is_empty());
});
}
#[test]
fn rewards_to_referer() {
ExtBuilder::default()
.session_per_era(6)
.num_delegators(2)
.build_and_execute(|| {
// 1001 is the default delegator
assert_eq!(Staking::delegator_count() as u64, 1);
assert_eq!(Staking::active_delegator_count() as u64, 1);
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
1,
Privilege::CreditAdmin
));
assert_ok!(Staking::set_user_referer(
RuntimeOrigin::signed(1),
1001,
1002
));
assert_eq!(Staking::user_referee_count(1002), 1);
run_to_block(BLOCKS_PER_ERA);
assert_eq!(
Staking::remainder_mining_reward().unwrap(),
TOTAL_MINING_REWARD
);
run_to_block(BLOCKS_PER_ERA + 1);
// 1001 is paid
assert_eq!(Balances::total_balance(&1001), 21369858941948251800);
assert_eq!(Balances::total_balance(&1002), 1068492947097412590);
let remainder = TOTAL_MINING_REWARD - 21369858941948251800 - 1068492947097412590;
assert_eq!(Staking::remainder_mining_reward().unwrap(), remainder);
assert_ok!(Staking::unset_user_referer(RuntimeOrigin::signed(1), 1001));
assert_eq!(Staking::user_referee_count(1002), 0);
run_to_block(BLOCKS_PER_ERA * 2 + 1);
assert_eq!(Balances::total_balance(&1001), 21369858941948251800 * 2);
assert_eq!(Balances::total_balance(&1002), 1068492947097412590);
});
}
#[test]
fn staking_usdt_delegate() {
ExtBuilder::default()
.session_per_era(6)
.num_delegators(1)
.build_and_execute(|| {
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
1,
Privilege::CreditAdmin
));
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
1,
Privilege::OracleWorker
));
let credit_setting = CreditSetting {
campaign_id: 5,
credit_level: CreditLevel::One,
staking_balance: 3_000,
base_apy: Percent::from_percent(20),
bonus_apy: Percent::from_percent(0),
max_rank_with_bonus: 0u32,
tax_rate: Percent::from_percent(0),
max_referees_with_rewards: 0,
reward_per_referee: 0,
};
assert_ok!(Credit::update_credit_setting(
RawOrigin::Root.into(),
credit_setting.clone()
));
let credit_setting = CreditSetting {
campaign_id: 5,
credit_level: CreditLevel::Two,
staking_balance: 5_000,
base_apy: Percent::from_percent(30),
bonus_apy: Percent::from_percent(0),
max_rank_with_bonus: 0u32,
tax_rate: Percent::from_percent(0),
max_referees_with_rewards: 0,
reward_per_referee: 0,
};
assert_ok!(Credit::update_credit_setting(
RawOrigin::Root.into(),
credit_setting.clone()
));
assert_ok!(Credit::set_dpr_price(
RuntimeOrigin::signed(1),
25_000_000_000_000_000,
H160::zero()
));
run_to_block(1);
assert_ok!(Credit::set_usdt_credit_balances(
RuntimeOrigin::signed(1),
vec![
UniqueSaturatedFrom::unique_saturated_from(50 * DPR),
UniqueSaturatedFrom::unique_saturated_from(75 * DPR),
UniqueSaturatedFrom::unique_saturated_from(125 * DPR),
UniqueSaturatedFrom::unique_saturated_from(200 * DPR),
UniqueSaturatedFrom::unique_saturated_from(300 * DPR),
UniqueSaturatedFrom::unique_saturated_from(450 * DPR),
UniqueSaturatedFrom::unique_saturated_from(600 * DPR),
UniqueSaturatedFrom::unique_saturated_from(800 * DPR),
UniqueSaturatedFrom::unique_saturated_from(1_000 * DPR),
]
));
assert_ok!(Staking::usdt_staking_delegate(
RuntimeOrigin::signed(1),
1002,
UniqueSaturatedFrom::unique_saturated_from(75 * DPR),
UniqueSaturatedFrom::unique_saturated_from(3000 * DPR)
));
assert_eq!(Credit::user_credit(&1002).unwrap().credit, 100);
run_to_block(BLOCKS_PER_ERA + 2);
assert_eq!(Balances::total_balance(&1002), 1643835616438356164);
// add 50 usdt
assert_ok!(Staking::usdt_staking_delegate(
RuntimeOrigin::signed(1),
1002,
UniqueSaturatedFrom::unique_saturated_from(50 * DPR),
UniqueSaturatedFrom::unique_saturated_from(2000 * DPR)
));
run_to_block(BLOCKS_PER_ERA * 2 + 2);
assert_eq!(
Balances::total_balance(&1002),
1643835616438356164 + 4109589041095890410
);
});
}
#[test]
fn npow_mint() {
ExtBuilder::default().build_and_execute(|| {
run_to_block(1);
assert_ok!(Staking::set_npow_mint_limit(RuntimeOrigin::root(), 100000));
assert_ok!(UserPrivileges::set_user_privilege(
RuntimeOrigin::root(),
1,
Privilege::NpowMint
));
assert_ok!(Staking::npow_mint(RuntimeOrigin::signed(1), 2, 100));
assert_eq!(
<frame_system::Pallet<Test>>::events()
.pop()
.expect("should contains events")
.event,
mock::RuntimeEvent::from(crate::Event::NpowMint(2, 100))
);
run_to_block(2);
assert!(Balances::free_balance(&2) > 100);
assert_err!(
Staking::npow_mint(RuntimeOrigin::signed(3), 2, 100),
Error::<Test>::UnauthorizedAccounts
);
run_to_block(3);
assert_err!(
Staking::npow_mint(RuntimeOrigin::signed(1), 2, 100_001),
Error::<Test>::NpowMintBeyoundDayLimit
);
assert_err!(
Staking::npow_mint(RuntimeOrigin::signed(1), 2, 99901),
Error::<Test>::NpowMintBeyoundDayLimit
);
RemainderMiningReward::<Test>::put(10000);
assert_err!(
Staking::npow_mint(RuntimeOrigin::signed(1), 2, 99900),
Error::<Test>::InsufficientValue
);
RemainderMiningReward::<Test>::put(1000000);
assert_ok!(Staking::npow_mint(RuntimeOrigin::signed(1), 2, 99900));
assert_err!(
Staking::npow_mint(RuntimeOrigin::signed(1), 2, 1),
Error::<Test>::NpowMintBeyoundDayLimit
);
});
}
#[test]
fn slash_staker() {
ExtBuilder::default().build_and_execute(|| {
ErasRewardPoints::<Test>::insert(
0,
EraRewardPoints {
individual: vec![(11, 50)].into_iter().collect(),
total: 50,
},
);
ErasRewardPoints::<Test>::insert(
1,
EraRewardPoints {
individual: vec![(11, 50)].into_iter().collect(),
total: 50,
},
);
ErasRewardPoints::<Test>::insert(
2,
EraRewardPoints {
individual: vec![(11, 50)].into_iter().collect(),
total: 50,
},
);
ErasRewardPoints::<Test>::insert(
3,
EraRewardPoints {
individual: vec![(11, 50)].into_iter().collect(),
total: 50,
},
);
ErasRewardPoints::<Test>::insert(
4,
EraRewardPoints {
individual: vec![(11, 50)].into_iter().collect(),
total: 50,
},
);
assert_eq!(Balances::free_balance(&11), 1000);
run_to_block(37);
assert_eq!(Balances::free_balance(&11), 60000000000000001000);
assert_eq!(Balances::usable_balance(&11), 0);
let _ = Staking::validator_burn(RuntimeOrigin::signed(10), 30000000000000001000);
assert_eq!(Balances::free_balance(&11), 30000000000000000000);
assert_eq!(Balances::usable_balance(&11), 0);
// can burn all the staked funds
let _ = Staking::validator_burn(RuntimeOrigin::signed(10), 40000000000000000000);
assert_eq!(Balances::free_balance(&11), 1);
assert_eq!(Balances::usable_balance(&11), 1);
// will be reward next era
run_to_block(120);
assert_eq!(Balances::free_balance(&11), 60000000000000000001);
});
}
|
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fs::File;
use std::io;
use std::os::unix::prelude::*;
use std::path::{Path, PathBuf};
use std::sync::RwLock;
use hashbrown::HashMap;
use hashbrown::HashSet;
use crate::elfkit::{self, ld_so_cache::LdsoCache, Elf};
fn replace_slice<T: Copy>(buf: &[T], from: &[T], to: &[T]) -> Vec<T>
where
T: Clone + PartialEq,
{
if buf.len() < from.len() {
return Vec::from(buf);
}
let mut res: Vec<T> = Vec::new();
let mut i = 0;
while i <= buf.len() - from.len() {
if buf[i..].starts_with(from) {
res.extend_from_slice(to);
i += from.len();
} else {
res.push(buf[i]);
i += 1;
}
}
if i < buf.len() {
res.extend_from_slice(&buf[i..buf.len()]);
}
res
}
pub struct Ldd<'a> {
pub ld_so_cache: Option<&'a LdsoCache>,
pub default_libdir: &'a [OsString],
pub canon_cache: RwLock<HashMap<OsString, OsString>>,
pub dest_path: OsString,
}
type OsStringDynQueueHandle<'a> = dynqueue::DynQueueHandle<
'a,
(OsString, HashSet<OsString>),
RwLock<Vec<(OsString, HashSet<OsString>)>>,
>;
impl<'a> Ldd<'a> {
pub fn new(
ld_so_cache: Option<&'a LdsoCache>,
slpath: &'a [OsString],
dest_path: &Path,
) -> Ldd<'a> {
Ldd {
ld_so_cache,
default_libdir: slpath,
canon_cache: RwLock::new(HashMap::new()),
dest_path: OsString::from(dest_path.as_os_str()),
}
}
pub fn recurse(
&self,
handle: OsStringDynQueueHandle,
path: &OsStr,
lpaths: &HashSet<OsString>,
visited: &RwLock<HashSet<OsString>>,
) -> Result<(), Box<dyn std::error::Error>> {
let mut lpaths = lpaths.clone();
let mut f = File::open(path)?;
let mut elf = match Elf::from_reader(&mut f) {
Ok(e) => e,
Err(elfkit::Error::InvalidMagic) => {
return Err("not a dynamic executable".into());
}
Err(e) => {
return Err(format!("{:#?}", e).into());
}
};
let mut deps: Vec<OsString> = Vec::new();
for shndx in 0..elf.sections.len() {
if elf.sections[shndx].header.shtype == elfkit::types::SectionType::DYNAMIC {
elf.load(shndx, &mut f).unwrap();
let dynamic = elf.sections[shndx].content.as_dynamic().unwrap();
for dyn_entry in dynamic.iter() {
if dyn_entry.dhtype == elfkit::types::DynamicType::RPATH {
if let elfkit::dynamic::DynamicContent::String(ref name) = dyn_entry.content
{
name.0.split(|e| *e == b':').for_each(|n| {
let n = replace_slice(
&n,
b"$ORIGIN",
PathBuf::from(path).parent().unwrap().as_os_str().as_bytes(),
);
lpaths.insert(OsString::from(OsStr::from_bytes(&n)));
});
}
}
if dyn_entry.dhtype == elfkit::types::DynamicType::RUNPATH {
if let elfkit::dynamic::DynamicContent::String(ref name) = dyn_entry.content
{
name.0.split(|e| *e == b':').for_each(|n| {
let n = replace_slice(
&n,
b"$ORIGIN",
PathBuf::from(path).parent().unwrap().as_os_str().as_bytes(),
);
lpaths.insert(OsString::from(OsStr::from_bytes(&n)));
});
}
}
if dyn_entry.dhtype == elfkit::types::DynamicType::NEEDED {
if let elfkit::dynamic::DynamicContent::String(ref name) = dyn_entry.content
{
deps.push(OsStr::from_bytes(&name.0).into());
}
}
}
}
}
'outer: for dep in deps {
//eprintln!("Search for {:#?}", dep);
for lpath in lpaths.iter() {
let joined = PathBuf::from(lpath).join(&dep);
let joined = self.canonicalize_dir(&joined).unwrap_or(joined);
//eprintln!("Checking {:#?}", joined);
if visited.write().unwrap().insert(joined.clone().into()) {
let mut dest = self.dest_path.clone();
dest.push(joined.as_os_str());
let dest = PathBuf::from(dest);
if joined.exists() && !dest.exists() {
handle.enqueue((joined.into(), lpaths.clone()));
continue 'outer;
}
} else {
continue 'outer;
}
}
if let Some(ld_so_cache) = self.ld_so_cache {
if let Some(vals) = ld_so_cache.get(dep.as_os_str()) {
for f in vals {
//eprintln!("LD_SO_CACHE Found {:#?}", val);
let joined = PathBuf::from(f);
let joined = self.canonicalize_dir(&joined).unwrap_or(joined);
//eprintln!("Checking {:#?}", joined);
if visited.write().unwrap().insert(joined.clone().into()) {
let mut dest = self.dest_path.clone();
dest.push(joined.as_os_str());
let dest = PathBuf::from(dest);
if joined.exists() && !dest.exists() {
handle.enqueue((joined.into(), lpaths.clone()));
}
}
}
continue 'outer;
}
}
for lpath in self.default_libdir.iter() {
let joined = PathBuf::from(lpath).join(&dep);
let joined = self.canonicalize_dir(&joined).unwrap_or(joined);
//eprintln!("Checking {:#?}", joined);
if visited.write().unwrap().insert(joined.clone().into()) {
let mut dest = self.dest_path.clone();
dest.push(&joined);
let dest = PathBuf::from(dest);
if joined.exists() && !dest.exists() {
//eprintln!("Standard LIBPATH Found {:#?}", joined);
handle.enqueue((joined.into(), lpaths.clone()));
continue 'outer;
}
} else {
continue 'outer;
}
}
return Err(format!("unable to find dependency {:#?} in {:?}", dep, lpaths).into());
}
//eprintln!("{:#?}", out);
Ok(())
}
#[inline]
pub fn canonicalize_dir(&self, path: &Path) -> std::result::Result<PathBuf, ()> {
let source_filename = path.file_name().ok_or(())?;
let dirname = path.parent().ok_or(())?;
let mut canon_dirname = self.canonicalize(dirname).map_err(|_| ())?;
canon_dirname.push(source_filename);
Ok(canon_dirname)
}
#[inline]
pub fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
{
if let Some(val) = self.canon_cache.read().unwrap().get(path.as_os_str()) {
return Ok(PathBuf::from(val));
}
}
let val = path.canonicalize()?;
{
self.canon_cache
.write()
.unwrap()
.insert(path.as_os_str().into(), val.as_os_str().into());
}
Ok(val)
}
}
#[cfg(test)]
mod test {
use super::replace_slice;
#[test]
fn test_replace_slice() {
assert_eq!(replace_slice(b"test", b"$ORIGIN", b"TEST"), b"test");
assert_eq!(replace_slice(b"$ORIGIN", b"$ORIGIN", b"TEST"), b"TEST");
assert_eq!(replace_slice(b"/$ORIGIN/", b"$ORIGIN", b"TEST"), b"/TEST/");
assert_eq!(
replace_slice(b"/_ORIGIN/", b"$ORIGIN", b"TEST"),
b"/_ORIGIN/"
);
assert_eq!(
replace_slice(b"/_ORIGIN//", b"$ORIGIN", b"TEST"),
b"/_ORIGIN//"
);
}
}
|
fn main() {
println!("{:?}", pkcs7("YELLOW SUBMARINE", 20));
}
fn pkcs7(str: &str, len: usize) -> String {
format!("{:\x04<1$}", str, len)
}
#[test]
fn test_pkcs7() {
assert_eq!(
pkcs7("YELLOW SUBMARINE", 20),
"YELLOW SUBMARINE\x04\x04\x04\x04"
);
}
|
use crate::{DatabaseName, SessionId};
use serde::{Deserialize, Serialize};
use super::with_tx::SessionWithTx;
/// Session with open database.
///
/// This session means there is no open transaction.
/// Only limited SQLs are valid for this type of session (auto-commit is work for query-processor. It must Create this kind of session to realize auto-commit).
#[derive(Hash, Debug, Serialize, Deserialize)]
pub struct SessionWithDb {
id: SessionId,
db: DatabaseName,
}
impl SessionWithDb {
/// Construct a session with open database.
///
/// A storage engine's implementation must call this after opening a database.
pub(super) fn new(sid: SessionId, db: DatabaseName) -> Self {
Self { id: sid, db }
}
/// Upgrade to `SessionWithTx`.
pub fn upgrade(self) -> SessionWithTx {
SessionWithTx::new(self.id, self.db)
}
/// Get session ID
pub fn get_id(&self) -> &SessionId {
&self.id
}
/// Get database name
pub fn database_name(&self) -> &DatabaseName {
&self.db
}
}
|
//! wmata is a simple interface to the [WMATA](https://wmata.com)'s API.
//!
//! # Design
//! wmata provides two main interfaces: [`MetroBus`] and [`MetroRail`].
//!
//! ## [`MetroBus`]
//! The interface to WMATA's MetroBus related methods
//!
//! ## [`MetroRail`]
//! The interface to WMATA's MetroRail related methods
//!
pub mod bus;
pub mod rail;
pub mod date;
pub mod error;
pub mod location;
mod requests;
pub use bus::client::Client as MetroBus;
pub use rail::client::Client as MetroRail;
pub use date::Date;
pub use location::RadiusAtLatLong;
pub use bus::route::Route;
pub use bus::stop::Stop;
pub use rail::line::Line;
pub use rail::station::Station;
|
pub mod bitmap;
pub mod consts;
pub mod error;
pub mod utility {
pub fn hexdump(data: &[u8]) {
use alloc::prelude::*;
let mut index: usize = 0;
for bytes in data.chunks(16) {
println!(
"{:08x}: {}",
index,
bytes
.iter()
.map(|x| format!("{:02x}", x))
.collect::<Vec<String>>()
.join(" ")
);
index += 0x10;
}
}
}
|
use lapin::ConnectionProperties;
// ConnectionProperties extension
pub trait LapinAsyncIoExt {
fn with_async_io(self) -> Self
where
Self: Sized,
{
self.with_async_io_reactor()
}
fn with_async_io_reactor(self) -> Self
where
Self: Sized;
}
impl LapinAsyncIoExt for ConnectionProperties {
fn with_async_io_reactor(self) -> Self {
self.with_reactor(async_reactor_trait::AsyncIo)
}
}
|
use boolinator::Boolinator;
use regex::Regex;
#[derive(Copy, Clone)]
struct State<V: Fn(&str, &str) -> bool> {
fields: Option<u8>,
count: usize,
validator: V,
}
impl<V: Fn(&str, &str) -> bool> State<V> {
pub fn new(validator: V) -> Self {
Self {
fields: Some(0),
count: 0,
validator,
}
}
pub fn count(&self) -> usize {
self.count
}
fn valid_fields(&self) -> bool {
self.fields.map(|f| f & 0x7F == 0x7F).unwrap_or(false)
}
pub fn step(&mut self, line: &str) {
if line.is_empty() {
if self.valid_fields() {
self.count += 1;
}
self.fields = Some(0);
} else {
self.fields = self.fields.and_then(|f| self.parse(line).map(|g| f | g));
}
}
pub fn step_last(&mut self) {
if self.valid_fields() {
self.count += 1;
}
}
fn validate_segment(&self, key: &str, value: &str) -> Option<u8> {
let fields = match key {
"byr" => 1 << 0,
"iyr" => 1 << 1,
"eyr" => 1 << 2,
"hgt" => 1 << 3,
"hcl" => 1 << 4,
"ecl" => 1 << 5,
"pid" => 1 << 6,
"cid" => 1 << 7,
_ => return None,
};
(self.validator)(key, value).as_some(fields)
}
fn parse(&self, line: &str) -> Option<u8> {
let mut fields = 0u8;
for segment in line.split_ascii_whitespace() {
let key = segment.split(':').nth(0)?;
let value = segment.split(':').nth(1)?;
fields |= self.validate_segment(key, value)?;
}
Some(fields)
}
}
fn common(validator: impl Fn(&str, &str) -> bool) -> usize {
let input = aoc2020::input_file!("04");
let mut state = State::new(validator);
input.lines().for_each(|line| state.step(line));
state.step_last();
state.count()
}
fn part1() -> usize {
common(|_, _| true)
}
fn part2() -> usize {
let hgt_re = Regex::new("^(?P<height>[0-9]+)(?P<unit>cm|in)$").unwrap();
let hcl_re = Regex::new("^#[0-9a-f]{6}$").unwrap();
let pid_re = Regex::new("^[0-9]{9}$").unwrap();
common(|key, value| match key {
"byr" => (1920..=2002).contains(&value.parse().unwrap_or(0)),
"iyr" => (2010..=2020).contains(&value.parse().unwrap_or(0)),
"eyr" => (2020..=2030).contains(&value.parse().unwrap_or(0)),
"hgt" => hgt_re
.captures(value)
.map(|c| {
let h = c["height"].parse().unwrap();
match &c["unit"] {
"cm" => (150..=193).contains(&h),
"in" => (59..=76).contains(&h),
u => panic!("invalid unit: {}", u),
}
})
.unwrap_or(false),
"hcl" => hcl_re.is_match(value),
"ecl" => match value {
"amb" | "blu" | "brn" | "gry" | "grn" | "hzl" | "oth" => true,
_ => false,
},
"pid" => pid_re.is_match(value),
"cid" => true,
_ => false,
})
}
fn main() {
println!("Day 4:");
println!("1: {}", part1());
println!("2: {}", part2());
}
|
use diesel::RunQueryDsl;
use radmin::diesel::PgConnection;
use radmin::serde::{Deserialize, Serialize};
use radmin::uuid::Uuid;
use crate::models::contacts::ContactTag;
use crate::schema::contact_tags;
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Insertable)]
#[table_name = "contact_tags"]
pub struct ContactTagFactory {
pub contact_id: Uuid,
pub tag_id: Uuid,
}
impl ContactTagFactory {
pub fn new(contact_id: Uuid, tag_id: Uuid) -> ContactTagFactory {
ContactTagFactory { contact_id, tag_id }
}
pub fn insert(self, conn: &PgConnection) -> ContactTag {
radmin::diesel::insert_into(contact_tags::table)
.values(&self)
.get_result(conn)
.expect("Failed to insert new Category Factory")
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
use reqwest;
use crate::apis::ResponseContent;
use super::{Error, configuration};
/// struct for typed errors of method `create_child_org`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateChildOrgError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_org`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetOrgError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `list_orgs`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ListOrgsError {
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `update_org`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateOrgError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `upload_id_p_for_org`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UploadIdPForOrgError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
Status415(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// Create a child organization. This endpoint requires the [multi-organization account](https://docs.datadoghq.com/account_management/multi_organization/) feature and must be enabled by [contacting support](https://docs.datadoghq.com/help/). Once a new child organization is created, you can interact with it by using the `org.public_id`, `pi_key.key`, and `application_key.hash` provided in the response.
pub async fn create_child_org(configuration: &configuration::Configuration, body: crate::models::OrganizationCreateBody) -> Result<crate::models::OrganizationCreateResponse, Error<CreateChildOrgError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/org", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<CreateChildOrgError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get organization information.
pub async fn get_org(configuration: &configuration::Configuration, public_id: &str) -> Result<crate::models::OrganizationResponse, Error<GetOrgError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/org/{public_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetOrgError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// List your managed organizations.
pub async fn list_orgs(configuration: &configuration::Configuration, ) -> Result<crate::models::OrganizationListResponse, Error<ListOrgsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/org", configuration.base_path);
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<ListOrgsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Update your organization.
pub async fn update_org(configuration: &configuration::Configuration, public_id: &str, body: crate::models::Organization) -> Result<crate::models::OrganizationResponse, Error<UpdateOrgError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/org/{public_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<UpdateOrgError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// There are a couple of options for updating the Identity Provider (IdP) metadata from your SAML IdP. * **Multipart Form-Data**: Post the IdP metadata file using a form post. * **XML Body:** Post the IdP metadata file as the body of the request.
pub async fn upload_id_p_for_org(configuration: &configuration::Configuration, public_id: &str, idp_file: std::path::PathBuf) -> Result<crate::models::IdpResponse, Error<UploadIdPForOrgError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/org/{public_id}/idp_metadata", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let mut local_var_form = reqwest::multipart::Form::new();
// TODO: support file upload for 'idp_file' parameter
local_var_req_builder = local_var_req_builder.multipart(local_var_form);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<UploadIdPForOrgError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
|
use core::alloc::{GlobalAlloc, Layout};
use core::cmp::min;
use core::ops::Deref;
use core::ptr::NonNull;
use alloc::alloc::{Allocator, Global};
use x86_64::VirtAddr;
use heap::LinkedListAllocator;
use crate::uses::*;
use crate::futex::Futex;
use crate::misc::mlayout_of;
pub mod heap;
#[derive(Debug)]
pub struct MemOwner<T>(*const T);
impl<T> MemOwner<T>
{
pub fn new(data: T) -> Self
{
let layout = mlayout_of::<T>();
let mem = Global.allocate(layout).expect("out of memory for MemOwner");
let ptr = mem.as_ptr() as *mut T;
unsafe {
core::ptr::write(ptr, data);
Self::from_raw(ptr)
}
}
pub unsafe fn from_raw(ptr: *const T) -> Self
{
MemOwner(ptr)
}
pub unsafe fn clone(&self) -> Self
{
MemOwner(self.0)
}
pub fn ptr(&self) -> *const T
{
self.0
}
pub fn ptr_mut(&self) -> *mut T
{
self.0 as *mut T
}
pub unsafe fn dealloc(self)
{
let ptr = NonNull::new(self.ptr_mut()).unwrap().cast();
Global.deallocate(ptr, mlayout_of::<T>());
}
}
impl<T> Deref for MemOwner<T>
{
type Target = T;
fn deref(&self) -> &Self::Target
{
unsafe { self.0.as_ref().unwrap() }
}
}
unsafe impl<T> Send for MemOwner<T> {}
#[derive(Debug, Clone, Copy)]
pub struct Allocation
{
ptr: VirtAddr,
len: usize,
pub zindex: usize,
}
impl Allocation
{
// NOTE: panics if addr is not canonical
pub fn new(addr: usize, len: usize) -> Self
{
Allocation {
ptr: VirtAddr::new(addr as _),
len,
zindex: 0,
}
}
pub fn addr(&self) -> VirtAddr
{
self.ptr
}
pub fn as_mut_ptr<T>(&mut self) -> *mut T
{
self.ptr.as_mut_ptr()
}
pub fn as_ptr<T>(&self) -> *const T
{
self.ptr.as_ptr()
}
pub fn as_slice(&self) -> &[u8]
{
unsafe { core::slice::from_raw_parts(self.as_ptr(), self.len) }
}
pub fn as_mut_slice(&mut self) -> &mut [u8]
{
unsafe { core::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
}
pub fn as_usize(&self) -> usize
{
self.ptr.as_u64() as usize
}
pub fn len(&self) -> usize
{
self.len
}
// returns number of bytes copied
pub fn copy_from_mem(&mut self, other: &[u8]) -> usize
{
let size = min(self.len(), other.len());
unsafe {
let dst: &mut [u8] = core::slice::from_raw_parts_mut(self.as_mut_ptr(), size);
let src: &[u8] = core::slice::from_raw_parts(other.as_ptr(), size);
dst.copy_from_slice(src);
}
size
}
}
#[cfg(not(feature = "kernel"))]
#[global_allocator]
static ALLOCATOR: GlobalAllocator = GlobalAllocator::new();
#[alloc_error_handler]
fn alloc_error_handler(layout: Layout) -> !
{
panic!("allocation error: {:?}", layout);
}
#[cfg(not(feature = "kernel"))]
pub fn init()
{
ALLOCATOR.init();
}
// TODO: add relloc function
#[cfg(not(feature = "kernel"))]
struct GlobalAllocator
{
allocer: Futex<Option<LinkedListAllocator>>,
}
#[cfg(not(feature = "kernel"))]
impl GlobalAllocator
{
const fn new() -> GlobalAllocator
{
GlobalAllocator {
allocer: Futex::new(None),
}
}
fn init(&self)
{
*self.allocer.lock() = Some(LinkedListAllocator::new());
}
}
#[cfg(not(feature = "kernel"))]
unsafe impl GlobalAlloc for GlobalAllocator
{
unsafe fn alloc(&self, layout: Layout) -> *mut u8
{
self.allocer.lock().as_mut().unwrap().alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout)
{
self.allocer.lock().as_mut().unwrap().dealloc(ptr, layout)
}
}
#[cfg(not(feature = "kernel"))]
unsafe impl Send for GlobalAllocator {}
#[cfg(not(feature = "kernel"))]
unsafe impl Sync for GlobalAllocator {}
|
//! Simulation running functions.
use crate::{Engine, Input, Output, Tracer};
use arctk::{err::Error, ord::X, tools::ProgressBar};
use rand::thread_rng;
use rayon::prelude::*;
use std::sync::{Arc, Mutex};
/// Run a multi-threaded render simulation.
/// # Errors
/// if the progress bar can not be locked.
#[allow(clippy::expect_used)]
#[inline]
pub fn multi_thread<'a>(engine: Engine, input: &'a Input) -> Result<Output<'a>, Error> {
let pb = ProgressBar::new("Multi-threaded", input.cam.num_samples());
let pb = Arc::new(Mutex::new(pb));
let threads: Vec<_> = (0..num_cpus::get()).collect();
let mut out: Vec<_> = threads
.par_iter()
.map(|_id| thread(engine, input, &Arc::clone(&pb)))
.collect();
pb.lock()?.finish_with_message("Render complete.");
let mut data = out.pop().expect("No data received.");
while let Some(o) = out.pop() {
data += &o;
}
Ok(data)
}
/// Run a render simulation using a single thread.
/// # Errors
/// if the progress bar can not be locked.
#[inline]
pub fn single_thread<'a>(engine: Engine, input: &'a Input) -> Result<Output<'a>, Error> {
let pb = ProgressBar::new("Single-threaded", input.cam.num_samples());
let pb = Arc::new(Mutex::new(pb));
Ok(thread(engine, input, &pb))
}
/// Thread control function.
#[allow(clippy::expect_used)]
#[inline]
#[must_use]
fn thread<'a>(engine: Engine, input: &'a Input, pb: &Arc<Mutex<ProgressBar>>) -> Output<'a> {
let res = *input.cam.res();
let mut data = Output::new(res, input.shader.data_grad());
let mut rng = thread_rng();
let super_samples = input.cam.num_super_samples();
let ss_power = input.cam.ss_power();
let init_weight = 1.0 / super_samples as f64;
let block_size = input.sett.block_size();
while let Some((start, end)) = {
let mut pb = pb.lock().expect("Could not lock progress bar.");
let b = pb.block(block_size);
std::mem::drop(pb);
b
} {
for n in start..end {
let p = n / super_samples;
let s = n - (p * super_samples);
let pixel = [p % res[X], p / res[X]];
let ss = [s % ss_power, s / ss_power];
let tracer = Tracer::new(input.cam.emit(pixel, ss), init_weight);
engine(input, &mut rng, tracer, &mut data, pixel);
}
}
data
}
|
use crate::test_utils::*;
use std::net::TcpStream;
use vndb_rs::{
common::get::{
character::{GetCharacterResults, CHARACTER_FLAGS},
producer::{GetProducerResults, PRODUCER_FLAGS},
release::{GetReleaseResults, RELEASE_FLAGS},
staff::{GetStaffResults, STAFF_FLAGS},
ulist::{GetUListResults, ULIST_FLAGS},
ulistlabels::{GetUListLabelsResults, ULIST_LABELS_FLAGS},
user::{GetUserResults, USER_FLAGS},
vn::{GetVnResults, VN_FLAGS},
},
sync::client::Client,
};
#[test]
fn get_vn() {
const DATA_PATH: &str = "tests/data/vn.json";
let mut buf = b"results ".to_vec();
let json: GetVnResults = load_json_from_file(DATA_PATH);
buf.extend(load_bytes_from_file(DATA_PATH));
let addr = test_listener_with_response(buf);
let mut client = Client::new(TcpStream::connect(addr).expect("Could not create test stream"));
let response = client
.get_vn(&VN_FLAGS, "(id = 1)".to_owned(), None)
.expect("Getting vns failed");
assert_eq!(json.results, response.results);
assert_eq!(
json.items.iter().next().expect("Could not parse json"),
response.items.iter().next().expect("Expected 1 item")
);
}
#[test]
fn get_release() {
const DATA_PATH: &str = "tests/data/release.json";
let mut buf = b"results ".to_vec();
let json: GetReleaseResults = load_json_from_file(DATA_PATH);
buf.extend(load_bytes_from_file(DATA_PATH));
let addr = test_listener_with_response(buf);
let mut client = Client::new(TcpStream::connect(addr).expect("Could not create test stream"));
let response = client
.get_release(&RELEASE_FLAGS, "(id > 1000)".to_owned(), None)
.expect("Getting releases failed");
assert_eq!(json.results, response.results);
assert_eq!(
json.items.iter().next().expect("Could not parse json"),
response.items.iter().next().expect("Expected 1 item")
);
}
#[test]
fn get_producer() {
const DATA_PATH: &str = "tests/data/producer.json";
let mut buf = b"results ".to_vec();
let json: GetProducerResults = load_json_from_file(DATA_PATH);
buf.extend(load_bytes_from_file(DATA_PATH));
let addr = test_listener_with_response(buf);
let mut client = Client::new(TcpStream::connect(addr).expect("Could not create test stream"));
let response = client
.get_producer(&PRODUCER_FLAGS, "(id > 1000)".to_owned(), None)
.expect("Getting producer failed");
assert_eq!(json.results, response.results);
assert_eq!(
json.items.iter().next().expect("Could not parse json"),
response.items.iter().next().expect("Expected 1 item")
);
}
#[test]
fn get_character() {
const DATA_PATH: &str = "tests/data/character.json";
let mut buf = b"results ".to_vec();
let json: GetCharacterResults = load_json_from_file(DATA_PATH);
buf.extend(load_bytes_from_file(DATA_PATH));
let addr = test_listener_with_response(buf);
let mut client = Client::new(TcpStream::connect(addr).expect("Could not create test stream"));
let response = client
.get_character(&CHARACTER_FLAGS, "(id > 1000)".to_owned(), None)
.expect("Getting character failed");
assert_eq!(json.results, response.results);
assert_eq!(
json.items.iter().next().expect("Could not parse json"),
response.items.iter().next().expect("Expected 1 item")
);
}
#[test]
fn get_staff() {
const DATA_PATH: &str = "tests/data/staff.json";
let mut buf = b"results ".to_vec();
let json: GetStaffResults = load_json_from_file(DATA_PATH);
buf.extend(load_bytes_from_file(DATA_PATH));
let addr = test_listener_with_response(buf);
let mut client = Client::new(TcpStream::connect(addr).expect("Could not create test stream"));
let response = client
.get_staff(&STAFF_FLAGS, "(id > 1000)".to_owned(), None)
.expect("Getting staff failed");
assert_eq!(json.results, response.results);
assert_eq!(
json.items.iter().next().expect("Could not parse json"),
response.items.iter().next().expect("Expected 1 item")
);
}
#[test]
fn get_user() {
const DATA_PATH: &str = "tests/data/user.json";
let mut buf = b"results ".to_vec();
let json: GetUserResults = load_json_from_file(DATA_PATH);
buf.extend(load_bytes_from_file(DATA_PATH));
let addr = test_listener_with_response(buf);
let mut client = Client::new(TcpStream::connect(addr).expect("Could not create test stream"));
let response = client
.get_user(&USER_FLAGS, "(id > 1000)".to_owned(), None)
.expect("Getting user failed");
assert_eq!(json.results, response.results);
assert_eq!(
json.items.iter().next().expect("Could not parse json"),
response.items.iter().next().expect("Expected 1 item")
);
}
#[test]
fn get_ulist_labels() {
const DATA_PATH: &str = "tests/data/ulistlabels.json";
let mut buf = b"results ".to_vec();
let json: GetUListLabelsResults = load_json_from_file(DATA_PATH);
buf.extend(load_bytes_from_file(DATA_PATH));
let addr = test_listener_with_response(buf);
let mut client = Client::new(TcpStream::connect(addr).expect("Could not create test stream"));
let response = client
.get_ulist_labels(&ULIST_LABELS_FLAGS, "(id > 1000)".to_owned(), None)
.expect("Getting ulist labels failed");
assert_eq!(json.results, response.results);
assert_eq!(
json.items.iter().next().expect("Could not parse json"),
response.items.iter().next().expect("Expected 1 item")
);
}
#[test]
fn get_ulist() {
const DATA_PATH: &str = "tests/data/ulist.json";
let mut buf = b"results ".to_vec();
let json: GetUListResults = load_json_from_file(DATA_PATH);
buf.extend(load_bytes_from_file(DATA_PATH));
let addr = test_listener_with_response(buf);
let mut client = Client::new(TcpStream::connect(addr).expect("Could not create test stream"));
let response = client
.get_ulist(&ULIST_FLAGS, "(id > 1000)".to_owned(), None)
.expect("Getting ulist failed");
assert_eq!(json.results, response.results);
assert_eq!(
json.items.iter().next().expect("Could not parse json"),
response.items.iter().next().expect("Expected 1 item")
);
}
|
extern crate itertools;
mod graphpath;
fn main() {
}
|
use aoc_lib::AocImplementation;
use std::collections::VecDeque;
use itertools::Itertools;
use std::ops::Range;
fn main() {
let day7 = Day7 {
program_input: 5
};
day7.start(7)
}
struct Day7 {
program_input: i32
}
impl AocImplementation<i32> for Day7 {
fn process_input(&self, input: &str) -> Vec<i32> {
input.split(',').map(|n| n.parse().unwrap_or_else(|_| panic!("Failed to parse number: {}", n))).collect()
}
fn execute(&self, program: Vec<i32>) -> Option<i32> {
let result = find_max_phase_signal(program, (5..=9).collect());
Some(result.signal)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum Parameter {
Position(i32),
Immediate(i32),
}
impl Parameter {
fn parse(mode: &str, value: &i32, index: &i32) -> Parameter {
match mode {
"0" => Parameter::Position(*value),
"1" => Parameter::Immediate(*index),
_ => panic!("Unexpected parameter mode: {}", mode)
}
}
fn get_value(&self, program: &Vec<i32>) -> i32 {
match self {
Parameter::Position(pos) => program[*pos as usize],
Parameter::Immediate(value) => program[*value as usize],
}
}
fn unwrap_inner(&self) -> i32 {
match self {
Parameter::Position(pos) => *pos,
Parameter::Immediate(value) => *value,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum Instruction {
Add {
left: Parameter,
right: Parameter,
out: i32,
},
Multiply {
left: Parameter,
right: Parameter,
out: i32,
},
Input {
out: i32
},
Output {
p: Parameter
},
Terminate,
JumpIfTrue { value: Parameter, target: Parameter },
JumpIfFalse { value: Parameter, target: Parameter },
LessThan { first: Parameter, second: Parameter, out: i32 },
Equals { first: Parameter, second: Parameter, out: i32 },
}
impl Instruction {
fn parse(index: &i32, program: &Vec<i32>) -> Instruction {
let op = program[*index as usize];
let op_parts = format!("{:05}", op);
let op_code = &op_parts[3..5];
match op_code {
"01" => {
let params = Instruction::parse_parameters(3, &op_parts[..], program, index);
let left = params[0].to_owned();
let right = params[1].to_owned();
let out = params[2].unwrap_inner();
Instruction::Add { left, right, out }
}
"02" => {
let params = Instruction::parse_parameters(3, &op_parts[..], program, index);
let left = params[0].to_owned();
let right = params[1].to_owned();
let out = params[2].unwrap_inner();
Instruction::Multiply { left, right, out }
}
"03" => {
let params = Instruction::parse_parameters(1, &op_parts[..], program, index);
let out = params[0].unwrap_inner();
Instruction::Input { out }
}
"04" => {
let params = Instruction::parse_parameters(1, &op_parts[..], program, index);
let p = params[0].to_owned();
Instruction::Output { p }
}
"05" => {
let params = Instruction::parse_parameters(2, &op_parts[..], program, index);
let value = params[0].to_owned();
let target = params[1].to_owned();
Instruction::JumpIfTrue { value, target }
}
"06" => {
let params = Instruction::parse_parameters(2, &op_parts[..], program, index);
let value = params[0].to_owned();
let target = params[1].to_owned();
Instruction::JumpIfFalse { value, target }
}
"07" => {
let params = Instruction::parse_parameters(3, &op_parts[..], program, index);
let first = params[0].to_owned();
let second = params[1].to_owned();
let out = params[2].unwrap_inner();
Instruction::LessThan { first, second, out }
}
"08" => {
let params = Instruction::parse_parameters(3, &op_parts[..], program, index);
let first = params[0].to_owned();
let second = params[1].to_owned();
let out = params[2].unwrap_inner();
Instruction::Equals { first, second, out }
}
"99" => {
Instruction::Terminate
}
_ => panic!("Unexpected instruction: {}", op_parts),
}
}
fn len(&self) -> i32 {
match self {
Instruction::Add { left, right, out } => 4,
Instruction::Multiply { left, right, out } => 4,
Instruction::Equals { first, second, out } => 4,
Instruction::LessThan { first, second, out } => 4,
Instruction::JumpIfTrue { value, target } => 3,
Instruction::JumpIfFalse { value, target } => 3,
Instruction::Input { out } => 2,
Instruction::Output { p } => 2,
Instruction::Terminate => 1,
}
}
fn parse_parameters(number: i32, op_parts: &str, program: &Vec<i32>, instruction_pointer: &i32) -> Vec<Parameter> {
let mut p = Vec::new();
for i in (0..3).rev().take(number as usize) {
let idx = i as usize;
let mode = &op_parts[idx..=idx];
let total_idx = (3 - i - 1) + *instruction_pointer + 1;
let value = program[total_idx as usize];
let param = Parameter::parse(mode, &value, &total_idx);
p.push(param)
}
p
}
// true if the program should continue
fn execute(&self, program: &mut Vec<i32>, input: &mut Inputs, outputs: &mut Vec<i32>) -> InstructionResult {
match self {
Instruction::Add { left, right, out } => {
program[*out as usize] = left.get_value(program) + right.get_value(program);
InstructionResult::Continue(self.len())
}
Instruction::Multiply { left, right, out } => {
program[*out as usize] = left.get_value(program) * right.get_value(program);
InstructionResult::Continue(self.len())
}
Instruction::Input { out } => {
program[*out as usize] = input.next();
InstructionResult::Continue(self.len())
}
Instruction::Output { p } => {
let value = p.get_value(program);
outputs.push(value);
InstructionResult::Continue(self.len())
}
Instruction::Terminate => {
InstructionResult::Halt
}
Instruction::LessThan { first, second, out } => {
let result = if first.get_value(program) < second.get_value(program) {
1
} else {
0
};
program[*out as usize] = result;
InstructionResult::Continue(self.len())
}
Instruction::Equals { first, second, out } => {
let result = if first.get_value(program) == second.get_value(program) {
1
} else {
0
};
program[*out as usize] = result;
InstructionResult::Continue(self.len())
}
Instruction::JumpIfTrue { value, target } => {
let v = value.get_value(program);
if v != 0 {
InstructionResult::GoTo(target.get_value(program))
} else {
InstructionResult::Continue(self.len())
}
}
Instruction::JumpIfFalse { value, target } => {
let v = value.get_value(program);
if v == 0 {
InstructionResult::GoTo(target.get_value(program))
} else {
InstructionResult::Continue(self.len())
}
}
}
}
}
#[derive(Debug)]
enum InstructionResult {
Continue(i32),
GoTo(i32),
Halt,
}
struct ExecutionResult {
program: Vec<i32>,
outputs: Vec<i32>,
}
struct Inputs {
values: VecDeque<i32>
}
impl Inputs {
fn new() -> Inputs {
return Inputs {
values: VecDeque::new()
}
}
fn push(&mut self, v: i32) {
self.values.push_back(v)
}
fn next(&mut self) -> i32 {
self.values.pop_front().unwrap_or(0)
}
}
impl From<i32> for Inputs {
fn from(v: i32) -> Self {
let mut input = Inputs::new();
input.push(v);
input
}
}
impl From<usize> for Inputs {
fn from(v: usize) -> Self {
(v as i32).into()
}
}
impl From<(i32, i32)> for Inputs {
fn from(v: (i32, i32)) -> Self {
let mut input = Inputs::new();
input.push(v.0);
input.push(v.1);
input
}
}
fn run_intcode(mut program: Vec<i32>, mut input: Inputs) -> ExecutionResult {
let end = program.len() as i32;
let mut outputs = Vec::new();
let mut i = 0;
while i < end {
let op = program[i as usize];
let instruction = Instruction::parse(&i, &program);
let result = instruction.execute(&mut program, &mut input, &mut outputs);
match result {
InstructionResult::Halt => return ExecutionResult { program, outputs },
InstructionResult::Continue(by) => i += by,
InstructionResult::GoTo(target) => i = target,
}
}
ExecutionResult {
program,
outputs,
}
}
struct PhaseResult {
sequence: Vec<i32>,
signal: i32,
}
#[derive(Debug)]
struct Amplifier {
program: Vec<i32>,
instruction_pointer: i32,
name: String,
initial: bool
}
enum AmplifierResult {
Output(i32),
Halt,
}
impl Amplifier {
fn new(program: Vec<i32>, name: char) -> Amplifier {
Amplifier {
program,
instruction_pointer: 0,
name: name.to_string(),
initial: true
}
}
fn run(&mut self, phase: i32, input: i32) -> AmplifierResult {
let end = self.program.len() as i32;
let mut outputs = Vec::new();
while self.instruction_pointer < end {
let op = self.program[self.instruction_pointer as usize];
let instruction = Instruction::parse(&self.instruction_pointer, &self.program);
let mut inputs = if self.initial {
(phase, input).into()
} else {
input.into()
};
self.initial = false;
let result = instruction.execute(&mut self.program, &mut inputs, &mut outputs);
match instruction {
Instruction::Output {..} => {
match result {
InstructionResult::Continue(by) => self.instruction_pointer += by,
_ => panic!("Output is supposed to have a continue result")
}
let o = *outputs.last().unwrap();
return AmplifierResult::Output(o)
}
_ => {
match result {
InstructionResult::Halt => return AmplifierResult::Halt,
InstructionResult::Continue(by) => self.instruction_pointer += by,
InstructionResult::GoTo(target) => self.instruction_pointer = target,
}
}
}
}
unreachable!()
}
}
fn run_for_phase_signal(sequence: &Vec<usize>, program: Vec<i32>) -> i32 {
let mut amplifiers: Vec<Amplifier> = (b'A'..=b'E').map(char::from).map(|name| Amplifier::new(program.clone(), name)).collect();
// println!("amps: {:#?}", amplifiers);
let mut last_e_output = 0;
let mut next_input = 0;
for (index, phase) in sequence.iter().enumerate().cycle() {
let amp = &mut amplifiers[index];
// println!("Running amp: {} with input {} and phase {}", amp.name, next_input, phase);
let result = amp.run(*phase as i32, next_input);
match result {
AmplifierResult::Output(o) => {
// println!("Got output: {} from {}", o, amp.name);
if amp.name == "E" {
last_e_output = o;
}
next_input = o;
},
AmplifierResult::Halt => {
println!("Got halt instruction, last from e: {}", last_e_output);
return last_e_output
},
}
}
// for i in sequence {
// let mut inputs: Inputs = (*i).into();
// inputs.push(next_input);
// let result = run_intcode(program.clone(), inputs);
// next_input = *result.outputs.last().unwrap();
//
// }
next_input
}
fn find_max_phase_signal(program: Vec<i32>, sequence: Vec<usize>) -> PhaseResult {
let amplifier_count = 5;
let max_sequence = sequence.into_iter().permutations(amplifier_count).max_by_key(|sequence| {
run_for_phase_signal(sequence, program.clone())
}).unwrap();
let signal = run_for_phase_signal(&max_sequence, program.clone());
PhaseResult {
signal,
sequence: max_sequence.into_iter().map(|v| v as i32).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
mod max_phase_signal {
use super::*;
// #[test]
// fn example1() {
// let result = find_max_phase_signal(vec![3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0], (0..5).collect());
// assert_eq!(result.signal, 43210);
// assert_eq!(result.sequence, vec![4,3,2,1,0])
// }
//
// #[test]
// fn example2() {
// let result = find_max_phase_signal(vec![3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0], (0..5).collect());
// assert_eq!(result.signal, 54321);
// assert_eq!(result.sequence, vec![0,1,2,3,4])
// }
//
// #[test]
// fn example3() {
// let result = find_max_phase_signal(vec![3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0], (0..5).collect());
// assert_eq!(result.signal, 65210);
// assert_eq!(result.sequence, vec![1,0,4,3,2])
// }
#[test]
fn example4() {
let result = find_max_phase_signal(vec![3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5], (5..=9).collect());
assert_eq!(result.signal, 139629729);
assert_eq!(result.sequence, vec![9,8,7,6,5]);
}
#[test]
fn example5() {
let result = find_max_phase_signal(vec![3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,
-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,
53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10], (5..=9).collect());
assert_eq!(result.signal, 18216);
assert_eq!(result.sequence, vec![9,7,8,5,6]);
}
}
mod intcode_machine {
use super::*;
#[test]
fn example1() {
let result = run_intcode(vec![1, 0, 0, 0, 99], 1.into());
assert_eq!(result.program, vec![2, 0, 0, 0, 99]);
}
#[test]
fn example2() {
let result = run_intcode(vec![2, 3, 0, 3, 99], 1.into());
assert_eq!(result.program, vec![2, 3, 0, 6, 99]);
}
#[test]
fn example3() {
let result = run_intcode(vec![2, 4, 4, 5, 99, 0], 1.into());
assert_eq!(result.program, vec![2, 4, 4, 5, 99, 9801]);
}
#[test]
fn example4() {
let result = run_intcode(vec![1, 1, 1, 4, 99, 5, 6, 0, 99], 1.into());
assert_eq!(result.program, vec![30, 1, 1, 4, 2, 5, 6, 0, 99]);
}
#[test]
fn example5() {
let result = run_intcode(vec![1002, 4, 3, 4, 33], 1.into());
assert_eq!(result.program, vec![1002, 4, 3, 4, 99]);
}
#[test]
fn example6_true() {
let result = run_intcode(vec![3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8], 8.into());
assert_eq!(result.outputs.last().unwrap(), &1);
}
#[test]
fn example6_false() {
let result = run_intcode(vec![3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8], 7.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example7_true() {
let result = run_intcode(vec![3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8], 7.into());
assert_eq!(result.outputs.last().unwrap(), &1);
}
#[test]
fn example7_false() {
let result = run_intcode(vec![3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8], 8.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example7_false2() {
let result = run_intcode(vec![3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8], 9.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example8_true() {
let result = run_intcode(vec![3, 3, 1108, -1, 8, 3, 4, 3, 99], 8.into());
assert_eq!(result.outputs.last().unwrap(), &1);
}
#[test]
fn example8_false1() {
let result = run_intcode(vec![3, 3, 1108, -1, 8, 3, 4, 3, 99], 7.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example8_false2() {
let result = run_intcode(vec![3, 3, 1108, -1, 8, 3, 4, 3, 99], 9.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example9_true() {
let result = run_intcode(vec![3, 3, 1107, -1, 8, 3, 4, 3, 99], 7.into());
assert_eq!(result.outputs.last().unwrap(), &1);
}
#[test]
fn example9_false1() {
let result = run_intcode(vec![3, 3, 1107, -1, 8, 3, 4, 3, 99], 8.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example9_false2() {
let result = run_intcode(vec![3, 3, 1107, -1, 8, 3, 4, 3, 99], 9.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example10() {
let result = run_intcode(vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9], 0.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example10_1() {
let result = run_intcode(vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9], 1.into());
assert_eq!(result.outputs.last().unwrap(), &1);
}
#[test]
fn example10_2() {
let result = run_intcode(vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9], 2.into());
assert_eq!(result.outputs.last().unwrap(), &1);
}
#[test]
fn example11_0() {
let result = run_intcode(vec![3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1], 0.into());
assert_eq!(result.outputs.last().unwrap(), &0);
}
#[test]
fn example11_1() {
let result = run_intcode(vec![3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1], 1.into());
assert_eq!(result.outputs.last().unwrap(), &1);
}
#[test]
fn example11_2() {
let result = run_intcode(vec![3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1], 2.into());
assert_eq!(result.outputs.last().unwrap(), &1);
}
fn get_large_program() -> Vec<i32> {
vec![3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99]
}
#[test]
fn example_large_less_than() {
let result = *run_intcode(get_large_program(), 7.into()).outputs.last().unwrap();
assert_eq!(result, 999);
}
#[test]
fn example_large_equal_to() {
let result = *run_intcode(get_large_program(), 8.into()).outputs.last().unwrap();
assert_eq!(result, 1000);
}
#[test]
fn example_large_greater_than() {
let result = *run_intcode(get_large_program(), 9.into()).outputs.last().unwrap();
assert_eq!(result, 1001);
}
#[test]
fn gets_parameters() {
let opcode = "01105";
let program = vec![1105, 2, 4];
let params = Instruction::parse_parameters(2, opcode, &program, &0);
assert_eq!(params, vec![Parameter::parse("1", &2, &1), Parameter::parse("1", &4, &2)]);
}
}
} |
#[cfg(test)]
mod tests {
use matrix::*;
use vector::*;
use traits::*;
use std::f32;
type Mat2 = Matrix2<f32>;
type Mat3 = Matrix3<f32>;
type Mat4 = Matrix4<f32>;
type Vec2 = Vector2<f32>;
type Vec3 = Vector3<f32>;
type Vec4 = Vector4<f32>;
// --------------------------------------------------------------------------
//
// Matrix2
//
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// Contructors
// --------------------------------------------------------------------------
#[test]
fn matrix2_from_components_row_major() {
let m1 = Mat2::from_components_row_major(1.0, 2.0, 3.0 ,4.0);
let m2 = Mat2{ m00: 1.0, m01: 2.0, m10: 3.0, m11: 4.0 };
assert_eq!(m1, m2);
}
#[test]
fn matrix2_from_components_col_major() {
let m1 = Mat2::from_components_col_major(1.0, 2.0, 3.0, 4.0);
let m2 = Mat2{ m00: 1.0, m10: 2.0, m01: 3.0, m11: 4.0 };
assert_eq!(m1, m2);
}
#[test]
fn matrix2_from_cols() {
let m1 = Mat2::from_cols(Vec2::new(1.0, 2.0), Vec2::new(3.0, 4.0));
let m2 = Mat2{ m00: 1.0, m10: 2.0, m01: 3.0, m11: 4.0 };
assert_eq!(m1, m2);
}
#[test]
fn matrix2_from_rows() {
let m1 = Mat2::from_rows(Vec2::new(1.0, 2.0), Vec2::new(3.0, 4.0));
let m2 = Mat2{ m00: 1.0, m01: 2.0, m10: 3.0, m11: 4.0 };
assert_eq!(m1, m2);
}
#[test]
fn matrix2_identity() {
let m1 = Mat2::identity();
let m2 = Mat2{ m00: 1.0, m01: 0.0, m10: 0.0, m11: 1.0 };
assert_eq!(m1, m2);
}
// --------------------------------------------------------------------------
// access
// --------------------------------------------------------------------------
#[test]
fn matrix2_col() {
assert_eq!(Mat2::identity().col(0), Vec2::new(1.0, 0.0));
}
#[test]
fn matrix2_row() {
assert_eq!(Mat2::identity().row(1), Vec2::new(0.0, 1.0));
}
// --------------------------------------------------------------------------
// transpose
// --------------------------------------------------------------------------
#[test]
fn maxtrix2_from_transpose1() {
let m1 = Mat2::from_components_row_major(1.0, 2.0, 3.0, 4.0);
let m2 = Mat2::from_components_col_major(1.0, 2.0, 3.0, 4.0);
assert_eq!(m1, m2.transpose());
}
#[test]
fn maxtrix2_from_transpose2() {
let m1 = Mat2::from_components_row_major(1.0, 2.0, 3.0, 4.0);
let m2 = Mat2::from_components_col_major(1.0, 2.0, 3.0, 4.0);
assert_eq!(m1.transpose(), m2);
}
#[test]
fn maxtrix2_from_transpose3() {
let m1 = Mat2::from_components_row_major(1.0, 2.0, 3.0, 4.0);
assert_eq!(m1, m1.transpose().transpose());
}
// --------------------------------------------------------------------------
// Mul
// --------------------------------------------------------------------------
#[test]
fn matrix2_mulmv_val_val() {
let m = Mat2::from_components_row_major(1.0, 2.0, 3.0, 4.0);
let v = Vec2::new(5.0, 6.0);
assert_eq!(m*v, Vec2::new(17.0, 39.0));
}
#[test]
fn matrix2_mulmv_ref_mutref() {
let ref m = Mat2::from_components_row_major(1.0, 2.0, 3.0, 4.0);
let ref mut v = Vec2::new(5.0, 6.0);
assert_eq!(m*v, Vec2::new(17.0, 39.0));
}
// --------------------------------------------------------------------------
//
// Matrix3
//
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// Contructors
// --------------------------------------------------------------------------
#[test]
fn matrix3_from_components_row_major() {
let m1 = Mat3::from_components_row_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
let m2 = Mat3{ m00: 1.0, m01: 2.0, m02: 3.0, m10: 4.0, m11: 5.0, m12: 6.0, m20: 7.0, m21: 8.0, m22: 9.0 };
assert_eq!(m1, m2);
}
#[test]
fn matrix3_from_components_col_major() {
let m1 = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
let m2 = Mat3{ m00: 1.0, m10: 2.0, m20: 3.0, m01: 4.0, m11: 5.0, m21: 6.0, m02: 7.0, m12: 8.0, m22: 9.0 };
assert_eq!(m1, m2);
}
#[test]
fn matrix3_from_cols() {
let m1 = Mat3::from_cols(Vec3::new(1.0, 2.0, 3.0), Vec3::new(4.0, 5.0, 6.0), Vec3::new(7.0, 8.0, 9.0));
let m2 = Mat3{ m00: 1.0, m10: 2.0, m20: 3.0, m01: 4.0, m11: 5.0, m21: 6.0, m02: 7.0, m12: 8.0, m22: 9.0 };
assert_eq!(m1, m2);
}
#[test]
fn matrix3_from_rows() {
let m1 = Mat3::from_rows(Vec3::new(1.0, 2.0, 3.0), Vec3::new(4.0, 5.0, 6.0), Vec3::new(7.0, 8.0, 9.0));
let m2 = Mat3{ m00: 1.0, m01: 2.0, m02: 3.0, m10: 4.0, m11: 5.0, m12: 6.0, m20: 7.0, m21: 8.0, m22: 9.0 };
assert_eq!(m1, m2);
}
// --------------------------------------------------------------------------
// col & row & elem
// --------------------------------------------------------------------------
#[test]
fn matrix3_col() {
let m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.col(1), Vec3::new(4.0, 5.0, 6.0));
}
#[test]
fn matrix3_row() {
let m = Mat3::from_components_row_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.row(2), Vec3::new(7.0, 8.0, 9.0));
}
#[test]
fn matrix3_elems() {
let m = Mat3::from_components_row_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.row(1).elem(1), 5.0);
}
// --------------------------------------------------------------------------
// col_elem
// --------------------------------------------------------------------------
#[test]
fn matrix3_col_elem() {
let mut m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
m.set_col_elem(1, 0, 40.0);
assert_eq!(m.col(1).elem(0), 40.0);
}
#[test]
fn matrix3_col_elem_val_to_val() {
let m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.col_elem(1, 1), 5.0);
}
#[test]
fn matrix3_col_elem_ref_to_val() {
let ref m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.col_elem(1, 1), 5.0);
}
#[test]
fn matrix3_col_elem_ref_to_ref() {
let ref m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.col_elem_ref(1, 1), &5.0);
}
#[test]
fn matrix3_col_elem_mutref_to_val() {
let ref mut m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.col_elem(1, 1), 5.0);
}
#[test]
fn matrix3_col_elem_mutref_to_ref() {
let ref mut m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.col_elem_ref(1, 1), &5.0);
}
#[test]
fn matrix3_col_elem_mutref_to_mutref() {
let ref mut m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m.col_elem_mut(1, 1), &mut 5.0);
}
#[test]
fn matrix3_set_col_elem1() {
let mut m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
m.set_col_elem(0, 0, 10.0);
m.set_col_elem(2, 1, 80.0);
assert_eq!(m.col_elem(0, 0), 10.0);
assert_eq!(m.col_elem(2, 1), 80.0);
}
#[test]
fn matrix3_set_col_elem2() {
let mut m = Mat3::zero();
for c in 0..3 {
for r in 0..3 {
m.set_col_elem(c, r, 1.0);
}
}
for c in 0..3 {
for r in 0..3 {
println!("now: {:?}", m.col_elem(c, r));
}
}
println!("this one: {:?}", m);
assert_eq!(m, Mat3::one());
}
// --------------------------------------------------------------------------
// approx_eq
// --------------------------------------------------------------------------
#[test]
fn matrix3_approx_eq1() {
let m1 = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
let mut m2 = m1.clone();
m2.set_col_elem(1, 0, 4.0 + f32::EPSILON);
assert!(m1.approx_eq(&m2, f32::EPSILON, 0));
}
#[test]
fn matrix3_approx_eq2() {
let m1 = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
let mut m2 = m1.clone();
m2.set_col_elem(1, 0, 4.0 + 3.0*f32::EPSILON);
assert!(!m1.approx_eq(&m2, f32::EPSILON, 0));
}
// --------------------------------------------------------------------------
// arrays
// --------------------------------------------------------------------------
#[test]
fn matrix3_as_array() {
let m = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
let a = m.as_array();
assert_eq!(a[0], 1.0);
assert_eq!(a[1], 2.0);
assert_eq!(a[2], 3.0);
assert_eq!(a[3], 4.0);
assert_eq!(a[4], 5.0);
assert_eq!(a[5], 6.0);
assert_eq!(a[6], 7.0);
assert_eq!(a[7], 8.0);
assert_eq!(a[8], 9.0);
}
// --------------------------------------------------------------------------
// transpose
// --------------------------------------------------------------------------
#[test]
fn matrix3_from_transpose1() {
let m1 = Mat3::from_components_row_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
let m2 = Mat3::from_components_col_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m1, m2.transpose());
}
// --------------------------------------------------------------------------
// from_diagional
// --------------------------------------------------------------------------
#[test]
fn matrix3_from_diagonal() {
let m1 = Mat3::from_diagonal(Vec3::new(1.0, 2.0, 3.0));
let m2 = Mat3 { m00: 1.0, m01: 0.0, m02: 0.0, m10: 0.0, m11: 2.0, m12: 0.0, m20: 0.0, m21: 0.0, m22: 3.0 };
assert_eq!(m1, m2);
}
// --------------------------------------------------------------------------
// Mul
// --------------------------------------------------------------------------
#[test]
fn matrix3_mul_val_val1() {
let m1 = Mat3::identity();
let m2 = Mat3::from_components_row_major(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
assert_eq!(m1*m2, m2);
}
#[test]
fn matrix3_mul_val_val2() {
let m1 = Mat3::from_components_row_major(
1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0
);
let m2 = Mat3::from_components_row_major(
1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0
);
let m3 = Mat3::from_components_row_major(
30.0, 36.0, 42.0,
66.0, 81.0, 96.0,
102.0, 126.0, 150.0,
);
assert_eq!(m1*m2, m3);
}
// --------------------------------------------------------------------------
// det
// --------------------------------------------------------------------------
#[test]
fn matrix3_det1() {
let m = Mat3::from_components_row_major(
1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0
);
assert_eq!(m.det(), 0.0);
}
#[test]
fn matrix3_det2() {
let m = Mat3::from_components_row_major(
2.0, 5.0, 2.0,
3.0, -3.0, 1.0,
1.0, 4.0, -4.0
);
assert_eq!(m.det(), 111.0);
}
#[test]
fn matrix3_det3() {
let m = Mat3::from_components_row_major(
5.0, -1.0, 9.0,
-1.0, 6.0, -1.0,
9.0, -1.0, 7.0
);
assert_eq!(m.det(), -270.0);
}
// --------------------------------------------------------------------------
// ApproxEq
// --------------------------------------------------------------------------
#[test]
fn matrix3_approx_eq() {
let m1 = Mat3::from_components_row_major(
2.0, 5.0, 2.0,
3.0, -3.0, 1.0,
1.0, 4.0, -4.0
);
let m2 = Mat3::from_components_row_major(
2.0, 5.0, 2.000000001,
3.0, -3.0, 1.0,
1.0, 4.00000001, -4.0
);
let m3 = Mat3::from_components_row_major(
3.0, 5.0, 2.0,
3.0, -3.0, 1.0,
1.0, 4.0, -6.0
);
assert!(m1.approx_eq(&m2, ::std::f32::EPSILON, 2));
assert!(!m1.approx_eq(&m3, ::std::f32::EPSILON, 2));
}
// --------------------------------------------------------------------------
// inverse
// --------------------------------------------------------------------------
#[test]
fn matrix3_inverse1() {
let m = Mat3::from_components_row_major(
2.0, 5.0, 2.0,
3.0, -3.0, 1.0,
1.0, 4.0, -4.0
);
assert!((m*m.inverse().unwrap()).approx_eq(&Mat3::identity(), f32::EPSILON, 2)); // TODO(henk): What?
}
// --------------------------------------------------------------------------
//
// Matrix4
//
// --------------------------------------------------------------------------
#[test]
fn matrix4_inverse0() {
assert!(Mat4::identity().inverse().unwrap().approx_eq(&Mat4::identity(), ::std::f32::EPSILON, 2));
}
#[test]
fn matrix4_inverse1() {
let m = Mat4::from_components_row_major(
1.0, -2.0, 3.0, 4.0,
-2.0, 3.0, 4.0, 5.0,
3.0, 4.0, 5.0, 6.0,
4.0, 5.0, 6.0, 7.0
);
let result = Mat4::from_components_row_major(
0.0, -4.0/16.0, 8.0/16.0, -4.0/16.0,
-4.0/16.0, 0.0, 12.0/16.0, -8.0/16.0,
8.0/16.0, 12.0/16.0, -160.0/16.0, 124.0/16.0,
-4.0/16.0, -8.0/16.0, 124.0/16.0, -96.0/16.0
);
assert!(m.inverse().unwrap().approx_eq(&result, f32::EPSILON, 2));
}
#[test]
fn matrix4_inverse2() {
let m = Mat4::from_components_row_major(
1.0, -2.0, 3.0, 4.0,
-2.0, 3.0, 4.0, 5.0,
3.0, 4.0, 5.0, 6.0,
4.0, 5.0, 6.0, 7.0
);
assert!((m*m.inverse().unwrap()).approx_eq(&Mat4::identity(), f32::EPSILON, 2));
}
#[test]
fn matrix4_inverse3() {
let m = Mat4::from_components_row_major(
1.0, 0.0, 12.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 4.0, -136.0,
0.0, -2.0, 0.0, 1.0
);
let result = Mat4::from_components_row_major(
1.0, -3264.0/4.0, -12.0/4.0, -1632.0/4.0,
0.0, 1.0, 0.0, 0.0,
0.0, 272.0/4.0, 1.0/4.0, 136.0/4.0,
0.0, 8.0/4.0, 0.0, 1.0
);
println!("m ?= result ... {:?} ?= {:?}", m.inverse().unwrap(), result);
assert!(m.inverse().unwrap().approx_eq(&result, ::std::f32::EPSILON, 2));
}
#[test]
fn matrix4_inverse4() {
let v = Mat4::new_look_at(Vec3::new(0.5, 1.0, 0.5), Vec3::zero(), Vec3::new(0.0, 1.0, 0.0));
let p = Mat4::new_orthographic_from_dimensions(100.0, 80.0, -1.0, 1.0);
let x = Vec4::new(0.6, 0.1, 3.3, 1.0);
println!("p*v = {:?}", p*v);
let u = (p*v*x).wdiv();
let r = (p*v).inverse().unwrap()*Vec4::new(u.x, u.y, u.z, 1.0);
println!("{:?} -> {:?}", x, r);
assert!(x.approx_eq(&r, 2.0*::std::f32::EPSILON, 3));
}
} |
use std::{fs, collections::HashSet};
type Instruction = (char, usize);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
struct Point {
x: isize,
y: isize,
}
impl Point {
fn touching(&self, other: &Self) -> bool {
let x_distance = self.x - other.x;
let y_distance = self.y - other.y;
(-1..=1).contains(&x_distance) && (-1..=1).contains(&y_distance)
}
}
fn parse_instructions(input: &str) -> Vec<Instruction> {
input
.lines()
.map(|line| {
// split at 2, so we get the direction and a space in the first part
// since we use chars().next() for extracting the direction there which
// will trim the space
let (c, n) = line.split_at(2);
(c.chars().next().unwrap(), n.parse().unwrap())
})
.collect()
}
fn do_the_thing(input: &str) -> usize {
let instructions = parse_instructions(input);
let mut head = Point::default();
let mut tail = Point::default();
let mut tail_positions = HashSet::<Point>::new();
for (direction, distance) in instructions {
for _ in 0..distance {
match direction {
'U' => head.y += 1,
'D' => head.y -= 1,
'R' => head.x += 1,
'L' => head.x -= 1,
_ => panic!("Unknown direction"),
}
if !tail.touching(&head) {
match tail.x.cmp(&head.x) {
std::cmp::Ordering::Less => tail.x += 1,
std::cmp::Ordering::Greater => tail.x -= 1,
std::cmp::Ordering::Equal => (),
};
match tail.y.cmp(&head.y) {
std::cmp::Ordering::Less => tail.y += 1,
std::cmp::Ordering::Greater => tail.y -= 1,
std::cmp::Ordering::Equal => (),
};
}
tail_positions.insert(tail);
}
}
tail_positions.len()
}
fn main() {
let input = fs::read_to_string("input.txt").unwrap();
println!("{:?}", do_the_thing(&input));
}
#[cfg(test)]
mod tests {
use super::*;
use test_case::test_case;
#[test_case("R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
" => 13)]
fn test(input: &str) -> usize {
do_the_thing(&input)
}
}
|
use crate::prelude::*;
use crate::{EntriesListView, GenericView, TreeView};
use futures::stream::{self, StreamExt};
use std::sync::{Arc, Mutex};
pub(crate) fn format(input: Vec<Value>, host: &mut dyn Host) {
let last = input.len() - 1;
for (i, item) in input.iter().enumerate() {
let view = GenericView::new(item);
crate::format::print_view(&view, &mut *host);
if last != i {
println!("");
}
}
}
|
#[doc = "Reader of register RTC_HWCFGR"]
pub type R = crate::R<u32, super::RTC_HWCFGR>;
#[doc = "Reader of field `ALARMB`"]
pub type ALARMB_R = crate::R<u8, u8>;
#[doc = "Reader of field `WAKEUP`"]
pub type WAKEUP_R = crate::R<u8, u8>;
#[doc = "Reader of field `SMOOTH_CALIB`"]
pub type SMOOTH_CALIB_R = crate::R<u8, u8>;
#[doc = "Reader of field `TIMESTAMP`"]
pub type TIMESTAMP_R = crate::R<u8, u8>;
#[doc = "Reader of field `OPTIONREG_OUT`"]
pub type OPTIONREG_OUT_R = crate::R<u8, u8>;
#[doc = "Reader of field `TRUST_ZONE`"]
pub type TRUST_ZONE_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:3 - ALARMB"]
#[inline(always)]
pub fn alarmb(&self) -> ALARMB_R {
ALARMB_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:7 - WAKEUP"]
#[inline(always)]
pub fn wakeup(&self) -> WAKEUP_R {
WAKEUP_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:11 - SMOOTH_CALIB"]
#[inline(always)]
pub fn smooth_calib(&self) -> SMOOTH_CALIB_R {
SMOOTH_CALIB_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - TIMESTAMP"]
#[inline(always)]
pub fn timestamp(&self) -> TIMESTAMP_R {
TIMESTAMP_R::new(((self.bits >> 12) & 0x0f) as u8)
}
#[doc = "Bits 16:23 - OPTIONREG_OUT"]
#[inline(always)]
pub fn optionreg_out(&self) -> OPTIONREG_OUT_R {
OPTIONREG_OUT_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:27 - TRUST_ZONE"]
#[inline(always)]
pub fn trust_zone(&self) -> TRUST_ZONE_R {
TRUST_ZONE_R::new(((self.bits >> 24) & 0x0f) as u8)
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// WidgetDefinition : [Definition of the widget](https://docs.datadoghq.com/dashboards/widgets/).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WidgetDefinition {
/// ID of the alert to use in the widget.
#[serde(rename = "alert_id")]
pub alert_id: String,
#[serde(rename = "time", skip_serializing_if = "Option::is_none")]
pub time: Option<Box<crate::models::WidgetTime>>,
/// Title of your widget.
#[serde(rename = "title", skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(rename = "title_align", skip_serializing_if = "Option::is_none")]
pub title_align: Option<crate::models::WidgetTextAlign>,
/// Size of the title.
#[serde(rename = "title_size", skip_serializing_if = "Option::is_none")]
pub title_size: Option<String>,
#[serde(rename = "type")]
pub _type: crate::models::ToplistWidgetDefinitionType,
#[serde(rename = "viz_type")]
pub viz_type: crate::models::WidgetVizType,
/// Number of decimals to show. If not defined, the widget uses the raw value.
#[serde(rename = "precision", skip_serializing_if = "Option::is_none")]
pub precision: Option<i64>,
#[serde(rename = "text_align", skip_serializing_if = "Option::is_none")]
pub text_align: Option<crate::models::WidgetTextAlign>,
/// Unit to display with the value.
#[serde(rename = "unit", skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
/// List of custom links.
#[serde(rename = "custom_links", skip_serializing_if = "Option::is_none")]
pub custom_links: Option<Vec<crate::models::WidgetCustomLink>>,
/// List of top list widget requests.
#[serde(rename = "requests")]
pub requests: Vec<crate::models::ToplistWidgetRequest>,
/// Name of the check to use in the widget.
#[serde(rename = "check")]
pub check: String,
/// List of tag prefixes to group by.
#[serde(rename = "group", skip_serializing_if = "Option::is_none")]
pub group: Option<Vec<String>>,
/// List of tag prefixes to group by in the case of a cluster check.
#[serde(rename = "group_by", skip_serializing_if = "Option::is_none")]
pub group_by: Option<Vec<String>>,
#[serde(rename = "grouping")]
pub grouping: crate::models::WidgetGrouping,
/// List of tags used to filter the groups reporting a cluster check.
#[serde(rename = "tags", skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
/// Available legend sizes for a widget. Should be one of \"0\", \"2\", \"4\", \"8\", \"16\", or \"auto\".
#[serde(rename = "legend_size", skip_serializing_if = "Option::is_none")]
pub legend_size: Option<String>,
/// List of markers.
#[serde(rename = "markers", skip_serializing_if = "Option::is_none")]
pub markers: Option<Vec<crate::models::WidgetMarker>>,
/// (screenboard only) Show the legend for this widget.
#[serde(rename = "show_legend", skip_serializing_if = "Option::is_none")]
pub show_legend: Option<bool>,
#[serde(rename = "xaxis", skip_serializing_if = "Option::is_none")]
pub xaxis: Option<Box<crate::models::WidgetAxis>>,
#[serde(rename = "yaxis", skip_serializing_if = "Option::is_none")]
pub yaxis: Option<Box<crate::models::WidgetAxis>>,
#[serde(rename = "event_size", skip_serializing_if = "Option::is_none")]
pub event_size: Option<crate::models::WidgetEventSize>,
/// Query to filter the monitors with.
#[serde(rename = "query")]
pub query: String,
/// The execution method for multi-value filters. Can be either and or or.
#[serde(rename = "tags_execution", skip_serializing_if = "Option::is_none")]
pub tags_execution: Option<String>,
/// Color of the text.
#[serde(rename = "color", skip_serializing_if = "Option::is_none")]
pub color: Option<String>,
/// Size of the text.
#[serde(rename = "font_size", skip_serializing_if = "Option::is_none")]
pub font_size: Option<String>,
/// Text to display.
#[serde(rename = "text")]
pub text: String,
#[serde(rename = "style")]
pub style: Box<crate::models::HostMapWidgetDefinitionStyle>,
#[serde(rename = "view")]
pub view: Box<crate::models::GeomapWidgetDefinitionView>,
/// Background color of the note.
#[serde(rename = "background_color", skip_serializing_if = "Option::is_none")]
pub background_color: Option<String>,
/// URL of image to display as a banner for the group.
#[serde(rename = "banner_img", skip_serializing_if = "Option::is_none")]
pub banner_img: Option<String>,
#[serde(rename = "layout_type")]
pub layout_type: crate::models::WidgetLayoutType,
/// Whether to show the title or not.
#[serde(rename = "show_title", skip_serializing_if = "Option::is_none")]
pub show_title: Option<bool>,
/// List of widget groups.
#[serde(rename = "widgets")]
pub widgets: Vec<crate::models::Widget>,
/// List of widget events.
#[serde(rename = "events", skip_serializing_if = "Option::is_none")]
pub events: Option<Vec<crate::models::WidgetEvent>>,
/// Whether to show the hosts that don’t fit in a group.
#[serde(rename = "no_group_hosts", skip_serializing_if = "Option::is_none")]
pub no_group_hosts: Option<bool>,
/// Whether to show the hosts with no metrics.
#[serde(rename = "no_metric_hosts", skip_serializing_if = "Option::is_none")]
pub no_metric_hosts: Option<bool>,
#[serde(rename = "node_type", skip_serializing_if = "Option::is_none")]
pub node_type: Option<crate::models::WidgetNodeType>,
/// Notes on the title.
#[serde(rename = "notes", skip_serializing_if = "Option::is_none")]
pub notes: Option<String>,
/// List of tags used to filter the map.
#[serde(rename = "scope", skip_serializing_if = "Option::is_none")]
pub scope: Option<Vec<String>>,
/// URL of the image.
#[serde(rename = "url")]
pub url: String,
/// Whether to display a background or not.
#[serde(rename = "has_background", skip_serializing_if = "Option::is_none")]
pub has_background: Option<bool>,
/// Whether to display a border or not.
#[serde(rename = "has_border", skip_serializing_if = "Option::is_none")]
pub has_border: Option<bool>,
#[serde(rename = "horizontal_align", skip_serializing_if = "Option::is_none")]
pub horizontal_align: Option<crate::models::WidgetHorizontalAlign>,
#[serde(rename = "margin", skip_serializing_if = "Option::is_none")]
pub margin: Option<crate::models::WidgetMargin>,
#[serde(rename = "sizing", skip_serializing_if = "Option::is_none")]
pub sizing: Option<crate::models::WidgetImageSizing>,
/// URL of the image in dark mode.
#[serde(rename = "url_dark_theme", skip_serializing_if = "Option::is_none")]
pub url_dark_theme: Option<String>,
#[serde(rename = "vertical_align", skip_serializing_if = "Option::is_none")]
pub vertical_align: Option<crate::models::WidgetVerticalAlign>,
/// Which columns to display on the widget.
#[serde(rename = "columns", skip_serializing_if = "Option::is_none")]
pub columns: Option<Vec<String>>,
/// An array of index names to query in the stream. Use [] to query all indexes at once.
#[serde(rename = "indexes", skip_serializing_if = "Option::is_none")]
pub indexes: Option<Vec<String>>,
/// ID of the log set to use.
#[serde(rename = "logset", skip_serializing_if = "Option::is_none")]
pub logset: Option<String>,
#[serde(rename = "message_display", skip_serializing_if = "Option::is_none")]
pub message_display: Option<crate::models::WidgetMessageDisplay>,
/// Whether to show the date column or not
#[serde(rename = "show_date_column", skip_serializing_if = "Option::is_none")]
pub show_date_column: Option<bool>,
/// Whether to show the message column or not
#[serde(rename = "show_message_column", skip_serializing_if = "Option::is_none")]
pub show_message_column: Option<bool>,
#[serde(rename = "sort", skip_serializing_if = "Option::is_none")]
pub sort: Option<crate::models::WidgetMonitorSummarySort>,
#[serde(rename = "color_preference", skip_serializing_if = "Option::is_none")]
pub color_preference: Option<crate::models::WidgetColorPreference>,
/// The number of monitors to display.
#[serde(rename = "count", skip_serializing_if = "Option::is_none")]
pub count: Option<i64>,
#[serde(rename = "display_format", skip_serializing_if = "Option::is_none")]
pub display_format: Option<crate::models::WidgetServiceSummaryDisplayFormat>,
/// Whether to show counts of 0 or not.
#[serde(rename = "hide_zero_counts", skip_serializing_if = "Option::is_none")]
pub hide_zero_counts: Option<bool>,
/// Whether to show the time that has elapsed since the monitor/group triggered.
#[serde(rename = "show_last_triggered", skip_serializing_if = "Option::is_none")]
pub show_last_triggered: Option<bool>,
/// The start of the list. Typically 0.
#[serde(rename = "start", skip_serializing_if = "Option::is_none")]
pub start: Option<i64>,
#[serde(rename = "summary_type", skip_serializing_if = "Option::is_none")]
pub summary_type: Option<crate::models::WidgetSummaryType>,
/// Content of the note.
#[serde(rename = "content")]
pub content: String,
/// Whether to add padding or not.
#[serde(rename = "has_padding", skip_serializing_if = "Option::is_none")]
pub has_padding: Option<bool>,
/// Whether to show a tick or not.
#[serde(rename = "show_tick", skip_serializing_if = "Option::is_none")]
pub show_tick: Option<bool>,
#[serde(rename = "tick_edge", skip_serializing_if = "Option::is_none")]
pub tick_edge: Option<crate::models::WidgetTickEdge>,
/// Where to position the tick on an edge.
#[serde(rename = "tick_pos", skip_serializing_if = "Option::is_none")]
pub tick_pos: Option<String>,
/// Whether to use auto-scaling or not.
#[serde(rename = "autoscale", skip_serializing_if = "Option::is_none")]
pub autoscale: Option<bool>,
/// Display a unit of your choice on the widget.
#[serde(rename = "custom_unit", skip_serializing_if = "Option::is_none")]
pub custom_unit: Option<String>,
/// List of groups used for colors.
#[serde(rename = "color_by_groups", skip_serializing_if = "Option::is_none")]
pub color_by_groups: Option<Vec<String>>,
/// Defined global time target.
#[serde(rename = "global_time_target", skip_serializing_if = "Option::is_none")]
pub global_time_target: Option<String>,
/// Defined error budget.
#[serde(rename = "show_error_budget", skip_serializing_if = "Option::is_none")]
pub show_error_budget: Option<bool>,
/// ID of the SLO displayed.
#[serde(rename = "slo_id", skip_serializing_if = "Option::is_none")]
pub slo_id: Option<String>,
/// Times being monitored.
#[serde(rename = "time_windows", skip_serializing_if = "Option::is_none")]
pub time_windows: Option<Vec<crate::models::WidgetTimeWindows>>,
#[serde(rename = "view_mode", skip_serializing_if = "Option::is_none")]
pub view_mode: Option<crate::models::WidgetViewMode>,
/// Type of view displayed by the widget.
#[serde(rename = "view_type")]
pub view_type: String,
/// Your environment and primary tag (or * if enabled for your account).
#[serde(rename = "filters")]
pub filters: Vec<String>,
/// APM service.
#[serde(rename = "service")]
pub service: String,
/// APM environment.
#[serde(rename = "env")]
pub env: String,
/// Whether to show the latency breakdown or not.
#[serde(rename = "show_breakdown", skip_serializing_if = "Option::is_none")]
pub show_breakdown: Option<bool>,
/// Whether to show the latency distribution or not.
#[serde(rename = "show_distribution", skip_serializing_if = "Option::is_none")]
pub show_distribution: Option<bool>,
/// Whether to show the error metrics or not.
#[serde(rename = "show_errors", skip_serializing_if = "Option::is_none")]
pub show_errors: Option<bool>,
/// Whether to show the hits metrics or not.
#[serde(rename = "show_hits", skip_serializing_if = "Option::is_none")]
pub show_hits: Option<bool>,
/// Whether to show the latency metrics or not.
#[serde(rename = "show_latency", skip_serializing_if = "Option::is_none")]
pub show_latency: Option<bool>,
/// Whether to show the resource list or not.
#[serde(rename = "show_resource_list", skip_serializing_if = "Option::is_none")]
pub show_resource_list: Option<bool>,
#[serde(rename = "size_format", skip_serializing_if = "Option::is_none")]
pub size_format: Option<crate::models::WidgetSizeFormat>,
/// APM span name.
#[serde(rename = "span_name")]
pub span_name: String,
#[serde(rename = "has_search_bar", skip_serializing_if = "Option::is_none")]
pub has_search_bar: Option<crate::models::TableWidgetHasSearchBar>,
/// Columns displayed in the legend.
#[serde(rename = "legend_columns", skip_serializing_if = "Option::is_none")]
pub legend_columns: Option<Vec<crate::models::TimeseriesWidgetLegendColumn>>,
#[serde(rename = "legend_layout", skip_serializing_if = "Option::is_none")]
pub legend_layout: Option<crate::models::TimeseriesWidgetLegendLayout>,
#[serde(rename = "right_yaxis", skip_serializing_if = "Option::is_none")]
pub right_yaxis: Option<Box<crate::models::WidgetAxis>>,
}
impl WidgetDefinition {
/// [Definition of the widget](https://docs.datadoghq.com/dashboards/widgets/).
pub fn new(alert_id: String, _type: crate::models::ToplistWidgetDefinitionType, viz_type: crate::models::WidgetVizType, requests: Vec<crate::models::ToplistWidgetRequest>, check: String, grouping: crate::models::WidgetGrouping, query: String, text: String, style: crate::models::HostMapWidgetDefinitionStyle, view: crate::models::GeomapWidgetDefinitionView, layout_type: crate::models::WidgetLayoutType, widgets: Vec<crate::models::Widget>, url: String, content: String, view_type: String, filters: Vec<String>, service: String, env: String, span_name: String) -> WidgetDefinition {
WidgetDefinition {
alert_id,
time: None,
title: None,
title_align: None,
title_size: None,
_type,
viz_type,
precision: None,
text_align: None,
unit: None,
custom_links: None,
requests,
check,
group: None,
group_by: None,
grouping,
tags: None,
legend_size: None,
markers: None,
show_legend: None,
xaxis: None,
yaxis: None,
event_size: None,
query,
tags_execution: None,
color: None,
font_size: None,
text,
style: Box::new(style),
view: Box::new(view),
background_color: None,
banner_img: None,
layout_type,
show_title: None,
widgets,
events: None,
no_group_hosts: None,
no_metric_hosts: None,
node_type: None,
notes: None,
scope: None,
url,
has_background: None,
has_border: None,
horizontal_align: None,
margin: None,
sizing: None,
url_dark_theme: None,
vertical_align: None,
columns: None,
indexes: None,
logset: None,
message_display: None,
show_date_column: None,
show_message_column: None,
sort: None,
color_preference: None,
count: None,
display_format: None,
hide_zero_counts: None,
show_last_triggered: None,
start: None,
summary_type: None,
content,
has_padding: None,
show_tick: None,
tick_edge: None,
tick_pos: None,
autoscale: None,
custom_unit: None,
color_by_groups: None,
global_time_target: None,
show_error_budget: None,
slo_id: None,
time_windows: None,
view_mode: None,
view_type,
filters,
service,
env,
show_breakdown: None,
show_distribution: None,
show_errors: None,
show_hits: None,
show_latency: None,
show_resource_list: None,
size_format: None,
span_name,
has_search_bar: None,
legend_columns: None,
legend_layout: None,
right_yaxis: None,
}
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// PagerDutyServiceKey : PagerDuty service object key.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PagerDutyServiceKey {
/// Your service key in PagerDuty.
#[serde(rename = "service_key")]
pub service_key: String,
}
impl PagerDutyServiceKey {
/// PagerDuty service object key.
pub fn new(service_key: String) -> PagerDutyServiceKey {
PagerDutyServiceKey {
service_key,
}
}
}
|
#[doc = "Register `CFGR` reader"]
pub type R = crate::R<CFGR_SPEC>;
#[doc = "Register `CFGR` writer"]
pub type W = crate::W<CFGR_SPEC>;
#[doc = "Field `CM4L` reader - CM4L"]
pub type CM4L_R = crate::BitReader;
#[doc = "Field `CM4L` writer - CM4L"]
pub type CM4L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PVDL` reader - PVDL"]
pub type PVDL_R = crate::BitReader;
#[doc = "Field `PVDL` writer - PVDL"]
pub type PVDL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FLASHL` reader - FLASHL"]
pub type FLASHL_R = crate::BitReader;
#[doc = "Field `FLASHL` writer - FLASHL"]
pub type FLASHL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CM7L` reader - CM7L"]
pub type CM7L_R = crate::BitReader;
#[doc = "Field `CM7L` writer - CM7L"]
pub type CM7L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `BKRAML` reader - BKRAML"]
pub type BKRAML_R = crate::BitReader;
#[doc = "Field `BKRAML` writer - BKRAML"]
pub type BKRAML_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM4L` reader - SRAM4L"]
pub type SRAM4L_R = crate::BitReader;
#[doc = "Field `SRAM4L` writer - SRAM4L"]
pub type SRAM4L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM3L` reader - SRAM3L"]
pub type SRAM3L_R = crate::BitReader;
#[doc = "Field `SRAM3L` writer - SRAM3L"]
pub type SRAM3L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM2L` reader - SRAM2L"]
pub type SRAM2L_R = crate::BitReader;
#[doc = "Field `SRAM2L` writer - SRAM2L"]
pub type SRAM2L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SRAM1L` reader - SRAM1L"]
pub type SRAM1L_R = crate::BitReader;
#[doc = "Field `SRAM1L` writer - SRAM1L"]
pub type SRAM1L_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DTCML` reader - DTCML"]
pub type DTCML_R = crate::BitReader;
#[doc = "Field `DTCML` writer - DTCML"]
pub type DTCML_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ITCML` reader - ITCML"]
pub type ITCML_R = crate::BitReader;
#[doc = "Field `ITCML` writer - ITCML"]
pub type ITCML_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AXISRAML` reader - AXISRAML"]
pub type AXISRAML_R = crate::BitReader;
#[doc = "Field `AXISRAML` writer - AXISRAML"]
pub type AXISRAML_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - CM4L"]
#[inline(always)]
pub fn cm4l(&self) -> CM4L_R {
CM4L_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 2 - PVDL"]
#[inline(always)]
pub fn pvdl(&self) -> PVDL_R {
PVDL_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - FLASHL"]
#[inline(always)]
pub fn flashl(&self) -> FLASHL_R {
FLASHL_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 6 - CM7L"]
#[inline(always)]
pub fn cm7l(&self) -> CM7L_R {
CM7L_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - BKRAML"]
#[inline(always)]
pub fn bkraml(&self) -> BKRAML_R {
BKRAML_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 9 - SRAM4L"]
#[inline(always)]
pub fn sram4l(&self) -> SRAM4L_R {
SRAM4L_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - SRAM3L"]
#[inline(always)]
pub fn sram3l(&self) -> SRAM3L_R {
SRAM3L_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - SRAM2L"]
#[inline(always)]
pub fn sram2l(&self) -> SRAM2L_R {
SRAM2L_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - SRAM1L"]
#[inline(always)]
pub fn sram1l(&self) -> SRAM1L_R {
SRAM1L_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - DTCML"]
#[inline(always)]
pub fn dtcml(&self) -> DTCML_R {
DTCML_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - ITCML"]
#[inline(always)]
pub fn itcml(&self) -> ITCML_R {
ITCML_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - AXISRAML"]
#[inline(always)]
pub fn axisraml(&self) -> AXISRAML_R {
AXISRAML_R::new(((self.bits >> 15) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - CM4L"]
#[inline(always)]
#[must_use]
pub fn cm4l(&mut self) -> CM4L_W<CFGR_SPEC, 0> {
CM4L_W::new(self)
}
#[doc = "Bit 2 - PVDL"]
#[inline(always)]
#[must_use]
pub fn pvdl(&mut self) -> PVDL_W<CFGR_SPEC, 2> {
PVDL_W::new(self)
}
#[doc = "Bit 3 - FLASHL"]
#[inline(always)]
#[must_use]
pub fn flashl(&mut self) -> FLASHL_W<CFGR_SPEC, 3> {
FLASHL_W::new(self)
}
#[doc = "Bit 6 - CM7L"]
#[inline(always)]
#[must_use]
pub fn cm7l(&mut self) -> CM7L_W<CFGR_SPEC, 6> {
CM7L_W::new(self)
}
#[doc = "Bit 7 - BKRAML"]
#[inline(always)]
#[must_use]
pub fn bkraml(&mut self) -> BKRAML_W<CFGR_SPEC, 7> {
BKRAML_W::new(self)
}
#[doc = "Bit 9 - SRAM4L"]
#[inline(always)]
#[must_use]
pub fn sram4l(&mut self) -> SRAM4L_W<CFGR_SPEC, 9> {
SRAM4L_W::new(self)
}
#[doc = "Bit 10 - SRAM3L"]
#[inline(always)]
#[must_use]
pub fn sram3l(&mut self) -> SRAM3L_W<CFGR_SPEC, 10> {
SRAM3L_W::new(self)
}
#[doc = "Bit 11 - SRAM2L"]
#[inline(always)]
#[must_use]
pub fn sram2l(&mut self) -> SRAM2L_W<CFGR_SPEC, 11> {
SRAM2L_W::new(self)
}
#[doc = "Bit 12 - SRAM1L"]
#[inline(always)]
#[must_use]
pub fn sram1l(&mut self) -> SRAM1L_W<CFGR_SPEC, 12> {
SRAM1L_W::new(self)
}
#[doc = "Bit 13 - DTCML"]
#[inline(always)]
#[must_use]
pub fn dtcml(&mut self) -> DTCML_W<CFGR_SPEC, 13> {
DTCML_W::new(self)
}
#[doc = "Bit 14 - ITCML"]
#[inline(always)]
#[must_use]
pub fn itcml(&mut self) -> ITCML_W<CFGR_SPEC, 14> {
ITCML_W::new(self)
}
#[doc = "Bit 15 - AXISRAML"]
#[inline(always)]
#[must_use]
pub fn axisraml(&mut self) -> AXISRAML_W<CFGR_SPEC, 15> {
AXISRAML_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr::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 [`cfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CFGR_SPEC;
impl crate::RegisterSpec for CFGR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cfgr::R`](R) reader structure"]
impl crate::Readable for CFGR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cfgr::W`](W) writer structure"]
impl crate::Writable for CFGR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CFGR to value 0"]
impl crate::Resettable for CFGR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
/*
* Rust自習(std::time::Instant)
* CreatedAt: 2019-07-26
*/
fn main() {
let ins = std::time::Instant::now();
println!("{:?}", ins);
}
|
use rand::rngs::ThreadRng;
use super::Material;
use crate::ray::Ray;
use crate::shape::HitRecord;
use crate::vec3::{Color, Vec3};
pub struct Metal {
color: Color,
fuzz: f64,
}
impl Metal {
pub fn new(color: Color, fuzz: f64) -> Self {
Self { color, fuzz }
}
}
impl Default for Metal {
fn default() -> Self {
Self {
color: Color::default(),
fuzz: 0.0,
}
}
}
impl Material for Metal {
fn scatter(&self, ray: &Ray, rec: &HitRecord, rng: &mut ThreadRng) -> Option<(Ray, Color)> {
let reflected = ray.direction().reflect(rec.normal());
let scattered = Ray::new(
rec.point(),
reflected + self.fuzz * Vec3::rand_in_unit_sphere(rng),
ray.time(),
);
let attenuation = self.color;
Some((scattered, attenuation))
}
}
|
/*
Copyright 2016 Robert Lathrop
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.*/
/// This module just declares the Moveable trait.
extern crate mio;
pub mod player;
pub mod connected;
pub mod item;
pub mod teleporter;
use game::gamemap::GameMap;
/// Enum for the direction that a moveable object just went. Gets sent to the connection when
/// deciding what tile to draw.
#[derive(Clone)]
pub enum Direction {
All,
North,
South,
East,
West,
NorthWest,
NorthEast,
SouthWest,
SouthEast,
}
///This is used to indicate the type, since there is no instanceOf in rust
pub enum ControllableType{
Road,
Wall,
Player,
Item,
Teleporter,
}
///This trait is used to define a set of functions for moveable objects. Helps with pathfinding.
pub trait Controllable {
///Called every game loop to update it
fn update(&mut self, width: u8, height: u8, blocked: &Vec<bool>) -> Option<Vec<(mio::Token, u8, String)>>;
///Used when drawing the screen
fn get_location(&self) -> u32;
///Gets the artwork
fn get_tile(&self) -> String;
///Gets the Item size
fn get_size(&self) -> (u32, u32);
///Get the token
fn get_token(&self) -> Option<mio::Token>;
///gets the current HP, if any
fn get_hp(&self) -> Option<i32>;
///moves an object
fn set_location(&mut self, index: u32);
///true if blocks player movement
fn does_block_index(&self, index: u32) -> bool;
///whether or not to try to draw this on the MapScreen
fn is_visible(&self, map: &GameMap) -> bool;
///Reduces a targets HP by damage (if supported)
fn hurt(&mut self, damage: i32);
///Sets the end location for some movement
fn set_movement(&mut self, end: u32);
///Adds a command to the queue
fn push_command(&mut self, command: String);
///Gets the correct direction tile for roads. This well connect any RoadWall objects
///of the same Road or Wall type.
fn modify_connected_tiles(&mut self, width: u8, height: u8, objects : &Vec<bool>);
///Returns a type because rust does not have instanceOf.
fn get_type(&self) -> ControllableType;
///Returns the dimensions of the screen to send down
fn get_viewport(&self) -> (u8, u8);
}
|
use super::auto::{HasInner, Abstract};
use super::container::{Container, ContainerInner};
use super::control::{Control};
use super::member::{Member, AMember, MemberBase};
define_abstract! {
SingleContainer: Container {
outer: {
fn set_child(&mut self, child: Option<Box<dyn Control>>) -> Option<Box<dyn Control>>;
fn child(&self) -> Option<&dyn Control>;
fn child_mut(&mut self) -> Option<&mut dyn Control>;
}
inner: {
fn set_child(&mut self, base: &mut MemberBase, child: Option<Box<dyn Control>>) -> Option<Box<dyn Control>>;
fn child(&self) -> Option<&dyn Control>;
fn child_mut(&mut self) -> Option<&mut dyn Control>;
}
}
}
impl<T: SingleContainerInner> SingleContainer for AMember<T> {
#[inline]
fn set_child(&mut self, child: Option<Box<dyn Control>>) -> Option<Box<dyn Control>> {
self.inner.set_child(&mut self.base, child)
}
#[inline]
fn child(&self) -> Option<&dyn Control> {
self.inner.child()
}
#[inline]
fn child_mut(&mut self) -> Option<&mut dyn Control> {
self.inner.child_mut()
}
#[inline]
fn as_single_container(&self) -> &dyn SingleContainer {
self
}
#[inline]
fn as_single_container_mut(&mut self) -> &mut dyn SingleContainer {
self
}
#[inline]
fn into_single_container(self: Box<Self>) -> Box<dyn SingleContainer> {
self
}
}
impl<II: SingleContainerInner, T: HasInner<I = II> + Abstract + 'static> SingleContainerInner for T {
#[inline]
fn set_child(&mut self, base: &mut MemberBase, child: Option<Box<dyn Control>>) -> Option<Box<dyn Control>> {
self.inner_mut().set_child(base, child)
}
#[inline]
fn child(&self) -> Option<&dyn Control> {
self.inner().child()
}
#[inline]
fn child_mut(&mut self) -> Option<&mut dyn Control> {
self.inner_mut().child_mut()
}
}
|
// q0079_word_search
struct Solution;
impl Solution {
pub fn exist(board: Vec<Vec<char>>, word: String) -> bool {
let ref mut used_pos = vec![];
let mut pos_pos = vec![];
for (i, line) in board.iter().enumerate() {
for (j, _) in line.iter().enumerate() {
pos_pos.push((i, j));
}
}
Solution::find_from(used_pos, &word[..], pos_pos, &board)
}
fn find_from(
used_pos: &mut Vec<(usize, usize)>,
word: &str,
pos_pos: Vec<(usize, usize)>,
board: &Vec<Vec<char>>,
) -> bool {
if word == "" {
return true;
}
let first_char = word.chars().next().unwrap();
for p in pos_pos.into_iter() {
if first_char == board[p.0][p.1] {
let mut nc_pos = vec![];
if p.0 != 0 {
nc_pos.push((p.0 - 1, p.1));
}
if p.0 != board.len() - 1 {
nc_pos.push((p.0 + 1, p.1));
}
if p.1 != 0 {
nc_pos.push((p.0, p.1 - 1));
}
if p.1 != board[0].len() - 1 {
nc_pos.push((p.0, p.1 + 1));
}
let nc_pos: Vec<(usize, usize)> = nc_pos
.into_iter()
.filter(|pp| !used_pos.contains(pp))
.collect();
// if nc_pos.is_empty() {
// return false;
// }
used_pos.push(p);
if Solution::find_from(used_pos, &word[1..], nc_pos, board) {
return true;
}
used_pos.pop();
}
}
return false;
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn it_works() {
let board = vec![
vec!['A', 'B', 'C', 'E'],
vec!['S', 'F', 'C', 'S'],
vec!['A', 'D', 'E', 'E'],
];
assert_eq!(true, Solution::exist(board.clone(), String::from("ABCCED")));
assert_eq!(true, Solution::exist(board.clone(), String::from("SEE")));
assert_eq!(false, Solution::exist(board.clone(), String::from("ABCB")));
assert_eq!(false, Solution::exist(board.clone(), String::from("ABCB")));
assert_eq!(true, Solution::exist(board.clone(), String::from("A")));
assert_eq!(true, Solution::exist(vec![vec!['A']], String::from("A")));
}
}
|
use response::{Links, Meta};
#[derive(Deserialize, Debug, Clone)]
pub struct Pages {
pub first: Option<String>,
pub prev: Option<String>,
pub next: Option<String>,
pub last: Option<String>,
}
#[derive(Deserialize)]
pub struct RawPagedResponse<T> {
pub collection: Vec<T>,
pub links: Links,
pub meta: Meta,
}
pub trait NewIter {
type Item;
fn new() -> Vec<Self::Item> { vec![] }
}
impl<R> NewIter for R
where R: Iterator
{
type Item = <Self as Iterator>::Item;
}
|
//! Union-find data structure, see [`UnionFind`].
use slotmap::{Key, SecondaryMap};
/// Union-find data structure.
///
/// Used to efficiently track sets of equivalent items.
///
/// <https://en.wikipedia.org/wiki/Disjoint-set_data_structure>
#[derive(Default, Clone)]
pub struct UnionFind<K>
where
K: Key,
{
links: SecondaryMap<K, K>,
}
impl<K> UnionFind<K>
where
K: Key,
{
/// Creates a new `UnionFind`, same as [`Default::default()`].
#[allow(dead_code)]
pub fn new() -> Self {
Self::default()
}
/// Creates a new `UnionFind` with the given key capacity pre-allocated.
pub fn with_capacity(capacity: usize) -> Self {
Self {
links: SecondaryMap::with_capacity(capacity),
}
}
/// Combines two items `a` and `b` as equivalent, in the same set.
pub fn union(&mut self, a: K, b: K) {
let i = self.find(a);
let j = self.find(b);
if i == j {
return;
}
self.links[i] = j;
}
/// Finds the "representative" item for `k`. Each set of equivalent items is represented by one
/// of its member items.
pub fn find(&mut self, k: K) -> K {
if let Some(next) = self.links.insert(k, k) {
if k == next {
return k;
}
self.links[k] = self.find(next);
}
self.links[k]
}
/// Returns if `a` and `b` are equivalent, i.e. in the same set.
pub fn same_set(&mut self, a: K, b: K) -> bool {
self.find(a) == self.find(b)
}
}
#[cfg(test)]
mod test {
use slotmap::SlotMap;
use super::*;
#[test]
fn test_basic() {
let mut sm = SlotMap::new();
let a = sm.insert(());
let b = sm.insert(());
let c = sm.insert(());
let d = sm.insert(());
let mut uf = UnionFind::new();
assert!(!uf.same_set(a, b));
uf.union(a, b);
assert!(uf.same_set(a, b));
uf.union(c, a);
assert!(uf.same_set(b, c));
assert!(!uf.same_set(a, d));
assert!(!uf.same_set(b, d));
assert!(!uf.same_set(d, c));
}
}
|
/* CANOpen */
/* Standard Industrial Protocol */
/* Uses Include - Robotics, Remote I/O, Safety I/O */
/* General Functions */
pub mod sdo;
pub mod pdo;
pub mod nmt;
use crate::stm32hal::{can::CanMsg};
/* State Commands For CANOpen */
pub const BOOTUP: u8 = 0x00; // Boot up (Initialising)
pub const STOPPED: u8 = 0x04; // Stopped State
pub const OPERATIONAL: u8 = 0x05; // Operationall State
pub const PREOPERATION: u8 = 0x7F; // Pre-Operational State
pub const UNKNOWN: u8 = 0xFF; // Unknown State
/* Function Codes For CANOpen */
pub const NMT: u32 = 0x0000; // Network Management
pub const SYNC: u32 = 0x0080; // Synchronization
pub const EMCY: u32 = 0x0080; // Emergency
pub const TIME: u32 = 0x0100; // Timestamp
pub const TPDO1: u32 = 0x0180; // Process Data Object
pub const RPDO1: u32 = 0x0200; // Process Data Object
pub const TPDO2: u32 = 0x0280; // Process Data Object
pub const RPDO2: u32 = 0x0300; // Process Data Object
pub const TPDO3: u32 = 0x0380; // Process Data Object
pub const RPDO3: u32 = 0x0400; // Process Data Object
pub const TPDO4: u32 = 0x0480; // Process Data Object
pub const RPDO4: u32 = 0x0500; // Process Data Object
pub const TSDO: u32 = 0x0580; // Service Data Object
pub const RSDO: u32 = 0x0600; // Service Data Object
pub const HEARTBEAT: u32 = 0x0700; // Node Monitoring (Heartbeat)
/* Function Code And Node Masks */
const NODE_MASK: u32 = 0x007F; // Standard ID, Node Mask (Not Extended)
const FC_MASK: u32 = 0x0780; // Standard ID, Function Code Mask
pub struct CANOpen {
node: u32, /* Internal Node Address Set By Program 1 - 127 */
state: CANOpenState, /* Internal State Of The Node */
toggle: bool /* Internal Bit For NMT Node Guarding */
}
#[derive(Clone, Copy)]
pub enum CANOpenState {
Bootup = 0x00,
Stopped = 0x04,
Operational = 0x05,
PreOperational = 0x7F,
Unknown = 0xFF
}
pub fn canopen_state_val(state: CANOpenState) -> u8 {
return state as u8;
}
pub fn canopen_state(state: u8) -> CANOpenState {
return match state {
BOOTUP => CANOpenState::Bootup,
STOPPED => CANOpenState::Stopped,
OPERATIONAL => CANOpenState::Operational,
PREOPERATION => CANOpenState::PreOperational,
_ => CANOpenState::Unknown
};
}
impl CANOpen {
pub fn init(node: u32) -> CANOpen {
return CANOpen {
node: node,
state: CANOpenState::Bootup,
toggle: false
};
}
/* Get The Node Of The Remote Message - Standard ID Only */
/* Used Externally To Get The Node Number, Or A Mask Can Applied At Higher Logic */
pub fn get_ext_node(cob_id: u32) -> u32 {
return cob_id & NODE_MASK;
}
/* Get The Node Of The Remote Message - Standard ID Only */
/* Used Against The Master To Get The Node Number, Or A Mask Can Applied At Higher Logic */
pub fn get_source_node(&self, cob_id: u32) -> u32 {
return cob_id & NODE_MASK;
}
/* Get The Function Code Of The Remote Message - Standard ID Only */
/* Used Against The Master Or Slave To Get The Function Code, Or A Mask Can Applied At Higher Logic */
pub fn get_source_fc(&self, cob_id: u32) -> u32 {
return cob_id & FC_MASK;
}
/* Obtain Own Node ID */
pub fn get_node(&self) -> u32 {
return self.node;
}
/* Obtain Own State */
pub fn get_state(&self) -> CANOpenState {
return self.state;
}
pub fn get_state_u8(&self) -> u8 {
return canopen_state_val(self.state);
}
/* Set Internal State */
pub fn set_state(&mut self, state: CANOpenState) {
self.state = state;
}
/* Decision Tree For Messages */
pub fn msg_handler(&self, msg: &mut CanMsg) {
let fc = msg.get_id();
}
/* FOR USE IN DOWN STEAM LOGIC WITHIN*/
/* Client Tx, Server Rx - Used In SDO Creation*/
pub fn get_rsdo(&self) -> u32 {
return RSDO;
}
pub fn get_tsdo(&self) -> u32 {
return TSDO;
}
}
|
fn main() {
use std::io::{self, BufRead};
let stdin = io::stdin();
let snumber = stdin.lock().lines().next().unwrap().unwrap()
.parse::<i32>().unwrap();
let grid = (1..=300).map(|x| (1..=300).map(|y|
(((x+10)*y + snumber)*(x+10)/100)%10 - 5
).collect::<Vec<i32>>()).collect::<Vec<Vec<i32>>>();
let tuples = (0..300 - 3).flat_map(|x|
(0..300 - 3).map(move |y| (x, y)));
let squares = tuples
.map(|(x, y)| (grid[x..x+3].iter()
.map::<i32, _>(|column| column[y..y+3].iter().sum()).sum::<i32>(), (x, y)));
let answer = squares.max().unwrap();
println!("{},{}", (answer.1).0 + 1, (answer.1).1 + 1);
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// WidgetFormula : Formula to be used in a widget query.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WidgetFormula {
/// Expression alias.
#[serde(rename = "alias", skip_serializing_if = "Option::is_none")]
pub alias: Option<String>,
/// String expression built from queries, formulas, and functions.
#[serde(rename = "formula")]
pub formula: String,
#[serde(rename = "limit", skip_serializing_if = "Option::is_none")]
pub limit: Option<Box<crate::models::WidgetFormulaLimit>>,
}
impl WidgetFormula {
/// Formula to be used in a widget query.
pub fn new(formula: String) -> WidgetFormula {
WidgetFormula {
alias: None,
formula,
limit: None,
}
}
}
|
//! Command line interface for operations on the EFI `BootNext` variable.
use clap::{Parser, Subcommand};
use efibootnext::Adapter;
/// The command line app invocation.
#[derive(Parser)]
#[command(name = "efibootnext")]
#[command(about = "Control BootNext EFI variable.", long_about = None)]
struct Invocation {
/// The command that is invoked.
#[command(subcommand)]
command: Command,
}
/// CLI commands.
#[derive(Subcommand)]
enum Command {
/// Prints possbile boot options.
List,
/// Print the given boot option description.
Describe {
/// The boot option to work with.
load_option: String,
/// The format to use when specifying the load option value.
#[arg(short, long, env = "LOAD_OPTION_FORMAT", value_enum, default_value_t = LoadOptionFormat::Hex)]
format: LoadOptionFormat,
},
/// Prints the value of the BootNext EFI variable.
Get,
/// Sets the BootNext EFI variable.
Set {
/// The value to set `BootNext` to.
load_option: String,
/// The format to use when specifying the load option value.
#[arg(short, long, env = "LOAD_OPTION_FORMAT", value_enum, default_value_t = LoadOptionFormat::Hex)]
format: LoadOptionFormat,
},
}
fn main() {
if let Err(err) = run() {
eprintln!("Error: {}", err);
std::process::exit(1);
}
}
/// Run the app and return the error.
fn run() -> Result<(), anyhow::Error> {
let mut adapter = Adapter::default();
let invocation = Invocation::parse();
match invocation.command {
Command::List => {
for load_option_result in adapter.load_options()? {
let load_option = load_option_result?;
println!("{:04X} {}", load_option.number, load_option.description);
}
Ok(())
}
Command::Describe {
format,
load_option,
} => {
let load_option: u16 = format.parse_boot_next(&load_option)?;
let load_option = adapter.get_load_option(load_option)?;
match load_option {
None => println!("unknown"),
Some(load_option) => {
println!("{:04X} {}", load_option.number, load_option.description)
}
}
Ok(())
}
Command::Get => {
let boot_next = adapter.get_boot_next()?;
match boot_next {
None => println!("unset"),
Some(boot_next) => println!("{:04X}", boot_next),
}
Ok(())
}
Command::Set {
format,
load_option,
} => {
let load_option: u16 = format.parse_boot_next(&load_option)?;
adapter.set_boot_next(load_option)?;
println!("{:04X}", load_option);
Ok(())
}
}
}
/// The format of the `BootNext` value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum LoadOptionFormat {
/// The value is a hex number.
#[value(alias("h"))]
#[value(alias("hexadecimal"))]
Hex,
/// The value is a decimal number.
#[value(alias("d"))]
#[value(alias("decimal"))]
Dec,
}
impl LoadOptionFormat {
/// Radix of the underlying numeric format.
pub fn radix(&self) -> u32 {
match self {
LoadOptionFormat::Hex => 16,
LoadOptionFormat::Dec => 10,
}
}
/// Parse the `BootNext` value using the format.
pub fn parse_boot_next(&self, value: &str) -> Result<u16, anyhow::Error> {
let val = u16::from_str_radix(value, self.radix()).map_err(|err| {
anyhow::format_err!("unable to parse the boot option in {self} format: {err}")
})?;
Ok(val)
}
}
impl std::fmt::Display for LoadOptionFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Dec => f.write_str("decimal"),
Self::Hex => f.write_str("hex"),
}
}
}
|
//! This example demonstrates reading a csv string to a [`Table`] struct.
//!
//! * Note the necessary step of representing the string as a byte array.
fn main() {
let syscalls = "\
0,INDIR,,\"int sys_syscall(int number, ...)\"\n\
1,STD,,\"void sys_exit(int rval)\"\n\
2,STD,,\"int sys_fork(void)\"\n\
3,STD,NOLOCK,\"ssize_t sys_read(int fd, void *buf, size_t nbyte)\"\n\
4,STD,NOLOCK,\"ssize_t sys_write(int fd, const void *buf, size_t nbyte)\"";
let table = csv_to_table::from_reader(syscalls.as_bytes()).unwrap();
println!("{table}")
}
|
extern crate num;
extern crate ring;
use self::num::BigUint;
use self::ring::digest::{ digest, SHA256 };
use std::cmp::Ordering;
use std::fmt::Write;
use block::Block;
const TARGET_BITS: u64 = 3;
pub fn run_pow(blk: &mut Block) {
let mut hash_int;
let mut hash: Vec<u8> = vec![];
let mut nonce = 0u64;
let target = {
let mut big_int_vec = vec![];
for i in 0..TARGET_BITS - 1 {
big_int_vec.push(0);
}
big_int_vec.push(1);
BigUint::new(big_int_vec)
};
println!("Mining Block containing: {}\n", blk.data);
while nonce < u64::max_value() {
let data = {
let mut data: String = "".to_string();
write!(&mut data, "{:?}{}{}{}{}",
blk.prev_block_hash.as_slice(),
blk.data,
blk.time_stamp,
TARGET_BITS,
nonce).unwrap();
data
};
hash = digest(&SHA256, data.as_ref()).as_ref().to_vec();
hash_int = BigUint::from_bytes_le(hash.as_ref());
println!("Nonce: {}\n", nonce);
println!("HI: {:x} TARGET: {:x}\n\n", hash.as_slice(), target);
match hash_int.cmp(&target) {
Ordering::Less => break,
Ordering::Greater => nonce += 1,
Ordering::Equal => {}
}
}
println!("Nonce: {}", nonce);
blk.hash = hash;
blk.nonce = nonce;
}
|
use core::mem;
use core::alloc::Layout;
use core::sync::atomic::AtomicPtr;
use core::cell::Cell;
use core::cmp::max;
use sys::PAGE_SIZE;
use crate::uses::*;
use crate::collections::LinkedList;
use crate::ptr::{UniqueMut, UniquePtr, UniqueRef};
use crate::{alloc, dealloc, impl_list_node};
use super::{Allocation, MemOwner};
const INITIAL_HEAP_SIZE: usize = PAGE_SIZE * 8;
const HEAP_INC_SIZE: usize = PAGE_SIZE * 4;
const CHUNK_SIZE: usize = 1 << log2_up_const(mem::size_of::<Node>());
// TODO: make not use 1 extra space in some scenarios
const INITIAL_CHUNK_SIZE: usize = align_up(mem::size_of::<HeapZone>(), CHUNK_SIZE);
#[derive(Debug, Clone, Copy)]
enum ResizeResult
{
Shrink(usize),
Remove(usize),
NoCapacity,
}
#[derive(Debug)]
struct Node
{
prev: AtomicPtr<Node>,
next: AtomicPtr<Node>,
size: Cell<usize>,
}
impl Node
{
unsafe fn new(addr: usize, size: usize) -> MemOwner<Self>
{
let ptr = addr as *mut Node;
let out = Node {
prev: AtomicPtr::new(null_mut()),
next: AtomicPtr::new(null_mut()),
size: Cell::new(size),
};
ptr.write(out);
MemOwner::from_raw(ptr)
}
unsafe fn resize(&self, size: usize, align: usize) -> ResizeResult
{
let self_size = self.size();
if size > self_size {
return ResizeResult::NoCapacity;
}
let naddr = align_down(self.addr() + (self_size - size), max(align, CHUNK_SIZE));
// alignment might make it less
if naddr < self.addr() {
return ResizeResult::NoCapacity;
}
let nsize = naddr - self.addr();
if nsize >= CHUNK_SIZE {
self.set_size(nsize);
ResizeResult::Shrink(naddr)
} else {
ResizeResult::Remove(naddr)
}
// shouldn't need to check for case where allocation only partly covers node, since this should be impossible
}
fn merge<'a>(&'a self, node: &'a Node) -> bool
{
if self.addr() + self.size() == node.addr() {
self.size.set(self.size() + node.size());
//self.size.fetch_add (node.size (), Ordering::SeqCst);
true
} else {
false
}
}
fn size(&self) -> usize
{
self.size.get()
}
fn set_size(&self, size: usize)
{
self.size.set(size);
}
}
impl_list_node!(Node, prev, next);
struct HeapZone
{
prev: AtomicPtr<HeapZone>,
next: AtomicPtr<HeapZone>,
mem: Allocation,
free_space: Cell<usize>,
list: LinkedList<Node>,
}
impl HeapZone
{
// size is aligned up to page size
unsafe fn new(size: usize) -> Option<MemOwner<Self>>
{
let size = align_up(size, PAGE_SIZE);
let mem = alloc(size)?;
let size = mem.len();
let ptr = mem.as_usize() as *mut HeapZone;
let mut out = HeapZone {
prev: AtomicPtr::new(null_mut()),
next: AtomicPtr::new(null_mut()),
mem,
free_space: Cell::new(size - INITIAL_CHUNK_SIZE),
list: LinkedList::new(),
};
let node = Node::new(
mem.as_usize() + INITIAL_CHUNK_SIZE,
size - INITIAL_CHUNK_SIZE,
);
out.list.push(node);
ptr.write(out);
Some(MemOwner::from_raw(ptr))
}
fn free_space(&self) -> usize
{
self.free_space.get()
}
fn empty(&self) -> bool
{
self.free_space() == 0
}
fn contains(&self, addr: usize, size: usize) -> bool
{
(addr >= self.addr() + CHUNK_SIZE)
&& (addr + size <= self.addr() + CHUNK_SIZE + self.mem.len())
}
unsafe fn delete(&mut self)
{
dealloc(self.mem);
}
unsafe fn alloc(&mut self, layout: Layout) -> *mut u8
{
let size = layout.size();
let align = layout.align();
if size > self.free_space() {
return null_mut();
}
let mut out = 0;
// to get around borrow checker
// node that may need to be removed
let mut rnode = None;
for free_zone in self.list.iter() {
let old_size = free_zone.size();
if old_size >= size {
match free_zone.resize(size, align) {
ResizeResult::Shrink(addr) => {
let free_space = self.free_space();
self.free_space
.set(free_space - old_size + free_zone.size());
out = addr;
break;
},
ResizeResult::Remove(addr) => {
rnode = Some(free_zone.ptr());
self.free_space.set(self.free_space() - old_size);
out = addr;
break;
},
ResizeResult::NoCapacity => continue,
}
}
}
if let Some(node) = rnode {
// FIXME: find a way to fix ownership issue without doing this
self.list
.remove_node(UniqueRef::new(node.as_ref().unwrap()));
}
out as *mut u8
}
// does not chack if ptr is in this zone
// ptr should be chuk_size aligned
unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout)
{
let addr = ptr as usize;
let size = align_up(layout.size(), max(CHUNK_SIZE, layout.align()));
let cnode = Node::new(addr, size);
let (pnode, nnode) = self.get_prev_next_node(addr);
// TODO: make less ugly
let pnode = pnode.map(|ptr| ptr.unbound());
let nnode = nnode.map(|ptr| ptr.unbound());
let cnode = if let Some(pnode) = pnode {
if pnode.merge(&cnode) {
// cnode was never in list, no need to remove
UniqueMut::from_ptr(pnode.ptr() as *mut _)
} else {
self.list.insert_after(cnode, pnode)
}
} else {
self.list.push_front(cnode)
};
if let Some(nnode) = nnode {
if cnode.merge(&nnode) {
self.list.remove_node(nnode);
}
}
self.free_space.set(self.free_space() + size);
}
// TODO: make less dangerous
fn get_prev_next_node(&self, addr: usize)
-> (Option<UniqueRef<Node>>, Option<UniqueRef<Node>>)
{
let mut pnode = None;
let mut nnode = None;
for region in self.list.iter() {
if region.addr() > addr {
nnode = Some(region);
break;
}
pnode = Some(region);
}
(pnode, nnode)
}
}
impl_list_node!(HeapZone, prev, next);
pub struct LinkedListAllocator
{
list: LinkedList<HeapZone>,
}
impl LinkedListAllocator
{
pub fn new() -> LinkedListAllocator
{
let node = unsafe {
HeapZone::new(INITIAL_HEAP_SIZE).expect("failed to allocate pages for kernel heap")
};
let mut list = LinkedList::new();
list.push(node);
LinkedListAllocator {
list,
}
}
pub unsafe fn alloc(&mut self, layout: Layout) -> *mut u8
{
let size = layout.size();
let align = layout.align();
for mut z in self.list.iter_mut() {
if z.free_space() >= size {
let ptr = z.alloc(layout);
if ptr.is_null() {
continue;
} else {
return ptr;
}
}
}
// allocate new heapzone because there was no space in any others
let size_inc = max(
HEAP_INC_SIZE,
size + max(align, CHUNK_SIZE) + INITIAL_CHUNK_SIZE,
);
let zone = match HeapZone::new(size_inc) {
Some(n) => n,
None => return null_mut(),
};
let mut zone = self.list.push(zone);
// shouldn't fail now
zone.alloc(layout)
}
pub unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout)
{
let addr = ptr as usize;
assert!(align_of(addr) >= CHUNK_SIZE);
let size = layout.size();
for mut z in self.list.iter_mut() {
if z.contains(addr, size) {
z.dealloc(ptr, layout);
return;
}
}
panic!("invalid pointer passed to dealloc");
}
}
|
use alloc::vec::Vec;
use util::{uint_from_bytes, Hash};
use crate::consts::{IV32, IV64, SIGMA};
macro_rules! g32 {
($self:ident, $block:expr, $r:expr, $i:expr, $a:expr, $b:expr, $c:expr, $d:expr) => {
$self.v[$a] = $self.v[$a]
.wrapping_add($self.v[$b])
.wrapping_add($block[SIGMA[$r % 10][2 * $i]]);
$self.v[$d] = ($self.v[$d] ^ $self.v[$a]).rotate_right(16);
$self.v[$c] = $self.v[$c].wrapping_add($self.v[$d]);
$self.v[$b] = ($self.v[$b] ^ $self.v[$c]).rotate_right(12);
$self.v[$a] = $self.v[$a]
.wrapping_add($self.v[$b])
.wrapping_add($block[SIGMA[$r % 10][2 * $i + 1]]);
$self.v[$d] = ($self.v[$d] ^ $self.v[$a]).rotate_right(8);
$self.v[$c] = $self.v[$c].wrapping_add($self.v[$d]);
$self.v[$b] = ($self.v[$b] ^ $self.v[$c]).rotate_right(7);
};
}
macro_rules! g64 {
($self:ident, $block:expr, $r:expr, $i:expr, $a:expr, $b:expr, $c:expr, $d:expr) => {
$self.v[$a] = $self.v[$a]
.wrapping_add($self.v[$b])
.wrapping_add($block[SIGMA[$r % 10][2 * $i]]);
$self.v[$d] = ($self.v[$d] ^ $self.v[$a]).rotate_right(32);
$self.v[$c] = $self.v[$c].wrapping_add($self.v[$d]);
$self.v[$b] = ($self.v[$b] ^ $self.v[$c]).rotate_right(24);
$self.v[$a] = $self.v[$a]
.wrapping_add($self.v[$b])
.wrapping_add($block[SIGMA[$r % 10][2 * $i + 1]]);
$self.v[$d] = ($self.v[$d] ^ $self.v[$a]).rotate_right(16);
$self.v[$c] = $self.v[$c].wrapping_add($self.v[$d]);
$self.v[$b] = ($self.v[$b] ^ $self.v[$c]).rotate_right(63);
};
}
macro_rules! impl_blake2s {
($T:ident, $( $r:expr ),+) => {
pub struct $T {
f: bool,
l: usize,
h: [u32; 8],
t: [u32; 2],
n: usize,
v: [u32; 16],
}
impl $T {
pub fn new(n: usize) -> Self {
if !(1..=32).contains(&n) {
panic!("{} is not a valid number. n must be between 1 and 32.", n);
}
Self {
f: false,
l: 0,
h: [
IV32[0] ^ (0x0101_0000 | n as u32),
IV32[1],
IV32[2],
IV32[3],
IV32[4],
IV32[5],
IV32[6],
IV32[7],
],
t: [0; 2],
n,
v: [0; 16],
}
}
pub fn with_key(n: usize, k: usize, salt: [u32; 2], personal: [u32; 2]) -> Self {
if !(1..=32).contains(&n) {
panic!("{} is not a valid number. n must be between 1 and 32.", n);
}
if k > 32 {
panic!("{} is not a valid number. k must be between 0 and 32.", k)
}
if k == 0 {
return Self::new(n);
}
Self {
f: false,
l: 0,
h: [
IV32[0] ^ (0x0101_0000 | (k << 8) as u32 | n as u32),
IV32[1],
IV32[2],
IV32[3],
IV32[4] ^ salt[0].swap_bytes(),
IV32[5] ^ salt[1].swap_bytes(),
IV32[6] ^ personal[0].swap_bytes(),
IV32[7] ^ personal[1].swap_bytes(),
],
t: [0; 2],
n,
v: [0; 16],
}
}
#[inline(always)]
fn compress(&mut self, block: &[u32; 16]) {
// update counter
if self.l > 64 {
self.t[0] += 64;
self.l -= 64;
} else {
self.t[0] += self.l as u32;
self.l = 0;
self.f = true;
}
// initialize state
self.v[0] = self.h[0];
self.v[1] = self.h[1];
self.v[2] = self.h[2];
self.v[3] = self.h[3];
self.v[4] = self.h[4];
self.v[5] = self.h[5];
self.v[6] = self.h[6];
self.v[7] = self.h[7];
self.v[8] = IV32[0];
self.v[9] = IV32[1];
self.v[10] = IV32[2];
self.v[11] = IV32[3];
self.v[12] = IV32[4] ^ self.t[0];
self.v[13] = IV32[5] ^ self.t[1];
if self.f {
self.v[14] = IV32[6] ^ u32::MAX;
self.v[15] = IV32[7] ^ u32::MIN;
} else {
self.v[14] = IV32[6];
self.v[15] = IV32[7];
}
// round
$(
g32!(self, block, $r, 0, 0, 4, 8, 12);
g32!(self, block, $r, 1, 1, 5, 9, 13);
g32!(self, block, $r, 2, 2, 6, 10, 14);
g32!(self, block, $r, 3, 3, 7, 11, 15);
g32!(self, block, $r, 4, 0, 5, 10, 15);
g32!(self, block, $r, 5, 1, 6, 11, 12);
g32!(self, block, $r, 6, 2, 7, 8, 13);
g32!(self, block, $r, 7, 3, 4, 9, 14);
)*
// finalize
self.h[0] = self.h[0] ^ self.v[0] ^ self.v[0 + 8];
self.h[1] = self.h[1] ^ self.v[1] ^ self.v[1 + 8];
self.h[2] = self.h[2] ^ self.v[2] ^ self.v[2 + 8];
self.h[3] = self.h[3] ^ self.v[3] ^ self.v[3 + 8];
self.h[4] = self.h[4] ^ self.v[4] ^ self.v[4 + 8];
self.h[5] = self.h[5] ^ self.v[5] ^ self.v[5 + 8];
self.h[6] = self.h[6] ^ self.v[6] ^ self.v[6 + 8];
self.h[7] = self.h[7] ^ self.v[7] ^ self.v[7 + 8];
}
}
impl Default for $T {
fn default() -> Self {
Self {
f: false,
l: 0,
h: [
// Default parameter(0x20 bytes of output length, 0x00 byte of key length, set fanout and depth to 0x01)
IV32[0] ^ 0x0101_0020,
IV32[1],
IV32[2],
IV32[3],
IV32[4],
IV32[5],
IV32[6],
IV32[7],
],
t: [0; 2],
n: 32,
v: [0; 16],
}
}
}
impl Hash for $T {
fn hash_to_bytes(&mut self, message: &[u8]) -> Vec<u8> {
self.l = message.len();
let l = message.len();
let mut block = [0u32; 16];
if l >= 64 {
message.chunks_exact(64).for_each(|bytes| {
uint_from_bytes!(u32 => 0, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 1, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 2, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 3, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 4, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 5, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 6, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 7, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 8, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 9, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 10, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 11, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 12, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 13, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 14, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 15, block, bytes, from_le_bytes);
self.compress(&block);
});
} else if l == 0 {
self.compress(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
}
if (l % 64) != 0 {
let offset = (l / 64) * 64;
let remainder = l % 64;
let mut bytes = [0u8; 64];
bytes[..remainder].copy_from_slice(&message[offset..]);
uint_from_bytes!(u32 => 0, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 1, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 2, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 3, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 4, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 5, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 6, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 7, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 8, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 9, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 10, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 11, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 12, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 13, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 14, block, bytes, from_le_bytes);
uint_from_bytes!(u32 => 15, block, bytes, from_le_bytes);
self.compress(&block);
}
let word_len = {
if self.n < 4 {
1
} else {
self.n.next_power_of_two() / 4
}
};
self.h[0..word_len]
.iter()
.flat_map(|word| word.to_le_bytes().to_vec())
.collect::<Vec<u8>>()[0..(self.n)]
.to_vec()
}
}
}
}
macro_rules! impl_blake2b {
($T:ident, $( $r:expr ),*) => {
pub struct $T {
f: bool,
l: usize,
h: [u64; 8],
t: [u64; 2],
n: usize,
v: [u64; 16],
}
impl $T {
pub fn new(n: usize) -> Self {
if !(1..=64).contains(&n) {
panic!("{} is not a valid number. n must be between 1 and 32.", n);
}
Self {
f: false,
l: 0,
h: [
IV64[0] ^ (0x0101_0000 | n as u64),
IV64[1],
IV64[2],
IV64[3],
IV64[4],
IV64[5],
IV64[6],
IV64[7],
],
t: [0; 2],
n,
v: [0; 16],
}
}
pub fn with_key(n: usize, k: usize, salt: [u64; 2], personal: [u64; 2]) -> Self {
if !(1..=64).contains(&n) {
panic!("{} is not a valid number. n must be between 1 and 32.", n);
}
if k > 64 {
panic!("{} is not a valid number. k must be between 0 and 64.", k)
}
if k == 0 {
return Self::new(n);
}
Self {
f: false,
l: 0,
h: [
IV64[0] ^ (0x0101_0000 | (k << 8) as u64 | n as u64),
IV64[1],
IV64[2],
IV64[3],
IV64[4] ^ salt[0].swap_bytes(),
IV64[5] ^ salt[1].swap_bytes(),
IV64[6] ^ personal[0].swap_bytes(),
IV64[7] ^ personal[1].swap_bytes(),
],
t: [0; 2],
n,
v: [0; 16],
}
}
fn compress(&mut self, block: &[u64; 16]) {
// update counter
if self.l > 128 {
self.t[0] += 128;
self.l -= 128;
} else {
self.t[0] += self.l as u64;
self.l = 0;
self.f = true;
}
// initialize state
self.v[0] = self.h[0];
self.v[1] = self.h[1];
self.v[2] = self.h[2];
self.v[3] = self.h[3];
self.v[4] = self.h[4];
self.v[5] = self.h[5];
self.v[6] = self.h[6];
self.v[7] = self.h[7];
self.v[8] = IV64[0];
self.v[9] = IV64[1];
self.v[10] = IV64[2];
self.v[11] = IV64[3];
self.v[12] = IV64[4] ^ self.t[0];
self.v[13] = IV64[5] ^ self.t[1];
if self.f {
self.v[14] = IV64[6] ^ u64::MAX;
self.v[15] = IV64[7] ^ u64::MIN;
} else {
self.v[14] = IV64[6];
self.v[15] = IV64[7];
}
// round
$(
g64!(self, block, $r, 0, 0, 4, 8, 12);
g64!(self, block, $r, 1, 1, 5, 9, 13);
g64!(self, block, $r, 2, 2, 6, 10, 14);
g64!(self, block, $r, 3, 3, 7, 11, 15);
g64!(self, block, $r, 4, 0, 5, 10, 15);
g64!(self, block, $r, 5, 1, 6, 11, 12);
g64!(self, block, $r, 6, 2, 7, 8, 13);
g64!(self, block, $r, 7, 3, 4, 9, 14);
)*
// finalize
self.h[0] = self.h[0] ^ self.v[0] ^ self.v[0 + 8];
self.h[1] = self.h[1] ^ self.v[1] ^ self.v[1 + 8];
self.h[2] = self.h[2] ^ self.v[2] ^ self.v[2 + 8];
self.h[3] = self.h[3] ^ self.v[3] ^ self.v[3 + 8];
self.h[4] = self.h[4] ^ self.v[4] ^ self.v[4 + 8];
self.h[5] = self.h[5] ^ self.v[5] ^ self.v[5 + 8];
self.h[6] = self.h[6] ^ self.v[6] ^ self.v[6 + 8];
self.h[7] = self.h[7] ^ self.v[7] ^ self.v[7 + 8];
}
}
impl Default for $T {
fn default() -> Self {
Self {
f: false,
l: 0,
h: [
// Default parameter(0x40 bytes of output length, 0x00 byte of key length, set fanout and depth to 0x01)
IV64[0] ^ 0x0101_0040,
IV64[1],
IV64[2],
IV64[3],
IV64[4],
IV64[5],
IV64[6],
IV64[7],
],
t: [0; 2],
n: 64,
v: [0; 16],
}
}
}
impl Hash for $T {
fn hash_to_bytes(&mut self, message: &[u8]) -> Vec<u8> {
self.l = message.len();
let l = message.len();
let mut block = [0u64; 16];
if l >= 128 {
message.chunks_exact(128).for_each(|bytes| {
uint_from_bytes!(u64 => 0, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 1, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 2, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 3, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 4, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 5, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 6, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 7, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 8, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 9, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 10, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 11, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 12, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 13, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 14, block, bytes, from_le_bytes);
uint_from_bytes!(u64 => 15, block, bytes, from_le_bytes);
self.compress(&block);
});
} else if l == 0 {
self.compress(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
}
if (l % 128) != 0 {
let offset = (l / 128) * 128;
let remainder = l % 128;
let mut byte_block = [0u8; 128];
byte_block[..remainder].copy_from_slice(&message[offset..]);
uint_from_bytes!(u64 => 0, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 1, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 2, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 3, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 4, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 5, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 6, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 7, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 8, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 9, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 10, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 11, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 12, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 13, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 14, block, byte_block, from_le_bytes);
uint_from_bytes!(u64 => 15, block, byte_block, from_le_bytes);
self.compress(&block);
}
let word_len = {
if self.n < 8 {
1
} else {
self.n.next_power_of_two() / 8
}
};
self.h[0..word_len]
.iter()
.flat_map(|word| word.to_le_bytes().to_vec())
.collect::<Vec<u8>>()[0..(self.n)]
.to_vec()
}
}
};
}
impl_blake2s!(Blake2s, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
impl_blake2b!(Blake2b, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
|
fn main() {
// When a specfic vector holds a specific type, the type is specified
// the type is specified withi the angle brackets
// We are sayint that the type here here will hold elements of i32 type
let v: Vec<i32> = Vec::new();
// Don't need the type annotation "Vec<i32>" here because compiler
// can infer we want i32
let x = vec![1, 2, 3];
// Compiler is able to infer type because we push in i32 values below
let mut a = Vec::new();
a.push(5);
a.push(6);
a.push(7);
a.push(8);
let z = vec![1, 2, 3, 4, 5];
// option 1 to get element
let third = &z[2];
println!("The third element is {}", third);
// option 2 to get element
match z.get(2) {
Some(thirdElement) => println!("The third element is {}", thirdElement),
None => println!("There is no third element."),
}
// using if let
if let Some(thirdElement) = z.get(2) {
println!("three");
} else {
println!("not found")
}
let q = vec![1, 2, 3, 4, 5];
// References nonexistent element
// let does_not_exist = &v[100];
// ******When get method is passed an index that is outside the vector,
// it returns "None" w/o panicking
let does_not_exist = v.get(100);
// **** DOESNT COMPILE ****
// Cannot borrow "w" as mutable b/c it is also borrowed as immutable
// This error is due to the way vectors work
// Adding a new element onto the end of the vector might require
// allocating new memory and copying the old elements to the new space
// In that case, the reference to the first element would be pointing
// deallocated memory
// The borrowing rules prevent programs from ending up in that situation
// let mut w = vec![1, 2, 3, 4, 5];
// let first = &w[0];
// w.push(6);
// println!("The first element is: {}", first);
let e = vec![100, 32, 57];
for i in &e {
println!("{}", i);
}
let mut r = vec![100, 32, 57];
for i in &mut r {
// * is the dereference operator
// have to do this to do the value in "i" before so
// we can use the "+="" operator
*i += 50;
}
println!("r: {:?}", r);
} // <- a && x && v goes out of scope and is freed here
|
use {
crate::{Backend, RawSession},
cookie::{Cookie, CookieBuilder},
serde_json,
std::{borrow::Cow, collections::HashMap, fmt, sync::Arc},
tsukuyomi::{
error::{Error, Result},
future::{Poll, TryFuture},
input::{Cookies, Input},
},
};
#[cfg(feature = "secure")]
use cookie::Key;
#[cfg(feature = "secure")]
enum Security {
Plain,
Signed(Key),
Private(Key),
}
#[cfg(not(feature = "secure"))]
enum Security {
Plain,
}
#[cfg_attr(tarpaulin, skip)]
impl fmt::Debug for Security {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Security::Plain => f.debug_tuple("Plain").finish(),
#[cfg(feature = "secure")]
Security::Signed(..) => f.debug_tuple("Signed").field(&"<secret key>").finish(),
#[cfg(feature = "secure")]
Security::Private(..) => f.debug_tuple("Private").field(&"<secret key>").finish(),
}
}
}
impl Security {
fn get(&self, name: &str, cookies: &mut Cookies<'_>) -> Result<Option<Cookie<'static>>> {
match self {
Security::Plain => Ok(cookies.jar()?.get(name).cloned()),
#[cfg(feature = "secure")]
Security::Signed(ref key) => Ok(cookies.signed_jar(key)?.get(name)),
#[cfg(feature = "secure")]
Security::Private(ref key) => Ok(cookies.private_jar(key)?.get(name)),
}
}
fn add(&self, cookie: Cookie<'static>, cookies: &mut Cookies<'_>) -> Result<()> {
match self {
Security::Plain => cookies.jar()?.add(cookie),
#[cfg(feature = "secure")]
Security::Signed(ref key) => cookies.signed_jar(key)?.add(cookie),
#[cfg(feature = "secure")]
Security::Private(ref key) => cookies.private_jar(key)?.add(cookie),
}
Ok(())
}
}
/// A `Backend` using a Cookie entry for storing the session data.
#[derive(Debug, Clone)]
pub struct CookieBackend {
inner: Arc<CookieBackendInner>,
}
impl CookieBackend {
fn new(security: Security) -> Self {
Self {
inner: Arc::new(CookieBackendInner {
security,
cookie_name: "tsukuyomi-session".into(),
builder: Box::new(|cookie| cookie),
}),
}
}
fn inner_mut(&mut self) -> &mut CookieBackendInner {
Arc::get_mut(&mut self.inner).expect("the instance has already shared")
}
/// Create a new `CookieBackend` that save uses the plain format.
pub fn plain() -> Self {
Self::new(Security::Plain)
}
/// Create a new `CookieBackend` that signs the cookie entry with the specified `Key`.
#[cfg(feature = "secure")]
pub fn signed(secret_key: Key) -> Self {
Self::new(Security::Signed(secret_key))
}
/// Create a new `CookieBackend` that encrypts the cookie entry with the specified `Key`.
#[cfg(feature = "secure")]
pub fn private(secret_key: Key) -> Self {
Self::new(Security::Private(secret_key))
}
/// Sets the name of Cookie entry to be used for storing the session data.
///
/// The default value is `"tsukuyomi-session"`.
pub fn cookie_name(mut self, value: impl Into<Cow<'static, str>>) -> Self {
self.inner_mut().cookie_name = value.into();
self
}
/// Sets the functions for modifying the saved Cookie entry.
pub fn builder(
mut self,
builder: impl Fn(CookieBuilder) -> CookieBuilder + Send + Sync + 'static,
) -> Self {
self.inner_mut().builder = Box::new(builder);
self
}
}
struct CookieBackendInner {
security: Security,
cookie_name: Cow<'static, str>,
builder: Box<dyn Fn(CookieBuilder) -> CookieBuilder + Send + Sync + 'static>,
}
#[cfg_attr(tarpaulin, skip)]
impl fmt::Debug for CookieBackendInner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CookieBackendInner")
.field("security", &self.security)
.field("cookie_name", &self.cookie_name)
.finish()
}
}
impl CookieBackendInner {
fn deserialize(&self, s: &str) -> Result<HashMap<String, String>> {
serde_json::from_str(s).map_err(tsukuyomi::error::bad_request)
}
fn serialize(&self, map: &HashMap<String, String>) -> String {
serde_json::to_string(&map).expect("should be success")
}
fn read(&self, input: &mut Input<'_>) -> tsukuyomi::Result<Inner> {
match self.security.get(&*self.cookie_name, input.cookies)? {
Some(cookie) => {
let map = self.deserialize(cookie.value())?;
Ok(Inner::Some(map))
}
None => Ok(Inner::Empty),
}
}
fn write(&self, input: &mut Input<'_>, inner: Inner) -> tsukuyomi::Result<()> {
match inner {
Inner::Empty => {}
Inner::Some(map) => {
let value = self.serialize(&map);
let cookie =
(self.builder)(Cookie::build(self.cookie_name.clone(), value)).finish();
self.security.add(cookie, input.cookies)?;
}
Inner::Clear => {
input
.cookies
.jar()?
.remove(Cookie::named(self.cookie_name.clone()));
}
}
Ok(())
}
}
impl Backend for CookieBackend {
type Session = CookieSession;
type ReadError = Error;
type ReadSession = ReadSession;
fn read(&self) -> Self::ReadSession {
ReadSession(Some(self.clone()))
}
}
#[doc(hidden)]
#[allow(missing_debug_implementations)]
pub struct ReadSession(Option<CookieBackend>);
impl TryFuture for ReadSession {
type Ok = CookieSession;
type Error = Error;
#[inline]
fn poll_ready(&mut self, input: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> {
let backend = self.0.take().expect("the future has already been polled");
backend
.inner
.read(input)
.map(|inner| CookieSession { inner, backend }.into())
}
}
#[derive(Debug)]
pub struct CookieSession {
inner: Inner,
backend: CookieBackend,
}
#[derive(Debug)]
enum Inner {
Empty,
Some(HashMap<String, String>),
Clear,
}
impl RawSession for CookieSession {
type WriteSession = WriteSession;
type WriteError = Error;
fn get(&self, name: &str) -> Option<&str> {
match self.inner {
Inner::Some(ref map) => map.get(name).map(|s| &**s),
_ => None,
}
}
fn set(&mut self, name: &str, value: String) {
match self.inner {
Inner::Empty => {}
Inner::Some(ref mut map) => {
map.insert(name.to_owned(), value);
return;
}
Inner::Clear => return,
}
match std::mem::replace(&mut self.inner, Inner::Empty) {
Inner::Empty => {
self.inner = Inner::Some({
let mut map = HashMap::new();
map.insert(name.to_owned(), value);
map
});
}
Inner::Some(..) | Inner::Clear => unreachable!(),
}
}
fn remove(&mut self, name: &str) {
if let Inner::Some(ref mut map) = self.inner {
map.remove(name);
}
}
fn clear(&mut self) {
self.inner = Inner::Clear;
}
fn write(self) -> Self::WriteSession {
WriteSession(Some(self))
}
}
#[doc(hidden)]
#[allow(missing_debug_implementations)]
pub struct WriteSession(Option<CookieSession>);
impl TryFuture for WriteSession {
type Ok = ();
type Error = Error;
#[inline]
fn poll_ready(&mut self, input: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> {
let session = self.0.take().expect("the future has already been polled");
session
.backend
.inner
.write(input, session.inner)
.map(Into::into)
}
}
|
use super::Byte;
use super::{coerce_whitespace, discard};
use std::iter;
#[derive(Clone)]
pub struct Input<'a> {
bytes: &'a [Byte],
}
impl<'a> Input<'a> {
#[doc(hidden)]
// TODO: This can probably made private with little effort
// since most usages of this field
// need to be moved in here anyway.
pub fn bytes(&self) -> &'a [Byte] {
self.bytes
}
}
impl<'a> From<&'a [Byte]> for Input<'a> {
fn from(bytes: &'a [Byte]) -> Self {
Input { bytes }
}
}
impl<'a> super::Input<'a> for Input<'a> {}
pub struct Iterator<'a> {
bytes: &'a [Byte],
/// One more than the position of the last element that was output.
/// If we are not at the end of the iteration
/// and there are no discardable bytes,
/// it happens to be the position of the next element.
next: usize,
}
impl<'a> Iterator<'a> {
pub fn new(i: &Input<'a>) -> Self {
let bytes = i.bytes;
let next = 0;
Iterator { bytes, next }
}
}
impl<'a> iter::Iterator for Iterator<'a> {
type Item = Byte;
fn next(&mut self) -> Option<Self::Item> {
macro_rules! next_byte {
() => {
self.bytes[self.next]
};
}
if self.next >= self.bytes.len() {
None
} else if discard(next_byte!()) {
self.next += 1;
self.next()
} else {
let res = next_byte!();
self.next += 1;
Some(coerce_whitespace(res))
}
}
}
pub struct Enumerator<'a>(Iterator<'a>);
impl<'a> Enumerator<'a> {
pub fn new(i: &Input<'a>) -> Self {
Enumerator(Iterator::new(i))
}
}
impl<'a> iter::Iterator for Enumerator<'a> {
type Item = (usize, Byte);
fn next(&mut self) -> Option<Self::Item> {
let Enumerator(iter) = self;
let byte = iter.next()?;
Some((iter.next - 1, byte))
}
}
|
extern crate tar = "tar";
#[test]
fn test_data_len() {
let tar = tar::new("/Users/matuzak/workspace/rust-tar/tests/tar_test.tar");
let data = tar.read();
assert_eq!(data.len(), 13);
}
#[test]
fn test_fields() {
let tar = tar::new("/Users/matuzak/workspace/rust-tar/tests/tar_test.tar");
let path = tar.fields.get(&"path");
let mode = tar.fields.get(&"mode");
let uid = tar.fields.get(&"uid");
let gid = tar.fields.get(&"gid");
let size = tar.fields.get(&"size");
let mtime = tar.fields.get(&"mtime");
let cksum = tar.fields.get(&"cksum");
let typ = tar.fields.get(&"type");
let linkpath = tar.fields.get(&"linkpath");
assert_eq!(path, &1);
assert_eq!(mode, &2);
assert_eq!(uid, &3);
assert_eq!(gid, &4);
assert_eq!(size, &5);
assert_eq!(mtime, &6);
assert_eq!(cksum, &7);
assert_eq!(typ, &8);
assert_eq!(linkpath, &9);
}
#[test]
fn test_field_sizes() {
let tar = tar::new("/Users/matuzak/workspace/rust-tar/tests/tar_test.tar");
let path = tar.fields.get(&"path");
let mode = tar.fields.get(&"mode");
let uid = tar.fields.get(&"uid");
let gid = tar.fields.get(&"gid");
let size = tar.fields.get(&"size");
let mtime = tar.fields.get(&"mtime");
let cksum = tar.fields.get(&"cksum");
let typ = tar.fields.get(&"type");
let linkpath = tar.fields.get(&"linkpath");
let path_size = tar.field_size.get(path);
let mode_size = tar.field_size.get(mode);
let uid_size = tar.field_size.get(uid);
let gid_size = tar.field_size.get(gid);
let size_size = tar.field_size.get(size);
let mtime_size = tar.field_size.get(mtime);
let cksum_size = tar.field_size.get(cksum);
let type_size = tar.field_size.get(typ);
let linkpath_size = tar.field_size.get(linkpath);
assert_eq!(path_size, &100);
assert_eq!(mode_size, &8);
assert_eq!(uid_size, &8);
assert_eq!(gid_size, &8);
assert_eq!(size_size, &12);
assert_eq!(mtime_size, &12);
assert_eq!(cksum_size, &8);
assert_eq!(type_size, &1);
assert_eq!(linkpath_size, &100);
}
|
pub mod line;
pub mod sector;
pub mod triangle;
pub mod triangulate;
pub mod wall;
|
use std::fmt;
#[derive(Debug, Clone)]
pub enum Component {
Property(String),
Index(usize),
}
#[derive(Debug, Clone)]
pub struct PathBuf {
components: Vec<Component>,
}
impl PathBuf {
pub fn new() -> PathBuf {
PathBuf { components: vec![] }
}
pub fn push_index(&mut self, index: usize) {
self.components.push(Component::Index(index));
}
pub fn push_property<S>(&mut self, property: S)
where
S: Into<String>,
{
self.components.push(Component::Property(property.into()))
}
}
impl fmt::Display for PathBuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (idx, component) in self.components.iter().enumerate() {
match component {
Component::Property(s) if idx > 0 => write!(f, ".{}", s)?,
Component::Property(s) => write!(f, "{}", s)?,
Component::Index(idx) => write!(f, "[{}]", idx)?,
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_buf() {
assert_eq!(&PathBuf::new().to_string(), "");
}
}
|
fn main() {
println!("part one: {}", find_last(&[1, 0, 15, 2, 10, 13], 2020));
println!("part one: {}", find_last(&[1, 0, 15, 2, 10, 13], 30000000));
}
fn find_last(nums: &[usize], nth_num: usize) -> usize {
let mut cache = vec![std::usize::MAX; nth_num];
for (i, &n) in nums.iter().enumerate() {
cache[n] = i;
}
let mut spoken = nums[nums.len() - 1];
for i in nums.len()..nth_num {
let n = cache[spoken];
cache[spoken] = i - 1;
spoken = (i - 1).saturating_sub(n);
}
spoken
}
mod tests {
#[test]
fn test_part_one() {
assert_eq!(211, super::find_last(&[1, 0, 15, 2, 10, 13], 2020));
}
#[test]
fn test_part_two() {
assert_eq!(2159626, super::find_last(&[1, 0, 15, 2, 10, 13], 30000000));
}
}
|
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* io/decoders/char_decoder.rs *
* *
* hprose char decoder for Rust. *
* *
* LastModified: Oct 8, 2016 *
* Author: Chen Fei <cf@hprose.com> *
* *
\**********************************************************/
use io::{Reader, Decoder, DecoderError};
use io::tags::*;
use io::reader::cast_error;
use io::util::utf8_slice_to_str;
use std::result;
type Result = result::Result<char, DecoderError>;
pub fn char_decode(r: &mut Reader, tag: u8) -> Result {
match tag {
b'0' => Ok('0'),
b'1' => Ok('1'),
b'2' => Ok('2'),
b'3' => Ok('3'),
b'4' => Ok('4'),
b'5' => Ok('5'),
b'6' => Ok('6'),
b'7' => Ok('7'),
b'8' => Ok('8'),
b'9' => Ok('9'),
TAG_UTF8_CHAR => read_utf8_char_as_char(r),
TAG_STRING => read_string_as_char(r),
TAG_REF => r.read_ref(),
_ => Err(cast_error(tag, "char"))
}
}
fn read_utf8_char_as_char(r: &mut Reader) -> Result {
r.byte_reader
.read_utf8_slice(1)
.map(|bytes| utf8_slice_to_str(bytes).chars().next().unwrap())
.map_err(|e| DecoderError::ParserError(e))
}
fn read_string_as_char(r: &mut Reader) -> Result {
r.read_string_without_tag().map(|s| s.chars().next().unwrap())
}
|
mod compute_submission;
mod get_args;
mod get_orig_state;
mod orig_state;
mod submission;
mod utilities;
mod write_submission;
use compute_submission::compute_submission;
use get_args::get_args;
use get_orig_state::get_orig_state;
use orig_state::OrigState;
use write_submission::write_submission;
fn sort_libs(orig_state: &mut OrigState) {
orig_state
.libs
.sort_by(|l1, l2| l1.books.len().cmp(&l2.books.len()));
}
fn main() -> Result<(), String> {
let args = get_args()?;
let mut orig_state = get_orig_state(&args.file_name)?;
sort_libs(&mut orig_state);
let submission = compute_submission(&orig_state);
write_submission(&args.file_name, &submission);
Ok(())
}
|
fn main () {
repeat("Hello", 3);
}
fn repeat(string: &str, times: i32) {
for _n in 0..times {
println!("{}", string)
}
}
|
use std::io;
pub enum StorageError
{
KeyNotFound, //Key is not available
CorruptStorage, //database file broken or something like that
Custom(String), //Custom error string
KeyIoError(io::Error), //io error when accessing key handle
ValueIoError(io::Error), //io error when accessing value handle
}
|
fn main() {
let x = 5; // 尾部注释
// 注释
// 多行注释
// 每行用 //
}
|
// Copyright 2020 Alex Dukhno
//
// 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 super::*;
use sql_types::SqlType;
#[rstest::rstest]
fn create_tables_with_different_names(catalog_manager_with_schema: CatalogManager) {
let schema_id = catalog_manager_with_schema
.schema_exists(SCHEMA)
.expect("schema exists");
assert_eq!(
catalog_manager_with_schema.create_table(
schema_id,
"table_name_1",
&[ColumnDefinition::new(
"column_test",
SqlType::SmallInt(i16::min_value())
)]
),
Ok(())
);
assert_eq!(
catalog_manager_with_schema.create_table(
schema_id,
"table_name_2",
&[ColumnDefinition::new(
"column_test",
SqlType::SmallInt(i16::min_value())
)]
),
Ok(())
);
}
#[rstest::rstest]
fn create_table_with_the_same_name_in_different_schemas(catalog_manager: CatalogManager) {
catalog_manager.create_schema(SCHEMA_1).expect("schema is created");
catalog_manager.create_schema(SCHEMA_2).expect("schema is created");
let schema_1_id = catalog_manager.schema_exists(SCHEMA_1).expect("schema exists");
assert_eq!(
catalog_manager.create_table(
schema_1_id,
"table_name",
&[ColumnDefinition::new(
"column_test",
SqlType::SmallInt(i16::min_value())
)]
),
Ok(())
);
let schema_2_id = catalog_manager.schema_exists(SCHEMA_2).expect("schema exists");
assert_eq!(
catalog_manager.create_table(
schema_2_id,
"table_name",
&[ColumnDefinition::new(
"column_test",
SqlType::SmallInt(i16::min_value())
)]
),
Ok(())
);
}
#[rstest::rstest]
fn drop_table(catalog_manager_with_schema: CatalogManager) {
let schema_id = catalog_manager_with_schema
.schema_exists(SCHEMA)
.expect("schema exists");
catalog_manager_with_schema
.create_table(
schema_id,
"table_name",
&[ColumnDefinition::new(
"column_test",
SqlType::SmallInt(i16::min_value()),
)],
)
.expect("table is created");
assert_eq!(catalog_manager_with_schema.drop_table(SCHEMA, "table_name"), Ok(()));
assert_eq!(
catalog_manager_with_schema.create_table(
schema_id,
"table_name",
&[ColumnDefinition::new(
"column_test",
SqlType::SmallInt(i16::min_value())
)]
),
Ok(())
);
}
#[rstest::rstest]
fn table_columns_on_empty_table(catalog_manager_with_schema: CatalogManager) {
let schema_id = catalog_manager_with_schema
.schema_exists(SCHEMA)
.expect("schema exists");
let column_names = vec![];
catalog_manager_with_schema
.create_table(schema_id, "table_name", column_names.as_slice())
.expect("table is created");
assert_eq!(
catalog_manager_with_schema
.table_columns(SCHEMA, "table_name")
.expect("no system errors"),
vec![]
);
}
|
#![cfg_attr(feature = "unstable", feature(test))]
// Launch program : cargo run --release < input/input.txt
// Launch benchmark : cargo +nightly bench --features "unstable"
/*
Benchmark results:
running 4 tests
test tests::test_part_1 ... ignored
test bench::bench_parse_input ... bench: 98,888 ns/iter (+/- 9,621)
test bench::bench_part_1 ... bench: 681 ns/iter (+/- 83)
test bench::bench_part_2 ... bench: 3,128 ns/iter (+/- 224)
*/
use std::convert::TryFrom;
use std::error::Error;
use std::io::{self, Read, Write};
type Result<T> = ::std::result::Result<T, Box<dyn Error>>;
macro_rules! err {
($($tt:tt)*) => { return Err(Box::<dyn Error>::from(format!($($tt)*))) }
}
#[derive(Eq, PartialEq, Ord, PartialOrd)]
struct Seat {
row: usize,
column: usize,
}
impl Seat {
fn get_seat_id(&self) -> usize {
self.row * 8 + self.column
}
}
impl TryFrom<&str> for Seat {
type Error = Box<dyn Error>;
fn try_from(value: &str) -> Result<Self> {
if value.len() != 10 {
err!("Input line should have a length of 10 chars")
} else {
let mut max_row = 127;
let mut min_row = 0;
let mut max_column = 7;
let mut min_column = 0;
for r in value[..7].chars() {
match r {
'F' => max_row = (max_row + min_row - 1) / 2,
'B' => min_row = (max_row + min_row + 1) / 2,
_ => err!("Invalid character found while determining row : {}", r),
}
}
for c in value[7..].chars() {
match c {
'L' => max_column = (max_column + min_column - 1) / 2,
'R' => min_column = (max_column + min_column + 1) / 2,
_ => err!("Invalid character found while determining column : {}", c),
}
}
Ok(Seat {
row: max_row,
column: max_column,
})
}
}
}
fn main() -> Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let mut seats = parse_input(&input)?;
writeln!(io::stdout(), "Part 1 : {}", part_1(&seats)?)?;
writeln!(io::stdout(), "Part 2 : {}", part_2(&mut seats)?)?;
Ok(())
}
fn parse_input(input: &str) -> Result<Vec<Seat>> {
input.lines().map(Seat::try_from).collect()
}
fn part_1(seats: &[Seat]) -> Result<usize> {
match seats.iter().map(|v| v.get_seat_id()).max() {
Some(max) => Ok(max),
None => err!("Input is empty!"),
}
}
fn part_2(seats: &mut Vec<Seat>) -> Result<usize> {
seats.sort();
let mut current_seat_id = 0;
for (i, seat) in seats.iter().enumerate() {
if i == 0 {
current_seat_id = seat.get_seat_id();
} else {
current_seat_id += 1;
if current_seat_id != seat.get_seat_id() {
return Ok(seat.get_seat_id() - 1);
}
}
}
err!("Couldn't find santa's seat!")
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
fn read_test_file() -> Result<String> {
let mut input = String::new();
File::open("input/test.txt")?.read_to_string(&mut input)?;
Ok(input)
}
#[test]
fn test_part_1() -> Result<()> {
let seats = parse_input(&read_test_file()?)?;
assert_eq!(part_1(&seats)?, 820);
Ok(())
}
}
#[cfg(all(feature = "unstable", test))]
mod bench {
extern crate test;
use super::*;
use std::fs::File;
use test::Bencher;
fn read_input_file() -> Result<String> {
let mut input = String::new();
File::open("input/input.txt")?.read_to_string(&mut input)?;
Ok(input)
}
#[bench]
fn bench_parse_input(b: &mut Bencher) -> Result<()> {
let input = read_input_file()?;
b.iter(|| test::black_box(parse_input(&input)));
Ok(())
}
#[bench]
fn bench_part_1(b: &mut Bencher) -> Result<()> {
let seats = parse_input(&read_input_file()?)?;
b.iter(|| test::black_box(part_1(&seats)));
Ok(())
}
#[bench]
fn bench_part_2(b: &mut Bencher) -> Result<()> {
let mut seats = parse_input(&read_input_file()?)?;
b.iter(|| test::black_box(part_2(&mut seats)));
Ok(())
}
}
|
//! LimitTracker type and Messenger trait to demonstrate [RefCell<T>] usage.
//!
//! [refcell<t>]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html
use std::cell::RefCell;
use the_book::ch15::sec05::{LimitTracker, Messenger};
fn main() {
let cacher = Cacher::new();
let mut tracker = LimitTracker::new(&cacher, 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!",
];
for (i, want) in wants.iter().enumerate() {
assert_eq!(*want, &cacher.msgs.borrow()[i]);
}
}
struct Cacher {
msgs: RefCell<Vec<String>>,
}
impl Cacher {
fn new() -> Self {
Self {
msgs: RefCell::new(Vec::new()),
}
}
}
impl Messenger for Cacher {
fn send(&self, msg: &str) {
self.msgs.borrow_mut().push(msg.to_string());
eprintln!("{}", msg);
}
}
|
use super::{schema::groups, user::User, PostgresPool};
use anyhow::Context;
use diesel::prelude::*;
#[derive(Identifiable, Queryable, Associations, PartialEq, Debug)]
#[belongs_to(User)]
pub struct Group {
pub id: uuid::Uuid,
pub user_id: uuid::Uuid,
pub name: String,
pub created_at: chrono::DateTime<chrono::Utc>,
pub updated_at: chrono::DateTime<chrono::Utc>,
}
pub struct GroupRepository;
impl GroupRepository {
pub fn find_by_user(user: &User, pool: &PostgresPool) -> anyhow::Result<Vec<Group>> {
Group::belonging_to(user)
.load(&pool.get()?)
.context(format!("Couldn't find this user's ({}) groups", user.id))
}
pub fn save(new_group: &NewGroup, pool: &PostgresPool) -> anyhow::Result<Group> {
diesel::insert_into(groups::table)
.values(new_group)
.get_result::<Group>(&pool.get()?)
.context("Couldn't save this group to the database")
}
pub fn update_one(group: &UpdateGroup, pool: &PostgresPool) -> anyhow::Result<()> {
if group.name.is_none() {
return Ok(());
}
diesel::update(groups::table.filter(groups::id.eq(group.id)))
.set(group)
.execute(&pool.get()?)
.context("Couldn't update this group to the database")
.map(|_| ())
}
pub fn delete_one(id: &uuid::Uuid, pool: &PostgresPool) -> anyhow::Result<()> {
diesel::delete(groups::table)
.filter(groups::id.eq(id))
.execute(&pool.get()?)
.context(format!("Couldn't delete this group ({})", id))
.map(|_| ())
}
}
#[derive(Insertable)]
#[table_name = "groups"]
pub struct NewGroup {
pub id: uuid::Uuid,
pub user_id: uuid::Uuid,
pub name: String,
}
#[derive(AsChangeset)]
#[table_name = "groups"]
pub struct UpdateGroup {
pub id: uuid::Uuid,
pub name: Option<String>,
}
|
use iron::prelude::*;
use regex::{Regex, Captures};
use common::http::*;
use common::utils::*;
use services::comment::*;
use services::comment::create_comment as service_create_comment;
use services::comment::delete_comment as service_delete_comment;
use services::comment_vote::*;
use services::user::get_user_id;
use services::topic::get_topic;
use services::message::create_message;
use controllers::upload::sync_upload_file;
pub fn create_comment(req: &mut Request) -> IronResult<Response> {
let params = get_request_body(req);
let user_id = ¶ms.get("userId").unwrap()[0];
let topic_id = ¶ms.get("topicId").unwrap()[0];
let content = ¶ms.get("content").unwrap()[0];
let reg = Regex::new(r"\B@([\da-zA-Z_]+)").unwrap();
let mut mentions: Vec<u16> = Vec::new();
let new_content = reg.replace_all(&content, |caps: &Captures| {
let username = caps.get(1).unwrap().as_str();
let user_id = get_user_id(username);
if user_id == 0 {
format!("@{}", username)
} else {
mentions.push(user_id);
format!("[@{}]({}{})", username, "/user/", username)
}
});
let obj = json!({
"user_id": user_id.to_owned(),
"topic_id": topic_id.to_owned(),
"content": sync_upload_file(&*new_content.to_string())
});
let result = service_create_comment(&obj);
let mut data = JsonData::new();
if result.is_none() {
data.success = false;
data.message = "回复失败".to_string();
return respond_json(&data);
}
let comment_id = result.unwrap();
let topic = get_topic(topic_id).unwrap();
if topic.user_id != user_id.parse::<u16>().unwrap() { // 忽略作者自己的回复
create_message(&json!({
"comment_id": comment_id,
"topic_id": topic_id.to_owned(),
"from_user_id": user_id.to_owned(),
"to_user_id": topic.user_id,
"type": 0
}));
}
mentions.dedup();
for mention in mentions.iter().filter(|&id| *id != topic.user_id && *id != user_id.parse::<u16>().unwrap()) { // 忽略@作者或自己
create_message(&json!({
"comment_id": comment_id,
"topic_id": topic_id.to_owned(),
"from_user_id": user_id.to_owned(),
"to_user_id": mention,
"type": 1
}));
}
data.message = "发表评论成功".to_owned();
data.data = json!("/topic/".to_string() + topic_id);
respond_json(&data)
}
pub fn render_edit_comment(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let comment_id = params.find("comment_id").unwrap();
if !is_comment_created(comment_id) {
return redirect_to("/not-found");
}
let content_wrapper = get_comment_content(comment_id);
if content_wrapper.is_none() {
return redirect_to("/not-found");
}
let content = content_wrapper.unwrap();
let mut data = ViewData::new(req);
data.insert("comment_id", json!(comment_id.to_string()));
data.insert("content", json!(content));
respond_view("comment-editor", &data)
}
pub fn edit_comment(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let body = get_request_body(req);
let comment_id = params.find("comment_id").unwrap();
let content = &body.get("content").unwrap()[0];
let mut data = JsonData::new();
if !is_comment_created(comment_id) {
data.success = false;
data.message = "未找到该回复".to_owned();
return respond_json(&data);
}
let result = update_comment(comment_id, &json!({
"comment_id": comment_id.to_owned(),
"content": sync_upload_file(content)
}));
if result.is_none() {
data.success = false;
data.message = "修改回复失败".to_owned();
return respond_json(&data);
}
let topic_id = &*get_comment(comment_id).unwrap().topic_id;
data.message = "修改回复成功".to_owned();
data.data = json!("/topic/".to_string() + topic_id);
respond_json(&data)
}
pub fn delete_comment(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let comment_id = params.find("comment_id").unwrap();
let body = get_request_body(req);
let topic_id = &body.get("topicId").unwrap()[0];
let mut data = JsonData::new();
if !is_comment_created(comment_id) {
data.success = false;
data.message = "未找到该回复".to_owned();
return respond_json(&data);
}
let result = service_delete_comment(comment_id);
if result.is_none() {
data.success = false;
data.message = "删除回复失败".to_owned();
return respond_json(&data);
}
data.message = "删除回复成功".to_owned();
data.data = json!("/topic/".to_owned() + topic_id);
respond_json(&data)
}
pub fn vote_comment(req: &mut Request) -> IronResult<Response> {
let params = get_router_params(req);
let comment_id = params.find("comment_id").unwrap();
let body = get_request_body(req);
let user_id = &body.get("userId").unwrap()[0];
let state = &body.get("state").unwrap()[0];
let result;
if state == "0" {
result = delete_comment_vote(user_id, comment_id);
} else {
if is_voted(user_id, comment_id) {
result = update_comment_vote(user_id, comment_id, state);
} else {
result = create_comment_vote(user_id, comment_id, state);
}
}
let mut data = JsonData::new();
if result.is_none() {
data.success = false;
data.message = "更新失败".to_owned();
}
respond_json(&data)
}
|
use amethyst::{
core::transform::Transform,
ecs::prelude::{Entity, World},
prelude::*,
};
use crate::components::{Destination, Sprite, Sprites, Velocity, Worker};
pub fn init_worker(world: &mut World, local: Transform) -> Entity {
world
.create_entity()
.with(Worker {})
.with(local)
.with(Sprite {
sprite: Sprites::Worker,
})
.with(Velocity { x: 0.0, y: 0.0 })
.with(Destination { x: 192.0, y: 128.0 })
.build()
}
|
//! Module for the user-facing [`Context`] object.
use std::any::Any;
use std::future::Future;
use std::marker::PhantomData;
use instant::Instant;
use tokio::sync::mpsc::UnboundedSender;
use tokio::task::JoinHandle;
use super::graph::StateData;
use super::state::StateHandle;
use super::{StateId, SubgraphId};
/// The main state of the Hydroflow instance, which is provided as a reference
/// to each operator as it is run.
///
/// As an optimization, each Hydroflow instances stores eactly one Context
/// inline, which allows us to avoid any construction/deconstruction costs.
/// Before the `Context` is provided to a running operator, the `subgraph_id`
/// field must be updated.
pub struct Context {
pub(crate) states: Vec<StateData>,
// TODO(mingwei): as long as this is here, it's impossible to know when all work is done.
// Second field (bool) is for if the event is an external "important" event (true).
pub(crate) event_queue_send: UnboundedSender<(SubgraphId, bool)>,
pub(crate) current_tick: usize,
pub(crate) current_stratum: usize,
pub(crate) current_tick_start: Instant,
/// The SubgraphId of the currently running operator. When this context is
/// not being forwarded to a running operator, this field is (mostly)
/// meaningless.
pub(crate) subgraph_id: SubgraphId,
/// Join handles for spawned tasks.
pub(crate) task_join_handles: Vec<JoinHandle<()>>,
}
impl Context {
/// Gets the current tick (local time) count.
pub fn current_tick(&self) -> usize {
self.current_tick
}
/// Gets the timestamp of the beginning of the current tick.
pub fn current_tick_start(&self) -> Instant {
self.current_tick_start
}
/// Gets the current stratum nubmer.
pub fn current_stratum(&self) -> usize {
self.current_stratum
}
/// Gets the ID of the current subgraph.
pub fn current_subgraph(&self) -> SubgraphId {
self.subgraph_id
}
/// Schedules a subgraph.
pub fn schedule_subgraph(&self, sg_id: SubgraphId, is_external: bool) {
self.event_queue_send.send((sg_id, is_external)).unwrap()
}
/// Returns a `Waker` for interacting with async Rust.
/// Waker events are considered to be extenral.
pub fn waker(&self) -> std::task::Waker {
use std::sync::Arc;
use futures::task::ArcWake;
struct ContextWaker {
subgraph_id: SubgraphId,
event_queue_send: UnboundedSender<(SubgraphId, bool)>,
}
impl ArcWake for ContextWaker {
fn wake_by_ref(arc_self: &Arc<Self>) {
let _recv_closed_error =
arc_self.event_queue_send.send((arc_self.subgraph_id, true));
}
}
let context_waker = ContextWaker {
subgraph_id: self.subgraph_id,
event_queue_send: self.event_queue_send.clone(),
};
futures::task::waker(Arc::new(context_waker))
}
/// Returns a shared reference to the state.
pub fn state_ref<T>(&self, handle: StateHandle<T>) -> &T
where
T: Any,
{
self.states
.get(handle.state_id.0)
.expect("Failed to find state with given handle.")
.state
.downcast_ref()
.expect("StateHandle wrong type T for casting.")
}
/// Returns an exclusive reference to the state.
pub fn state_mut<T>(&mut self, handle: StateHandle<T>) -> &mut T
where
T: Any,
{
self.states
.get_mut(handle.state_id.0)
.expect("Failed to find state with given handle.")
.state
.downcast_mut()
.expect("StateHandle wrong type T for casting.")
}
/// Adds state to the context and returns the handle.
pub fn add_state<T>(&mut self, state: T) -> StateHandle<T>
where
T: Any,
{
let state_id = StateId(self.states.len());
let state_data = StateData {
state: Box::new(state),
};
self.states.push(state_data);
StateHandle {
state_id,
_phantom: PhantomData,
}
}
/// Removes state from the context returns it as an owned heap value.
pub fn remove_state<T>(&mut self, handle: StateHandle<T>) -> Box<T>
where
T: Any,
{
self.states
.remove(handle.state_id.0)
.state
.downcast()
.expect("StateHandle wrong type T for casting.")
}
/// Spawns an async task on the internal Tokio executor.
pub fn spawn_task<Fut>(&mut self, future: Fut)
where
Fut: Future<Output = ()> + 'static,
{
self.task_join_handles
.push(tokio::task::spawn_local(future));
}
/// Aborts all tasks spawned with [`Self::spawn_task`].
pub fn abort_tasks(&mut self) {
for task in self.task_join_handles.drain(..) {
task.abort();
}
}
/// Waits for all tasks spawned with [`Self::spawn_task`] to complete.
///
/// Will probably just hang.
pub async fn join_tasks(&mut self) {
futures::future::join_all(self.task_join_handles.drain(..)).await;
}
}
|
pub mod payload_types;
pub mod payload_serializers;
|
use thiserror::Error;
use warp::{reject::Reject, Rejection, Reply};
#[derive(Error, Debug, serde::Serialize)]
#[serde(untagged)]
pub enum Error {
#[error("Database error")]
DbError(
#[from]
#[serde(skip)]
sqlx::Error,
),
#[error(transparent)]
Session(#[from] super::SessionError),
#[error(transparent)]
Token(#[from] super::TokenError),
}
impl Reject for Error {}
#[derive(serde::Serialize)]
struct ErrorMessage<'e> {
error: &'e Error,
#[serde(skip_serializing_if = "Option::is_none")]
info: Option<String>,
}
pub async fn handle_error(err: Rejection) -> Result<impl Reply, Rejection> {
if let Some(e) = err.find::<Error>() {
let message = ErrorMessage {
error: e,
info: None,
};
let reply = warp::reply::json(&message);
return Ok(warp::reply::with_status(
reply,
warp::http::StatusCode::BAD_REQUEST,
));
}
Err(err)
}
|
// Corresponds to the R:N and W:N in the memory access text
#[derive(Debug, PartialEq)]
pub enum AccessType {
Read,
Write,
}
// Helps us keep track of the different results when trying to access a page
// MissSimple simply means that we can push the page because we have space in physical memory
// MissReplace is when we don't have space and need to evict a page
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum AccessResult {
MissSimple,
MissReplace(MissReplacement),
Hit,
}
// This helps us track who was replaced, at what index, and which page replaced the old one
// Did this so we can unit test and get accurate testing results
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct MissReplacement {
pub replaced : usize,
pub frame_index : usize,
pub new_page : usize,
}
impl MissReplacement {
// Constructor
pub fn new(replaced : usize , frame_index : usize , new_page : usize) -> MissReplacement {
MissReplacement {
replaced,
frame_index,
new_page,
}
}
}
// Simple data structure to represent the R:N and W:N in the text
pub struct MemoryAccess {
pub frame_number : usize,
pub access_type : AccessType,
}
impl MemoryAccess {
// Constructor to create a collection by parsing the input string
pub fn create(input_string : String) -> Vec<MemoryAccess> {
let vals = input_string
.split_whitespace()
.map(|ss| ss.split(':'))
.map(|mut ps| MemoryAccess {
access_type : match ps.next().unwrap() {
"R" => AccessType::Read,
"W" => AccessType::Write,
other => panic!("Invalid access token: {}", other),
},
frame_number : {
match ps.next().unwrap().parse::<usize>() {
Ok(n) => n,
Err(e) => panic!("Invalid memory access token: {}", e)
}
}});
vals.collect()
}
}
// Optimal and Second Chance Parameters from the CLI args
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub struct ORA_SCA_Params {
pub total_frames : usize,
pub access_string : String,
}
// WSClock Page Replacement Parameters from the CLI args
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub struct WSCPR_Params {
pub total_frames : usize,
pub access_string : String,
pub tau : usize,
}
impl ORA_SCA_Params {
// Constructor collecting CLI args directly, emitting errors in the process
pub fn get() -> ORA_SCA_Params {
let args : Vec<String> = std::env::args().collect();
let frames = parse_number("frame count", args.get(1))
.unwrap_or_else(|e| {
eprintln!("Args Error: {}", e);
std::process::exit(1);
});
let file = parse_file(args.get(2))
.unwrap_or_else(|e| {
eprintln!("Args Error: {}", e);
std::process::exit(1);
});
ORA_SCA_Params {
total_frames: frames,
access_string: file,
}
}
}
impl WSCPR_Params {
// Constructor collecting CLI args directly, emitting errors in the process
pub fn get() -> WSCPR_Params {
let args : Vec<String> = std::env::args().collect();
let frames = parse_number("frame count", args.get(1))
.unwrap_or_else(|e| {
eprintln!("Args Error: {}", e);
std::process::exit(1);
});
let tau = parse_number("tau", args.get(2))
.unwrap_or_else(|e| {
eprintln!("Args Error: {}", e);
std::process::exit(1);
});
let file = parse_file(args.get(3))
.unwrap_or_else(|e| {
eprintln!("Args Error: {}", e);
std::process::exit(1);
});
WSCPR_Params {
total_frames: frames,
access_string: file,
tau,
}
}
}
pub fn get_total_faults(results : &Vec<AccessResult>) -> usize {
results.iter()
.filter(|r| **r != AccessResult::Hit)
.count()
}
pub fn parse_file(filename : Option<&String>) -> Result<String, String> {
match filename {
None => Err(String::from("No filename provided")),
Some(f) => std::fs::read_to_string(f).map_err(|_| format!("File {} not found", f)),
}
}
pub fn parse_number(num_kind : &str , num_string : Option<&String>) -> Result<usize, String> {
match num_string {
None => Err(format!("No {} count provided", num_kind)),
Some(a) => a.parse::<usize>().map_err(|_| format!("Invalid {} count provided", num_kind)),
}
}
|
use crate::{
cmd::*,
keypair::{KeyTag, KeyType, Network, KEYTYPE_ED25519_STR, NETTYPE_MAIN_STR},
mnemonic::SeedType,
result::Result,
wallet::{ShardConfig, Wallet},
};
use std::path::PathBuf;
#[derive(Debug, StructOpt)]
/// Create a new wallet
pub enum Cmd {
Basic(Basic),
Sharded(Sharded),
}
#[derive(Debug, StructOpt)]
/// Create a new basic wallet
pub struct Basic {
#[structopt(short, long, default_value = "wallet.key")]
/// Output file to store the key in
output: PathBuf,
#[structopt(long)]
/// Overwrite an existing file
force: bool,
#[structopt(long, possible_values = &["bip39", "mobile"], case_insensitive = true)]
/// Use a BIP39 or mobile app seed phrase to generate the wallet keys
seed: Option<SeedType>,
#[structopt(long, default_value = NETTYPE_MAIN_STR)]
/// The network to generate the wallet (testnet/mainnet)
network: Network,
#[structopt(long, default_value = KEYTYPE_ED25519_STR)]
/// The type of key to generate (ecc_compact/ed25519)
key_type: KeyType,
}
#[derive(Debug, StructOpt)]
/// Create a new sharded wallet
pub struct Sharded {
#[structopt(short, long, default_value = "wallet.key")]
/// Output file to store the key in
output: PathBuf,
#[structopt(long)]
/// Overwrite an existing file
force: bool,
#[structopt(short = "n", long = "shards", default_value = "5")]
/// Number of shards to break the key into
key_share_count: u8,
#[structopt(short = "k", long = "required-shards", default_value = "3")]
/// Number of shards required to recover the key
recovery_threshold: u8,
#[structopt(long, possible_values = &["bip39", "mobile"], case_insensitive = true)]
/// Use a BIP39 or mobile app seed phrase to generate the wallet keys
seed: Option<SeedType>,
#[structopt(long, default_value = NETTYPE_MAIN_STR)]
/// The network to generate the wallet (testnet/mainnet)
network: Network,
#[structopt(long, default_value = KEYTYPE_ED25519_STR)]
/// The type of key to generate (ecc_compact/ed25519)
key_type: KeyType,
}
impl Cmd {
pub async fn run(&self, opts: Opts) -> Result {
match self {
Cmd::Basic(cmd) => cmd.run(opts).await,
Cmd::Sharded(cmd) => cmd.run(opts).await,
}
}
}
impl Basic {
pub async fn run(&self, opts: Opts) -> Result {
let seed_words = match &self.seed {
Some(seed_type) => Some(get_seed_words(seed_type)?),
None => None,
};
let password = get_password(true)?;
let tag = KeyTag {
network: self.network,
key_type: self.key_type,
};
let wallet = Wallet::builder()
.output(&self.output)
.password(&password)
.key_tag(&tag)
.force(self.force)
.seed_type(self.seed.to_owned())
.seed_words(seed_words)
.create()?;
verify::print_result(
&wallet,
&wallet.decrypt(password.as_bytes()),
None,
opts.format,
)
}
}
impl Sharded {
pub async fn run(&self, opts: Opts) -> Result {
let seed_words = match &self.seed {
Some(seed_type) => Some(get_seed_words(seed_type)?),
None => None,
};
let password = get_password(true)?;
let tag = KeyTag {
network: self.network,
key_type: self.key_type,
};
let shard_config = ShardConfig {
key_share_count: self.key_share_count,
recovery_threshold: self.recovery_threshold,
};
let wallet = Wallet::builder()
.output(&self.output)
.password(&password)
.key_tag(&tag)
.force(self.force)
.seed_type(self.seed.to_owned())
.seed_words(seed_words)
.shard(Some(shard_config))
.create()?;
verify::print_result(
&wallet,
&wallet.decrypt(password.as_bytes()),
None,
opts.format,
)
}
}
|
use device::LuxaforDeviceDescriptor;
pub const FULL_FLAG : LuxaforDeviceDescriptor = LuxaforDeviceDescriptor {
vendor_id: 0x04d8,
product_id: 0xf372
}; |
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
//! ???
use rayon::prelude::*;
use rustagious::{gen_phase_fn, Person, Phase};
use std::collections::HashMap;
//type Res = (String, u64, String, u64, String, u64);
type Res = (u64, u64);
fn main() {
println!("a, ac, c, ca, offset, a_test, b_test, n, tot_days_unaware, n_infected");
let n = 100_000;
//for (a, ac, c, ca) in gen_phases() {
#[allow(clippy::print_literal)]
gen_phases()
.par_iter()
.map(move |phase_desc| {
let (a, ac, c, ca, offset) = *phase_desc;
let cycle_len = a + ac + c + ca;
let phase_fn = &gen_phase_fn(a, ac, c, ca, offset);
for d in 0..cycle_len {
// isolate always, we keep that one
if a == 0 && c == 0 {
continue;
}
// if it's the weekend
if d % 7 == 5 || d % 7 == 6 {
// no isolation on the weekend...
if phase_fn(d) == Phase::Isolate {
return;
}
}
}
// A is getting tested
let a_test = true;
let outcomes = run_n(n, a_test, None, cycle_len, phase_fn);
for (res, n) in outcomes {
println!(
"{}, {}, {}, {}, {}, {}, {}, {}, {}, {}",
a, ac, c, ca, offset, a_test, "NA", n, res.0, res.1
);
}
// B is no getting tested
let a_test = false;
let outcomes = run_n(n, a_test, None, cycle_len, phase_fn);
for (res, n) in outcomes {
println!(
"{}, {}, {}, {}, {}, {}, {}, {}, {}, {}",
a, ac, c, ca, offset, a_test, "NA", n, res.0, res.1
);
}
/*
for b_test in 0..cycle_len {
let outcomes = run_n(n, Some(b_test), cycle_len, phase_fn);
for (res, n) in outcomes {
println!(
"{}, {}, {}, {}, {}, {}, {}, {}, {}",
a, ac, c, ca, offset, b_test, n, res.0, res.1
);
}
}
*/
})
.collect::<()>();
}
fn gen_phases() -> Vec<(u64, u64, u64, u64, u64)> {
let mut phases = Vec::new();
phases.push((1, 0, 1, 0, 0)); // alternating
for offset in 0..7 {
phases.push((16, 5, 16, 5, offset)); // current and variations
}
phases.push((14, 0, 0, 0, 0)); // always A-B
phases.push((0, 0, 14, 0, 0)); // always C-B
for duration in (14..43).step_by(14) {
phases.push((0, duration / 2, 0, duration / 2, 0)); // isolating completly
for tot_isolation_days in (0..11).step_by(2) {
let phase_duration = (duration - tot_isolation_days) / 2;
if phase_duration < 5 {
continue;
}
for ac in 0..(tot_isolation_days + 1) {
// no isolating on weekends
if ac > 5 || tot_isolation_days - ac > 5 {
continue;
}
for offset in 0..7 {
phases.push((
phase_duration,
ac,
phase_duration,
tot_isolation_days - ac,
offset,
));
}
}
}
}
phases
}
fn run_n(
n: u64,
a_test: bool,
b_test: Option<u64>,
cycle_len: u64,
phase_fn: &dyn Fn(u64) -> Phase,
) -> HashMap<Res, u64> {
let mut res = HashMap::new();
for day in 0..cycle_len {
for source in 1..4 {
for _ in 0..n {
let run = run_trial(day, source, a_test, b_test, cycle_len, phase_fn);
let cur = res.get(&run).or_else(|| Some(&0)).unwrap() + 1;
res.insert(run, cur);
}
}
}
res
}
/// Runs a single experiment
fn run_trial(
moment: u64,
who: u64,
a_test: bool,
b_test: Option<u64>,
cycle_len: u64,
phase_fn: &dyn Fn(u64) -> Phase,
) -> Res {
let mut a = Person::new();
let mut b = Person::new();
let mut c = Person::new();
match who {
1 => a.expose(moment), //, format!("A.{:}", moment)),
2 => b.expose(moment), //, format!("B.{:}", moment)),
3 => c.expose(moment), //, format!("C.{:}", moment)),
_ => unreachable!(),
}
let mut max_day = 0;
for day in moment..300 {
max_day = day;
// someone is isolating, stop sim
if a.is_isolating(day) || b.is_isolating(day) || c.is_isolating(day) {
break;
}
// everyone has recovered, stop
if a.has_recovered(day) && b.has_recovered(day) && c.has_recovered(day) {
break;
}
match day % 7 {
1 | 4 => {
if a_test {
a.test(day, 1);
}
}
0 | 3 => {}
_ => {}
}
if b_test.is_some() && day % cycle_len == b_test.unwrap() {
b.test(day, 2);
}
match phase_fn(day) {
Phase::A => b.interact(day, &mut a),
Phase::C => {
// a.interact(day, &mut z);
b.interact(day, &mut c);
}
Phase::Isolate => {}
}
}
(
a.days_unaware(max_day) + b.days_unaware(max_day) + c.days_unaware(max_day),
a.was_sick(max_day) as u64 + b.was_sick(max_day) as u64 + c.was_sick(max_day) as u64,
)
}
/*
fn get_source(p: &Person) -> String {
if let Some(infection) = p.get_infection() {
infection.source.to_string()
} else {
"-.00".to_string()
}
}
*/
|
#[doc = "Register `APB2SECSR` reader"]
pub type R = crate::R<APB2SECSR_SPEC>;
#[doc = "Field `SYSCFGSECF` reader - SYSCFGSECF"]
pub type SYSCFGSECF_R = crate::BitReader;
#[doc = "Field `TIM1SECF` reader - TIM1SECF"]
pub type TIM1SECF_R = crate::BitReader;
#[doc = "Field `SPI1SECF` reader - SPI1SECF"]
pub type SPI1SECF_R = crate::BitReader;
#[doc = "Field `TIM8SECF` reader - TIM8SECF"]
pub type TIM8SECF_R = crate::BitReader;
#[doc = "Field `USART1SECF` reader - USART1SECF"]
pub type USART1SECF_R = crate::BitReader;
#[doc = "Field `TIM15SECF` reader - TIM15SECF"]
pub type TIM15SECF_R = crate::BitReader;
#[doc = "Field `TIM16SECF` reader - TIM16SECF"]
pub type TIM16SECF_R = crate::BitReader;
#[doc = "Field `TIM17SECF` reader - TIM17SECF"]
pub type TIM17SECF_R = crate::BitReader;
#[doc = "Field `SAI1SECF` reader - SAI1SECF"]
pub type SAI1SECF_R = crate::BitReader;
#[doc = "Field `SAI2SECF` reader - SAI2SECF"]
pub type SAI2SECF_R = crate::BitReader;
#[doc = "Field `DFSDM1SECF` reader - DFSDM1SECF"]
pub type DFSDM1SECF_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - SYSCFGSECF"]
#[inline(always)]
pub fn syscfgsecf(&self) -> SYSCFGSECF_R {
SYSCFGSECF_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 11 - TIM1SECF"]
#[inline(always)]
pub fn tim1secf(&self) -> TIM1SECF_R {
TIM1SECF_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - SPI1SECF"]
#[inline(always)]
pub fn spi1secf(&self) -> SPI1SECF_R {
SPI1SECF_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - TIM8SECF"]
#[inline(always)]
pub fn tim8secf(&self) -> TIM8SECF_R {
TIM8SECF_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - USART1SECF"]
#[inline(always)]
pub fn usart1secf(&self) -> USART1SECF_R {
USART1SECF_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 16 - TIM15SECF"]
#[inline(always)]
pub fn tim15secf(&self) -> TIM15SECF_R {
TIM15SECF_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - TIM16SECF"]
#[inline(always)]
pub fn tim16secf(&self) -> TIM16SECF_R {
TIM16SECF_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - TIM17SECF"]
#[inline(always)]
pub fn tim17secf(&self) -> TIM17SECF_R {
TIM17SECF_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 21 - SAI1SECF"]
#[inline(always)]
pub fn sai1secf(&self) -> SAI1SECF_R {
SAI1SECF_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - SAI2SECF"]
#[inline(always)]
pub fn sai2secf(&self) -> SAI2SECF_R {
SAI2SECF_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 24 - DFSDM1SECF"]
#[inline(always)]
pub fn dfsdm1secf(&self) -> DFSDM1SECF_R {
DFSDM1SECF_R::new(((self.bits >> 24) & 1) != 0)
}
}
#[doc = "RCC APB2 security status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2secsr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB2SECSR_SPEC;
impl crate::RegisterSpec for APB2SECSR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb2secsr::R`](R) reader structure"]
impl crate::Readable for APB2SECSR_SPEC {}
#[doc = "`reset()` method sets APB2SECSR to value 0"]
impl crate::Resettable for APB2SECSR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
extern crate vmm;
#[macro_use(crate_version, crate_authors)]
extern crate clap;
use clap::{App, Arg};
use std::process;
use vmm::config;
fn main() {
let cmd_arguments = App::new("cloud-hypervisor")
.version(crate_version!())
.author(crate_authors!())
.about("Launch a cloud-hypervisor VMM.")
.arg(
Arg::with_name("cpus")
.long("cpus")
.help("Number of virtual CPUs")
.default_value(config::DEFAULT_VCPUS),
)
.arg(
Arg::with_name("memory")
.long("memory")
.help("Amount of RAM (in MiB)")
.default_value(config::DEFAULT_MEMORY),
)
.arg(
Arg::with_name("kernel")
.long("kernel")
.help("Path to kernel image (vmlinux)")
.takes_value(true),
)
.arg(
Arg::with_name("cmdline")
.long("cmdline")
.help("Kernel command line")
.takes_value(true),
)
.arg(
Arg::with_name("disk")
.long("disk")
.help("Path to VM disk image")
.takes_value(true)
.min_values(1),
)
.arg(
Arg::with_name("net")
.long("net")
.help(
"Network parameters \"tap=<if_name>,\
ip=<ip_addr>,mask=<net_mask>,mac=<mac_addr>\"",
)
.takes_value(true),
)
.arg(
Arg::with_name("rng")
.long("rng")
.help("Path to entropy source")
.default_value(config::DEFAULT_RNG_SOURCE),
)
.get_matches();
// These .unwrap()s cannot fail as there is a default value defined
let cpus = cmd_arguments.value_of("cpus").unwrap();
let memory = cmd_arguments.value_of("memory").unwrap();
let kernel = cmd_arguments
.value_of("kernel")
.expect("Missing argument: kernel");
let cmdline = cmd_arguments.value_of("cmdline");
let disks: Vec<&str> = cmd_arguments
.values_of("disk")
.expect("Missing argument: disk. Provide at least one")
.collect();
let net = cmd_arguments.value_of("net");
// This .unwrap() cannot fail as there is a default value defined
let rng = cmd_arguments.value_of("rng").unwrap();
let vm_config = match config::VmConfig::parse(config::VmParams {
cpus,
memory,
kernel,
cmdline,
disks,
rng,
net,
}) {
Ok(config) => config,
Err(e) => {
println!("Failed parsing parameters {:?}", e);
process::exit(1);
}
};
println!(
"Cloud Hypervisor Guest\n\tvCPUs: {}\n\tMemory: {} MB\
\n\tKernel: {:?}\n\tKernel cmdline: {}\n\tDisk(s): {:?}",
u8::from(&vm_config.cpus),
u64::from(&vm_config.memory),
vm_config.kernel.path,
vm_config.cmdline.args.as_str(),
vm_config.disks,
);
if let Err(e) = vmm::boot_kernel(vm_config) {
println!("Guest boot failed: {}", e);
process::exit(1);
}
}
#[cfg(test)]
#[cfg(feature = "integration_tests")]
#[macro_use]
extern crate credibility;
#[cfg(test)]
#[cfg(feature = "integration_tests")]
mod tests {
use ssh2::Session;
use std::fs;
use std::io::Read;
use std::net::TcpStream;
use std::process::Command;
use std::thread;
fn ssh_command(command: &str) -> String {
let mut s = String::new();
#[derive(Debug)]
enum Error {
Connection,
Authentication,
Command,
};
let mut counter = 0;
loop {
match (|| -> Result<(), Error> {
let tcp = TcpStream::connect("192.168.2.2:22").map_err(|_| Error::Connection)?;
let mut sess = Session::new().unwrap();
sess.handshake(&tcp).map_err(|_| Error::Connection)?;
sess.userauth_password("admin", "cloud123")
.map_err(|_| Error::Authentication)?;
assert!(sess.authenticated());
let mut channel = sess.channel_session().map_err(|_| Error::Command)?;
channel.exec(command).map_err(|_| Error::Command)?;
// Intentionally ignore these results here as their failure
// does not precipitate a repeat
let _ = channel.read_to_string(&mut s);
let _ = channel.close();
let _ = channel.wait_close();
Ok(())
})() {
Ok(_) => break,
Err(e) => {
counter += 1;
if counter >= 6 {
panic!("Took too many attempts to run command. Last error: {:?}", e);
}
}
};
thread::sleep(std::time::Duration::new(10, 0));
}
s
}
fn prepare_files() -> (Vec<&'static str>, String) {
let mut workload_path = dirs::home_dir().unwrap();
workload_path.push("workloads");
let mut fw_path = workload_path.clone();
fw_path.push("hypervisor-fw");
let mut osdisk_base_path = workload_path.clone();
osdisk_base_path.push("clear-29810-cloud.img");
let osdisk_path = "/tmp/osdisk.img";
let cloudinit_path = "/tmp/cloudinit.img";
fs::copy(osdisk_base_path, osdisk_path).expect("copying of OS source disk image failed");
let disks = vec![osdisk_path, cloudinit_path];
(disks, String::from(fw_path.to_str().unwrap()))
}
fn get_cpu_count() -> u32 {
ssh_command("grep -c processor /proc/cpuinfo")
.trim()
.parse()
.unwrap()
}
fn get_initial_apicid() -> u32 {
ssh_command("grep \"initial apicid\" /proc/cpuinfo | grep -o \"[0-9]*\"")
.trim()
.parse()
.unwrap()
}
fn get_total_memory() -> u32 {
ssh_command("grep MemTotal /proc/meminfo | grep -o \"[0-9]*\"")
.trim()
.parse::<u32>()
.unwrap()
}
fn get_entropy() -> u32 {
ssh_command("cat /proc/sys/kernel/random/entropy_avail")
.trim()
.parse::<u32>()
.unwrap()
}
#[test]
fn test_simple_launch() {
test_block!(tb, "", {
let (disks, fw_path) = prepare_files();
let mut child = Command::new("target/debug/cloud-hypervisor")
.args(&["--cpus", "1"])
.args(&["--memory", "512"])
.args(&["--kernel", fw_path.as_str()])
.args(&["--disk", disks[0], disks[1]])
.args(&["--net", "tap=,mac=,ip=192.168.2.1,mask=255.255.255.0"])
.spawn()
.unwrap();
thread::sleep(std::time::Duration::new(10, 0));
aver_eq!(tb, get_cpu_count(), 1);
aver_eq!(tb, get_initial_apicid(), 0);
aver!(tb, get_total_memory() > 496_000);
aver!(tb, get_entropy() >= 1000);
ssh_command("sudo reboot");
thread::sleep(std::time::Duration::new(10, 0));
let _ = child.kill();
let _ = child.wait();
Ok(())
});
}
#[test]
fn test_multi_cpu() {
test_block!(tb, "", {
let (disks, fw_path) = prepare_files();
let mut child = Command::new("target/debug/cloud-hypervisor")
.args(&["--cpus", "2"])
.args(&["--memory", "512"])
.args(&["--kernel", fw_path.as_str()])
.args(&["--disk", disks[0], disks[1]])
.args(&["--net", "tap=,mac=,ip=192.168.2.1,mask=255.255.255.0"])
.spawn()
.unwrap();
thread::sleep(std::time::Duration::new(10, 0));
aver_eq!(tb, get_cpu_count(), 2);
ssh_command("sudo reboot");
thread::sleep(std::time::Duration::new(10, 0));
let _ = child.kill();
let _ = child.wait();
Ok(())
});
}
#[test]
fn test_large_memory() {
test_block!(tb, "", {
let (disks, fw_path) = prepare_files();
let mut child = Command::new("target/debug/cloud-hypervisor")
.args(&["--cpus", "1"])
.args(&["--memory", "5120"])
.args(&["--kernel", fw_path.as_str()])
.args(&["--disk", disks[0], disks[1]])
.args(&["--net", "tap=,mac=,ip=192.168.2.1,mask=255.255.255.0"])
.spawn()
.unwrap();
thread::sleep(std::time::Duration::new(10, 0));
aver!(tb, get_total_memory() > 5_063_000);
ssh_command("sudo reboot");
thread::sleep(std::time::Duration::new(10, 0));
let _ = child.kill();
let _ = child.wait();
Ok(())
});
}
#[test]
fn test_pci_msi() {
test_block!(tb, "", {
let (disks, fw_path) = prepare_files();
let mut child = Command::new("target/debug/cloud-hypervisor")
.args(&["--cpus", "1"])
.args(&["--memory", "512"])
.args(&["--kernel", fw_path.as_str()])
.args(&["--disk", disks[0], disks[1]])
.args(&["--net", "tap=,mac=,ip=192.168.2.1,mask=255.255.255.0"])
.spawn()
.unwrap();
thread::sleep(std::time::Duration::new(10, 0));
aver_eq!(
tb,
ssh_command("grep -c PCI-MSI /proc/interrupts")
.trim()
.parse::<u32>()
.unwrap(),
8
);
ssh_command("sudo reboot");
thread::sleep(std::time::Duration::new(10, 0));
let _ = child.kill();
let _ = child.wait();
Ok(())
});
}
#[test]
fn test_vmlinux_boot() {
test_block!(tb, "", {
let (disks, _) = prepare_files();
let mut workload_path = dirs::home_dir().unwrap();
workload_path.push("workloads");
let mut kernel_path = workload_path.clone();
kernel_path.push("vmlinux");
let mut child = Command::new("target/debug/cloud-hypervisor")
.args(&["--cpus", "1"])
.args(&["--memory", "512"])
.args(&["--kernel", kernel_path.to_str().unwrap()])
.args(&["--disk", disks[0], disks[1]])
.args(&["--net", "tap=,mac=,ip=192.168.2.1,mask=255.255.255.0"])
.args(&["--cmdline", "root=PARTUUID=3cb0e0a5-925d-405e-bc55-edf0cec8f10a console=tty0 console=ttyS0,115200n8 console=hvc0 quiet init=/usr/lib/systemd/systemd-bootchart initcall_debug tsc=reliable no_timer_check noreplace-smp cryptomgr.notests rootfstype=ext4,btrfs,xfs kvm-intel.nested=1 rw"])
.spawn()
.unwrap();
thread::sleep(std::time::Duration::new(10, 0));
aver_eq!(tb, get_cpu_count(), 1);
aver!(tb, get_total_memory() > 496_000);
aver!(tb, get_entropy() >= 1000);
aver_eq!(
tb,
ssh_command("grep -c PCI-MSI /proc/interrupts")
.trim()
.parse::<u32>()
.unwrap(),
8
);
ssh_command("sudo reboot");
thread::sleep(std::time::Duration::new(10, 0));
let _ = child.kill();
let _ = child.wait();
Ok(())
});
}
#[test]
fn test_bzimage_boot() {
test_block!(tb, "", {
let (disks, _) = prepare_files();
let mut workload_path = dirs::home_dir().unwrap();
workload_path.push("workloads");
let mut kernel_path = workload_path.clone();
kernel_path.push("bzImage");
let mut child = Command::new("target/debug/cloud-hypervisor")
.args(&["--cpus", "1"])
.args(&["--memory", "512"])
.args(&["--kernel", kernel_path.to_str().unwrap()])
.args(&["--disk", disks[0], disks[1]])
.args(&["--net", "tap=,mac=,ip=192.168.2.1,mask=255.255.255.0"])
.args(&["--cmdline", "root=PARTUUID=3cb0e0a5-925d-405e-bc55-edf0cec8f10a console=tty0 console=ttyS0,115200n8 console=hvc0 quiet init=/usr/lib/systemd/systemd-bootchart initcall_debug tsc=reliable no_timer_check noreplace-smp cryptomgr.notests rootfstype=ext4,btrfs,xfs kvm-intel.nested=1 rw"])
.spawn()
.unwrap();
thread::sleep(std::time::Duration::new(10, 0));
aver_eq!(tb, get_cpu_count(), 1);
aver!(tb, get_total_memory() > 496_000);
aver!(tb, get_entropy() >= 1000);
aver_eq!(
tb,
ssh_command("grep -c PCI-MSI /proc/interrupts")
.trim()
.parse::<u32>()
.unwrap(),
8
);
ssh_command("sudo reboot");
thread::sleep(std::time::Duration::new(10, 0));
let _ = child.kill();
let _ = child.wait();
Ok(())
});
}
}
|
//! Responses from MetroBus related methods from the WMATA API.
use crate::{Route, Stop};
use chrono::{DateTime, FixedOffset};
use serde::Deserialize;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct BusPositions {
/// See [`BusPosition`].
pub bus_positions: Box<[BusPosition]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct BusPosition {
/// Date and time (Eastern Standard Time) of last position update.
#[serde(deserialize_with = "crate::date::deserialize")]
pub date_time: DateTime<FixedOffset>,
/// Deviation, in minutes, from schedule. Positive values indicate that the bus is running late while negative ones are for buses running ahead of schedule.
pub deviation: f64,
/// Deprecated. Use the DirectionText for a customer-friendly description of direction.
#[serde(rename = "DirectionNum")]
pub direction_number: i32,
/// General direction of the trip, not the bus itself (e.g.: NORTH, SOUTH, EAST, WEST).
pub direction_text: String,
/// Latitude of bus.
#[serde(rename = "Lat")]
pub latitude: f64,
/// Longitude of bus.
#[serde(rename = "Lon")]
pub longitude: f64,
/// Base route name as shown on the bus. Note that the base route name could also refer to any variant, so a RouteID of 10A could refer to 10A, 10Av1, 10Av2, etc.
#[serde(rename = "RouteID")]
pub route: Route,
/// Scheduled end date and time (Eastern Standard Time) of the bus's current trip.
#[serde(deserialize_with = "crate::date::deserialize")]
pub trip_end_time: DateTime<FixedOffset>,
/// Destination of the bus.
pub trip_headsign: String,
/// Unique trip ID. This can be correlated with the data returned from the schedule-related methods.
#[serde(rename = "TripID")]
pub trip_id: String,
/// Scheduled start date and time (Eastern Standard Time) of the bus's current trip.
#[serde(deserialize_with = "crate::date::deserialize")]
pub trip_start_time: DateTime<FixedOffset>,
/// Unique identifier for the bus. This is usually visible on the bus itself.
#[serde(rename = "VehicleID")]
pub vehicle_id: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Routes {
/// See [`Route`].
pub routes: Box<[RouteResponse]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct RouteResponse {
/// Unique identifier for a given route variant. Can be used in various other bus-related methods.
#[serde(rename = "RouteID")]
pub route: Route,
/// Descriptive name of the route variant.
pub name: String,
/// Denotes the route variant’s grouping – lines are a combination of routes which lie in the same corridor and which have significant portions of their paths along the same roadways.
pub line_description: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Stops {
/// See [`Stop`].
pub stops: Box<[StopResponse]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct StopResponse {
/// 7-digit regional ID which can be used in various bus-related methods. If unavailable, the StopID will be 0 or NULL.
#[serde(rename = "StopID")]
pub stop: Option<Stop>,
/// Stop name. May be slightly different from what is spoken or displayed in the bus.
pub name: String,
/// Latitude of stop.
#[serde(rename = "Lat")]
pub latitude: f64,
/// Longitude of bus.
#[serde(rename = "Lon")]
pub longitude: f64,
/// String array of route variants which provide service at this stop. Note that these are not date-specific; any route variant which stops at this stop on any day will be listed.
pub routes: Box<[Route]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Incidents {
/// See [`Incident`]
#[serde(rename = "BusIncidents")]
pub incidents: Box<[Incident]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Incident {
/// Date and time (Eastern Standard Time) of last update.
#[serde(deserialize_with = "crate::date::deserialize")]
pub date_updated: DateTime<FixedOffset>,
/// Free-text description of the delay or incident.
pub description: String,
/// Unique identifier for an incident.
#[serde(rename = "IncidentID")]
pub incident_id: String,
/// Free-text description of the incident type. Usually Delay or Alert but is subject to change at any time.
pub incident_type: String,
/// Array containing routes affected. Routes listed are usually identical to base route names (i.e.: not 10Av1 or 10Av2, but 10A), but may differ from what our bus methods return.
pub routes_affected: Box<[Route]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct PathDetails {
/// [`Route`] of the route.
#[serde(rename = "RouteID")]
pub route: Route,
/// Descriptive name for the route.
pub name: String,
/// Structures describing path/stop information.
/// Most routes will return content in both Direction0 and Direction1 elements, though a few will return NULL for Direction0 or for Direction1.
/// 0 or 1 are binary properties. There is no specific mapping to direction, but a different value for the same route signifies that the route is in an opposite direction.
#[serde(rename = "Direction0")]
pub direction_zero: PathDirection,
/// Structures describing path/stop information.
/// Most routes will return content in both Direction0 and Direction1 elements, though a few will return NULL for Direction0 or for Direction1.
/// 0 or 1 are binary properties. There is no specific mapping to direction, but a different value for the same route signifies that the route is in an opposite direction.
#[serde(rename = "Direction1")]
pub direction_one: PathDirection,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct PathDirection {
/// Descriptive text of where the bus is headed. This is similar, but not necessarily identical, to what is displayed on the bus.
pub trip_headsign: String,
/// General direction of the route variant (NORTH, SOUTH, EAST, WEST, LOOP, etc.).
pub direction_text: String,
/// Warning: Deprecated. Use the DirectionText element to denote the general direction of the route variant.
#[serde(rename = "DirectionNum")]
pub direction_number: String,
/// See [`PathStop`]
pub shape: Box<[PathShape]>,
/// See [`Stop`]
pub stops: Box<[StopRoutes]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct PathShape {
/// Latitude of stop.
#[serde(rename = "Lat")]
pub latitude: f64,
/// Longitude of stop.
#[serde(rename = "Lon")]
pub longitude: f64,
/// Order of the point in the sequence of PathStop.
#[serde(rename = "SeqNum")]
pub sequence_number: i32,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Predictions {
/// See [`Prediction`].
pub predictions: Box<[Prediction]>,
/// Full name of the given StopID.
pub stop_name: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Prediction {
/// Denotes a binary direction (0 or 1) of the bus. There is no specific mapping to direction, but a different value for the same route signifies that the buses are traveling in opposite directions. Use the DirectionText element to show the actual destination of the bus.
#[serde(rename = "DirectionNum")]
pub direction_number: String,
/// Customer-friendly description of direction and destination for a bus.
pub direction_text: String,
/// Minutes until bus arrival at this stop.
pub minutes: i32,
#[serde(rename = "RouteID")]
/// [`Route`] of the bus. Base route name as shown on the bus. This can be used in other bus-related methods. Note that all variants will be shown as their base route names (i.e.: 10Av1 and 10Av2 will be shown as 10A).
pub route: Route,
/// Trip identifier. This can be correlated with the data in our bus schedule information as well as bus positions.
#[serde(rename = "TripID")]
pub trip_id: String,
/// Bus identifier. This can be correlated with results returned from bus positions.
#[serde(rename = "VehicleID")]
pub vehicle_id: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct StopSchedule {
/// See [`Arrival`].
#[serde(rename = "ScheduleArrivals")]
pub arrivals: Box<[Arrival]>,
/// See [`StopRoutes`].
pub stop: StopRoutes,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Arrival {
/// Date and time (Eastern Standard Time) when the bus is scheduled to stop at this location.
#[serde(deserialize_with = "crate::date::deserialize")]
pub schedule_time: DateTime<FixedOffset>,
/// Denotes a binary direction (0 or 1) of the bus. There is no specific mapping to direction, but a different value for the same route signifies that the buses are traveling in opposite directions. Use the TripDirectionText element to show the actual destination of the bus.
#[serde(rename = "DirectionNum")]
pub direction_number: String,
/// Scheduled start date and time (Eastern Standard Time) for this trip.
#[serde(deserialize_with = "crate::date::deserialize")]
pub start_time: DateTime<FixedOffset>,
/// Scheduled end date and time (Eastern Standard Time) for this trip.
#[serde(deserialize_with = "crate::date::deserialize")]
pub end_time: DateTime<FixedOffset>,
/// [`Route`] of the bus. Bus route variant identifier (pattern). This variant can be used in several other bus methods which accept variants. Note that customers will never see anything other than the base route name, so variants 10A, 10Av1, 10Av2, etc. will be displayed as 10A on the bus.
#[serde(rename = "RouteID")]
pub route: Route,
/// General direction of the trip (e.g.: NORTH, SOUTH, EAST, WEST).
pub trip_direction_text: String,
/// Destination of the bus.
pub trip_headsign: String,
/// Trip identifier. This can be correlated with the data in our bus schedule information as well as bus positions.
#[serde(rename = "TripID")]
pub trip_id: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct StopRoutes {
/// 7-digit regional ID which can be used in various bus-related methods. If unavailable, the StopID will be 0 or NULL.
#[serde(rename = "StopID")]
pub stop: Option<Stop>,
/// Stop name. May be slightly different from what is spoken or displayed in the bus.
pub name: String,
/// Latitude of stop.
#[serde(rename = "Lat")]
pub latitude: f64,
/// Longitude of stop.
#[serde(rename = "Lon")]
pub longitude: f64,
/// String array of route variants which provide service at this stop. Note that these are not date-specific; any route variant which stops at this stop on any day will be listed.
pub routes: Box<[Route]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct RouteSchedule {
/// Descriptive name for the route.
pub name: String,
/// See [`RouteInfo`].
#[serde(rename = "Direction0")]
pub direction_zero: Box<[RouteInfo]>,
/// See [`RouteInfo`].
#[serde(rename = "Direction1")]
pub direction_one: Box<[RouteInfo]>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct RouteInfo {
/// [`Route`] of the route. Bus route variant. This can be used in several other bus methods which accept variants.
#[serde(rename = "RouteID")]
pub route: Route,
/// Warning: Deprecated. Use the TripDirectionText element to denote the general direction of the trip.
#[serde(rename = "DirectionNum")]
pub direction_number: String,
/// General direction of the trip (NORTH, SOUTH, EAST, WEST, LOOP, etc.).
pub trip_direction_text: String,
/// Descriptive text of where the bus is headed. This is similar, but not necessarily identical, to what is displayed on the bus.
pub trip_headsign: String,
/// Scheduled start date and time (Eastern Standard Time) for this trip. Will be in YYYY-MM-DDTHH:mm:ss format (e.g.: 2014-10-27T13:17:00).
#[serde(deserialize_with = "crate::date::deserialize")]
pub start_time: DateTime<FixedOffset>,
/// Scheduled end date and time (Eastern Standard Time) for this trip. Will be in YYYY-MM-DDTHH:mm:ss format (e.g.: 2014-10-27T13:17:00).
#[serde(deserialize_with = "crate::date::deserialize")]
pub end_time: DateTime<FixedOffset>,
/// See [`StopInfo`].
pub stop_times: Box<[StopInfo]>,
/// Unique trip ID. This can be correlated with the data returned from the schedule-related methods.
#[serde(rename = "TripID")]
pub trip_id: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct StopInfo {
/// 7-digit regional ID which can be used in various bus-related methods. If unavailable, the StopID will be 0 or NULL.
#[serde(rename = "StopID")]
pub stop: Stop,
/// Stop name. May be slightly different from what is spoken or displayed in the bus.
pub stop_name: String,
/// Order of the stop in the sequence of StopInfo.
#[serde(rename = "StopSeq")]
pub stop_sequence: i32,
/// Scheduled departure date and time (Eastern Standard Time) from this stop.
#[serde(deserialize_with = "crate::date::deserialize")]
pub time: DateTime<FixedOffset>,
}
|
use std::ffi::CStr;
use assets::AssetId;
use crypto::{PublicKey, Signature};
use hex::FromHex;
use libc::{c_char, size_t};
use error::{Error, ErrorKind};
pub fn hex_string(bytes: Vec<u8>) -> String {
let strs: Vec<String> = bytes.iter().map(|b| format!("{:02x}", b)).collect();
strs.join("")
}
pub fn parse_str<'a>(string: *const c_char) -> Result<&'a str, Error> {
match unsafe { CStr::from_ptr(string).to_str() } {
Ok(string_str) => Ok(string_str),
Err(err) => Err(Error::new(ErrorKind::Utf8(err))),
}
}
pub fn parse_public_key(public_key: *const c_char) -> Result<PublicKey, Error> {
let pk_str = parse_str(public_key)?;
match PublicKey::from_hex(pk_str) {
Ok(pk) => Ok(pk),
Err(err) => Err(Error::new(ErrorKind::Hex(err))),
}
}
pub fn parse_signature(signature: *const c_char) -> Result<Signature, Error> {
let sig_str = parse_str(signature)?;
match Signature::from_hex(sig_str) {
Ok(sig) => Ok(sig),
Err(err) => Err(Error::new(ErrorKind::Hex(err))),
}
}
pub fn parse_asset_id(asset_id: *const c_char) -> Result<AssetId, Error> {
let asset_id_str = parse_str(asset_id)?;
match AssetId::from_hex(asset_id_str) {
Ok(asset_id) => Ok(asset_id),
Err(err) => Err(Error::new(ErrorKind::Asset(err))),
}
}
ffi_fn! {
fn dmbc_bytes_free(ptr: *mut u8, len: size_t) {
let len = len as usize;
unsafe {
drop(Vec::from_raw_parts(ptr, len, len));
}
}
}
|
use crate::{
enum_default, enum_display, enum_fmt_impl, enum_impls, impl_enums,
};
use std::fmt::Binary;
use std::fmt::Display;
use std::fmt::LowerHex;
use std::fmt::Octal;
use std::fmt::UpperHex;
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum Weight {
Default,
Bold = 1,
Dim = 2,
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum Underline {
Default,
Single = 4,
Double = 21,
}
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct StyleMap {
weight: Weight,
underline: Underline,
italic: bool,
blink: bool,
invert: bool,
hidden: bool
}
impl_enums!(Weight, Underline);
impl Display for StyleMap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut ansi_str = String::with_capacity(3);
// initially set it to the weight if there is one
if self.weight != Weight::Default {
ansi_str += format!("\x1b[{}m", self.weight).as_str();
}
if self.underline != Underline::Default {
ansi_str += format!("\x1b[{}m", self.underline).as_str();
}
if self.italic {
ansi_str += "\x1b[3m";
}
if self.blink {
ansi_str += "\x1b[6m"
}
if self.invert {
ansi_str += "\x1b[7m";
}
if self.hidden {
ansi_str += "\x1b[8m";
}
write!(f, "{}", ansi_str)
}
}
impl StyleMap {
pub fn reset_style(&mut self) -> &mut Self {
self.reset_weight();
self.stop_blink();
self.no_underline();
self.unitalic();
self.uninvert();
self.unhide();
self
}
pub fn reset_weight(&mut self) -> &mut Self {
self.weight = Weight::Default;
self
}
pub fn bold(&mut self) -> &mut Self {
self.weight = Weight::Bold;
self
}
pub fn dim(&mut self) -> &mut Self {
self.weight = Weight::Dim;
self
}
pub fn is_normal_weight(&self) -> bool {
self.weight == Weight::Default
}
pub fn is_bold(&self) -> bool {
self.weight == Weight::Bold
}
pub fn is_dim(&self) -> bool {
self.weight == Weight::Dim
}
pub fn italic(&mut self) -> &mut Self {
self.italic = true;
self
}
pub fn unitalic(&mut self) -> &mut Self {
self.italic = false;
self
}
pub const fn is_italicized(&self) -> bool {
self.italic
}
pub fn no_underline(&mut self) -> &mut Self {
self.underline = Underline::Default;
self
}
pub fn underline(&mut self) -> &mut Self {
self.underline = Underline::Single;
self
}
pub fn double_underline(&mut self) -> &mut Self {
self.underline = Underline::Double;
self
}
pub fn num_underlines(&self) -> u8 {
match self.underline {
Underline::Default => 0,
Underline::Single => 1,
Underline::Double => 2,
}
}
pub fn has_underlines(&self) -> bool {
self.underline != Underline::Default
}
pub fn is_single_underlined(&self) -> bool {
self.underline == Underline::Single
}
pub fn is_double_underlined(&self) -> bool {
self.underline == Underline::Double
}
pub fn stop_blink(&mut self) -> &mut Self {
self.blink = false;
self
}
pub fn blink(&mut self) -> &mut Self {
self.blink = true;
self
}
pub const fn is_blinking(&self) -> bool {
self.blink
}
pub fn invert(&mut self) -> &mut Self {
self.invert = true;
self
}
pub fn uninvert(&mut self) -> &mut Self {
self.invert = false;
self
}
pub const fn is_inverted(&self) -> bool {
self.invert
}
pub fn hide(&mut self) -> &mut Self {
self.hidden = true;
self
}
pub fn unhide(&mut self) -> &mut Self {
self.hidden = false;
self
}
pub const fn is_hidden(&self) -> bool {
self.hidden
}
}
|
// https://doc.rust-lang.org/std/primitive.u32.html
fn main() {
proconio::input! {
n: usize,
a: [i32; n]
}
println!("{}", a.iter()
.map(|x| x.trailing_zeros())
.min()
.unwrap()
);
}
|
use preexplorer::prelude::*;
fn main() -> anyhow::Result<()> {
let times = vec![1., 10., 100.];
let values = vec![1, 2, 4];
(times, values)
.preexplore()
.set_title("My Title")
.set_logx(-3) // Negative values imply logx(10), gnuplot sintaxis
.plot("identifier")?;
Ok(())
}
|
use crate::network_group::{Group, NetworkGroup};
use crate::{multiaddr::Multiaddr, ProtocolId, ProtocolVersion, SessionType};
use p2p::{secio::PeerId, SessionId};
use std::collections::HashMap;
use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub struct PeerIdentifyInfo {
pub client_version: String,
}
#[derive(Clone, Debug)]
pub struct Peer {
pub connected_addr: Multiaddr,
pub listened_addrs: Vec<Multiaddr>,
pub peer_id: PeerId,
// Client or Server
pub identify_info: Option<PeerIdentifyInfo>,
pub last_ping_time: Option<Instant>,
pub last_message_time: Option<Instant>,
pub ping: Option<Duration>,
pub is_feeler: bool,
pub connected_time: Instant,
pub session_id: SessionId,
pub session_type: SessionType,
pub protocols: HashMap<ProtocolId, ProtocolVersion>,
pub is_whitelist: bool,
}
impl Peer {
pub fn new(
session_id: SessionId,
session_type: SessionType,
peer_id: PeerId,
connected_addr: Multiaddr,
is_whitelist: bool,
) -> Self {
Peer {
connected_addr,
listened_addrs: Vec::new(),
identify_info: None,
ping: None,
last_ping_time: None,
last_message_time: None,
connected_time: Instant::now(),
is_feeler: false,
peer_id,
session_id,
session_type,
protocols: HashMap::with_capacity_and_hasher(1, Default::default()),
is_whitelist,
}
}
pub fn is_outbound(&self) -> bool {
self.session_type.is_outbound()
}
pub fn is_inbound(&self) -> bool {
self.session_type.is_inbound()
}
pub fn network_group(&self) -> Group {
self.connected_addr.network_group()
}
pub fn protocol_version(&self, protocol_id: ProtocolId) -> Option<ProtocolVersion> {
self.protocols.get(&protocol_id).cloned()
}
}
|
use std::{fs, io};
fn main() -> io::Result<()> {
let input = fs::read_to_string("input.txt")?
.trim()
.split('\n')
.map(|x| x.parse().expect("not a number"))
.collect::<Vec<u64>>();
for a in &input {
if *a < 2020 {
for b in &input {
if a + b < 2020 {
for c in &input {
if a + b + c == 2020 {
println!("{:?}", a * b * c);
return Ok(());
}
}
}
}
}
}
Ok(())
}
|
/// An enum to represent all characters in the CJKUnifiedIdeographsExtensionF block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum CJKUnifiedIdeographsExtensionF {
/// \u{2ceb0}: '𬺰'
CjkIdeographExtensionFFirst,
/// \u{2ebe0}: '𮯠'
CjkIdeographExtensionFLast,
}
impl Into<char> for CJKUnifiedIdeographsExtensionF {
fn into(self) -> char {
match self {
CJKUnifiedIdeographsExtensionF::CjkIdeographExtensionFFirst => '𬺰',
CJKUnifiedIdeographsExtensionF::CjkIdeographExtensionFLast => '𮯠',
}
}
}
impl std::convert::TryFrom<char> for CJKUnifiedIdeographsExtensionF {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'𬺰' => Ok(CJKUnifiedIdeographsExtensionF::CjkIdeographExtensionFFirst),
'𮯠' => Ok(CJKUnifiedIdeographsExtensionF::CjkIdeographExtensionFLast),
_ => Err(()),
}
}
}
impl Into<u32> for CJKUnifiedIdeographsExtensionF {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for CJKUnifiedIdeographsExtensionF {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for CJKUnifiedIdeographsExtensionF {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl CJKUnifiedIdeographsExtensionF {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
CJKUnifiedIdeographsExtensionF::CjkIdeographExtensionFFirst
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("CJKUnifiedIdeographsExtensionF{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
extern crate byteorder;
extern crate i2cdev;
extern crate rust_pigpio;
use self::rust_pigpio::pwm::*;
use self::rust_pigpio::*;
pub struct Servo {
pub pwm_pin: u32,
}
impl Servo {
pub fn init(&self) {
set_mode(self.pwm_pin, OUTPUT).unwrap();
servo(self.pwm_pin, 0).unwrap();
//set_pwm_frequency(self.pwm_pin, 500).unwrap();
//set_pwm_range(self.pwm_pin, 1000).unwrap();
}
pub fn set_pulse_width(&self, mut width: u32) {
if width < 500 {
width = 500;
}
if width > 2500 {
width = 2500;
}
servo(self.pwm_pin, width).unwrap();
}
}
pub fn build_servo(pwm_pin: u32) -> Servo {
Servo { pwm_pin }
}
|
/* This is part of mktcb - which is under the MIT License ********************/
use snafu::{Snafu};
#[derive(Debug, Snafu)]
#[snafu(visibility(pub))]
pub enum Error {
#[snafu(display("Failed to initialize logging"))]
LogInitFailed {
},
#[snafu(display("The version must be of format 'X.Y'. Found {}", orig))]
InvalidVersionFormat {
orig: String,
},
#[snafu(display("Failed to parse version component in '{}': {}", string, source))]
InvalidVersionNumber {
source: std::num::ParseIntError,
string: String,
},
#[snafu(display("Cannot retrieve Linux updates because no source has been downloaded (run --fetch?)"))]
LinuxNotFetched {
},
#[snafu(display("The URL to retrieve Linux seems invalid: {}", source))]
InvalidLinuxURL {
source: url::ParseError,
},
#[snafu(display("The URL to retrieve the toolchain seems invalid: {}", source))]
InvalidToolchainURL {
source: url::ParseError,
},
#[snafu(display("The URL to retrieve U-Boot seems invalid: {}", source))]
InvalidUbootURL {
source: url::ParseError,
},
#[snafu(display("Failed to read version file {:#?}: {}", path, source))]
FailedToReadVersion {
path: std::path::PathBuf,
source: std::io::Error,
},
#[snafu(display("Failed to decode UTF-8 string {}", source))]
FailedToDecodeUTF8 {
source: std::string::FromUtf8Error,
},
#[snafu(display("Corrupted download directory: the version file {:#?} does \
not exist, but the source directory {:#?} exists. Please remove this directory.",
version_file, dir))]
CorruptedSourceDir {
dir: std::path::PathBuf,
version_file: std::path::PathBuf,
},
#[snafu(display("Could not retrieve current directory: {}", source))]
CwdAccess {
source: std::io::Error,
},
#[snafu(display("Target option (--target, -t) is required"))]
MissingTarget {
},
#[snafu(display("Invalid job number: {}", source))]
InvalidJobNumber {
source: std::num::ParseIntError,
},
#[snafu(display("A value of 0 jobs is meaningless"))]
ZeroJob {
},
#[snafu(display("Failed to read file {:#?}: {}", path, source))]
FailedToRead {
path: std::path::PathBuf,
source: std::io::Error,
},
#[snafu(display("Failed to open file {:#?}: {}", path, source))]
FailedToOpen {
path: std::path::PathBuf,
source: std::io::Error,
},
#[snafu(display("Failed to decode Xz data at path {:#?}: {}", path, source))]
FailedToDecodeXz {
path: std::path::PathBuf,
source: std::io::Error,
},
#[snafu(display("Failed to read file {:#?}: {}", path, source))]
FailedToDeser {
path: std::path::PathBuf,
source: toml::de::Error,
},
#[snafu(display("File {:#?} does not exist", path))]
FileDoesNotExist {
path: std::path::PathBuf,
},
#[snafu(display("Ill-formed path {:#?}", path))]
IllFormedPath {
path: std::path::PathBuf,
},
#[snafu(display("Failed to run process '{}': {}", proc, source))]
ProgFailed {
source: std::io::Error,
proc: String,
},
#[snafu(display("Failed to decompress {:#?}", path))]
TarFailed {
path: std::path::PathBuf,
},
#[snafu(display("Failed to apply patch to {:#?}", path))]
PatchFailed {
path: std::path::PathBuf,
},
#[snafu(display("Archive {:#?} was expected to be decompressed as directory {:#?}", arch, dir))]
UnexpectedUntar {
arch: std::path::PathBuf,
dir: std::path::PathBuf,
},
#[snafu(display("Failed to create directory {:?}: {}", path, source))]
CreateDirError {
source: std::io::Error,
path: std::path::PathBuf,
},
#[snafu(display("Failed to create/open file {:#?}: {}", path, source))]
CreateFileError {
source: std::io::Error,
path: std::path::PathBuf,
},
#[snafu(display("curl refused url '{:#?}': {}", url, source))]
URLError {
source: curl::Error,
url: url::Url,
},
#[snafu(display("Failed to setup curl: {}", source))]
CURLSetupError {
source: curl::Error,
},
#[snafu(display("Failed to write data at path {:#?}: {}", path, source))]
FailedToWrite {
source: std::io::Error,
path: std::path::PathBuf,
},
#[snafu(display("Failed to download file from URL {:#?}: HTTP code: {}", url, code))]
DownloadError {
code: u32,
url: url::Url,
},
#[snafu(display("Failed to download file from URL {:#?}: {}", url, source))]
RequestError {
source: curl::Error,
url: url::Url,
},
#[snafu(display("Failed to setup signal handler: {}", source))]
CtrlCFailed {
source: ctrlc::Error,
},
#[snafu(display("Failed to iterate over directory {:#?}: {}", dir, source))]
DirIterFailed {
dir: std::path::PathBuf,
source: std::io::Error,
},
#[snafu(display("Failed to retrieve the canonical path to {:#?}: {}", dir, source))]
CanonFailed {
dir: std::path::PathBuf,
source: std::io::Error,
},
#[snafu(display("Failed to copy {:#?} to {:#?}: {}", from, to, source))]
CopyFailed {
from: std::path::PathBuf,
to: std::path::PathBuf,
source: std::io::Error,
},
#[snafu(display("Failed to run the make target '{}'", target))]
MakeFailed {
target: String,
},
#[snafu(display("Failed to extract last URL component from {:#?}", url))]
URLExtractError {
url: url::Url,
},
#[snafu(display("Failed retrieve mandatory environment variable '{}': {}", var, source))]
MaintainerError {
source: std::env::VarError,
var: String,
},
#[snafu(display("Failed to create Debian package '{}'", package))]
DebFailed {
package: String,
},
#[snafu(display("We were expected to have created a Debian package at path {:#?}", path))]
NoPackage {
path: std::path::PathBuf,
},
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
|
use std::borrow::Borrow;
use std::collections::{hash_map, HashMap};
use std::fmt::{self, Debug};
use std::hash::{BuildHasher, Hash};
use std::iter::FromIterator;
use std::ops::{Deref, DerefMut, Index};
use std::panic::UnwindSafe;
/// A [`HashMap`](std::collections::HashMap) using [`ABuildHasher`](crate::ABuildHasher) to hash the items.
/// Requires the `std` feature to be enabled.
#[derive(Clone)]
pub struct AHashMap<K, V, S = crate::ABuildHasher>(HashMap<K, V, S>);
impl<K, V, S> AHashMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher + Default,
{
pub fn new() -> Self {
AHashMap(HashMap::with_hasher(S::default()))
}
pub fn with_capacity(capacity: usize) -> Self {
AHashMap(HashMap::with_capacity_and_hasher(capacity, S::default()))
}
}
impl<K, V, S> AHashMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
pub fn with_hasher(hash_builder: S) -> Self {
AHashMap(HashMap::with_hasher(hash_builder))
}
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
AHashMap(HashMap::with_capacity_and_hasher(capacity, hash_builder))
}
}
impl<K, V, S> Deref for AHashMap<K, V, S> {
type Target = HashMap<K, V, S>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<K, V, S> DerefMut for AHashMap<K, V, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<K, V, S> UnwindSafe for AHashMap<K, V, S>
where
K: UnwindSafe,
V: UnwindSafe,
{
}
impl<K, V, S> PartialEq for AHashMap<K, V, S>
where
K: Eq + Hash,
V: PartialEq,
S: BuildHasher,
{
fn eq(&self, other: &AHashMap<K, V, S>) -> bool {
self.0.eq(&other.0)
}
}
impl<K, V, S> Eq for AHashMap<K, V, S>
where
K: Eq + Hash,
V: Eq,
S: BuildHasher,
{
}
impl<K, Q: ?Sized, V, S> Index<&Q> for AHashMap<K, V, S>
where
K: Eq + Hash + Borrow<Q>,
Q: Eq + Hash,
S: BuildHasher,
{
type Output = V;
/// Returns a reference to the value corresponding to the supplied key.
///
/// # Panics
///
/// Panics if the key is not present in the `HashMap`.
#[inline]
fn index(&self, key: &Q) -> &V {
self.0.index(key)
}
}
impl<K, V, S> Debug for AHashMap<K, V, S>
where
K: Eq + Hash + Debug,
V: Debug,
S: BuildHasher,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(fmt)
}
}
impl<K, V, S> FromIterator<(K, V)> for AHashMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher + Default,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
AHashMap(HashMap::from_iter(iter))
}
}
impl<'a, K, V, S> IntoIterator for &'a AHashMap<K, V, S> {
type Item = (&'a K, &'a V);
type IntoIter = hash_map::Iter<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
(&self.0).iter()
}
}
impl<'a, K, V, S> IntoIterator for &'a mut AHashMap<K, V, S> {
type Item = (&'a K, &'a mut V);
type IntoIter = hash_map::IterMut<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
(&mut self.0).iter_mut()
}
}
impl<K, V, S> IntoIterator for AHashMap<K, V, S> {
type Item = (K, V);
type IntoIter = hash_map::IntoIter<K, V>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<K, V, S> Extend<(K, V)> for AHashMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher,
{
#[inline]
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
self.0.extend(iter)
}
}
impl<'a, K, V, S> Extend<(&'a K, &'a V)> for AHashMap<K, V, S>
where
K: Eq + Hash + Copy + 'a,
V: Copy + 'a,
S: BuildHasher,
{
#[inline]
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
self.0.extend(iter)
}
}
impl<K, V, S> Default for AHashMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher + Default,
{
#[inline]
fn default() -> AHashMap<K, V, S> {
AHashMap::with_hasher(Default::default())
}
}
|
use ::rgb::{ToRGB, RGB};
pub struct HSV {
h: f32,
s: f32,
v: f32
}
impl HSV {
pub fn from_hsv(h: f32, s: f32, v: f32) -> HSV {
HSV {h: h, s: s, v: v}
}
pub fn get_values(&self) -> (f32, f32, f32) {
(self.h, self.s, self.v)
}
}
impl ToRGB for HSV {
fn to_rgb(&self) -> RGB {
let h_prime = self.h / 60.0;
let hexant_index = h_prime.floor() as i32 % 6;
let hexant_ratio = h_prime.fract();
let chroma = self.v * self.s;
let lesser_chroma_even = chroma * hexant_ratio;
let lesser_chroma_odd = chroma * (1.0 - hexant_ratio);
let offset = self.v - chroma;
let (r_prime, g_prime, b_prime) = match hexant_index {
0 => (chroma, lesser_chroma_even, 0.0),
1 => (lesser_chroma_odd, chroma, 0.0),
2 => (0.0, chroma, lesser_chroma_even),
3 => (0.0, lesser_chroma_odd, chroma),
4 => (lesser_chroma_even, 0.0, chroma),
5 => (chroma, 0.0, lesser_chroma_odd),
_ => (0.0, 0.0, 0.0)
};
RGB::from_rgb(r_prime + offset, g_prime + offset, b_prime + offset)
}
}
#[cfg(test)]
mod test_hsv {
mod from_hsv {
use ::hsv::HSV;
#[test]
fn should_initialize_struct_components() {
let hsv = HSV::from_hsv(0.2, 0.3, 0.1);
let (h, s, v) = hsv.get_values();
assert_eq!(0.2, h, "hue component");
assert_eq!(0.3, s, "saturation component");
assert_eq!(0.1, v, "value component");
}
}
mod to_rgb {
use ::hsv::HSV;
use ::rgb::{ToRGB};
struct TestCase {
name: &'static str,
hsv_values: (f32, f32, f32),
rgb_values: (f32, f32, f32)
}
fn evaluate_test_case(case: &TestCase) {
let (h, s, v) = case.hsv_values;
let (r, g, b) = case.rgb_values;
let hsv = HSV::from_hsv(h, s, v);
let (actual_r, actual_g, actual_b) = hsv.to_rgb().get_values();
approx_eq!(r, actual_r,
format!("incorrect r component in {}", case.name));
approx_eq!(g, actual_g,
format!("incorrect g component in {}", case.name));
approx_eq!(b, actual_b,
format!("incorrect b component in {}", case.name));
}
#[test]
fn should_convert_to_rgb()
{
let test_cases = vec!{
TestCase {name: "black",
hsv_values: (0.0, 0.0, 0.0),
rgb_values: (0.0, 0.0, 0.0)},
TestCase {name: "hexant 0",
hsv_values: (24.0, 0.2, 0.7),
rgb_values: (0.7, 0.616, 0.56)},
TestCase {name: "hexant 1",
hsv_values: (75.0, 0.88, 0.44),
rgb_values: (0.3432, 0.44, 0.0528)},
TestCase {name: "hexant 2",
hsv_values: (157.0, 0.27, 0.98),
rgb_values: (0.7154, 0.98, 0.87856996)},
TestCase {name: "hexant 3",
hsv_values: (228.0, 0.72, 0.12),
rgb_values: (0.033599995, 0.05088, 0.12)},
TestCase {name: "hexant 4",
hsv_values: (264.0, 0.4, 0.7),
rgb_values: (0.532, 0.42, 0.7)},
TestCase {name: "hexant 5",
hsv_values: (348.0, 0.8, 0.9),
rgb_values: (0.9, 0.18, 0.32399988)},
TestCase {name: "big angle, hexant 3",
hsv_values: (552.0, 1.0, 1.0),
rgb_values: (0.0, 0.8000002, 1.0)}
};
for test_case in test_cases {
evaluate_test_case(&test_case);
}
}
}
}
|
#![cfg_attr(feature = "nightly", feature(alloc))]
#![cfg_attr(not(test), no_std)]
#[cfg(test)]
extern crate core;
#[cfg(all(not(test), feature = "use_std"))]
#[macro_use]
extern crate std;
// Use liballoc on nightly to avoid a dependency on libstd
#[cfg(feature = "nightly")]
extern crate alloc;
#[cfg(not(feature = "nightly"))]
mod alloc {
// Tweak the module layout to match the one in liballoc
extern crate std;
pub use self::std::vec;
}
extern crate crossbeam_epoch as epoch;
extern crate crossbeam_utils as utils;
extern crate scopeguard;
pub mod base;
#[cfg(feature = "use_std")]
pub mod map;
#[cfg(feature = "use_std")]
pub mod set;
pub use base::SkipList;
#[cfg(feature = "use_std")]
pub use map::SkipMap;
#[cfg(feature = "use_std")]
pub use set::SkipSet;
/// An endpoint of a range of keys.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum Bound<T> {
/// An inclusive bound.
Included(T),
/// An exclusive bound.
Excluded(T),
/// An infinite endpoint. Indicates that there is no bound in this direction.
Unbounded,
}
|
use std::fs::File;
use std::io::{ ErrorKind, Read };
fn read_from_file() -> Result<String, io::Error> {
let mut s = String::new();
// what is ? is immediatly return if Enum type: Error through From Func
// From convert from Error type to Function Error Type
// must using in return Result func
File::open("example.txt")?.read_to_string(&mut s)?;
Ok(s)
}
// or
fn read_from_file() -> Result<String, io::Error> {
std::fs::read_to_string("example.txt")
}
// Why Can't it Compile?
fn main() {
// if Result return value is Error(Enum), call Panic
// Un Expected Error
let f_1 = File::open("example.txt").unwrap();
// same above but, control message
let f_2 = File::open("example.txt").expect("File Open Error");
// for match
let f = File::open("example.txt");
let f = match f {
Ok(file) => file,
Err(ref error) => match error.kind() {
ErrorKind::NotFound => match File::create("example.txt") {
Ok(fc) => fc,
Err(e) => panic!("File not Created: {:?}", e)
},
other_error => panic!("Not Recoverable Error Panic!! : {:?}", other_error)
},
};
}
|
use crate::zx::video::colors::{ZXBrightness, ZXColor};
pub enum FrameBufferSource {
Screen,
Border,
}
pub trait FrameBuffer {
type Context: Clone;
/// Creates canvas size with required dimensions (`width`, `height`)
fn new(width: usize, height: usize, source: FrameBufferSource, context: Self::Context) -> Self;
/// Set `color` with `brightness` for pixel on canvas at (`x`, `y`)
fn set_color(&mut self, x: usize, y: usize, color: ZXColor, brightness: ZXBrightness);
}
|
#[test]
fn cpuid() {
let cpuid = unsafe { &*crate::peripheral::CPUID::PTR };
assert_eq!(address(&cpuid.base), 0xE000_ED00);
assert_eq!(address(&cpuid.pfr), 0xE000_ED40);
assert_eq!(address(&cpuid.dfr), 0xE000_ED48);
assert_eq!(address(&cpuid.afr), 0xE000_ED4C);
assert_eq!(address(&cpuid.mmfr), 0xE000_ED50);
assert_eq!(address(&cpuid.isar), 0xE000_ED60);
assert_eq!(address(&cpuid.clidr), 0xE000_ED78);
assert_eq!(address(&cpuid.ctr), 0xE000_ED7C);
assert_eq!(address(&cpuid.ccsidr), 0xE000_ED80);
assert_eq!(address(&cpuid.csselr), 0xE000_ED84);
}
#[test]
fn dcb() {
let dcb = unsafe { &*crate::peripheral::DCB::PTR };
assert_eq!(address(&dcb.dhcsr), 0xE000_EDF0);
assert_eq!(address(&dcb.dcrsr), 0xE000_EDF4);
assert_eq!(address(&dcb.dcrdr), 0xE000_EDF8);
assert_eq!(address(&dcb.demcr), 0xE000_EDFC);
}
#[test]
fn dwt() {
let dwt = unsafe { &*crate::peripheral::DWT::PTR };
assert_eq!(address(&dwt.ctrl), 0xE000_1000);
#[cfg(not(armv6m))]
assert_eq!(address(&dwt.cyccnt), 0xE000_1004);
#[cfg(not(armv6m))]
assert_eq!(address(&dwt.cpicnt), 0xE000_1008);
#[cfg(not(armv6m))]
assert_eq!(address(&dwt.exccnt), 0xE000_100C);
#[cfg(not(armv6m))]
assert_eq!(address(&dwt.sleepcnt), 0xE000_1010);
#[cfg(not(armv6m))]
assert_eq!(address(&dwt.lsucnt), 0xE000_1014);
#[cfg(not(armv6m))]
assert_eq!(address(&dwt.foldcnt), 0xE000_1018);
assert_eq!(address(&dwt.pcsr), 0xE000_101C);
assert_eq!(address(&dwt.c[0].comp), 0xE000_1020);
assert_eq!(address(&dwt.c[0].mask), 0xE000_1024);
assert_eq!(address(&dwt.c[0].function), 0xE000_1028);
assert_eq!(address(&dwt.c[1].comp), 0xE000_1030);
assert_eq!(address(&dwt.c[1].mask), 0xE000_1034);
assert_eq!(address(&dwt.c[1].function), 0xE000_1038);
#[cfg(not(armv6m))]
assert_eq!(address(&dwt.lar), 0xE000_1FB0);
#[cfg(not(armv6m))]
assert_eq!(address(&dwt.lsr), 0xE000_1FB4);
}
#[test]
fn fpb() {
let fpb = unsafe { &*crate::peripheral::FPB::PTR };
assert_eq!(address(&fpb.ctrl), 0xE000_2000);
assert_eq!(address(&fpb.remap), 0xE000_2004);
assert_eq!(address(&fpb.comp), 0xE000_2008);
assert_eq!(address(&fpb.comp[1]), 0xE000_200C);
assert_eq!(address(&fpb.lar), 0xE000_2FB0);
assert_eq!(address(&fpb.lsr), 0xE000_2FB4);
}
#[test]
fn fpu() {
let fpu = unsafe { &*crate::peripheral::FPU::PTR };
assert_eq!(address(&fpu.fpccr), 0xE000_EF34);
assert_eq!(address(&fpu.fpcar), 0xE000_EF38);
assert_eq!(address(&fpu.fpdscr), 0xE000_EF3C);
assert_eq!(address(&fpu.mvfr), 0xE000_EF40);
assert_eq!(address(&fpu.mvfr[1]), 0xE000_EF44);
assert_eq!(address(&fpu.mvfr[2]), 0xE000_EF48);
}
#[test]
fn itm() {
let itm = unsafe { &*crate::peripheral::ITM::PTR };
assert_eq!(address(&itm.stim), 0xE000_0000);
assert_eq!(address(&itm.ter), 0xE000_0E00);
assert_eq!(address(&itm.tpr), 0xE000_0E40);
assert_eq!(address(&itm.tcr), 0xE000_0E80);
assert_eq!(address(&itm.lar), 0xE000_0FB0);
assert_eq!(address(&itm.lsr), 0xE000_0FB4);
}
#[test]
fn mpu() {
let mpu = unsafe { &*crate::peripheral::MPU::PTR };
assert_eq!(address(&mpu._type), 0xE000ED90);
assert_eq!(address(&mpu.ctrl), 0xE000ED94);
assert_eq!(address(&mpu.rnr), 0xE000ED98);
assert_eq!(address(&mpu.rbar), 0xE000ED9C);
assert_eq!(address(&mpu.rasr), 0xE000EDA0);
assert_eq!(address(&mpu.rbar_a1), 0xE000EDA4);
assert_eq!(address(&mpu.rasr_a1), 0xE000EDA8);
assert_eq!(address(&mpu.rbar_a2), 0xE000EDAC);
assert_eq!(address(&mpu.rasr_a2), 0xE000EDB0);
assert_eq!(address(&mpu.rbar_a3), 0xE000EDB4);
assert_eq!(address(&mpu.rasr_a3), 0xE000EDB8);
}
#[test]
fn nvic() {
let nvic = unsafe { &*crate::peripheral::NVIC::PTR };
assert_eq!(address(&nvic.iser), 0xE000E100);
assert_eq!(address(&nvic.icer), 0xE000E180);
assert_eq!(address(&nvic.ispr), 0xE000E200);
assert_eq!(address(&nvic.icpr), 0xE000E280);
assert_eq!(address(&nvic.iabr), 0xE000E300);
assert_eq!(address(&nvic.ipr), 0xE000E400);
#[cfg(not(armv6m))]
assert_eq!(address(&nvic.stir), 0xE000EF00);
}
#[test]
fn scb() {
let scb = unsafe { &*crate::peripheral::SCB::PTR };
assert_eq!(address(&scb.icsr), 0xE000_ED04);
assert_eq!(address(&scb.vtor), 0xE000_ED08);
assert_eq!(address(&scb.aircr), 0xE000_ED0C);
assert_eq!(address(&scb.scr), 0xE000_ED10);
assert_eq!(address(&scb.ccr), 0xE000_ED14);
assert_eq!(address(&scb.shpr), 0xE000_ED18);
assert_eq!(address(&scb.shcsr), 0xE000_ED24);
assert_eq!(address(&scb.cfsr), 0xE000_ED28);
assert_eq!(address(&scb.hfsr), 0xE000_ED2C);
assert_eq!(address(&scb.dfsr), 0xE000_ED30);
assert_eq!(address(&scb.mmfar), 0xE000_ED34);
assert_eq!(address(&scb.bfar), 0xE000_ED38);
assert_eq!(address(&scb.afsr), 0xE000_ED3C);
assert_eq!(address(&scb.cpacr), 0xE000_ED88);
}
#[test]
fn syst() {
let syst = unsafe { &*crate::peripheral::SYST::PTR };
assert_eq!(address(&syst.csr), 0xE000_E010);
assert_eq!(address(&syst.rvr), 0xE000_E014);
assert_eq!(address(&syst.cvr), 0xE000_E018);
assert_eq!(address(&syst.calib), 0xE000_E01C);
}
#[test]
fn tpiu() {
let tpiu = unsafe { &*crate::peripheral::TPIU::PTR };
assert_eq!(address(&tpiu.sspsr), 0xE004_0000);
assert_eq!(address(&tpiu.cspsr), 0xE004_0004);
assert_eq!(address(&tpiu.acpr), 0xE004_0010);
assert_eq!(address(&tpiu.sppr), 0xE004_00F0);
assert_eq!(address(&tpiu.ffcr), 0xE004_0304);
assert_eq!(address(&tpiu.lar), 0xE004_0FB0);
assert_eq!(address(&tpiu.lsr), 0xE004_0FB4);
assert_eq!(address(&tpiu._type), 0xE004_0FC8);
}
fn address<T>(r: *const T) -> usize {
r as usize
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.