text stringlengths 8 4.13M |
|---|
#[doc = "Reader of register ETH_DMADSR"]
pub type R = crate::R<u32, super::ETH_DMADSR>;
#[doc = "Reader of field `AXWHSTS`"]
pub type AXWHSTS_R = crate::R<bool, bool>;
#[doc = "Reader of field `AXRHSTS`"]
pub type AXRHSTS_R = crate::R<bool, bool>;
#[doc = "Reader of field `RPS0`"]
pub type RPS0_R = crate::R<u8, u8>;
#[doc = "Reader of field `TPS0`"]
pub type TPS0_R = crate::R<u8, u8>;
#[doc = "Reader of field `RPS1`"]
pub type RPS1_R = crate::R<u8, u8>;
#[doc = "Reader of field `TPS1`"]
pub type TPS1_R = crate::R<u8, u8>;
impl R {
#[doc = "Bit 0 - AHB Master Write Channel"]
#[inline(always)]
pub fn axwhsts(&self) -> AXWHSTS_R {
AXWHSTS_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - AXRHSTS"]
#[inline(always)]
pub fn axrhsts(&self) -> AXRHSTS_R {
AXRHSTS_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bits 8:11 - RPS0"]
#[inline(always)]
pub fn rps0(&self) -> RPS0_R {
RPS0_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - TPS0"]
#[inline(always)]
pub fn tps0(&self) -> TPS0_R {
TPS0_R::new(((self.bits >> 12) & 0x0f) as u8)
}
#[doc = "Bits 16:19 - RPS1"]
#[inline(always)]
pub fn rps1(&self) -> RPS1_R {
RPS1_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 20:23 - TPS1"]
#[inline(always)]
pub fn tps1(&self) -> TPS1_R {
TPS1_R::new(((self.bits >> 20) & 0x0f) as u8)
}
}
|
//! A set of utilities to help with common use cases that are not required to
//! fully use the library.
#[macro_use]
pub mod macros;
pub mod builder;
mod colour;
mod message_builder;
pub use self::colour::Colour;
use base64;
use std::ffi::OsStr;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use ::internal::prelude::*;
pub use self::message_builder::MessageBuilder;
#[doc(hidden)]
pub fn decode_array<T, F: Fn(Value) -> Result<T>>(value: Value, f: F) -> Result<Vec<T>> {
into_array(value).and_then(|x| x.into_iter().map(f).collect())
}
#[doc(hidden)]
pub fn into_array(value: Value) -> Result<Vec<Value>> {
match value {
Value::Array(v) => Ok(v),
value => Err(Error::Decode("Expected array", value)),
}
}
/// Retrieves the "code" part of an [invite][`RichInvite`] out of a URL.
///
/// # Examples
///
/// Three formats of codes are supported:
///
/// 1. Retrieving the code from the URL `"https://discord.gg/0cDvIgU2voY8RSYL"`:
///
/// ```rust
/// use serenity::utils;
///
/// let url = "https://discord.gg/0cDvIgU2voY8RSYL";
///
/// assert_eq!(utils::parse_invite(url), "0cDvIgU2voY8RSYL");
/// ```
///
/// 2. Retrieving the code from the URL `"http://discord.gg/0cDvIgU2voY8RSYL"`:
///
/// ```rust
/// use serenity::utils;
///
/// let url = "http://discord.gg/0cDvIgU2voY8RSYL";
///
/// assert_eq!(utils::parse_invite(url), "0cDvIgU2voY8RSYL");
/// ```
///
/// 3. Retrieving the code from the URL `"discord.gg/0cDvIgU2voY8RSYL"`:
///
/// ```rust
/// use serenity::utils;
///
/// let url = "discord.gg/0cDvIgU2voY8RSYL";
///
/// assert_eq!(utils::parse_invite(url), "0cDvIgU2voY8RSYL");
/// ```
///
/// [`RichInvite`]: ../model/struct.RichInvite.html
pub fn parse_invite(code: &str) -> &str {
if code.starts_with("https://discord.gg/") {
&code[19..]
} else if code.starts_with("http://discord.gg/") {
&code[18..]
} else if code.starts_with("discord.gg/") {
&code[11..]
} else {
code
}
}
/// Reads an image from a path and encodes it into base64.
///
/// This can be used for methods like [`EditProfile::avatar`].
///
/// # Examples
///
/// Reads an image located at `./cat.png` into a base64-encoded string:
///
/// ```rust,no_run
/// use serenity::utils;
///
/// let image = utils::read_image("./cat.png")
/// .expect("Failed to read image");
/// ```
///
/// [`EditProfile::avatar`]: ../builder/struct.EditProfile.html#method.avatar
pub fn read_image<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
let mut v = Vec::default();
let mut f = try!(File::open(path));
let _ = f.read_to_end(&mut v);
let b64 = base64::encode(&v);
let ext = if path.extension() == Some(OsStr::new("png")) {
"png"
} else {
"jpg"
};
Ok(format!("data:image/{};base64,{}", ext, b64))
}
|
//! Defines the main structure to be used in this library.
//!
//! It wraps Lua, and ensures that the correct callbacks are defined for
//! each of the methods used by the Awesome Lua libraries.
use std::path::PathBuf;
use super::lua::{Lua, LuaErr};
use super::callbacks::{self, Button, Client, Drawin, Keygrabber,
Mousegrabber, Mouse, Root, Screen, Tag};
/// Represents the bindings to the awesome libraries.
/// Contains the raw Lua context, as well as the struct that has all of the
/// necessary callbacks defined that are called from Lua.
#[derive(Debug)]
pub struct Awesome<T>
where T: callbacks::Awesome + Button + Client + Drawin + Keygrabber +
Mousegrabber + Mouse + Root + Screen + Tag {
/// The user-provided data that is operated on by the callbacks.
pub callbacks: T
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum AwesomeErr {
Lua(LuaErr)
}
impl From<LuaErr> for AwesomeErr {
fn from(err: LuaErr) -> Self {
AwesomeErr::Lua(err)
}
}
impl<T> Awesome<T>
where T: Default + callbacks::Awesome + Button + Client + Drawin + Keygrabber +
Mousegrabber + Mouse + Root + Screen + Tag {
/// Constructs a new `Awesome` instance, and calls the default constructor
/// for the `T` value.
pub fn new() -> Self {
let callbacks = T::default();
Awesome{
callbacks
}
}
}
impl<T> Awesome<T>
where T: callbacks::Awesome + Button + Client + Drawin + Keygrabber +
Mousegrabber + Mouse + Root + Screen + Tag {
/// Load the rc.lua configuration file from the specified path.
pub fn load_configuration(&mut self, path: PathBuf, lua: &Lua)
-> Result<(), AwesomeErr> {
Ok(lua.load_and_run(path)?)
}
}
|
use token;
use std::fmt;
#[derive(PartialEq, Clone)]
pub enum EvalType {
TInvalid,
TInteger,
TVector
}
#[derive(Clone)]
pub enum Nodes {
AddNode(Box<Nodes>),
SubNode(Box<Nodes>),
MulNode(Box<Nodes>),
DivNode(Box<Nodes>),
IntNode(Box<Nodes>),
UMinusNode(Box<Nodes>),
ExprNode(EvalType, Box<Nodes>),
AST(Option<token::Token>, Vec<Box<Nodes>>)
}
pub trait AstTrait: fmt::Display {
fn new(Option<token::Token>) -> Self;
fn get_node_type(&self) -> token::TokenType;
fn add_child(&mut self, t: Nodes);
fn is_nil(&self) -> bool;
fn get_children(&self) -> &Vec<Box<Nodes>>;
fn to_string_tree(&self) -> String {
let mut return_string = String::from("");
let children = self.get_children();
if children.len() == 0 {
return_string.push_str(self.to_string().as_str())
} else {
if !self.is_nil() {
return_string.push_str("(");
return_string.push_str(self.to_string().as_str());
return_string.push_str(" ");
}
for i in 0..children.len() {
if i > 0 {
return_string.push_str(" ");
}
return_string.push_str(children[i].to_string_tree().as_str());
}
if !self.is_nil() {
return_string.push_str(")");
}
}
return_string
}
}
pub trait ExprTrait: AstTrait {
fn new_expr(token::Token) -> Self;
fn get_eval_type(&self) -> EvalType;
}
pub trait BinaryTrait: ExprTrait {
fn new_bin(Nodes, token::Token, Nodes) -> Self;
}
pub trait UnaryTrait: ExprTrait {
fn new_un(Nodes, token::Token) -> Self;
}
impl AstTrait for Nodes {
fn new(t: Option<token::Token>) -> Self {
if let Some(x) = t {
match x.token_type {
token::TokenType::ADD |
token::TokenType::DIV |
token::TokenType::MUL |
token::TokenType::SUB => {
let tmp = x.clone();
let a = Nodes::AST(Some(x), vec![]);
let b = Nodes::ExprNode(EvalType::TInvalid, Box::new(a));
match tmp.token_type {
token::TokenType::ADD => Nodes::AddNode(Box::new(b)),
token::TokenType::SUB => Nodes::SubNode(Box::new(b)),
token::TokenType::MUL => Nodes::MulNode(Box::new(b)),
token::TokenType::DIV => Nodes::DivNode(Box::new(b)),
// This should never happen
_ => unimplemented!()
}
},
token::TokenType::INT => {
let a = Nodes::AST(Some(x), vec![]);
let b = Nodes::ExprNode(EvalType::TInteger, Box::new(a));
Nodes::IntNode(Box::new(b))
},
_ => {
Nodes::AST(Some(x), vec![])
}
}
} else {
Nodes::AST(None, vec![])
}
}
fn get_node_type(&self) -> token::TokenType {
if !self.is_nil() {
match *self {
Nodes::AST(ref to, _) => {
to.clone().unwrap().token_type
},
Nodes::ExprNode(_, ref n) |
Nodes::AddNode(ref n) |
Nodes::SubNode(ref n) |
Nodes::MulNode(ref n) |
Nodes::DivNode(ref n) |
Nodes::UMinusNode(ref n) |
Nodes::IntNode(ref n) => n.get_node_type(),
}
} else {
token::TokenType::Invalid
}
}
fn add_child(&mut self, t: Nodes) {
match *self {
Nodes::AST(_, ref mut vn) => {
vn.push(Box::new(t))
},
Nodes::ExprNode(_, ref mut n) |
Nodes::AddNode(ref mut n) |
Nodes::SubNode(ref mut n) |
Nodes::MulNode(ref mut n) |
Nodes::DivNode(ref mut n) |
Nodes::UMinusNode(ref mut n) |
Nodes::IntNode(ref mut n) => {
n.add_child(t)
},
}
}
fn is_nil(&self) -> bool {
match *self {
Nodes::AST(ref to, _) => {
if let Some(_) = to.clone() {
false
} else {
true
}
},
Nodes::ExprNode(_, ref n) |
Nodes::AddNode(ref n) |
Nodes::SubNode(ref n) |
Nodes::MulNode(ref n) |
Nodes::DivNode(ref n) |
Nodes::UMinusNode(ref n) |
Nodes::IntNode(ref n) => n.is_nil(),
}
}
fn get_children(&self) -> &Vec<Box<Nodes>> {
match *self {
Nodes::AST(_, ref vn) => vn,
Nodes::ExprNode(_, ref n) |
Nodes::AddNode(ref n) |
Nodes::SubNode(ref n) |
Nodes::MulNode(ref n) |
Nodes::DivNode(ref n) |
Nodes::UMinusNode(ref n) |
Nodes::IntNode(ref n) => n.get_children(),
}
}
}
impl fmt::Display for Nodes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let printable = match *self {
Nodes::AddNode(ref n) |
Nodes::SubNode(ref n) |
Nodes::MulNode(ref n) |
Nodes::DivNode(ref n) |
Nodes::UMinusNode(ref n) |
Nodes::IntNode(ref n) => n.to_string(),
Nodes::ExprNode(ref e, ref n) => {
let mut a = n.to_string();
let t = e.clone();
if t != EvalType::TInvalid {
let b = if t == EvalType::TInteger { "<type=TInteger>" } else { "<type=TVector>" };
a.push_str(b);
}
a
},
Nodes::AST(ref t, _) => {
if let Some(x) = t.clone() {
x.to_string()
} else {
"nil".to_string()
}
},
};
write!(f, "{}", printable)
}
}
impl ExprTrait for Nodes {
fn new_expr(t: token::Token) -> Self {
Nodes::new(Some(t))
}
fn get_eval_type(&self) -> EvalType {
match *self {
Nodes::AddNode(ref n) |
Nodes::SubNode(ref n) |
Nodes::MulNode(ref n) |
Nodes::DivNode(ref n) => {
let c_all = n.get_children();
let ref left = c_all[0];
let ref right = c_all[1];
if left.get_eval_type() == EvalType::TInteger && right.get_eval_type() == EvalType::TInteger {
EvalType::TInteger
} else if left.get_eval_type() == EvalType::TVector && right.get_eval_type() == EvalType::TVector {
EvalType::TVector
} else {
EvalType::TInvalid
}
},
Nodes::UMinusNode(ref n) => {
n.get_children()[0].get_eval_type()
}
Nodes::IntNode(_) => {
EvalType::TInteger
},
Nodes::ExprNode(_, _) => {
unimplemented!()
},
Nodes::AST(_, _) => {
unimplemented!()
},
}
}
}
impl BinaryTrait for Nodes {
fn new_bin(l: Nodes, t: token::Token, r: Nodes) -> Self {
match t.token_type {
token::TokenType::ADD |
token::TokenType::DIV |
token::TokenType::MUL |
token::TokenType::SUB => {
let tmp = t.clone();
let a = Nodes::AST(Some(t), vec![]);
let mut b = Nodes::ExprNode(EvalType::TInvalid, Box::new(a));
b.add_child(l);
b.add_child(r);
match tmp.token_type {
token::TokenType::ADD => Nodes::AddNode(Box::new(b)),
token::TokenType::SUB => Nodes::SubNode(Box::new(b)),
token::TokenType::MUL => Nodes::MulNode(Box::new(b)),
token::TokenType::DIV => Nodes::DivNode(Box::new(b)),
// This should never happen
_ => unimplemented!()
}
},
_ => unimplemented!()
}
}
}
impl UnaryTrait for Nodes {
fn new_un(l: Nodes, t: token::Token) -> Self {
match t.token_type {
token::TokenType::UMINUS |
token::TokenType::INT => {
let tmp = t.clone();
let a = Nodes::AST(Some(t), vec![]);
let mut b = Nodes::ExprNode(EvalType::TInvalid, Box::new(a));
b.add_child(l);
match tmp.token_type {
token::TokenType::INT => Nodes::IntNode(Box::new(b)),
token::TokenType::UMINUS => Nodes::UMinusNode(Box::new(b)),
// This should never happen
_ => unimplemented!()
}
},
_ => unimplemented!()
}
}
} |
/*!
```rudra-poc
[target]
crate = "ms3d"
version = "0.1.2"
[report]
issue_url = "https://github.com/andrewhickman/ms3d/issues/1"
issue_date = 2021-01-26
rustsec_url = "https://github.com/RustSec/advisory-db/pull/723"
rustsec_id = "RUSTSEC-2021-0016"
[[bugs]]
analyzer = "UnsafeDataflow"
bug_class = "UninitExposure"
rudra_report_locations = ["src/read.rs:19:5: 26:6"]
```
!*/
#![forbid(unsafe_code)]
fn main() {
panic!("This issue was reported without PoC");
}
|
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Loc(pub usize, pub usize);
impl fmt::Display for Loc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}-{}", self.0, self.1)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Annot<T> {
pub value: T,
pub loc: Loc,
}
impl<T> Annot<T> {
pub fn new(value: T, loc: Loc) -> Self {
Self { value, loc }
}
}
pub fn print_annot(input: &str, loc: Loc) {
eprintln!("{}", input);
eprintln!("{}{}", " ".repeat(loc.0), "^".repeat(loc.1 - loc.0));
}
|
use std::collections::HashMap;
use crate::util::prelude::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WorldId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MaterialId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Tick(u64);
impl std::ops::Add<u64> for Tick {
type Output = Self;
fn add(self, offset: u64) -> Self::Output {
Self(self.0 + offset)
}
}
impl std::ops::Sub<u64> for Tick {
type Output = Self;
fn sub(self, offset: u64) -> Self::Output {
Self(self.0 - offset)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BlockFill {
/// This block is filled solid.
Solid(MaterialId),
/// This block is filled in only at the bottom.
Floor(MaterialId),
/// This block is filled in only at the top.
Ceiling(MaterialId),
/// This block is filled at the top and the bottom.
FloorCeiling(MaterialId, MaterialId),
/// This block is completely empty.
Empty,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Block {
pub fill: BlockFill,
}
#[derive(Clone, Debug)]
pub struct Region {
/// This vector is guaranteed to be REGION_DIM^2 in size.
pub blocks: Vec<Block>,
}
#[derive(Clone, Debug)]
pub struct CachedRegion {
pub region: Region,
/// The last tick on which this region was updated in world memory. This is useful for caching
/// world state on render.
pub last_update_tick: Tick,
}
#[derive(Clone, Debug)]
pub struct World {
pub id: WorldId,
/// Regions currently loaded into memory.
regions: HashMap<(i32, i32, i32), CachedRegion>,
/// The current tick of the simulated world. There are 1000 ticks in a given turn. If a player
/// makes 10,000 turns per second (a massive overestimate), then a world may safely be simulated
/// for over 50,000 consecutive years before overflow becomes a concern.
pub current_tick: Tick,
}
impl World {
pub fn new() -> Self {
// TODO: Remove this camera; this is only here so we can generate a debug map that fills
// the screen.
let camera = crate::gfx::camera::Camera {
world_offset: (0, 0, 0),
region_offset: (0, 0),
// TODO: Assuming glyph size of (10, 20) and window size of (1280, 720).
tiles_dims: (128, 36),
};
Self {
id: WorldId(0),
regions: DEBUG_gen_regions(&camera),
current_tick: Tick(1),
}
}
pub fn get_cached_region(&self, offset: (i32, i32, i32)) -> Option<&CachedRegion> {
self.regions.get(&offset)
}
}
//
// TEMP/DEBUG MAP GENERATION CODE
//
use rand::distributions::{Distribution, Uniform};
#[allow(non_snake_case)]
fn DEBUG_gen_regions(camera: &crate::gfx::camera::Camera) -> HashMap<(i32, i32, i32), CachedRegion> {
let (num_tiles_x, num_tiles_y) = camera.tiles_dims;
let mut map_builder = MapBuilder {
width: num_tiles_x,
height: num_tiles_y,
rooms: Vec::new(),
};
for _ in 0..20 {
map_builder.add_random_room();
}
map_builder.build()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Rect {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Rect {
fn overlaps(&self, other: Rect) -> bool {
self.x1 < other.x2 && self.x2 > other.x1 && self.y1 > other.y2 && self.y2 < other.y1
}
}
struct MapBuilder {
width: u32,
height: u32,
rooms: Vec<Rect>,
}
impl MapBuilder {
fn add_room(&mut self, x: i32, y: i32, width: u32, height: u32) -> bool {
let r = Rect {
x1: x,
y1: y,
x2: x + width as i32,
y2: y + height as i32,
};
if r.x2 > self.width as i32 || r.y2 > self.height as i32 { return false };
if let Some(_) = self.rooms.iter().find(|&&room| room.overlaps(r)) {
false
} else {
self.rooms.push(r);
true
}
}
fn add_random_room(&mut self) -> bool {
let mut rng = rand::thread_rng();
let x = Uniform::from(0..self.width);
let y = Uniform::from(0..self.height);
let width = Uniform::from(4..12);
let height = Uniform::from(3..6);
let mut tries: u32 = 0;
loop {
let rand_x = x.sample(&mut rng);
let rand_y = y.sample(&mut rng);
let rand_width = width.sample(&mut rng);
let rand_height = height.sample(&mut rng);
if self.add_room(rand_x as i32, rand_y as i32, rand_width, rand_height) {
return true
} else if tries >= 200 {
return false
} else {
tries += 1;
continue
}
}
}
fn build(self) -> HashMap<(i32, i32, i32), CachedRegion> {
let mut map = HashMap::new();
let mut flat_map = vec!['#'; (self.width * self.height) as usize];
for room in self.rooms {
for y in room.y1..room.y2 {
for x in room.x1..room.x2 {
flat_map[(y * self.width as i32 + x) as usize] = '.';
}
}
}
let regions_wide = (self.width / REGION_DIM as u32) + 1;
let regions_tall = (self.height / REGION_DIM as u32) + 1;
for ry in 0..regions_tall {
for rx in 0..regions_wide {
let mut blocks = vec![ Block { fill: BlockFill::Solid(MaterialId(0)) }; REGION_LEN];
for y in 0..REGION_DIM {
for x in 0..REGION_DIM {
let global_y = ry * (REGION_DIM as u32) + y as u32;
let global_x = rx * (REGION_DIM as u32) + x as u32;
let idx: usize = (global_y * self.width + global_x) as usize;
if idx >= flat_map.len() {
continue
} else {
if flat_map[idx] == '.' {
blocks[(y * REGION_DIM + x) as usize] = Block {
fill: BlockFill::Floor(MaterialId(0)),
};
}
}
}
}
map.insert((rx as i32, ry as i32, 0), CachedRegion {
region: Region {
blocks,
},
last_update_tick: Tick(1),
});
}
}
map
}
}
|
use std::{
fs::File,
io::{BufWriter, Write},
};
pub fn write_to_file(best : i32, time : f64, filename : std::string::String) {
let file = File::create(&filename).unwrap();
let mut writer = BufWriter::new(&file);
write!(&mut writer, "{}\t{}", best, time);
} |
use wasm_bindgen::prelude::wasm_bindgen;
use crate::Matrix;
/// An instance of NeuralNet is able to perform calculations on some
/// input data. It can be "trained" to give a specific result on some
/// specific input. It consists of layers of nodes, through which data
/// "flows".
#[wasm_bindgen]
pub struct NeuralNet {
hidden_nodes: Vec<u32>,
hidden_weights: Vec<Matrix>,
learning_rate: f64,
bias: u8,
}
#[wasm_bindgen]
impl NeuralNet
{
/// Returns a new instance of a `NeuralNet`. The first argument
/// is the size of the input layer. The second arg is a `vec`
/// where each item represents the size of one hidden layer.
/// An empty vector can be supplied to create an `Perceptron`.
/// The third argument is the size of the output layer.
/// ```
/// use neural_net_rs::NeuralNet;
/// let nn = NeuralNet::new(3, vec![2, 3], 2);
/// ```
/// This `Neural Network` would consist of an input layer with
/// `3` nodes, a hidden layer with `2`, one with `3` nodes
/// and an output layer with `2` nodes.
#[wasm_bindgen(constructor)]
pub fn new(input_nodes: u32, hidden_nodes: Vec<u32>, output_nodes: u32) -> NeuralNet
{
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
let hn_len = hidden_nodes.len();
let mut hidden_weights: Vec<Matrix> = Vec::new();
if hn_len > 0 {
hidden_weights.push(Matrix::new(hidden_nodes[0], input_nodes));
for i in 1..hn_len {
hidden_weights.push(Matrix::new(hidden_nodes[i], hidden_nodes[i-1]));
}
hidden_weights.push(Matrix::new(output_nodes, hidden_nodes[hn_len - 1]));
} else {
hidden_weights.push(Matrix::new(output_nodes, input_nodes));
}
NeuralNet {
learning_rate: 0.1_f64,
bias: 1,
hidden_nodes,
hidden_weights
}
}
}
#[cfg(test)]
mod tests
{
use super::NeuralNet;
#[test]
fn nn_new()
{
let nn = NeuralNet::new(2, vec![3, 4, 5], 2);
assert_eq!(nn.hidden_weights.len(), 4);
}
#[test]
fn new_perceptron()
{
let nn = NeuralNet::new(2, Vec::new(), 1);
assert_eq!(nn.hidden_weights.len(), 1);
}
}
|
use crate::Gc;
use std::{cmp::Ordering, hash::Hash, iter::FromIterator, ops::Index};
use vec_map::{Entry, VecMap};
pub struct OneToMany<ONE, MANY>(VecMap<ONE, Box<[MANY]>>);
impl<ONE, MANY> OneToMany<ONE, MANY> {
pub fn get(&self, index: &ONE) -> &[MANY]
where
ONE: Clone + Into<usize>,
{
self.0.get(index).map_or(&[], |v| &**v)
}
pub fn iter(&self) -> vec_map::Iter<ONE, Box<[MANY]>> {
self.0.iter()
}
}
impl<ONE, MANY> Gc for OneToMany<ONE, MANY>
where
ONE: From<usize> + Send,
MANY: Gc + Send + Sync,
{
const SUPPORT_GC: bool = MANY::SUPPORT_GC;
fn gc(&mut self, ctx: &crate::GcCtx) {
self.0.iter_mut().for_each(|(_, item)| item.gc(ctx));
}
}
impl<'a, ONE, MANY> IntoIterator for &'a OneToMany<ONE, MANY>
where
ONE: From<usize>,
{
type Item = (ONE, &'a Box<[MANY]>);
type IntoIter = vec_map::Iter<'a, ONE, Box<[MANY]>>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl<ONE, MANY> Index<&ONE> for OneToMany<ONE, MANY>
where
ONE: Clone + Into<usize>,
{
type Output = [MANY];
#[inline]
fn index(&self, index: &ONE) -> &Self::Output {
self.get(index)
}
}
impl<ONE, MANY> FromIterator<(ONE, MANY)> for OneToMany<ONE, MANY>
where
ONE: Clone + From<usize> + Into<usize>,
MANY: Eq + Hash,
{
fn from_iter<T: IntoIterator<Item = (ONE, MANY)>>(iter: T) -> Self {
Self(
collect_vec_map(iter.into_iter())
.into_iter()
.map(|(one, many)| (one, many.into_boxed_slice()))
.collect(),
)
}
}
pub trait OneToManyFromIter<ONE, MANY>: IntoIterator<Item = (ONE, MANY)> + Sized
where
ONE: Clone + From<usize> + Into<usize>,
{
/// Collect the items and sort them.
fn collect_sort<F>(self) -> OneToMany<ONE, MANY>
where
MANY: Ord,
{
self.collect_sort_by(|a, b| a.cmp(b))
}
/// Collect the items and sort them by the cmp function specified.
fn collect_sort_by<F>(self, cmp: F) -> OneToMany<ONE, MANY>
where
F: Fn(&MANY, &MANY) -> Ordering,
{
OneToMany(
collect_vec_map(self.into_iter())
.into_iter()
.map(|(one, mut many)| {
many.sort_unstable_by(&cmp);
(one, many.into_boxed_slice())
})
.collect(),
)
}
/// Collect the items and sort them using a key_cmp function.
fn collect_sort_by_key<F, K>(self, key_cmp: F) -> OneToMany<ONE, MANY>
where
F: Fn(&MANY) -> K,
K: Ord,
{
self.collect_sort_by(|a, b| key_cmp(a).cmp(&key_cmp(b)))
}
fn collect_sort_dedup(self) -> OneToMany<ONE, MANY>
where
MANY: Ord,
{
self.collect_sort_dedup_by(|a, b| a.cmp(b))
}
/// Collect the items and sort them by the cmp function specified.
/// Also removes duplicate MANY items using the same cmp function.
fn collect_sort_dedup_by<F>(self, cmp: F) -> OneToMany<ONE, MANY>
where
F: Fn(&MANY, &MANY) -> Ordering,
{
OneToMany(
collect_vec_map(self.into_iter())
.into_iter()
.map(|(one, mut many)| {
many.sort_unstable_by(&cmp);
many.dedup_by(|a, b| cmp(a, b).is_eq());
(one, many.into_boxed_slice())
})
.collect(),
)
}
/// Collect the items and sort them by the key_cmp function specified.
/// Also removes duplicate MANY items using the same key_cmp function.
fn collect_sort_dedup_by_key<F, K>(self, key_cmp: F) -> OneToMany<ONE, MANY>
where
F: Fn(&MANY) -> K,
K: Ord,
{
self.collect_sort_dedup_by(|a, b| key_cmp(a).cmp(&key_cmp(b)))
}
}
impl<ONE, MANY, T> OneToManyFromIter<ONE, MANY> for T
where
T: IntoIterator<Item = (ONE, MANY)> + Sized,
ONE: Clone + From<usize> + Into<usize>,
{
}
fn collect_vec_map<ONE, MANY, I>(iter: I) -> VecMap<ONE, Vec<MANY>>
where
I: Iterator<Item = (ONE, MANY)>,
ONE: Clone + Into<usize>,
{
iter.fold(VecMap::<ONE, Vec<MANY>>::new(), |mut map, (one, many)| {
match map.entry(one) {
Entry::Occupied(mut o) => {
o.get_mut().push(many);
}
Entry::Vacant(v) => {
v.insert(vec![many]);
}
}
map
})
}
|
use bson;
use mongodb::coll::results::InsertOneResult;
use mongodb::db::{Database, ThreadedDatabase};
use mongodb::oid::ObjectId;
use mongodb::DecoderError;
use r2d2::{Pool, PooledConnection};
use r2d2_mongodb::MongodbConnectionManager;
use crate::utils;
use crate::utils::HandlerErrors;
pub type APIKey = String;
pub type MongoPool = Pool<MongodbConnectionManager>;
type MongoPooledConnection = PooledConnection<MongodbConnectionManager>;
fn get_db_conn(pool: &MongoPool) -> Result<MongoPooledConnection, &'static str> {
pool.get().map_err(|_| "Can't get database connection")
}
pub type ImagePath = Option<String>;
#[derive(Debug, Serialize, Deserialize)]
pub struct APIMovieData {
pub backdrop_path: ImagePath,
pub genre_ids: Vec<u32>,
pub id: u32,
pub original_language: String,
pub title: String,
pub overview: String,
pub poster_path: ImagePath,
pub release_date: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct APIResponse {
pub results: Vec<APIMovieData>,
}
#[derive(Debug, Deserialize)]
pub struct NewUserForm {
pub name: String,
pub email: String,
pub password: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct LoginForm {
pub email: String,
pub password: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct User {
pub _id: ObjectId,
pub name: String,
pub email: String,
pub password: String,
}
impl User {
// The create method adds user to the database. It raises an error if a user
// account already exists or if a database operation goes wrong.
pub fn create(
new_user: NewUserForm,
pool: &MongoPool,
) -> Result<InsertOneResult, HandlerErrors> {
let db_conn: &Database = &get_db_conn(pool).unwrap();
let users_coll = db_conn.collection("users");
match users_coll.find_one(Some(doc! {"email":&new_user.email}), None) {
Ok(search_result) => match search_result {
Some(_) => {
return Err(HandlerErrors::ValidationError(utils::ExistingUserError));
}
None => {
let hashed_password = utils::encrypt_password(&new_user.password);
match hashed_password {
Ok(encrypted_password) => {
return users_coll.insert_one(
doc! {"name":new_user.name,"email":new_user.email,"password":encrypted_password},
None,
).map_err(|e| HandlerErrors::DatabaseError(e));
}
Err(_) => return Err(HandlerErrors::HashingError),
}
}
},
Err(e) => {
return Err(HandlerErrors::DatabaseError(e));
}
};
}
pub fn find_by_email(login_form: LoginForm, pool: &MongoPool) -> Result<User, HandlerErrors> {
let db_conn: &Database = &get_db_conn(pool).unwrap();
let users_coll = db_conn.collection("users");
let search_result = users_coll.find_one(Some(doc! {"email":login_form.email}), None);
match search_result {
Ok(result) => match result {
Some(user_doc) => {
let decoded_user: Result<User, DecoderError> =
bson::from_bson(bson::Bson::Document(user_doc));
match decoded_user {
Ok(user) => return Ok(user),
Err(e) => return Err(HandlerErrors::DecoderError(e)),
};
}
None => return Err(HandlerErrors::UserNotExistError),
},
Err(e) => return Err(HandlerErrors::DatabaseError(e)),
};
}
pub fn find_by_id(id: &str, pool: &MongoPool) -> Result<User, HandlerErrors> {
let db_conn: &Database = &get_db_conn(pool).unwrap();
let users_coll = db_conn.collection("users");
let obj_id = ObjectId::with_string(id).unwrap();
match users_coll.find_one(Some(doc! {"_id":obj_id}), None) {
Ok(search_result) => match search_result {
Some(user_doc) => {
let decoded_user: Result<User, DecoderError> =
bson::from_bson(bson::Bson::Document(user_doc));
match decoded_user {
Ok(user) => return Ok(user),
Err(e) => return Err(HandlerErrors::DecoderError(e)),
};
}
None => return Err(HandlerErrors::UserNotExistError),
},
Err(e) => {
return Err(HandlerErrors::DatabaseError(e));
}
}
}
}
|
use super::*;
/// An incoming inline query.
#[derive(Debug,Deserialize)]
pub struct InlineQuery {
/// The unique identifier for this query.
pub id: String,
/// The sender.
pub from: Box<User>,
/// The sender's location.
pub location: Option<Box<Location>>,
/// The text of the query.
pub query: String,
/// The offset of the results to be returned.
pub offset: String,
}
|
use crate::prelude::*;
fn decompress(s: &str) -> Result<String> {
use parsers::*;
#[derive(Debug, Clone)]
enum Section<'s> {
Text(&'s str),
Repetition(usize, &'s str),
}
let section = alt((
map(alpha1, |s: &str| Section::Text(s)),
map(
flat_map(
terminated(
preceded(char('('), pair(usize_str, preceded(char('x'), usize_str))),
char(')'),
),
|(length, count)| map(take(length), move |substr: &str| (count, substr)),
),
|(count, substr)| Section::Repetition(count, substr),
),
));
let (_, sections) =
many1(section)(s).map_err(|_| anyhow!("invalid characters while decompressing"))?;
let mut out = String::new();
for section in sections {
match section {
Section::Text(s) => out.push_str(s),
Section::Repetition(count, s) => {
for _ in 0..count {
out.push_str(s);
}
}
}
}
Ok(out)
}
pub fn pt1(input: &str) -> Result<usize> {
Ok(decompress(input)?.len())
}
pub fn pt2(input: &str) -> Result<u64> {
use parsers::*;
#[derive(Debug, Clone)]
enum Section<'s> {
Text(u64),
Repetition(u64, &'s str),
}
fn parse_sections(s: &str) -> Result<Vec<Section>> {
let (_, sections) = many0(alt((
map(alpha1, |s: &str| Section::Text(s.len() as u64)),
map(
flat_map(
terminated(
preceded(char('('), pair(u64_str, preceded(char('x'), u64_str))),
char(')'),
),
|(length, count)| map(take(length), move |substr: &str| (count, substr)),
),
|(count, substr)| Section::Repetition(count, substr),
),
)))(s)
.map_err(|_| anyhow!("invalid characters while decompressing"))?;
Ok(sections)
}
fn calc_len(input: &str) -> Result<u64> {
let mut sum = 0;
for section in parse_sections(input)? {
sum += match section {
Section::Text(len) => len,
Section::Repetition(count, substr) => count * calc_len(substr)?,
};
}
Ok(sum)
}
Ok(calc_len(input)?)
}
#[test]
fn day09() -> Result<()> {
assert_eq!(&decompress("ADVENT")?, "ADVENT");
assert_eq!(&decompress("A(1x5)BC")?, "ABBBBBC");
assert_eq!(&decompress("(3x3)XYZ")?, "XYZXYZXYZ");
assert_eq!(&decompress("A(2x2)BCD(2x2)EFG")?, "ABCBCDEFEFG");
assert_eq!(&decompress("(6x1)(1x3)A")?, "(1x3)A");
assert_eq!(&decompress("X(8x2)(3x3)ABCY")?, "X(3x3)ABC(3x3)ABCY");
test_part!(pt2,
"(27x12)(20x12)(13x14)(7x10)(1x12)A" => 241920,
"(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN" => 445
);
Ok(())
}
|
mod file;
mod gzip;
use rustzx_core::{
error::IoError,
host::{BufferCursor, DataRecorder, LoadableAsset, SeekFrom, SeekableAsset},
};
use std::boxed::Box;
pub use file::FileAsset;
pub use gzip::GzipAsset;
pub trait DynamicAssetImpl: LoadableAsset + SeekableAsset {}
impl<T: AsRef<[u8]>> DynamicAssetImpl for BufferCursor<T> {}
pub struct DynamicAsset {
inner: Box<dyn DynamicAssetImpl>,
}
impl<T: DynamicAssetImpl + 'static> From<T> for DynamicAsset {
fn from(inner: T) -> Self {
Self {
inner: Box::new(inner),
}
}
}
impl LoadableAsset for DynamicAsset {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> {
self.inner.read(buf)
}
}
impl SeekableAsset for DynamicAsset {
fn seek(&mut self, pos: SeekFrom) -> Result<usize, IoError> {
self.inner.seek(pos)
}
}
pub trait DynamicDataRecorderImpl: DataRecorder {}
pub struct DynamicDataRecorder {
inner: Box<dyn DynamicDataRecorderImpl>,
}
impl DataRecorder for DynamicDataRecorder {
fn write(&mut self, buf: &[u8]) -> Result<usize, IoError> {
self.inner.write(buf)
}
}
pub(crate) fn into_std_seek_pos(pos: SeekFrom) -> std::io::SeekFrom {
match pos {
SeekFrom::Start(offset) => std::io::SeekFrom::Start(offset as u64),
SeekFrom::End(offset) => std::io::SeekFrom::End(offset as i64),
SeekFrom::Current(offset) => std::io::SeekFrom::Current(offset as i64),
}
}
|
/*
* RIDB API Additional Functions 0.1
*
* The Recreation Information Database (RIDB) provides data resources to citizens, offering a single point of access to information about recreational opportunities nationwide. The RIDB represents an authoritative source of information and services for millions of visitors to federal lands, historic sites, museums, and other attractions/resources. This initiative integrates multiple Federal channels and sources about recreation opportunities into a one-stop, searchable database of recreational areas nationwide.
*
* OpenAPI spec version: 0.1.0
*
* Generated by: https://openapi-generator.tech
*/
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct SearchAvailabilityOkPayloadQuotaTypeMaps {
#[serde(rename = "ConstantQuotaUsageByStartDate")]
constant_quota_usage_by_start_date: Option<::std::collections::HashMap<String, ::models::SearchEntry>>
}
impl SearchAvailabilityOkPayloadQuotaTypeMaps {
pub fn new() -> SearchAvailabilityOkPayloadQuotaTypeMaps {
SearchAvailabilityOkPayloadQuotaTypeMaps {
constant_quota_usage_by_start_date: None
}
}
pub fn set_constant_quota_usage_by_start_date(&mut self, constant_quota_usage_by_start_date: ::std::collections::HashMap<String, ::models::SearchEntry>) {
self.constant_quota_usage_by_start_date = Some(constant_quota_usage_by_start_date);
}
pub fn with_constant_quota_usage_by_start_date(mut self, constant_quota_usage_by_start_date: ::std::collections::HashMap<String, ::models::SearchEntry>) -> SearchAvailabilityOkPayloadQuotaTypeMaps {
self.constant_quota_usage_by_start_date = Some(constant_quota_usage_by_start_date);
self
}
pub fn constant_quota_usage_by_start_date(&self) -> Option<&::std::collections::HashMap<String, ::models::SearchEntry>> {
self.constant_quota_usage_by_start_date.as_ref()
}
pub fn reset_constant_quota_usage_by_start_date(&mut self) {
self.constant_quota_usage_by_start_date = None;
}
}
|
use std::borrow::Cow;
use std::error::Error;
use heed_traits::{BytesDecode, BytesEncode};
use bytemuck::{Pod, PodCastError, bytes_of, bytes_of_mut, try_from_bytes};
/// Describes a type that must be [memory aligned] and
/// will be reallocated if it is not.
///
/// A [`Cow`] type is returned to represent this behavior.
///
/// If you need to store a type that doesn't depends on any
/// memory alignment it is recommended to use the [`UnalignedType`].
///
/// If you don't want to be bored with the [`Cow`] type you can
/// use the [`OwnedType`].
///
/// To store slices, you must look at the [`CowSlice`],
/// [`OwnedSlice`] or [`UnalignedSlice`] types.
///
/// [memory aligned]: std::mem::align_of()
/// [`Cow`]: std::borrow::Cow
/// [`UnalignedType`]: crate::UnalignedType
/// [`OwnedType`]: crate::OwnedType
/// [`UnalignedSlice`]: crate::UnalignedSlice
/// [`OwnedSlice`]: crate::OwnedSlice
/// [`CowSlice`]: crate::CowSlice
pub struct CowType<T>(std::marker::PhantomData<T>);
impl<T: Pod> BytesEncode for CowType<T> {
type EItem = T;
fn bytes_encode(item: &Self::EItem) -> Result<Cow<[u8]>, Box<dyn Error>> {
Ok(Cow::Borrowed(bytes_of(item)))
}
}
impl<'a, T: Pod> BytesDecode<'a> for CowType<T> {
type DItem = Cow<'a, T>;
fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, Box<dyn Error>> {
match try_from_bytes(bytes) {
Ok(item) => Ok(Cow::Borrowed(item)),
Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned) => {
let mut item = T::zeroed();
bytes_of_mut(&mut item).copy_from_slice(bytes);
Ok(Cow::Owned(item))
},
Err(e) => Err(e.into()),
}
}
}
unsafe impl<T> Send for CowType<T> {}
unsafe impl<T> Sync for CowType<T> {}
|
//! Math helpers.
use std::ops::Sub;
use crc::crc32;
/// Feature scaling helper - normalization (also called min-max scaling)
pub fn normalize<T>(value: T, min: T, max: T) -> f64
where
T: Copy + Sub<Output = T> + Into<f64>,
{
(value - min).into() / (max - min).into()
}
/// Given some data and a ratio, for instance the bytes of an image and a ratio of 20%,
/// this function computes whether or not or not the data should be retained.
/// You can use it as a predicate to split a dataset between a training set and a testing set.
/// This method is deteministic, applying it to a collection should result in datasets matching the
/// specified ratio closely, but not perfectly.
///
/// ## Example
/// ```rust
/// let input = "anything that can be converted to a slice of bytes";
/// let ratio = 20; // For 20%
/// assert!(retain(input, ratio));
/// ```
pub fn retain<T>(input: T, ratio: u8) -> bool
where
T: AsRef<[u8]>,
{
let ratio = if ratio > 100 {
100f64
} else {
ratio as f64 / 100f64
};
// Compute a hash of the input, if the hash is below ratio% of the maximum
// hash value, it is retained.
let threshold = (u32::max_value() as f64 * ratio).round() as u32;
let bytes = input.as_ref();
let crc = crc32::checksum_ieee(&bytes);
crc < threshold
}
#[test]
fn test_normalize() {
assert_eq!(normalize(50, 0, 100), 0.5);
assert_eq!(normalize(50.0, 0.0, 100.0), 0.5);
assert_eq!(normalize(10u32, 0u32, 100u32), 0.1);
}
#[test]
fn test_split() {
let input = vec![
vec![1],
vec![2],
vec![3],
vec![4],
vec![5],
vec![6],
vec![7],
vec![8],
vec![9],
vec![10],
];
let retained = input
.clone()
.iter()
.filter(|element| retain(element, 50))
.count();
assert_eq!(retained, 5);
let retained = input
.clone()
.iter()
.filter(|element| retain(element, 20))
.count();
// It SHOULD retain 2 elements.
// The CRC method provides a deterministic way to split the data
// and the ratio should be close enough to what we ask, but it's not perfect
assert_eq!(retained, 1);
}
#[test]
fn test_split_dataset() {
let input = vec![
include_bytes!("../dataset/1.jpg").to_vec(),
include_bytes!("../dataset/2.jpg").to_vec(),
include_bytes!("../dataset/3.jpg").to_vec(),
include_bytes!("../dataset/4.jpg").to_vec(),
include_bytes!("../dataset/5.jpg").to_vec(),
include_bytes!("../dataset/6.jpg").to_vec(),
];
// Same comment, 20% is about 1.2 here it appears to be rounded to 2
let retained = input
.clone()
.iter()
.filter(|element| retain(element, 20))
.count();
assert_eq!(retained, 2);
let input = vec![
include_str!("../dataset/1.xml"),
include_str!("../dataset/2.xml"),
include_str!("../dataset/3.xml"),
include_str!("../dataset/4.xml"),
include_str!("../dataset/5.xml"),
include_str!("../dataset/6.xml"),
];
// ... and here to one
let retained = input
.clone()
.iter()
.filter(|element| retain(element, 20))
.count();
assert_eq!(retained, 1);
}
|
#![recursion_limit="128"]
use std::collections::HashMap;
use std::u32;
extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate syn;
#[macro_use]
extern crate quote;
use proc_macro2::{Span, TokenStream};
trait IterExt: Iterator + Sized {
fn collect_vec( self ) -> Vec< Self::Item > {
self.collect()
}
}
impl< T > IterExt for T where T: Iterator + Sized {}
#[proc_macro_derive(Readable, attributes(speedy))]
pub fn readable( input: proc_macro::TokenStream ) -> proc_macro::TokenStream {
let input = parse_macro_input!( input as syn::DeriveInput );
let tokens = impl_readable( input );
proc_macro::TokenStream::from( tokens )
}
#[proc_macro_derive(Writable, attributes(speedy))]
pub fn writable( input: proc_macro::TokenStream ) -> proc_macro::TokenStream {
let input = parse_macro_input!( input as syn::DeriveInput );
let tokens = impl_writable( input );
proc_macro::TokenStream::from( tokens )
}
#[derive(Copy, Clone, PartialEq)]
enum Variant {
Readable,
Writable
}
fn possibly_uses_generic_ty( generic_types: &[&syn::Ident], ty: &syn::Type ) -> bool {
match ty {
syn::Type::Path( syn::TypePath { qself: None, path: syn::Path { leading_colon: None, segments } } ) => {
segments.iter().any( |segment| {
if generic_types.iter().any( |&ident| ident == &segments[ 0 ].ident ) {
return true;
}
match segment.arguments {
syn::PathArguments::None => false,
syn::PathArguments::AngleBracketed( syn::AngleBracketedGenericArguments { ref args, .. } ) => {
args.iter().any( |arg| {
match arg {
syn::GenericArgument::Lifetime( .. ) => false,
syn::GenericArgument::Type( inner_ty ) => possibly_uses_generic_ty( generic_types, inner_ty ),
// TODO: How to handle these?
syn::GenericArgument::Binding( .. ) => true,
syn::GenericArgument::Constraint( .. ) => true,
syn::GenericArgument::Const( .. ) => true
}
})
},
_ => true
}
})
},
_ => true
}
}
fn common_tokens( ast: &syn::DeriveInput, types: &[&syn::Type], variant: Variant ) -> (TokenStream, TokenStream, TokenStream) {
let impl_params = {
let lifetime_params = ast.generics.lifetimes().map( |alpha| quote! { #alpha } );
let type_params = ast.generics.type_params().map( |ty| quote! { #ty } );
let params = lifetime_params.chain( type_params ).collect_vec();
quote! {
#(#params,)*
}
};
let ty_params = {
let lifetime_params = ast.generics.lifetimes().map( |alpha| quote! { #alpha } );
let type_params = ast.generics.type_params().map( |ty| { let ident = &ty.ident; quote! { #ident } } );
let params = lifetime_params.chain( type_params ).collect_vec();
if params.is_empty() {
quote! {}
} else {
quote! { < #(#params),* > }
}
};
let generics: Vec< _ > = ast.generics.type_params().map( |ty| &ty.ident ).collect();
let where_clause = {
let constraints = types.iter().filter_map( |&ty| {
let possibly_generic = possibly_uses_generic_ty( &generics, ty );
match (variant, possibly_generic) {
(Variant::Readable, true) => Some( quote! { #ty: ::speedy::Readable< 'a_, C_ > } ),
(Variant::Readable, false) => Some( quote! { #ty: 'a_ } ),
(Variant::Writable, true) => Some( quote! { #ty: ::speedy::Writable< C_ > } ),
(Variant::Writable, false) => None
}
});
let mut predicates = Vec::new();
if let Some( where_clause ) = ast.generics.where_clause.as_ref() {
predicates = where_clause.predicates.iter().map( |pred| quote! { #pred } ).collect();
}
if variant == Variant::Readable {
for lifetime in ast.generics.lifetimes() {
predicates.push(
quote! { 'a_: #lifetime }
);
}
}
let items = constraints.chain( predicates.into_iter() ).collect_vec();
if items.is_empty() {
quote! {}
} else {
quote! { where #(#items),* }
}
};
(impl_params, ty_params, where_clause)
}
struct Field< 'a > {
index: usize,
name: Option< &'a syn::Ident >,
ty: &'a syn::Type,
default_on_eof: bool
}
impl< 'a > Field< 'a > {
fn var_name( &self ) -> syn::Ident {
if let Some( name ) = self.name {
name.clone()
} else {
syn::Ident::new( &format!( "v{}_", self.index ), Span::call_site() )
}
}
fn name( &self ) -> syn::Member {
if let Some( name ) = self.name {
syn::Member::Named( name.clone() )
} else {
syn::Member::Unnamed( syn::Index { index: self.index as u32, span: Span::call_site() } )
}
}
}
fn get_fields< 'a, I: IntoIterator< Item = &'a syn::Field > + 'a >( fields: I ) -> impl Iterator< Item = Field< 'a > > {
let iter = fields.into_iter()
.enumerate()
.map( |(index, field)| {
let mut default_on_eof = false;
for attr in &field.attrs {
match attr.parse_meta().expect( "unable to parse attribute" ) {
syn::Meta::List( syn::MetaList { ref ident, ref nested, .. } ) if ident == "speedy" => {
let nested: Vec< _ > = nested.iter().collect();
match &nested[..] {
[syn::NestedMeta::Meta( syn::Meta::Word( ident ) )] if ident == "default_on_eof" => {
default_on_eof = true;
},
_ => panic!( "Unrecognized attribute: {:?}", attr )
}
},
_ => {}
}
}
Field {
index,
name: field.ident.as_ref(),
ty: &field.ty,
default_on_eof
}
});
iter
}
fn readable_body< 'a, I >( types: &mut Vec< &'a syn::Type >, fields: I ) -> (TokenStream, TokenStream, TokenStream)
where I: IntoIterator< Item = &'a syn::Field > + 'a
{
let fields = fields.into_iter();
let mut field_names = Vec::new();
let mut field_readers = Vec::new();
let mut minimum_bytes_needed = Vec::new();
for field in get_fields( fields ) {
let ident = field.var_name();
types.push( field.ty );
let name = quote! { #ident };
field_names.push( name );
if field.default_on_eof {
field_readers.push( quote! {
let #ident = match _reader_.read_value() {
Ok( value ) => value,
Err( ref error ) if error.kind() == ::std::io::ErrorKind::UnexpectedEof => ::std::default::Default::default(),
Err( error ) => return Err( error )
};
});
} else {
field_readers.push( quote! { let #ident = _reader_.read_value()?; } );
}
if let Some( minimum_bytes ) = get_minimum_bytes( &field ) {
minimum_bytes_needed.push( minimum_bytes );
}
}
let body = quote! { #(#field_readers)* };
let initializer = quote! { #(#field_names),* };
let minimum_bytes_needed = sum( minimum_bytes_needed );
(body, initializer, minimum_bytes_needed)
}
fn writable_body< 'a, I >( types: &mut Vec< &'a syn::Type >, fields: I, is_unpacked: bool ) -> (TokenStream, TokenStream)
where I: IntoIterator< Item = &'a syn::Field > + 'a
{
let fields = fields.into_iter();
let mut field_names = Vec::new();
let mut field_writers = Vec::new();
for field in get_fields( fields ) {
types.push( field.ty );
let reference = if is_unpacked {
let name = field.var_name();
field_names.push( name.clone() );
quote! { #name }
} else {
let name = field.name();
quote! { &self.#name }
};
field_writers.push( quote! { _writer_.write_value( #reference )?; } );
}
let body = quote! { #(#field_writers)* };
let initializer = quote! { #(ref #field_names),* };
(body, initializer)
}
struct EnumCtx {
ident: syn::Ident,
previous_kind: Option< u32 >,
kind_to_full_name: HashMap< u32, String >
}
impl EnumCtx {
fn new( ident: &syn::Ident ) -> Self {
EnumCtx {
ident: ident.clone(),
previous_kind: None,
kind_to_full_name: HashMap::new()
}
}
fn next( &mut self, variant: &syn::Variant ) -> u32 {
let full_name = format!( "{}::{}", self.ident, variant.ident );
let kind = match variant.discriminant {
None => {
let kind = if let Some( previous_kind ) = self.previous_kind {
if previous_kind >= u32::MAX {
panic!( "Enum discriminant `{}` is too big!", full_name );
}
previous_kind + 1
} else {
0
};
self.previous_kind = Some( kind );
kind
},
Some( (_, syn::Expr::Lit( syn::ExprLit { lit: syn::Lit::Int( ref value ), .. } )) ) => {
let value = value.value();
if value > u32::MAX as u64 {
panic!( "Enum discriminant `{}` is too big!", full_name );
}
let kind = value as u32;
self.previous_kind = Some( kind );
kind
},
_ => panic!( "Enum discriminant `{}` is currently unsupported!", full_name )
};
if let Some( other_full_name ) = self.kind_to_full_name.get( &kind ) {
panic!( "Two discriminants with the same value of '{}': `{}`, `{}`", kind, full_name, other_full_name );
}
self.kind_to_full_name.insert( kind, full_name );
kind
}
}
fn get_minimum_bytes( field: &Field ) -> Option< TokenStream > {
if field.default_on_eof {
None
} else {
let ty = &field.ty;
Some( quote! { <#ty as ::speedy::Readable< 'a_, C_ >>::minimum_bytes_needed() } )
}
}
fn sum< I >( values: I ) -> TokenStream where I: IntoIterator< Item = TokenStream >, <I as IntoIterator>::IntoIter: ExactSizeIterator {
let iter = values.into_iter();
if iter.len() == 0 {
quote! { 0 }
} else {
quote! {{
let mut out = 0;
#(out += #iter;)*
out
}}
}
}
fn min< I >( values: I ) -> TokenStream where I: IntoIterator< Item = TokenStream >, <I as IntoIterator>::IntoIter: ExactSizeIterator {
let iter = values.into_iter();
if iter.len() == 0 {
quote! { 0 }
} else {
quote! {{
let mut out = 0;
#(out = ::std::cmp::min( out, #iter );)*
out
}}
}
}
fn impl_readable( input: syn::DeriveInput ) -> TokenStream {
let name = &input.ident;
let mut types = Vec::new();
let (reader_body, minimum_bytes_needed_body) = match &input.data {
syn::Data::Struct( syn::DataStruct { fields: syn::Fields::Named( syn::FieldsNamed { named, .. } ), .. } ) => {
let (body, initializer, minimum_bytes) = readable_body( &mut types, named );
let reader_body = quote! {
#body
Ok( #name { #initializer } )
};
(reader_body, minimum_bytes)
},
syn::Data::Struct( syn::DataStruct { fields: syn::Fields::Unnamed( syn::FieldsUnnamed { unnamed, .. } ), .. } ) => {
let (body, initializer, minimum_bytes) = readable_body( &mut types, unnamed );
let reader_body = quote! {
#body
Ok( #name( #initializer ) )
};
(reader_body, minimum_bytes)
},
syn::Data::Enum( syn::DataEnum { variants, .. } ) => {
let mut ctx = EnumCtx::new( &name );
let mut variant_matches = Vec::with_capacity( variants.len() );
let mut variant_minimum_sizes = Vec::with_capacity( variants.len() );
variants.iter()
.for_each( |variant| {
let kind = ctx.next( &variant );
let unqualified_ident = &variant.ident;
let variant_path = quote! { #name::#unqualified_ident };
match variant.fields {
syn::Fields::Named( syn::FieldsNamed { ref named, .. } ) => {
let (body, initializer, minimum_bytes) = readable_body( &mut types, named );
variant_matches.push( quote! {
#kind => {
#body
Ok( #variant_path { #initializer } )
}
});
variant_minimum_sizes.push( minimum_bytes );
},
syn::Fields::Unnamed( syn::FieldsUnnamed { ref unnamed, .. } ) => {
let (body, initializer, minimum_bytes) = readable_body( &mut types, unnamed );
variant_matches.push( quote! {
#kind => {
#body
Ok( #variant_path( #initializer ) )
}
});
variant_minimum_sizes.push( minimum_bytes );
},
syn::Fields::Unit => {
variant_matches.push( quote! {
#kind => {
Ok( #variant_path )
}
});
}
}
});
let reader_body = quote! {
let kind_: u32 = _reader_.read_value()?;
match kind_ {
#(#variant_matches),*
_ => Err( ::std::io::Error::new( ::std::io::ErrorKind::InvalidData, "invalid enum variant" ) )
}
};
let minimum_bytes_needed_body = min( variant_minimum_sizes.into_iter() );
let minimum_bytes_needed_body = quote! { (#minimum_bytes_needed_body) + 4 }; // For the tag.
(reader_body, minimum_bytes_needed_body)
},
syn::Data::Struct( syn::DataStruct { fields: syn::Fields::Unit, .. } ) => {
let reader_body = quote! {
Ok( #name )
};
let minimum_bytes_needed_body = quote! { 0 };
(reader_body, minimum_bytes_needed_body)
},
syn::Data::Union( .. ) => panic!( "Unions are not supported!" )
};
let (impl_params, ty_params, where_clause) = common_tokens( &input, &types, Variant::Readable );
quote! {
impl< 'a_, #impl_params C_: ::speedy::Context > ::speedy::Readable< 'a_, C_ > for #name #ty_params #where_clause {
#[inline]
fn read_from< R_: ::speedy::Reader< 'a_, C_ > >( _reader_: &mut R_ ) -> ::std::io::Result< Self > {
#reader_body
}
#[inline]
fn minimum_bytes_needed() -> usize {
#minimum_bytes_needed_body
}
}
}
}
fn impl_writable( input: syn::DeriveInput ) -> TokenStream {
let name = &input.ident;
let mut types = Vec::new();
let writer_body = match input.data {
syn::Data::Struct( syn::DataStruct { fields: syn::Fields::Unit, .. } ) => {
quote! {}
},
syn::Data::Struct( syn::DataStruct { fields: syn::Fields::Named( syn::FieldsNamed { ref named, .. } ), .. } ) => {
let (body, _) = writable_body( &mut types, named, false );
quote! { #body }
},
syn::Data::Struct( syn::DataStruct { fields: syn::Fields::Unnamed( syn::FieldsUnnamed { ref unnamed, .. } ), .. } ) => {
let (body, _) = writable_body( &mut types, unnamed, false );
quote! { #body }
},
syn::Data::Enum( syn::DataEnum { ref variants, .. } ) => {
let mut ctx = EnumCtx::new( &name );
let variants = variants.iter()
.map( |variant| {
let kind = ctx.next( &variant );
let unqualified_ident = &variant.ident;
let variant_path = quote! { #name::#unqualified_ident };
match variant.fields {
syn::Fields::Named( syn::FieldsNamed { ref named, .. } ) => {
let (body, identifiers) = writable_body( &mut types, named, true );
quote! {
#variant_path { #identifiers } => {
_writer_.write_value( &#kind )?;
#body
}
}
},
syn::Fields::Unnamed( syn::FieldsUnnamed { ref unnamed, .. } ) => {
let (body, identifiers) = writable_body( &mut types, unnamed, true );
quote! {
#variant_path( #identifiers ) => {
_writer_.write_value( &#kind )?;
#body
}
}
},
syn::Fields::Unit => {
quote! { #variant_path => {
_writer_.write_value( &#kind )?;
}}
},
}
})
.collect_vec();
quote! { match *self { #(#variants),* } }
},
syn::Data::Union( .. ) => panic!( "Unions are not supported!" )
};
let (impl_params, ty_params, where_clause) = common_tokens( &input, &types, Variant::Writable );
quote! {
impl< #impl_params C_: ::speedy::Context > ::speedy::Writable< C_ > for #name #ty_params #where_clause {
#[inline]
fn write_to< 'a_, T_: ?Sized + ::speedy::Writer< 'a_, C_ > >( &'a_ self, _writer_: &mut T_ ) -> ::std::io::Result< () > {
#writer_body
Ok(())
}
}
}
}
|
fn is_whitespace(text: &str) -> bool {
text.chars()
.all(|c| c.is_whitespace())
}
fn main(){
print!("{}\n", is_whitespace("Vilmar Catafesta"))
}
|
use rand::{prelude::*, seq::SliceRandom};
use std::{collections::HashMap, fmt::Debug, hash::Hash};
/// Represents the relation between a location and neighbors
pub trait Relation: Debug {
type Loc;
type Item;
/// Returns an iterator over all relations to a given location
fn related(&self, at: Self::Loc, f: impl FnMut(Self::Loc, Self::Item));
}
/// WaveFunctionCollapse maintains state for the wave function collapse function
#[derive(Debug)]
pub struct WaveFunctionCollapse<L, T, R> {
pub possibilities: HashMap<L, Vec<T>>,
pub relations: HashMap<T, Vec<R>>,
frequencies: HashMap<T, f32>,
entropy_cache: HashMap<L, f32>,
}
impl<L, T, R> WaveFunctionCollapse<L, T, R>
where
L: Hash + Eq + Copy + Debug + Ord,
T: Hash + Eq + Copy + Debug,
R: Relation<Loc = L, Item = T>,
{
pub fn new(
locations: impl IntoIterator<Item = L>,
items: impl IntoIterator<Item = T>,
relations: impl IntoIterator<Item = (T, Vec<R>)>,
) -> Self {
let rels: HashMap<_, _> = relations.into_iter().collect();
let uniq_items: Vec<T> = items.into_iter().collect();
let possibilities: HashMap<_, _> = locations
.into_iter()
.map(|l| (l, uniq_items.clone()))
.collect();
let freqs: HashMap<_, _> = rels
.keys()
.map(|v| (*v, (possibilities.len() as f32).recip()))
.collect();
let mut out = Self {
possibilities,
relations: rels,
frequencies: freqs,
entropy_cache: HashMap::new(),
};
for l in out.possibilities.keys() {
out.entropy_cache.insert(*l, out.shannon_entropy_at(&l));
}
out
}
/// Collapses the wave function at the given location
pub fn collapse_at(&mut self, l: L) {
// select choice for possibility
let mut rng = thread_rng();
// can move the buffer to the WFC struct
let mut buffer = vec![];
buffer.extend(
self.possibilities[&l]
.iter()
.map(|&choice| (choice, self.frequencies[&choice])),
);
assert!(!buffer.is_empty());
let choice = buffer.choose_weighted(&mut rng, |item| item.1).unwrap().0;
let item = self.possibilities.get_mut(&l).unwrap();
item.clear();
item.push(choice);
buffer.clear();
}
/// Propogates the effects starting from a given location.
/// Mutates the state of the WFC.
pub fn propogate(&mut self, start: L) -> Result<(), &'static str> {
let mut changed = vec![start];
let mut touched = vec![start];
// get all effects from these set of choices
let mut effects: HashMap<L, Vec<T>> = HashMap::new();
while let Some(l) = changed.pop() {
// must take the & over possibilities but | with relations
for poss in self.possibilities[&l].iter() {
for relation in self.relations[&poss].iter() {
relation.related(l, |related, allowed| {
// TODO this is missing the effects
effects
.entry(related)
.or_insert_with(Vec::new)
.push(allowed);
});
}
}
// TODO possibly combine these two loops
for (loc, mut permitted) in effects.drain() {
if let Some(ref mut prev_posses) = self.possibilities.get_mut(&loc) {
permitted.dedup();
let original_len = prev_posses.len();
prev_posses.retain(|l| permitted.contains(&l));
if prev_posses.is_empty() {
return Err("Failed wfc");
}
if prev_posses.len() != original_len {
if !changed.contains(&loc) {
changed.push(loc);
}
touched.push(loc);
}
}
}
}
touched.sort_unstable();
touched.dedup();
for l in touched.drain(..) {
self.entropy_cache.insert(l, self.shannon_entropy_at(&l));
}
Ok(())
}
/// Computers the shannon entropy at a location.
/// Stateless, so if caching is necessary use the entropy_else_get fn.
pub fn shannon_entropy_at(&self, l: &L) -> f32 {
let posses = &self.possibilities[l];
assert!(!posses.is_empty());
-posses
.iter()
.map(|poss| self.frequencies[poss])
.map(|p| p * p.ln())
.sum::<f32>()
}
/// returns the index into the location set of what should be used for the next
/// collapsed location.
fn next_collapse(&self) -> &L {
self
.possibilities
.iter()
.filter(|(_, posses)| posses.len() > 1)
.map(|(l, _)| (l, self.entropy_cache[&l]))
.min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.expect("none left")
.0
}
/// collapses the location with the lowest shannon entropy
/// returns Ok if success or Err or if reached invalid state
pub fn observe(&mut self) -> Result<(), &'static str> {
let l = *self.next_collapse();
self.collapse_at(l);
self.propogate(l)
}
/// returns the number of complete tiles and the total number of tiles
pub fn num_complete(&self) -> (usize, usize) {
(
self
.possibilities
.values()
.filter(|poss| poss.len() == 1)
.count(),
self.possibilities.len(),
)
}
pub fn is_fully_collapsed(&self) -> bool {
self.possibilities.values().all(|posses| posses.len() <= 1)
}
// Returns a hashmap of locations to items or Err if not complete.
pub fn get_collapsed(&self) -> Result<impl Iterator<Item = (L, T)> + '_, ()> {
if !self.is_fully_collapsed() {
return Err(());
}
let ok = self
.possibilities
.iter()
.map(|(&l, choice_of_one)| (l, choice_of_one[0]));
Ok(ok)
}
pub fn get_partial(&self) -> impl Iterator<Item = (L, Option<T>)> + '_ {
self.possibilities.iter().map(|(&l, choices)| {
(
l,
if choices.len() == 1 {
Some(*choices.iter().next().unwrap())
} else {
None
},
)
})
}
}
|
fn f() {
print!("1");
}
fn main() {
f();
// prints 2
{
f();
// prints 3
fn f() { print!("3"); }
}
f();
// prints 2
fn f() { print!("2"); }
}
|
use anyhow::*;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fmt, iter::FromIterator};
use super::super::*;
/// A value assigned to an attribute in a widget.
/// This can be a primitive String that contains any amount of variable
/// references, as would be generated by the string "foo {{var}} bar".
#[derive(Serialize, Deserialize, Clone, PartialEq, derive_more::Into, derive_more::From, Default)]
pub struct AttrValue(Vec<AttrValueElement>);
impl fmt::Display for AttrValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.iter().map(|x| format!("{}", x)).join(""))
}
}
impl fmt::Debug for AttrValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AttrValue({:?})", self.0)
}
}
impl IntoIterator for AttrValue {
type IntoIter = std::vec::IntoIter<Self::Item>;
type Item = AttrValueElement;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<AttrValueElement> for AttrValue {
fn from_iter<T: IntoIterator<Item = AttrValueElement>>(iter: T) -> Self {
AttrValue(iter.into_iter().collect())
}
}
impl AttrValue {
pub fn from_primitive<T: Into<PrimitiveValue>>(v: T) -> Self {
AttrValue(vec![AttrValueElement::Primitive(v.into())])
}
pub fn from_var_ref<T: Into<VarName>>(v: T) -> Self {
AttrValue(vec![AttrValueElement::Expr(AttrValueExpr::VarRef(v.into()))])
}
pub fn iter(&self) -> std::slice::Iter<AttrValueElement> {
self.0.iter()
}
pub fn var_refs(&self) -> impl Iterator<Item = &VarName> {
self.0.iter().filter_map(|x| Some(x.as_expr()?.var_refs())).flatten()
}
/// resolve partially.
/// If a var-ref links to another var-ref, that other var-ref is used.
/// If a referenced variable is not found in the given hashmap, returns the var-ref unchanged.
pub fn resolve_one_level(self, variables: &HashMap<VarName, AttrValue>) -> AttrValue {
self.into_iter()
.map(|entry| match entry {
AttrValueElement::Expr(expr) => AttrValueElement::Expr(expr.map_terminals_into(|child_expr| match child_expr {
AttrValueExpr::VarRef(var_name) => match variables.get(&var_name) {
Some(value) => AttrValueExpr::Literal(value.clone()),
None => AttrValueExpr::VarRef(var_name),
},
other => other,
})),
_ => entry,
})
.collect()
}
/// resolve fully.
/// As the variables here have to be primitive values,
/// this enforces that var-refs are not linking to other variables.
pub fn resolve_fully(self, variables: &HashMap<VarName, PrimitiveValue>) -> Result<PrimitiveValue> {
self.into_iter()
.map(|element| match element {
AttrValueElement::Primitive(x) => Ok(x),
AttrValueElement::Expr(expr) => expr.eval(variables),
})
.collect()
}
// TODO this could be a fancy Iterator implementation, ig
pub fn parse_string(s: &str) -> AttrValue {
let mut elements = Vec::new();
let mut cur_word = "".to_owned();
let mut cur_varref: Option<String> = None;
let mut curly_count = 0;
for c in s.chars() {
if let Some(ref mut varref) = cur_varref {
if c == '}' {
curly_count -= 1;
if curly_count == 0 {
elements.push(AttrValueElement::Expr(AttrValueExpr::parse(varref).unwrap()));
cur_varref = None
}
} else {
curly_count = 2;
varref.push(c);
}
} else if c == '{' {
curly_count += 1;
if curly_count == 2 {
if !cur_word.is_empty() {
elements.push(AttrValueElement::primitive(std::mem::take(&mut cur_word)));
}
cur_varref = Some(String::new())
}
} else {
if curly_count == 1 {
cur_word.push('{');
}
curly_count = 0;
cur_word.push(c);
}
}
if let Some(unfinished_varref) = cur_varref.take() {
elements.push(AttrValueElement::primitive(unfinished_varref));
} else if !cur_word.is_empty() {
elements.push(AttrValueElement::primitive(cur_word));
}
AttrValue(elements)
}
}
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub enum AttrValueElement {
Primitive(PrimitiveValue),
Expr(AttrValueExpr),
}
impl fmt::Display for AttrValueElement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AttrValueElement::Primitive(x) => write!(f, "{}", x),
AttrValueElement::Expr(x) => write!(f, "{{{{{}}}}}", x),
}
}
}
impl fmt::Debug for AttrValueElement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AttrValueElement::Primitive(x) => write!(f, "Primitive({:?})", x),
AttrValueElement::Expr(x) => write!(f, "Expr({:?})", x),
}
}
}
impl AttrValueElement {
pub fn primitive(s: String) -> Self {
AttrValueElement::Primitive(PrimitiveValue::from_string(s))
}
pub fn as_expr(&self) -> Option<&AttrValueExpr> {
match self {
AttrValueElement::Expr(x) => Some(&x),
_ => None,
}
}
pub fn as_primitive(&self) -> Option<&PrimitiveValue> {
match self {
AttrValueElement::Primitive(x) => Some(&x),
_ => None,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_parse_string_or_var_ref_list() {
let input = "{{foo}}{{bar}}b{}azb{a}z{{bat}}{}quok{{test}}";
let output = AttrValue::parse_string(input);
assert_eq!(
output,
AttrValue(vec![
AttrValueElement::Expr(AttrValueExpr::VarRef(VarName("foo".to_owned()))),
AttrValueElement::Expr(AttrValueExpr::VarRef(VarName("bar".to_owned()))),
AttrValueElement::primitive("b{}azb{a}z".to_owned()),
AttrValueElement::Expr(AttrValueExpr::VarRef(VarName("bat".to_owned()))),
AttrValueElement::primitive("{}quok".to_owned()),
AttrValueElement::Expr(AttrValueExpr::VarRef(VarName("test".to_owned()))),
]),
)
}
#[test]
fn test_parse_string_with_var_refs_attr_value() {
assert_eq!(
AttrValue(
vec![
AttrValueElement::Expr(AttrValueExpr::VarRef(VarName("var".to_owned()))),
AttrValueElement::primitive("something".to_owned())
]
.into()
),
AttrValue::parse_string("{{var}}something")
);
}
}
|
#[doc = "Register `TOCC` reader"]
pub type R = crate::R<TOCC_SPEC>;
#[doc = "Register `TOCC` writer"]
pub type W = crate::W<TOCC_SPEC>;
#[doc = "Field `ETOC` reader - Enable Timeout Counter"]
pub type ETOC_R = crate::BitReader;
#[doc = "Field `ETOC` writer - Enable Timeout Counter"]
pub type ETOC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TOS` reader - Timeout Select"]
pub type TOS_R = crate::FieldReader;
#[doc = "Field `TOS` writer - Timeout Select"]
pub type TOS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>;
#[doc = "Field `TOP` reader - Timeout Period"]
pub type TOP_R = crate::FieldReader<u16>;
#[doc = "Field `TOP` writer - Timeout Period"]
pub type TOP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>;
impl R {
#[doc = "Bit 0 - Enable Timeout Counter"]
#[inline(always)]
pub fn etoc(&self) -> ETOC_R {
ETOC_R::new((self.bits & 1) != 0)
}
#[doc = "Bits 1:2 - Timeout Select"]
#[inline(always)]
pub fn tos(&self) -> TOS_R {
TOS_R::new(((self.bits >> 1) & 3) as u8)
}
#[doc = "Bits 16:31 - Timeout Period"]
#[inline(always)]
pub fn top(&self) -> TOP_R {
TOP_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
impl W {
#[doc = "Bit 0 - Enable Timeout Counter"]
#[inline(always)]
#[must_use]
pub fn etoc(&mut self) -> ETOC_W<TOCC_SPEC, 0> {
ETOC_W::new(self)
}
#[doc = "Bits 1:2 - Timeout Select"]
#[inline(always)]
#[must_use]
pub fn tos(&mut self) -> TOS_W<TOCC_SPEC, 1> {
TOS_W::new(self)
}
#[doc = "Bits 16:31 - Timeout Period"]
#[inline(always)]
#[must_use]
pub fn top(&mut self) -> TOP_W<TOCC_SPEC, 16> {
TOP_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "FDCAN Timeout Counter Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tocc::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 [`tocc::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct TOCC_SPEC;
impl crate::RegisterSpec for TOCC_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`tocc::R`](R) reader structure"]
impl crate::Readable for TOCC_SPEC {}
#[doc = "`write(|w| ..)` method takes [`tocc::W`](W) writer structure"]
impl crate::Writable for TOCC_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets TOCC to value 0xffff_0000"]
impl crate::Resettable for TOCC_SPEC {
const RESET_VALUE: Self::Ux = 0xffff_0000;
}
|
#[derive(Debug)]
#[repr(packed)]
pub struct Tss {
pub prev_tss: u32,
pub sp0: usize,
pub ss0: usize,
pub sp1: usize,
pub ss1: usize,
pub sp2: usize,
pub ss2: usize,
pub cr3: usize,
pub ip: usize,
pub flags: usize,
pub ax: usize,
pub cx: usize,
pub dx: usize,
pub bx: usize,
pub sp: usize,
pub bp: usize,
pub si: usize,
pub di: usize,
pub es: usize,
pub cs: usize,
pub ss: usize,
pub ds: usize,
pub fs: usize,
pub gs: usize,
pub ldt: usize,
pub trap: u16,
pub iomap_base: u16,
}
|
extern crate tinymt;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use tinymt::tinymt32;
// NOTE: 本当はパスが適切に解釈される `module` を使うのが望ましいが, バグのため使用できないので `raw_module` で代用している
// ref: https://github.com/rustwasm/wasm-bindgen/issues/1921
// #[wasm_bindgen(module = "/src/crate/import")]
#[cfg(not(test))]
#[wasm_bindgen(raw_module = "../src/crate/import")]
extern {
fn postProgressAction(foundSeeds: &[u32], seed: u32);
}
// NOTE: `wasm-pack test` によるテスト環境では `postMessage` のようなAPIは提供されていないので,
// import.js の `postProgressAction` を呼び出すと実行時エラーになる. そのため, テスト環境では
// ダミーの実装にすり替え, 実行時エラーを回避している.
#[cfg(test)]
#[allow(non_snake_case)]
fn postProgressAction(_foundSeeds: &[u32], _seed: u32) {
// noop
}
trait Rng {
fn gen_range(&mut self, m: u32) -> u32;
fn skip(&mut self, n: usize);
}
impl Rng for tinymt32::Rng {
fn gen_range(&mut self, m: u32) -> u32 {
self.gen() % m
}
fn skip(&mut self, n: usize) {
for _i in 0..n {
self.next_state();
}
}
}
macro_rules! each_u32 {
($var:ident => $code:block) => {
each_u32!(0x0000_0000, 0xFFFF_FFFF, $var => $code)
};
($from:expr, $to:expr, $var:ident => $code:block) => {
let mut count: u32 = $from;
loop {
let $var: u32 = count;
{ $code }
if count == $to {
break;
}
count = count.wrapping_add(1);
}
};
}
fn get_egg_nature(rng: &mut tinymt32::Rng, has_shiny_charm: bool) -> u32 {
rng.skip(1); // gender
let nature = rng.gen_range(25); // nature
rng.skip(1); // ability
// inheriting IVs
let mut inherit = [false; 6];
for _i in 0..3 {
let mut r = rng.gen_range(6) as usize;
while inherit[r] {
r = rng.gen_range(6) as usize;
}
inherit[r] = true;
rng.skip(1);
}
rng.skip(6); // IVs
rng.skip(1); // EC
if has_shiny_charm {
rng.skip(2); // shiny charm
}
// rng.skip(1); // ball
rng.skip(2); // unknown
nature
}
#[wasm_bindgen]
pub fn search_tinymt_seed(natures: &[u32], has_shiny_charm: bool) -> Vec<u32> {
assert_eq!(natures.len(), 8);
natures.iter().for_each(|&nature| assert!(nature < 25));
let mut found_seeds: Vec<u32> = Vec::new();
let param = tinymt32::Param {
mat1: 0x8F7011EE,
mat2: 0xFC78FF1F,
tmat: 0x3793FDFF,
};
each_u32!(seed => {
let mut rng = tinymt32::from_seed(param, seed);
let found = natures
.iter()
.all(|&nature| nature == get_egg_nature(&mut rng, has_shiny_charm));
if seed % 0x0100_0000 == 0 && seed != 0 {
postProgressAction(found_seeds.as_slice(), seed);
}
if found {
found_seeds.push(seed);
postProgressAction(found_seeds.as_slice(), seed);
}
});
found_seeds
}
#[cfg(test)]
mod tests {
use super::*;
extern crate wasm_bindgen_test;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn case1() {
let natures: [u32; 8] = [17, 24, 7, 16, 6, 20, 12, 18];
let has_shiny_charm = false;
let actual = search_tinymt_seed(&natures, has_shiny_charm);
let expected: Vec<u32> = vec![0x0B76_DDAF, 0x261C6F52];
assert_eq!(actual, expected);
}
#[wasm_bindgen_test]
fn case2() {
let natures: [u32; 8] = [17, 19, 24, 7, 5, 18, 1, 16];
let has_shiny_charm = true;
let actual = search_tinymt_seed(&natures, has_shiny_charm);
let expected: Vec<u32> = vec![0x0B76_DDAF];
assert_eq!(actual, expected);
}
}
|
//! <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b7133593f835927b8046/libraries/eosiolib/core/eosio/time.hpp#L134-L210>
use crate::{TimePoint, TimePointSec, NumBytes, Read, Write};
use alloc::string::ToString;
use chrono::{Utc, TimeZone, SecondsFormat};
use codec::{Encode, Decode};
#[cfg(feature = "std")]
use serde::ser::{Serialize, Serializer};
/// This class is used in the block headers to represent the block time
/// It is a parameterised class that takes an Epoch in milliseconds and
/// and an interval in milliseconds and computes the number of slots.
#[derive(Read, Write, NumBytes, PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy, Hash, Default, Encode, Decode)]
#[eosio_core_root_path = "crate"]
#[repr(C)]
pub struct BlockTimestamp(pub u32);
#[cfg(feature = "std")]
impl Serialize for BlockTimestamp {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl BlockTimestamp {
/// Time between blocks.
pub const BLOCK_INTERVAL_MS: i32 = 500;
/// Epoch is 2000-01-01T00:00.000Z.
pub const BLOCK_TIMESTAMP_EPOCH: u64 = 946_684_800_000;
/// Gets the milliseconds
#[inline]
pub const fn as_u32(self) -> u32 {
self.0
}
#[cfg(feature = "std")]
pub fn now() -> Self {
TimePointSec::now().into()
}
}
#[cfg(feature = "std")]
struct BlockTimestampVisitor;
#[cfg(feature = "std")]
impl<'de> ::serde::de::Visitor<'de> for BlockTimestampVisitor {
type Value = BlockTimestamp;
#[inline]
fn expecting(
&self,
formatter: &mut core::fmt::Formatter,
) -> core::fmt::Result {
formatter.write_str("a second timestamp as a number or string")
}
#[inline]
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
match value.parse::<u32>() {
Ok(n) => Ok(BlockTimestamp(n)),
Err(e) => Err(::serde::de::Error::custom(e)),
}
}
#[inline]
fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
Ok(BlockTimestamp(value))
}
}
#[cfg(feature = "std")]
impl<'de> ::serde::de::Deserialize<'de> for BlockTimestamp {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::de::Deserializer<'de>,
{
deserializer.deserialize_any(BlockTimestampVisitor)
}
}
impl From<u32> for BlockTimestamp {
#[inline]
fn from(i: u32) -> Self {
Self(i)
}
}
impl From<BlockTimestamp> for u32 {
#[inline]
fn from(t: BlockTimestamp) -> Self {
t.0
}
}
impl From<TimePoint> for BlockTimestamp {
#[inline]
fn from(t: TimePoint) -> Self {
let micro_since_epoch = t.time_since_epoch();
let msec_since_epoch = micro_since_epoch / 1_000_000;
Self(((msec_since_epoch - BlockTimestamp::BLOCK_TIMESTAMP_EPOCH as i64) / BlockTimestamp::BLOCK_INTERVAL_MS as i64) as u32)
}
}
impl From<TimePointSec> for BlockTimestamp {
#[inline]
fn from(t: TimePointSec) -> Self {
let sec_since_epoch = t.sec_since_epoch();
Self((((sec_since_epoch as u64 * 1000) - BlockTimestamp::BLOCK_TIMESTAMP_EPOCH) / BlockTimestamp::BLOCK_INTERVAL_MS as u64) as u32)
}
}
#[cfg(feature = "std")]
impl std::fmt::Display for BlockTimestamp {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let sec_since_epoch = (self.0 as i64 * BlockTimestamp::BLOCK_INTERVAL_MS as i64) + BlockTimestamp::BLOCK_TIMESTAMP_EPOCH as i64;
let dt = Utc.timestamp_millis(sec_since_epoch);
write!(f, "{}", dt.to_rfc3339_opts(SecondsFormat::Millis, true))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn time_should_work() {
let tps = TimePointSec::now();
let block_time = BlockTimestamp::now();
let block_timestamp = BlockTimestamp::from(tps);
assert_eq!(block_time, block_timestamp);
assert_eq!(BlockTimestamp::from(100), BlockTimestamp(100));
}
}
|
#[doc = "Flash macro control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [fm_ctl](fm_ctl) module"]
pub type FM_CTL = crate::Reg<u32, _FM_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FM_CTL;
#[doc = "`read()` method returns [fm_ctl::R](fm_ctl::R) reader structure"]
impl crate::Readable for FM_CTL {}
#[doc = "`write(|w| ..)` method takes [fm_ctl::W](fm_ctl::W) writer structure"]
impl crate::Writable for FM_CTL {}
#[doc = "Flash macro control"]
pub mod fm_ctl;
#[doc = "Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [status](status) module"]
pub type STATUS = crate::Reg<u32, _STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _STATUS;
#[doc = "`read()` method returns [status::R](status::R) reader structure"]
impl crate::Readable for STATUS {}
#[doc = "Status"]
pub mod status;
#[doc = "Flash macro address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [fm_addr](fm_addr) module"]
pub type FM_ADDR = crate::Reg<u32, _FM_ADDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FM_ADDR;
#[doc = "`read()` method returns [fm_addr::R](fm_addr::R) reader structure"]
impl crate::Readable for FM_ADDR {}
#[doc = "`write(|w| ..)` method takes [fm_addr::W](fm_addr::W) writer structure"]
impl crate::Writable for FM_ADDR {}
#[doc = "Flash macro address"]
pub mod fm_addr;
#[doc = "Regular flash geometry\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [geometry](geometry) module"]
pub type GEOMETRY = crate::Reg<u32, _GEOMETRY>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GEOMETRY;
#[doc = "`read()` method returns [geometry::R](geometry::R) reader structure"]
impl crate::Readable for GEOMETRY {}
#[doc = "Regular flash geometry"]
pub mod geometry;
#[doc = "Supervisory flash geometry\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [geometry_supervisory](geometry_supervisory) module"]
pub type GEOMETRY_SUPERVISORY = crate::Reg<u32, _GEOMETRY_SUPERVISORY>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GEOMETRY_SUPERVISORY;
#[doc = "`read()` method returns [geometry_supervisory::R](geometry_supervisory::R) reader structure"]
impl crate::Readable for GEOMETRY_SUPERVISORY {}
#[doc = "Supervisory flash geometry"]
pub mod geometry_supervisory;
#[doc = "Timer control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [timer_ctl](timer_ctl) module"]
pub type TIMER_CTL = crate::Reg<u32, _TIMER_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMER_CTL;
#[doc = "`read()` method returns [timer_ctl::R](timer_ctl::R) reader structure"]
impl crate::Readable for TIMER_CTL {}
#[doc = "`write(|w| ..)` method takes [timer_ctl::W](timer_ctl::W) writer structure"]
impl crate::Writable for TIMER_CTL {}
#[doc = "Timer control"]
pub mod timer_ctl;
#[doc = "Analog control 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ana_ctl0](ana_ctl0) module"]
pub type ANA_CTL0 = crate::Reg<u32, _ANA_CTL0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ANA_CTL0;
#[doc = "`read()` method returns [ana_ctl0::R](ana_ctl0::R) reader structure"]
impl crate::Readable for ANA_CTL0 {}
#[doc = "`write(|w| ..)` method takes [ana_ctl0::W](ana_ctl0::W) writer structure"]
impl crate::Writable for ANA_CTL0 {}
#[doc = "Analog control 0"]
pub mod ana_ctl0;
#[doc = "Analog control 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ana_ctl1](ana_ctl1) module"]
pub type ANA_CTL1 = crate::Reg<u32, _ANA_CTL1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ANA_CTL1;
#[doc = "`read()` method returns [ana_ctl1::R](ana_ctl1::R) reader structure"]
impl crate::Readable for ANA_CTL1 {}
#[doc = "`write(|w| ..)` method takes [ana_ctl1::W](ana_ctl1::W) writer structure"]
impl crate::Writable for ANA_CTL1 {}
#[doc = "Analog control 1"]
pub mod ana_ctl1;
#[doc = "N/A, DNU\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [geometry_gen](geometry_gen) module"]
pub type GEOMETRY_GEN = crate::Reg<u32, _GEOMETRY_GEN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GEOMETRY_GEN;
#[doc = "`read()` method returns [geometry_gen::R](geometry_gen::R) reader structure"]
impl crate::Readable for GEOMETRY_GEN {}
#[doc = "N/A, DNU"]
pub mod geometry_gen;
#[doc = "Test mode control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [test_ctl](test_ctl) module"]
pub type TEST_CTL = crate::Reg<u32, _TEST_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TEST_CTL;
#[doc = "`read()` method returns [test_ctl::R](test_ctl::R) reader structure"]
impl crate::Readable for TEST_CTL {}
#[doc = "`write(|w| ..)` method takes [test_ctl::W](test_ctl::W) writer structure"]
impl crate::Writable for TEST_CTL {}
#[doc = "Test mode control"]
pub mod test_ctl;
#[doc = "Wiat State control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [wait_ctl](wait_ctl) module"]
pub type WAIT_CTL = crate::Reg<u32, _WAIT_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WAIT_CTL;
#[doc = "`read()` method returns [wait_ctl::R](wait_ctl::R) reader structure"]
impl crate::Readable for WAIT_CTL {}
#[doc = "`write(|w| ..)` method takes [wait_ctl::W](wait_ctl::W) writer structure"]
impl crate::Writable for WAIT_CTL {}
#[doc = "Wiat State control"]
pub mod wait_ctl;
#[doc = "Monitor Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [monitor_status](monitor_status) module"]
pub type MONITOR_STATUS = crate::Reg<u32, _MONITOR_STATUS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MONITOR_STATUS;
#[doc = "`read()` method returns [monitor_status::R](monitor_status::R) reader structure"]
impl crate::Readable for MONITOR_STATUS {}
#[doc = "Monitor Status"]
pub mod monitor_status;
#[doc = "Scratch Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [scratch_ctl](scratch_ctl) module"]
pub type SCRATCH_CTL = crate::Reg<u32, _SCRATCH_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SCRATCH_CTL;
#[doc = "`read()` method returns [scratch_ctl::R](scratch_ctl::R) reader structure"]
impl crate::Readable for SCRATCH_CTL {}
#[doc = "`write(|w| ..)` method takes [scratch_ctl::W](scratch_ctl::W) writer structure"]
impl crate::Writable for SCRATCH_CTL {}
#[doc = "Scratch Control"]
pub mod scratch_ctl;
#[doc = "High voltage control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [hv_ctl](hv_ctl) module"]
pub type HV_CTL = crate::Reg<u32, _HV_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _HV_CTL;
#[doc = "`read()` method returns [hv_ctl::R](hv_ctl::R) reader structure"]
impl crate::Readable for HV_CTL {}
#[doc = "`write(|w| ..)` method takes [hv_ctl::W](hv_ctl::W) writer structure"]
impl crate::Writable for HV_CTL {}
#[doc = "High voltage control"]
pub mod hv_ctl;
#[doc = "Aclk control\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [aclk_ctl](aclk_ctl) module"]
pub type ACLK_CTL = crate::Reg<u32, _ACLK_CTL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ACLK_CTL;
#[doc = "`write(|w| ..)` method takes [aclk_ctl::W](aclk_ctl::W) writer structure"]
impl crate::Writable for ACLK_CTL {}
#[doc = "Aclk control"]
pub mod aclk_ctl;
#[doc = "Interrupt\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"]
pub type INTR = crate::Reg<u32, _INTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR;
#[doc = "`read()` method returns [intr::R](intr::R) reader structure"]
impl crate::Readable for INTR {}
#[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"]
impl crate::Writable for INTR {}
#[doc = "Interrupt"]
pub mod intr;
#[doc = "Interrupt set\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"]
pub type INTR_SET = crate::Reg<u32, _INTR_SET>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_SET;
#[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"]
impl crate::Readable for INTR_SET {}
#[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"]
impl crate::Writable for INTR_SET {}
#[doc = "Interrupt set"]
pub mod intr_set;
#[doc = "Interrupt mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"]
pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASK;
#[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"]
impl crate::Readable for INTR_MASK {}
#[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"]
impl crate::Writable for INTR_MASK {}
#[doc = "Interrupt mask"]
pub mod intr_mask;
#[doc = "Interrupt masked\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"]
pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTR_MASKED;
#[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"]
impl crate::Readable for INTR_MASKED {}
#[doc = "Interrupt masked"]
pub mod intr_masked;
#[doc = "Flash macro high Voltage page latches data (for all page latches)\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [fm_hv_data_all](fm_hv_data_all) module"]
pub type FM_HV_DATA_ALL = crate::Reg<u32, _FM_HV_DATA_ALL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FM_HV_DATA_ALL;
#[doc = "`write(|w| ..)` method takes [fm_hv_data_all::W](fm_hv_data_all::W) writer structure"]
impl crate::Writable for FM_HV_DATA_ALL {}
#[doc = "Flash macro high Voltage page latches data (for all page latches)"]
pub mod fm_hv_data_all;
#[doc = "Cal control BG LO trim bits\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cal_ctl0](cal_ctl0) module"]
pub type CAL_CTL0 = crate::Reg<u32, _CAL_CTL0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CAL_CTL0;
#[doc = "`read()` method returns [cal_ctl0::R](cal_ctl0::R) reader structure"]
impl crate::Readable for CAL_CTL0 {}
#[doc = "`write(|w| ..)` method takes [cal_ctl0::W](cal_ctl0::W) writer structure"]
impl crate::Writable for CAL_CTL0 {}
#[doc = "Cal control BG LO trim bits"]
pub mod cal_ctl0;
#[doc = "Cal control BG HI trim bits\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cal_ctl1](cal_ctl1) module"]
pub type CAL_CTL1 = crate::Reg<u32, _CAL_CTL1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CAL_CTL1;
#[doc = "`read()` method returns [cal_ctl1::R](cal_ctl1::R) reader structure"]
impl crate::Readable for CAL_CTL1 {}
#[doc = "`write(|w| ..)` method takes [cal_ctl1::W](cal_ctl1::W) writer structure"]
impl crate::Writable for CAL_CTL1 {}
#[doc = "Cal control BG HI trim bits"]
pub mod cal_ctl1;
#[doc = "Cal control BG LO&HI ipref trim, ref sel, fm_active, turbo_ext\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cal_ctl2](cal_ctl2) module"]
pub type CAL_CTL2 = crate::Reg<u32, _CAL_CTL2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CAL_CTL2;
#[doc = "`read()` method returns [cal_ctl2::R](cal_ctl2::R) reader structure"]
impl crate::Readable for CAL_CTL2 {}
#[doc = "`write(|w| ..)` method takes [cal_ctl2::W](cal_ctl2::W) writer structure"]
impl crate::Writable for CAL_CTL2 {}
#[doc = "Cal control BG LO&HI ipref trim, ref sel, fm_active, turbo_ext"]
pub mod cal_ctl2;
#[doc = "Cal control osc trim bits, idac, sdac, itim, bdac.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cal_ctl3](cal_ctl3) module"]
pub type CAL_CTL3 = crate::Reg<u32, _CAL_CTL3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CAL_CTL3;
#[doc = "`read()` method returns [cal_ctl3::R](cal_ctl3::R) reader structure"]
impl crate::Readable for CAL_CTL3 {}
#[doc = "`write(|w| ..)` method takes [cal_ctl3::W](cal_ctl3::W) writer structure"]
impl crate::Writable for CAL_CTL3 {}
#[doc = "Cal control osc trim bits, idac, sdac, itim, bdac."]
pub mod cal_ctl3;
#[doc = "Bookmark register - keeps the current FW HV seq\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [bookmark](bookmark) module"]
pub type BOOKMARK = crate::Reg<u32, _BOOKMARK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BOOKMARK;
#[doc = "`write(|w| ..)` method takes [bookmark::W](bookmark::W) writer structure"]
impl crate::Writable for BOOKMARK {}
#[doc = "Bookmark register - keeps the current FW HV seq"]
pub mod bookmark;
#[doc = "Redundancy Control normal sectors 0,1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [red_ctl01](red_ctl01) module"]
pub type RED_CTL01 = crate::Reg<u32, _RED_CTL01>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RED_CTL01;
#[doc = "`read()` method returns [red_ctl01::R](red_ctl01::R) reader structure"]
impl crate::Readable for RED_CTL01 {}
#[doc = "`write(|w| ..)` method takes [red_ctl01::W](red_ctl01::W) writer structure"]
impl crate::Writable for RED_CTL01 {}
#[doc = "Redundancy Control normal sectors 0,1"]
pub mod red_ctl01;
#[doc = "Redundancy Controll normal sectors 2,3\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [red_ctl23](red_ctl23) module"]
pub type RED_CTL23 = crate::Reg<u32, _RED_CTL23>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RED_CTL23;
#[doc = "`read()` method returns [red_ctl23::R](red_ctl23::R) reader structure"]
impl crate::Readable for RED_CTL23 {}
#[doc = "`write(|w| ..)` method takes [red_ctl23::W](red_ctl23::W) writer structure"]
impl crate::Writable for RED_CTL23 {}
#[doc = "Redundancy Controll normal sectors 2,3"]
pub mod red_ctl23;
#[doc = "Redundancy Controll normal sectors 4,5\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [red_ctl45](red_ctl45) module"]
pub type RED_CTL45 = crate::Reg<u32, _RED_CTL45>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RED_CTL45;
#[doc = "`read()` method returns [red_ctl45::R](red_ctl45::R) reader structure"]
impl crate::Readable for RED_CTL45 {}
#[doc = "`write(|w| ..)` method takes [red_ctl45::W](red_ctl45::W) writer structure"]
impl crate::Writable for RED_CTL45 {}
#[doc = "Redundancy Controll normal sectors 4,5"]
pub mod red_ctl45;
#[doc = "Redundancy Controll normal sectors 6,7\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [red_ctl67](red_ctl67) module"]
pub type RED_CTL67 = crate::Reg<u32, _RED_CTL67>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RED_CTL67;
#[doc = "`read()` method returns [red_ctl67::R](red_ctl67::R) reader structure"]
impl crate::Readable for RED_CTL67 {}
#[doc = "`write(|w| ..)` method takes [red_ctl67::W](red_ctl67::W) writer structure"]
impl crate::Writable for RED_CTL67 {}
#[doc = "Redundancy Controll normal sectors 6,7"]
pub mod red_ctl67;
#[doc = "Redundancy Controll special sectors 0,1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [red_ctl_sm01](red_ctl_sm01) module"]
pub type RED_CTL_SM01 = crate::Reg<u32, _RED_CTL_SM01>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RED_CTL_SM01;
#[doc = "`read()` method returns [red_ctl_sm01::R](red_ctl_sm01::R) reader structure"]
impl crate::Readable for RED_CTL_SM01 {}
#[doc = "`write(|w| ..)` method takes [red_ctl_sm01::W](red_ctl_sm01::W) writer structure"]
impl crate::Writable for RED_CTL_SM01 {}
#[doc = "Redundancy Controll special sectors 0,1"]
pub mod red_ctl_sm01;
#[doc = "Do Not Use\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [tm_cmpr](tm_cmpr) module"]
pub type TM_CMPR = crate::Reg<u32, _TM_CMPR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TM_CMPR;
#[doc = "`read()` method returns [tm_cmpr::R](tm_cmpr::R) reader structure"]
impl crate::Readable for TM_CMPR {}
#[doc = "Do Not Use"]
pub mod tm_cmpr;
#[doc = "Flash macro high Voltage page latches data\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [fm_hv_data](fm_hv_data) module"]
pub type FM_HV_DATA = crate::Reg<u32, _FM_HV_DATA>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FM_HV_DATA;
#[doc = "`read()` method returns [fm_hv_data::R](fm_hv_data::R) reader structure"]
impl crate::Readable for FM_HV_DATA {}
#[doc = "`write(|w| ..)` method takes [fm_hv_data::W](fm_hv_data::W) writer structure"]
impl crate::Writable for FM_HV_DATA {}
#[doc = "Flash macro high Voltage page latches data"]
pub mod fm_hv_data;
#[doc = "Flash macro memory sense amplifier and column decoder data\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [fm_mem_data](fm_mem_data) module"]
pub type FM_MEM_DATA = crate::Reg<u32, _FM_MEM_DATA>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FM_MEM_DATA;
#[doc = "`read()` method returns [fm_mem_data::R](fm_mem_data::R) reader structure"]
impl crate::Readable for FM_MEM_DATA {}
#[doc = "Flash macro memory sense amplifier and column decoder data"]
pub mod fm_mem_data;
|
use bytes::Bytes;
use future::{select_all, Either};
use futures_util::{future, pin_mut, stream::StreamExt, stream::TryStreamExt};
use mpsc::UnboundedSender;
use time::Duration;
use tokio::{
sync::mpsc::{self, Receiver, Sender},
time,
};
use tracing::{info, info_span};
use tracing_futures::Instrument;
use mqtt3::{
proto::{Publication, QoS, SubscribeTo},
Client, Event, PublishHandle, ReceivedPublication, UpdateSubscriptionHandle,
};
use mqtt_broker_tests_util::client;
use mqtt_util::client_io::ClientIoSource;
use trc_client::TrcClient;
use crate::{
message_channel::{
MessageChannel, MessageHandler, RelayingMessageHandler, ReportResultMessageHandler,
},
settings::{Settings, TestScenario},
MessageTesterError, BACKWARDS_TOPIC, FORWARDS_TOPIC,
};
const EDGEHUB_CONTAINER_ADDRESS: &str = "edgeHub:8883";
#[derive(Debug, Clone)]
pub struct MessageTesterShutdownHandle {
poll_client_shutdown: Sender<()>,
send_messages_shutdown: Sender<()>,
}
impl MessageTesterShutdownHandle {
fn new(poll_client_shutdown: Sender<()>, send_messages_shutdown: Sender<()>) -> Self {
Self {
poll_client_shutdown,
send_messages_shutdown,
}
}
pub async fn shutdown(mut self) -> Result<(), MessageTesterError> {
self.poll_client_shutdown
.send(())
.await
.map_err(MessageTesterError::SendShutdownSignal)?;
self.send_messages_shutdown
.send(())
.await
.map_err(MessageTesterError::SendShutdownSignal)?;
Ok(())
}
}
/// Abstracts the test logic for this generic mqtt telemetry test module.
/// This module is designed to test generic (non-iothub) mqtt telemetry in both a single-node and nested environment.
/// The module will run in one of two modes. The behavior depends on this mode.
///
/// 1: Initiate mode
/// - If nested scenario, test module runs on the lowest node in the topology.
/// - Spawn a thread that publishes messages continuously to upstream edge.
/// - Receives same message routed back from upstream edge and reports the result to the Test Result Coordinator test module.
///
/// 2: Relay mode
/// - If nested scenario, test module runs on the middle node in the topology.
/// - Receives a message from downstream edge and relays it back to downstream edge.
pub struct MessageTester {
settings: Settings,
client: Client<ClientIoSource>,
publish_handle: PublishHandle,
message_channel: MessageChannel<dyn MessageHandler + Send>,
shutdown_handle: MessageTesterShutdownHandle,
poll_client_shutdown_recv: Receiver<()>,
message_loop_shutdown_recv: Receiver<()>,
}
impl MessageTester {
pub async fn new(settings: Settings) -> Result<Self, MessageTesterError> {
info!("initializing MessageTester");
let client = client::create_client_from_module_env(EDGEHUB_CONTAINER_ADDRESS)
.map_err(MessageTesterError::ParseEnvironment)?;
let publish_handle = client
.publish_handle()
.map_err(MessageTesterError::PublishHandle)?;
let test_result_coordinator_url = settings.test_result_coordinator_url().to_string();
let reporting_client = TrcClient::new(test_result_coordinator_url);
let message_handler: Box<dyn MessageHandler + Send> = match settings.test_scenario() {
TestScenario::Initiate => Box::new(ReportResultMessageHandler::new(reporting_client)),
TestScenario::Relay => Box::new(RelayingMessageHandler::new(publish_handle.clone())),
};
let message_channel = MessageChannel::new(message_handler);
let (poll_client_shutdown_send, poll_client_shutdown_recv) = mpsc::channel::<()>(1);
let (message_loop_shutdown_send, message_loop_shutdown_recv) = mpsc::channel::<()>(1);
let shutdown_handle =
MessageTesterShutdownHandle::new(poll_client_shutdown_send, message_loop_shutdown_send);
info!("finished initializing message tester");
Ok(Self {
settings,
client,
publish_handle,
message_channel,
shutdown_handle,
poll_client_shutdown_recv,
message_loop_shutdown_recv,
})
}
pub async fn run(self) -> Result<(), MessageTesterError> {
// start poll client and make subs
let client_sub_handle = self
.client
.update_subscription_handle()
.map_err(MessageTesterError::UpdateSubscriptionHandle)?;
let message_send_handle = self.message_channel.message_channel();
let poll_client_join = tokio::spawn(
poll_client(
message_send_handle,
self.client,
self.poll_client_shutdown_recv,
)
.instrument(info_span!("client")),
);
Self::subscribe(client_sub_handle, self.settings.clone()).await?;
// run message channel
let message_channel_shutdown = self.message_channel.shutdown_handle();
let message_channel_join = tokio::spawn(
self.message_channel
.run()
.instrument(info_span!("message channel")),
);
let mut tasks = vec![message_channel_join, poll_client_join];
// maybe start message loop depending on mode
if let TestScenario::Initiate = self.settings.test_scenario() {
let message_loop = tokio::spawn(
send_initial_messages(self.publish_handle.clone(), self.message_loop_shutdown_recv)
.instrument(info_span!("initiation message loop")),
);
tasks.push(message_loop);
}
info!("waiting for tasks to exit");
let (exited, _, join_handles) = select_all(tasks).await;
exited.map_err(MessageTesterError::WaitForShutdown)??;
message_channel_shutdown.shutdown().await?;
for handle in join_handles {
handle
.await
.map_err(MessageTesterError::WaitForShutdown)??;
}
Ok(())
}
pub fn shutdown_handle(&self) -> MessageTesterShutdownHandle {
self.shutdown_handle.clone()
}
async fn subscribe(
mut client_sub_handle: UpdateSubscriptionHandle,
settings: Settings,
) -> Result<(), MessageTesterError> {
info!("subscribing to test topics");
match settings.test_scenario() {
TestScenario::Initiate => client_sub_handle
.subscribe(SubscribeTo {
topic_filter: BACKWARDS_TOPIC.to_string(),
qos: QoS::AtLeastOnce,
})
.await
.map_err(MessageTesterError::UpdateSubscription)?,
TestScenario::Relay => client_sub_handle
.subscribe(SubscribeTo {
topic_filter: FORWARDS_TOPIC.to_string(),
qos: QoS::AtLeastOnce,
})
.await
.map_err(MessageTesterError::UpdateSubscription)?,
};
info!("finished subscribing to test topics");
Ok(())
}
}
async fn send_initial_messages(
mut publish_handle: PublishHandle,
mut shutdown_recv: Receiver<()>,
) -> Result<(), MessageTesterError> {
info!("starting message loop");
let mut seq_num: u32 = 0;
loop {
info!("publishing message {} to upstream broker", seq_num);
let publication = Publication {
topic_name: "forwards/1".to_string(),
qos: QoS::ExactlyOnce,
retain: true,
payload: Bytes::from(seq_num.to_string()),
};
let shutdown_recv_fut = shutdown_recv.next();
let publish_fut = publish_handle.publish(publication);
pin_mut!(publish_fut);
match future::select(shutdown_recv_fut, publish_fut).await {
Either::Left((shutdown, _)) => {
info!("received shutdown signal");
shutdown.ok_or(MessageTesterError::ListenForShutdown)?;
break;
}
Either::Right((publish, _)) => {
publish.map_err(MessageTesterError::Publish)?;
}
};
time::delay_for(Duration::from_secs(1)).await;
seq_num += 1;
}
Ok(())
}
async fn poll_client(
message_send_handle: UnboundedSender<ReceivedPublication>,
mut client: Client<ClientIoSource>,
mut shutdown_recv: Receiver<()>,
) -> Result<(), MessageTesterError> {
info!("starting poll client");
loop {
let message_send_handle = message_send_handle.clone();
let event = client.try_next();
let shutdown = shutdown_recv.next();
match future::select(event, shutdown).await {
Either::Left((event, _)) => {
if let Ok(Some(event)) = event {
process_event(event, message_send_handle)?;
}
}
Either::Right((shutdown, _)) => {
break;
}
}
}
Ok(())
}
fn process_event(
event: Event,
message_send_handle: UnboundedSender<ReceivedPublication>,
) -> Result<(), MessageTesterError> {
match event {
Event::NewConnection { .. } => {
info!("received new connection");
}
Event::Publication(publication) => {
info!("received publication");
message_send_handle
.send(publication)
.map_err(MessageTesterError::SendPublicationInChannel)?;
}
Event::SubscriptionUpdates(sub) => {
info!("received subscription update {:?}", sub);
}
Event::Disconnected(_) => {
info!("received disconnect");
}
};
Ok(())
}
|
#[doc = "Register `OTG_GAHBCFG` reader"]
pub type R = crate::R<OTG_GAHBCFG_SPEC>;
#[doc = "Register `OTG_GAHBCFG` writer"]
pub type W = crate::W<OTG_GAHBCFG_SPEC>;
#[doc = "Field `GINTMSK` reader - GINTMSK"]
pub type GINTMSK_R = crate::BitReader;
#[doc = "Field `GINTMSK` writer - GINTMSK"]
pub type GINTMSK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HBSTLEN` reader - HBSTLEN"]
pub type HBSTLEN_R = crate::FieldReader;
#[doc = "Field `HBSTLEN` writer - HBSTLEN"]
pub type HBSTLEN_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>;
#[doc = "Field `DMAEN` reader - DMAEN"]
pub type DMAEN_R = crate::BitReader;
#[doc = "Field `DMAEN` writer - DMAEN"]
pub type DMAEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TXFELVL` reader - TXFELVL"]
pub type TXFELVL_R = crate::BitReader;
#[doc = "Field `TXFELVL` writer - TXFELVL"]
pub type TXFELVL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PTXFELVL` reader - PTXFELVL"]
pub type PTXFELVL_R = crate::BitReader;
#[doc = "Field `PTXFELVL` writer - PTXFELVL"]
pub type PTXFELVL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - GINTMSK"]
#[inline(always)]
pub fn gintmsk(&self) -> GINTMSK_R {
GINTMSK_R::new((self.bits & 1) != 0)
}
#[doc = "Bits 1:4 - HBSTLEN"]
#[inline(always)]
pub fn hbstlen(&self) -> HBSTLEN_R {
HBSTLEN_R::new(((self.bits >> 1) & 0x0f) as u8)
}
#[doc = "Bit 5 - DMAEN"]
#[inline(always)]
pub fn dmaen(&self) -> DMAEN_R {
DMAEN_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 7 - TXFELVL"]
#[inline(always)]
pub fn txfelvl(&self) -> TXFELVL_R {
TXFELVL_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - PTXFELVL"]
#[inline(always)]
pub fn ptxfelvl(&self) -> PTXFELVL_R {
PTXFELVL_R::new(((self.bits >> 8) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - GINTMSK"]
#[inline(always)]
#[must_use]
pub fn gintmsk(&mut self) -> GINTMSK_W<OTG_GAHBCFG_SPEC, 0> {
GINTMSK_W::new(self)
}
#[doc = "Bits 1:4 - HBSTLEN"]
#[inline(always)]
#[must_use]
pub fn hbstlen(&mut self) -> HBSTLEN_W<OTG_GAHBCFG_SPEC, 1> {
HBSTLEN_W::new(self)
}
#[doc = "Bit 5 - DMAEN"]
#[inline(always)]
#[must_use]
pub fn dmaen(&mut self) -> DMAEN_W<OTG_GAHBCFG_SPEC, 5> {
DMAEN_W::new(self)
}
#[doc = "Bit 7 - TXFELVL"]
#[inline(always)]
#[must_use]
pub fn txfelvl(&mut self) -> TXFELVL_W<OTG_GAHBCFG_SPEC, 7> {
TXFELVL_W::new(self)
}
#[doc = "Bit 8 - PTXFELVL"]
#[inline(always)]
#[must_use]
pub fn ptxfelvl(&mut self) -> PTXFELVL_W<OTG_GAHBCFG_SPEC, 8> {
PTXFELVL_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 = "This register can be used to configure the core after power-on or a change in mode. This register mainly contains AHB system-related configuration parameters. Do not change this register after the initial programming. The application must program this register before starting any transactions on either the AHB or the USB.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`otg_gahbcfg::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 [`otg_gahbcfg::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct OTG_GAHBCFG_SPEC;
impl crate::RegisterSpec for OTG_GAHBCFG_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`otg_gahbcfg::R`](R) reader structure"]
impl crate::Readable for OTG_GAHBCFG_SPEC {}
#[doc = "`write(|w| ..)` method takes [`otg_gahbcfg::W`](W) writer structure"]
impl crate::Writable for OTG_GAHBCFG_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets OTG_GAHBCFG to value 0"]
impl crate::Resettable for OTG_GAHBCFG_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
mod server;
pub use server::Server;
mod util;
mod importer;
pub use importer::Importer;
pub const BUFFER_SIZE: usize = 10000;
pub const SOCKET_PATH: &str = env!("SOCKET_PATH");
pub const CONFIG_PATH: &str = env!("CONFIG_PATH");
pub const STATE_PATH: &str = env!("STATE_PATH");
pub const REPOSITORY_DIR: &str = env!("REPOSITORY_DIR");
pub const BACKUP_DIR: &str = env!("BACKUP_DIR");
|
// endianness is not configurable
pub fn int_to_bytes(int: u64, length: usize) -> Vec<u8> {
let mut vec = int.to_le_bytes().to_vec();
vec.resize(length, 0);
vec
}
pub fn integer_squareroot(n: u64) -> u64 {
let mut x = n;
let mut y = (x + 1) / 2;
while y < x {
x = y;
y = (x + n / x) / 2
}
x
}
pub fn bytes_to_int(bytes: [u8; 8]) -> u64 {
u64::from_le_bytes(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_int_to_bytes_value0_length_8() {
let expected_bytes = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let output = int_to_bytes(0, 8);
let calculated_bytes = output.as_ref();
assert_eq!(expected_bytes, calculated_bytes);
}
#[test]
fn test_int_to_bytes_value2521273052_length_8() {
let expected_bytes = [0xdc, 0x92, 0x47, 0x96, 0x00, 0x00, 0x00, 0x00];
let output = int_to_bytes(2_521_273_052, 8);
let calculated_bytes = output.as_ref();
assert_eq!(expected_bytes, calculated_bytes);
}
#[test]
fn test_int_to_bytes_value4294967295_length_8() {
let expected_bytes = [0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00];
let output = int_to_bytes(0xFFFF_FFFF, 8);
let calculated_bytes = output.as_ref();
assert_eq!(expected_bytes, calculated_bytes);
}
#[test]
fn test_int_to_bytes_value88813769_length_32() {
let expected_bytes = [
0xc9, 0x30, 0x4b, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
];
let output = int_to_bytes(88_813_769, 32);
let calculated_bytes = output.as_ref();
assert_eq!(expected_bytes, calculated_bytes);
}
#[test]
fn test_integer_squareroot() {
assert_eq!(integer_squareroot(49), 7);
assert_eq!(integer_squareroot(1), 1);
assert_eq!(integer_squareroot(25), 5);
assert_eq!(integer_squareroot(20), 4);
}
#[test]
fn test_bytes_to_int() {
assert_eq!(
bytes_to_int([0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
2
);
assert_eq!(
bytes_to_int([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
0
);
assert_eq!(
bytes_to_int([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]),
0x0100_0000_0000_0000
);
}
}
|
#[doc = "Reader of register CMD_RESP_CTRL"]
pub type R = crate::R<u32, super::CMD_RESP_CTRL>;
#[doc = "Writer for register CMD_RESP_CTRL"]
pub type W = crate::W<u32, super::CMD_RESP_CTRL>;
#[doc = "Register CMD_RESP_CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::CMD_RESP_CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `BASE_RD_ADDR`"]
pub type BASE_RD_ADDR_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `BASE_RD_ADDR`"]
pub struct BASE_RD_ADDR_W<'a> {
w: &'a mut W,
}
impl<'a> BASE_RD_ADDR_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01ff) | ((value as u32) & 0x01ff);
self.w
}
}
#[doc = "Reader of field `BASE_WR_ADDR`"]
pub type BASE_WR_ADDR_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `BASE_WR_ADDR`"]
pub struct BASE_WR_ADDR_W<'a> {
w: &'a mut W,
}
impl<'a> BASE_WR_ADDR_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01ff << 16)) | (((value as u32) & 0x01ff) << 16);
self.w
}
}
impl R {
#[doc = "Bits 0:8 - I2C/SPI read base address for CMD_RESP mode. At the start of a read transfer this BASE_RD_ADDR is copied to CMD_RESP_STATUS.CURR_RD_ADDR. This field should not be modified during ongoing bus transfers."]
#[inline(always)]
pub fn base_rd_addr(&self) -> BASE_RD_ADDR_R {
BASE_RD_ADDR_R::new((self.bits & 0x01ff) as u16)
}
#[doc = "Bits 16:24 - I2C/SPI write base address for CMD_RESP mode. At the start of a write transfer this BASE_WR_ADDR is copied to CMD_RESP_STATUS.CURR_WR_ADDR. This field should not be modified during ongoing bus transfers."]
#[inline(always)]
pub fn base_wr_addr(&self) -> BASE_WR_ADDR_R {
BASE_WR_ADDR_R::new(((self.bits >> 16) & 0x01ff) as u16)
}
}
impl W {
#[doc = "Bits 0:8 - I2C/SPI read base address for CMD_RESP mode. At the start of a read transfer this BASE_RD_ADDR is copied to CMD_RESP_STATUS.CURR_RD_ADDR. This field should not be modified during ongoing bus transfers."]
#[inline(always)]
pub fn base_rd_addr(&mut self) -> BASE_RD_ADDR_W {
BASE_RD_ADDR_W { w: self }
}
#[doc = "Bits 16:24 - I2C/SPI write base address for CMD_RESP mode. At the start of a write transfer this BASE_WR_ADDR is copied to CMD_RESP_STATUS.CURR_WR_ADDR. This field should not be modified during ongoing bus transfers."]
#[inline(always)]
pub fn base_wr_addr(&mut self) -> BASE_WR_ADDR_W {
BASE_WR_ADDR_W { w: self }
}
}
|
use std::collections::HashMap;
use super::Parser;
use crate::dom::{AttrMap, Node};
pub struct HTMLParser {
pos: usize,
input: String,
}
impl HTMLParser {
pub fn new(input: String) -> HTMLParser {
HTMLParser { pos: 0, input }
}
pub fn run(&mut self) -> Node {
self.consume_whitespace();
let mut nodes = self.parse_nodes();
if nodes.len() == 1 {
nodes.swap_remove(0)
} else {
Node::new_element("html".into(), HashMap::new(), nodes)
}
}
fn parse_nodes(&mut self) -> Vec<Node> {
let mut nodes = vec![];
loop {
if self.eof() || self.starts_with("</") {
break;
}
if let Some(node) = self.parse_node() {
nodes.push(node);
}
}
nodes
}
fn parse_node(&mut self) -> Option<Node> {
let text = self.consume_while(|c| c != '<');
let white_spaces = text.chars().take_while(|c| c.is_whitespace());
if text.chars().count() == white_spaces.count() {
if self.eof() || self.starts_with("</") {
return None;
}
return self.parse_element();
}
Some(Node::new_text(text))
}
fn parse_element(&mut self) -> Option<Node> {
// Consumed character should be '<' in here.
self.consume_char();
let tag_name = self.parse_tag_name();
let attrs = self.parse_attributes();
if self.eof() {
return Some(Node::new_element(tag_name, attrs, vec![]));
}
if self.next_char() != '>' {
self.consume_while(|c| c != '>');
} else {
self.consume_char();
}
let children = self.parse_nodes();
if self.eof() {
return Some(Node::new_element(tag_name, attrs, children));
}
if self.next_char() != '<' {
return Some(Node::new_element(tag_name, attrs, children));
} else {
self.consume_char();
}
if self.next_char() != '/' {
return Some(Node::new_element(tag_name, attrs, children));
} else {
self.consume_char();
}
if tag_name != self.parse_tag_name() {
return Some(Node::new_element(tag_name, attrs, children));
}
if self.next_char() != '>' {
loop {
if self.eof() || self.next_char() == '<' {
break;
}
if self.next_char() == '>' {
self.consume_char();
break;
}
self.consume_char();
}
} else {
self.consume_char();
}
Some(Node::new_element(tag_name, attrs, children))
}
fn parse_attributes(&mut self) -> AttrMap {
let mut attrs = HashMap::new();
loop {
if self.eof() {
break;
}
self.consume_whitespace();
if self.next_char() == '/' {
self.consume_char();
continue;
}
if self.next_char() == '>' {
break;
}
let (name, value) = self.parse_attr();
attrs.insert(name, value);
}
attrs
}
fn parse_attr(&mut self) -> (String, String) {
let name = self.consume_while(|c| match c {
'>' => false,
'=' => false,
c if c.is_whitespace() => false,
_ => true,
});
if self.next_char() != '=' {
return (name, "".into());
} else {
self.consume_char();
}
let val = self.parse_attr_value();
(name, val)
}
fn parse_attr_value(&mut self) -> String {
let open_quote = self.next_char();
let is_quote = open_quote == '"' || open_quote == '\'';
if is_quote {
self.consume_char();
}
let val = self.consume_while(|c| {
if is_quote {
return c != open_quote;
}
if c == '>' || c.is_whitespace() {
return false;
}
true
});
if !self.eof() && is_quote {
self.consume_char();
}
val
}
fn parse_tag_name(&mut self) -> String {
self.consume_while(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9'))
}
}
impl Parser for HTMLParser {
fn input(&self) -> &str {
&self.input
}
fn pos(&self) -> usize {
self.pos
}
fn set_pos(&mut self, next_pos: usize) {
self.pos += next_pos;
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::dom::*;
#[test]
fn test_parse_node() {
let input = "
<div id=\"main\" class=\"test\">
<p>Hello <em> world</em>!</p>
<p>Test</p>
</div>
";
let mut p = HTMLParser::new(input.into());
let div = p.run();
if let NodeType::Element(elm) = div.node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.get("id").unwrap(), &"main");
assert_eq!(&elm.attributes.get("class").unwrap(), &"test");
}
assert_eq!(div.children.len(), 2);
let p_tag = &div.children[0];
if let NodeType::Element(elm) = &p_tag.node_type {
assert_eq!(&elm.tag_name, "p");
assert_eq!(&elm.attributes.len(), &0);
}
let text_node = &p_tag.children[0];
if let NodeType::Text(s) = &text_node.node_type {
assert_eq!(s, "Hello ");
}
let em_tag = &p_tag.children[1];
if let NodeType::Element(elm) = &em_tag.node_type {
assert_eq!(&elm.tag_name, "em");
assert_eq!(&elm.attributes.len(), &0);
}
let text_node = &em_tag.children[0];
if let NodeType::Text(s) = &text_node.node_type {
assert_eq!(s, " world");
}
let text_node = &p_tag.children[2];
if let NodeType::Text(s) = &text_node.node_type {
assert_eq!(s, "!");
}
let p_tag = &div.children[1];
if let NodeType::Element(elm) = &p_tag.node_type {
assert_eq!(&elm.tag_name, "p");
assert_eq!(&elm.attributes.len(), &0);
}
let text_node = &p_tag.children[0];
if let NodeType::Text(s) = &text_node.node_type {
assert_eq!(s, "Test");
}
}
/// https://html.spec.whatwg.org/multipage/parsing.html#parse-error-end-tag-with-attributes
#[test]
fn test_parse_end_tag_with_attributes() {
let input = "<body><div></div attr=\"test\"><p></p></body>";
let mut p = HTMLParser::new(input.into());
let body = p.run();
if let NodeType::Element(elm) = &body.children[0].node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &0);
}
if let NodeType::Element(elm) = &body.children[1].node_type {
assert_eq!(&elm.tag_name, "p");
assert_eq!(&elm.attributes.len(), &0);
}
}
/// https://html.spec.whatwg.org/multipage/parsing.html#parse-error-end-tag-with-trailing-solidus
#[test]
fn test_parse_end_tag_with_trailing_solidus() {
let input = "<body><div></div/><p></p></body>";
let mut p = HTMLParser::new(input.into());
let body = p.run();
if let NodeType::Element(elm) = &body.children[0].node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &0);
}
if let NodeType::Element(elm) = &body.children[1].node_type {
assert_eq!(&elm.tag_name, "p");
assert_eq!(&elm.attributes.len(), &0);
}
}
/// https://html.spec.whatwg.org/multipage/parsing.html#parse-error-missing-end-tag-name
#[test]
fn test_parse_missing_end_tag_name() {
let input = "<body><div></><p></p></body>";
let mut p = HTMLParser::new(input.into());
let body = p.run();
if let NodeType::Element(elm) = &body.children[0].node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &0);
}
if let NodeType::Element(elm) = &body.children[1].node_type {
assert_eq!(&elm.tag_name, "p");
assert_eq!(&elm.attributes.len(), &0);
}
}
#[test]
fn test_parse_missing_close() {
let input = "<body><div></div attr=\"test\" </body>";
let mut p = HTMLParser::new(input.into());
let body = p.run();
assert_eq!(&body.children.len(), &1);
if let NodeType::Element(elm) = &body.children[0].node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &0);
}
}
/// https://html.spec.whatwg.org/multipage/parsing.html#parse-error-non-void-html-element-start-tag-with-trailing-solidus
#[test]
fn test_parse_non_void_html_element_start_tag_with_trailing_solidus() {
let input = "<body><div /><p></p><span></span></body>";
let mut p = HTMLParser::new(input.into());
let body = p.run();
let div = &body.children[0];
if let NodeType::Element(elm) = &div.node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &0);
}
if let NodeType::Element(elm) = &div.children[0].node_type {
assert_eq!(&elm.tag_name, "p");
assert_eq!(&elm.attributes.len(), &0);
}
if let NodeType::Element(elm) = &div.children[1].node_type {
assert_eq!(&elm.tag_name, "span");
assert_eq!(&elm.attributes.len(), &0);
}
}
/// https://html.spec.whatwg.org/multipage/parsing.html#parse-error-unexpected-character-in-attribute-name
#[test]
fn test_parse_unexpected_character_in_attribute_name() {
let input = "<body><div foo<div><div id'bar'></div></body>";
let mut p = HTMLParser::new(input.into());
let body = p.run();
if let NodeType::Element(elm) = &body.children[0].node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &1);
assert_eq!(&elm.attributes.get("foo<div").unwrap(), &"");
}
if let NodeType::Element(elm) = &body.children[1].node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &1);
assert_eq!(&elm.attributes.get("id'bar'").unwrap(), &"");
}
}
/// https://html.spec.whatwg.org/multipage/parsing.html#parse-error-unexpected-character-in-unquoted-attribute-value
#[test]
fn test_parse_unexpected_character_in_unquoted_attribute_value() {
let input = "<body><div id=b'ar'></div><div id=\"></body>";
let mut p = HTMLParser::new(input.into());
let body = p.run();
if let NodeType::Element(elm) = &body.children[0].node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &1);
assert_eq!(&elm.attributes.get("id").unwrap(), &"b'ar'");
}
if let NodeType::Element(elm) = &body.children[1].node_type {
assert_eq!(&elm.tag_name, "div");
assert_eq!(&elm.attributes.len(), &1);
assert_eq!(&elm.attributes.get("id").unwrap(), &"></body>");
}
}
}
|
use std::cell::RefCell;
use std::rc;
use crate::object;
use crate::store;
use crate::transaction;
use crate::network::client_messages;
use crate::network::*;
pub struct ReadResponse {
pub client_id: ClientId,
pub request_id: RequestId,
pub object_id: object::Id,
pub result: Result<store::ReadState, store::ReadError>
}
pub struct NullMessengerState {
pub reads: Vec<ReadResponse>,
pub txs: Vec<transaction::Message>,
pub clis: Vec<client_messages::Message>
}
pub struct NullMessenger {
state: rc::Rc<RefCell<NullMessengerState>>
}
impl NullMessenger {
pub fn new() -> (rc::Rc<RefCell<NullMessengerState>>, rc::Rc<dyn Messenger>) {
let s = rc::Rc::new( RefCell::new(NullMessengerState {
reads: Vec::new(),
txs: Vec::new(),
clis: Vec::new(),
}));
let n = rc::Rc::new( NullMessenger{
state: s.clone()
});
(s, n)
}
}
impl Messenger for NullMessenger {
fn send_read_response(
&self,
client_id: ClientId,
request_id: RequestId,
object_id: object::Id,
result: Result<store::ReadState, store::ReadError>) {
self.state.borrow_mut().reads.push( ReadResponse {
client_id,
request_id,
object_id,
result
});
}
fn send_transaction_message(&self, msg: transaction::Message) {
self.state.borrow_mut().txs.push(msg);
}
fn send_client_message(&self, msg: client_messages::Message) {
self.state.borrow_mut().clis.push(msg);
}
} |
extern crate speedtest_rs;
#[macro_use]
extern crate log;
extern crate env_logger;
#[macro_use]
extern crate clap;
use clap::{App, Arg};
// use speedtest_rs::speedtest::run_speedtest;
use speedtest_rs::speedtest;
use std::io::{self, Write};
#[allow(dead_code)]
fn main() {
env_logger::init().unwrap();
let matches = App::new("speedtest-rs")
.version(&crate_version!()[..])
.about("Command line interface for testing internet bandwidth using speedtest.net.")
.arg(Arg::with_name("list")
.long("list")
.help("Display a list of speedtest.net servers sorted by distance"))
.arg(Arg::with_name("share")
.long("share")
.help("Generate and provide an URL to the speedtest.net share results image"))
.arg(Arg::with_name("bytes")
.long("bytes")
.help("Display values in bytes instead of bits."))
.arg(Arg::with_name("simple")
.long("simple")
.help("Suppress verbose output, only show basic informatio"))
.get_matches();
if !matches.is_present("simple") {
println!("Retrieving speedtest.net configuration...");
}
let config = speedtest::get_configuration().unwrap();
if !matches.is_present("simple") {
println!("Retrieving speedtest.net server list...");
}
let server_list = speedtest::get_server_list_with_config(Some(&config)).unwrap();
let mut server_list_sorted = server_list.servers_sorted_by_distance(&config);
if matches.is_present("list") {
for server in server_list_sorted {
println!("{:4}) {} ({}, {}) [{:.2} km]",
server.id,
server.sponsor,
server.name,
server.country,
server.distance.unwrap(),
);
}
return;
}
if !matches.is_present("simple") {
println!("Testing from {} ({})...", config.isp, config.ip);
println!("Selecting best server based on latency...");
}
info!("Five Closest Servers");
server_list_sorted.truncate(5);
for server in &server_list_sorted {
info!("Close Server: {:?}", server);
}
let latecy_test_result = speedtest::get_best_server_based_on_latency(&server_list_sorted[..])
.unwrap();
if !matches.is_present("simple") {
println!("Hosted by {} ({}) [{:.2} km]: {}.{} ms",
latecy_test_result.server.sponsor,
latecy_test_result.server.name,
latecy_test_result.server.distance.unwrap(),
latecy_test_result.latency.num_milliseconds(),
latecy_test_result.latency.num_microseconds().unwrap() % 1000,
);
} else {
println!("Ping: {}.{} ms",
latecy_test_result.latency.num_milliseconds(),
latecy_test_result.latency.num_microseconds().unwrap() % 1000,
);
}
let best_server = latecy_test_result.server;
let download_measurement;
if !matches.is_present("simple") {
print!("Testing download speed");
download_measurement = speedtest::test_download_with_progress(best_server, print_dot)
.unwrap();
println!("");
} else {
download_measurement = speedtest::test_download_with_progress(best_server, do_nothing)
.unwrap();
}
if matches.is_present("bytes") {
println!("Download: {:.2} Mbyte/s",
((download_measurement.kbps() / 8) as f32 / 1000.00));
} else {
println!("Download: {:.2} Mbit/s",
(download_measurement.kbps()) as f32 / 1000.00);
}
let upload_measurement;
if !matches.is_present("simple") {
print!("Testing upload speed");
upload_measurement = speedtest::test_upload_with_progress(best_server, print_dot).unwrap();
println!("");
} else {
upload_measurement = speedtest::test_upload_with_progress(best_server, do_nothing).unwrap();
}
if matches.is_present("bytes") {
println!("Upload: {:.2} Mbyte/s",
((upload_measurement.kbps() / 8) as f32 / 1000.00));
} else {
println!("Upload: {:.2} Mbit/s",
(upload_measurement.kbps() as f32 / 1000.00));
}
if matches.is_present("share") {
let request = speedtest::ShareUrlRequest {
download_measurement: &download_measurement,
upload_measurement: &upload_measurement,
server: &best_server,
latency_measurement: &latecy_test_result,
};
info!("Share Request {:?}", request);
println!("Share results: {}", speedtest::get_share_url(&request));
}
}
fn print_dot() {
print!(".");
io::stdout().flush().unwrap();
}
fn do_nothing() {}
|
use rand::os::OsRng;
use rand::Rng;
use hmac::{Hmac, Mac};
use sha2::Sha512;
use base64;
pub fn make_random_string() -> String {
let mut rng = OsRng::new().expect("can't access the OS random number generator");
rng.gen_ascii_chars().take(30).collect()
}
pub fn authenticate(challenge: &str, key: &str, digest: &str) -> bool {
match base64::decode(digest) {
Err(_) => false,
Ok(bin_digest) => {
if bin_digest.len() != 64 {
false
} else {
let mut mac = Hmac::<Sha512>::new(key.as_bytes());
mac.input(challenge.as_bytes());
mac.verify(&bin_digest)
}
}
}
}
|
//
// Copyright 2020 The Project Oak Authors
//
// 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.
//
//! Shared data structures and functionality for inter-node communication.
mod decodable;
mod encodable;
mod error;
pub mod handle;
mod receiver;
mod sender;
pub use decodable::Decodable;
use either::Either;
pub use encodable::Encodable;
pub use error::OakError;
use handle::{ReadHandle, WriteHandle};
pub use oak_abi::{Handle, OakStatus};
pub use receiver::Receiver;
pub use sender::Sender;
/// A simple holder for bytes + handles, using internally owned buffers.
#[derive(Clone, PartialEq, Eq)]
pub struct Message {
pub bytes: Vec<u8>,
pub handles: Vec<Handle>,
}
/// Manual `Debug` implementation to allow hex display.
impl std::fmt::Debug for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Message")
.field("handles", &self.handles)
.field("bytes", &format_args!("{}", hex::encode(&self.bytes)))
.finish()
}
}
/// Implementation of [`Encodable`] for [`Either`] that encodes the variant (0 or 1) in the first
/// byte of the resulting [`Message`].
impl<L: Encodable, R: Encodable> Encodable for Either<L, R> {
fn encode(&self) -> Result<Message, OakError> {
let (variant, mut inner) = match self {
// Left variant == 0.
Either::Left(m) => (0, m.encode()?),
// Right variant == 1.
Either::Right(m) => (1, m.encode()?),
};
// Insert the variant byte as the beginning of the message bytes, and leave handles as they
// are.
inner.bytes.insert(0, variant);
Ok(inner)
}
}
/// Implementation of [`Decodable`] for [`Either`] that decodes the variant (0 or 1) from the first
/// byte of the provided [`Message`].
impl<L: Decodable, R: Decodable> Decodable for Either<L, R> {
fn decode(message: &Message) -> Result<Self, OakError> {
match message.bytes.get(0) {
// Left variant == 0.
Some(0) => {
let inner_message = Message {
bytes: message.bytes[1..].to_vec(),
handles: message.handles.clone(),
};
Ok(Either::Left(L::decode(&inner_message)?))
}
// Right variant == 1.
Some(1) => {
let inner_message = Message {
bytes: message.bytes[1..].to_vec(),
handles: message.handles.clone(),
};
Ok(Either::Right(R::decode(&inner_message)?))
}
// Invalid variant, or not enough bytes.
_ => Err(OakStatus::ErrInvalidArgs.into()),
}
}
}
/// A wrapper struct that holds an init message, plus the handle of a channel from which to read
/// command messages. This is useful for patterns in which an Oak node needs some data at
/// initialization time, but then handles commands of a different type and possibly coming from a
/// different channel, to be processed in an event-loop pattern.
#[derive(Clone, Debug, PartialEq)]
pub struct InitWrapper<Init, Command: Decodable> {
pub init: Init,
pub command_receiver: Receiver<Command>,
}
/// Implementation of [`Encodable`] for [`InitWrapper`] that encodes the handle of the command
/// receiver channel in the first handle of the resulting [`Message`].
impl<Init: Encodable, Command: Encodable + Decodable> Encodable for InitWrapper<Init, Command> {
fn encode(&self) -> Result<Message, OakError> {
let mut init_message = self.init.encode()?;
// Insert the handle of the command receiver handle at the beginning of the handle list
// (i.e. at position 0).
init_message
.handles
.insert(0, self.command_receiver.handle.handle);
Ok(init_message)
}
}
/// Implementation of [`Decodable`] for [`InitWrapper`] that decodes the handle of the command
/// receiver channel from the first handle of the provided [`Message`].
impl<Init: Decodable, Command: Decodable> Decodable for InitWrapper<Init, Command> {
fn decode(message: &Message) -> Result<Self, OakError> {
match message.handles.get(0) {
Some(handle) => {
let init_message = Message {
bytes: message.bytes.clone(),
handles: message.handles[1..].to_vec(),
};
Ok(Self {
init: Init::decode(&init_message)?,
command_receiver: Receiver::new(ReadHandle::from(*handle)),
})
}
_ => Err(OakStatus::ErrInvalidArgs.into()),
}
}
}
#[cfg(test)]
#[cfg(not(feature = "linear-handles"))]
mod tests {
use super::*;
use assert_matches::assert_matches;
#[derive(Debug, PartialEq)]
struct TestStruct {
receiver_0: Receiver<()>,
field_0: u8,
receiver_1: Receiver<()>,
field_1: u8,
}
impl Encodable for TestStruct {
fn encode(&self) -> Result<Message, OakError> {
Ok(Message {
bytes: vec![self.field_0, self.field_1],
handles: vec![self.receiver_0.handle.handle, self.receiver_1.handle.handle],
})
}
}
impl Decodable for TestStruct {
fn decode(message: &Message) -> Result<Self, OakError> {
match (message.bytes.as_slice(), message.handles.as_slice()) {
([byte_0, byte_1], [handle_0, handle_1]) => Ok(TestStruct {
receiver_0: Receiver::from(ReadHandle::from(*handle_0)),
field_0: *byte_0,
receiver_1: Receiver::from(ReadHandle::from(*handle_1)),
field_1: *byte_1,
}),
_ => panic!("invalid Message for TestStruct"),
}
}
}
#[test]
fn test_struct_round_trip() {
let original = TestStruct {
receiver_0: Receiver::from(ReadHandle::from(100)),
field_0: 10,
receiver_1: Receiver::from(ReadHandle::from(101)),
field_1: 11,
};
let encoded = original.encode().unwrap();
assert_eq!(
Message {
bytes: vec![10, 11],
handles: vec![100, 101],
},
encoded
);
let decoded = TestStruct::decode(&encoded).unwrap();
assert_eq!(original, decoded);
}
#[test]
fn either_round_trip() {
type T = Either<u32, TestStruct>;
{
// This test case is just a baseline reference for the ones below, to spell out the
// protobuf encoding of the inner object.
let original = 1988;
let encoded = original.encode().unwrap();
assert_eq!(
Message {
bytes: vec![8, 196, 15],
handles: vec![],
},
encoded
);
let decoded = u32::decode(&encoded).unwrap();
assert_eq!(original, decoded);
}
{
let original = T::Left(1988);
let encoded = original.encode().unwrap();
// Note the first byte corresponds to the variant == 0.
assert_eq!(
Message {
bytes: vec![0, 8, 196, 15],
handles: vec![],
},
encoded
);
let decoded = T::decode(&encoded).unwrap();
assert_eq!(original, decoded);
}
{
let original = T::Right(TestStruct {
receiver_0: Receiver::from(ReadHandle::from(100)),
field_0: 10,
receiver_1: Receiver::from(ReadHandle::from(101)),
field_1: 11,
});
let encoded = original.encode().unwrap();
// Note the first byte corresponds to the variant == 1.
assert_eq!(
Message {
bytes: vec![1, 10, 11],
handles: vec![100, 101],
},
encoded
);
let decoded = T::decode(&encoded).unwrap();
assert_eq!(original, decoded);
}
{
let invalid_variant = 42;
let encoded_invalid = Message {
bytes: vec![invalid_variant, 8, 196, 15],
handles: vec![],
};
assert_matches!(
T::decode(&encoded_invalid),
Err(OakError::OakStatus(OakStatus::ErrInvalidArgs))
);
}
}
#[test]
fn init_wrapper_round_trip() {
type T = InitWrapper<TestStruct, ()>;
{
let original = T {
init: TestStruct {
receiver_0: Receiver::from(ReadHandle::from(100)),
field_0: 10,
receiver_1: Receiver::from(ReadHandle::from(101)),
field_1: 11,
},
command_receiver: Receiver::from(ReadHandle::from(123)),
};
let encoded = original.encode().unwrap();
// Note the handle list contains the command receiver handle at the beginning.
assert_eq!(
Message {
bytes: vec![10, 11],
handles: vec![123, 100, 101],
},
encoded
);
let decoded = T::decode(&encoded).unwrap();
assert_eq!(original, decoded);
}
}
}
|
pub mod asset;
pub mod bindings;
mod reader;
mod util;
pub use asset::*;
|
use crate::net::SignerID;
use tapyrus::PublicKey;
pub fn sender_index(sender_id: &SignerID, pubkey_list: &[PublicKey]) -> usize {
//Unknown sender is already ignored.
pubkey_list
.iter()
.position(|pk| pk == &sender_id.pubkey)
.unwrap()
}
|
// Crate linkage metadata
#[ link(name = "closures",
vers = "0.1.2",
author = "smadhueagle") ];
#[pkg(id = "closures", vers = "0.1.2")];
// Additional metadata attributes
#[ desc = "A simple example of closures in rust"];
#[ license = "MIT" ];
#[crate_type = "bin"];
// returning an owned closure - the elegant way
fn owned_foo( a: int ) -> ~fn(int){
|b| println(fmt!("a=%d, b=%d", a, b))
}
// returning an managed/boxed closure - the elegant way
fn boxed_foo( a: int ) -> @fn(int){
|b| println(fmt!("a=%d, b=%d", a, b))
}
// passing in a closure
fn each(v: &[int], op: &fn(v: int)) {
let mut n = 0;
while n < v.len() {
op(v[n]);
n += 1;
}
}
fn main(){
// returning a closure
let add5 = owned_foo(5);
let add4 = owned_foo(4);
add4(10);
add5(8);
//passing a stack closure as an argument
let elegant_print = |val: int| println(fmt!("val = %d", val));
fn inelegant_print(val: int){
println(fmt!("val = %d",val));
}
each([2,4,1,5,3], elegant_print);
each([2,4,1,5,3], inelegant_print);
}
|
use std::convert::From;
use std::i32;
use crate::mesh::{Vec2, Vec4};
use std::ops::{Add, Mul};
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct RGBA {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl RGBA {
pub fn alpha(&self, a: f32) -> Self {
Self {
r: self.r,
g: self.g,
b: self.b,
a: (self.a as f32 * a) as u8,
}
}
pub fn over(&self, b: RGBA) -> Self {
// draw self over b
// Porter-Duff algorithm
let alpha_a = self.a as f32 / 255.0;
let alpha_b = b.a as f32 / 255.0;
let alpha_c = alpha_a + (1.0 - alpha_a) * alpha_b;
let mut new_p = self * (alpha_a / alpha_c) + b * (((1.0 - alpha_a) * alpha_b) / alpha_c);
new_p.a = (alpha_c * 255.0) as u8;
new_p
}
}
impl Mul<f32> for RGBA {
type Output = RGBA;
fn mul(self, rhs: f32) -> Self::Output {
Self::Output {
r: (self.r as f32 * rhs) as u8,
g: (self.g as f32 * rhs) as u8,
b: (self.b as f32 * rhs) as u8,
a: self.a,
}
}
}
impl Mul<f32> for &RGBA {
type Output = RGBA;
fn mul(self, rhs: f32) -> Self::Output {
*self * rhs
}
}
impl Add for RGBA {
type Output = RGBA;
fn add(self, rhs: Self) -> Self::Output {
Self::Output {
r: (self.r as i32 + rhs.r as i32) as u8,
g: (self.g as i32 + rhs.g as i32) as u8,
b: (self.b as i32 + rhs.b as i32) as u8,
a: (self.a as i32 + rhs.a as i32) as u8,
}
}
}
impl From<(u8, u8, u8, u8)> for RGBA {
fn from(rgba: (u8, u8, u8, u8)) -> Self {
Self {
r: rgba.0,
g: rgba.1,
b: rgba.2,
a: rgba.3,
}
}
}
impl From<(f32, f32, f32, f32)> for RGBA {
fn from(rgba: (f32, f32, f32, f32)) -> Self {
Self {
r: (rgba.0.min(1.0).max(0.0) * 255.0) as u8,
g: (rgba.1.min(1.0).max(0.0) * 255.0) as u8,
b: (rgba.2.min(1.0).max(0.0) * 255.0) as u8,
a: (rgba.3.min(1.0).max(0.0) * 255.0) as u8,
}
}
}
impl From<&str> for RGBA {
fn from(rgba: &str) -> Self {
assert_eq!(rgba.len(), 8, "expected format: 'RRGGBBAA'");
Self {
r: i32::from_str_radix(&rgba[0..2], 16).unwrap() as u8,
g: i32::from_str_radix(&rgba[2..4], 16).unwrap() as u8,
b: i32::from_str_radix(&rgba[4..6], 16).unwrap() as u8,
a: i32::from_str_radix(&rgba[6..8], 16).unwrap() as u8,
}
}
}
impl From<&Vec4> for RGBA {
fn from(vec: &Vec4) -> Self {
Self {
r: (vec.x.min(1.0).max(0.0) * 255.0) as u8,
g: (vec.y.min(1.0).max(0.0) * 255.0) as u8,
b: (vec.z.min(1.0).max(0.0) * 255.0) as u8,
a: (vec.w.min(1.0).max(0.0) * 255.0) as u8,
}
}
}
#[derive(Debug)]
pub struct Picture {
data: Vec<u8>,
width: u32,
height: u32,
depth: u32,
}
impl Picture {
pub fn new(width: u32, height: u32) -> Self {
let depth = 4;
let mut data = Vec::new();
data.resize((width * height * depth) as usize, 0);
let mut pic = Picture {
data,
width,
height,
depth,
};
pic.fill(&(0, 0, 0, 255).into());
pic
}
pub fn stride(&self) -> u32 {
self.width * self.depth
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn depth(&self) -> u32 {
self.depth
}
pub fn data(&self) -> &[u8] {
self.data.as_slice()
}
pub fn to_bgra(&self) -> Vec<u8> {
let mut bgra = Vec::<u8>::with_capacity(self.data.len());
for i in (0..self.data.len()).step_by(4) {
bgra.push(self.data[i + 2]);
bgra.push(self.data[i + 1]);
bgra.push(self.data[i]);
bgra.push(self.data[i + 3]);
}
bgra
}
pub fn data_as_boxed_slice(&mut self) -> Box<[u8]> {
self.data.clone().into_boxed_slice()
}
pub fn fill(&mut self, rgba: &RGBA) {
for y in 0..self.height {
for x in 0..self.width {
self.set(x, y, rgba);
}
}
}
pub fn line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, rgba: &RGBA) {
// Bresenham's line algorithm
let mut x = x0;
let mut y = y0;
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 as i32 - y0 as i32).abs();
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy;
loop {
self.set(x as u32, y as u32, rgba);
if x == x1 && y == y1 {
break;
}
let e2 = 2 * err;
if e2 > dy {
err += dy;
x += sx;
}
if e2 <= dx {
err += dx;
y += sy;
}
}
}
pub fn thick_line(&mut self, mut x0: i32, mut y0: i32, x1: i32, y1: i32, rgba: &RGBA, width: f32) {
// Anti-aliased thick line
// Ref: http://members.chello.at/~easyfilter/bresenham.html
let dx = (x1 - x0).abs();
let dy = (y1 - y0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx - dy;
let ed = if dx + dy == 0 {
1.0
} else {
((dx * dx + dy * dy) as f32).sqrt()
};
let mut x2;
let mut y2;
let mut e2;
let wd = (width + 1.0) / 2.0;
loop {
let a = 1.0 - ((err - dx + dy).abs() as f32 / ed - wd).max(0.0);
self.alpha_blend(x0 as u32, y0 as u32, rgba.alpha(a));
e2 = err;
x2 = x0;
if 2 * e2 >= -dx {
e2 += dy;
y2 = y0;
while (e2 as f32) < ed * wd && (y1 != y2 || dx > dy) {
e2 += dx;
y2 += sy;
let a = 1.0 - (e2.abs() as f32 / ed - wd).max(0.0);
self.alpha_blend(x0 as u32, y2 as u32, rgba.alpha(a));
}
if x0 == x1 {
break;
}
e2 = err;
err -= dy;
x0 += sx;
}
if 2 * e2 <= dy {
e2 = dx - e2;
while (e2 as f32) < ed * wd && (x1 != x2 || dx < dy) {
e2 += dy;
x2 += sx;
let a = 1.0 - (e2.abs() as f32 / ed - wd).max(0.0);
self.alpha_blend(x2 as u32, y0 as u32, rgba.alpha(a));
}
if y0 == y1 {
break;
}
err += dx;
y0 += sy;
}
}
}
pub fn set(&mut self, x: u32, y: u32, rgba: &RGBA) {
if x >= self.width || y >= self.height {
return;
}
let stride = self.stride();
self.data[(stride * y + (x * self.depth)) as usize] = rgba.r;
self.data[(stride * y + (x * self.depth) + 1) as usize] = rgba.g;
self.data[(stride * y + (x * self.depth) + 2) as usize] = rgba.b;
self.data[(stride * y + (x * self.depth) + 3) as usize] = rgba.a;
}
pub fn alpha_blend(&mut self, x: u32, y: u32, rgba: RGBA) {
if x >= self.width || y >= self.height {
return;
}
// draw a over b
let b = self.get(x, y);
let a = rgba;
self.set(x, y, &a.over(b));
}
pub fn get(&self, x: u32, y: u32) -> RGBA {
let stride = self.stride();
RGBA {
r: self.data[(stride * y + (x * self.depth)) as usize],
g: self.data[(stride * y + (x * self.depth) + 1) as usize],
b: self.data[(stride * y + (x * self.depth) + 2) as usize],
a: self.data[(stride * y + (x * self.depth) + 3) as usize],
}
}
pub fn save(&self, path: &str) -> std::io::Result<()> {
let file = std::fs::File::create(path)?;
let buf = std::io::BufWriter::new(file);
let mut encoder = png::Encoder::new(buf, self.width as u32, self.height as u32);
encoder.set_color(png::ColorType::RGBA);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header()?;
writer.write_image_data(&self.data)?;
Ok(())
}
pub fn stroke_string(&mut self, x: u32, y: u32, s: &str, char_size: f32, rgba: &RGBA) {
for (i, c) in s.chars().into_iter().enumerate() {
self.stroke_letter(x + i as u32 * (char_size * 0.7 + 6.0) as u32, y, c, char_size, rgba);
}
}
pub fn stroke_letter(&mut self, x: u32, y: u32, c: char, char_size: f32, rgba: &RGBA) {
let points = match c {
'0' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(0.0, 1.0),
Vec2::new(0.0, 1.0),
Vec2::new(0.0, 0.0),
],
'1' => vec![Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0)],
'2' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 0.5),
Vec2::new(1.0, 0.5),
Vec2::new(0.0, 0.5),
Vec2::new(0.0, 0.5),
Vec2::new(0.0, 1.0),
Vec2::new(0.0, 1.0),
Vec2::new(1.0, 1.0),
],
'3' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(0.0, 1.0),
Vec2::new(1.0, 0.5),
Vec2::new(0.0, 0.5),
],
'4' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(0.0, 0.5),
Vec2::new(0.0, 0.5),
Vec2::new(1.0, 0.5),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 1.0),
],
'5' => vec![
Vec2::new(0.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 0.5),
Vec2::new(1.0, 0.5),
Vec2::new(0.0, 0.5),
Vec2::new(0.0, 0.5),
Vec2::new(0.0, 0.0),
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
],
'6' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(0.0, 0.0),
Vec2::new(0.0, 1.0),
Vec2::new(0.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 0.5),
Vec2::new(1.0, 0.5),
Vec2::new(0.0, 0.5),
],
'7' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 1.0),
],
'8' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(0.0, 1.0),
Vec2::new(0.0, 1.0),
Vec2::new(0.0, 0.0),
Vec2::new(0.0, 0.5),
Vec2::new(1.0, 0.5),
],
'9' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 0.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 1.0),
Vec2::new(0.0, 1.0),
Vec2::new(0.0, 0.0),
Vec2::new(0.0, 0.5),
Vec2::new(0.0, 0.5),
Vec2::new(1.0, 0.5),
],
'x' => vec![
Vec2::new(0.0, 0.0),
Vec2::new(1.0, 1.0),
Vec2::new(1.0, 0.0),
Vec2::new(0.0, 1.0),
],
'm' => vec![
Vec2::new(0.0, 0.5),
Vec2::new(1.0, 0.5),
Vec2::new(0.0, 0.5),
Vec2::new(0.0, 1.0),
Vec2::new(0.5, 0.5),
Vec2::new(0.5, 1.0),
Vec2::new(1.0, 0.5),
Vec2::new(1.0, 1.0),
],
_ => vec![],
};
for p in points.chunks(2) {
let x0 = p[0].x * char_size * 0.7 + x as f32;
let y0 = p[0].y * char_size + y as f32;
let x1 = p[1].x * char_size * 0.7 + x as f32;
let y1 = p[1].y * char_size + y as f32;
self.thick_line(x0 as i32, y0 as i32, x1 as i32, y1 as i32, rgba, 3.0);
}
}
pub fn fill_rect(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, rgba: &RGBA) {
for x in x0.max(0)..=x1.min(self.width as i32 - 1) {
for y in y0.max(0)..=y1.min(self.height as i32 - 1) {
self.set(x as u32, y as u32, rgba);
}
}
}
}
mod tests {
use super::*;
#[test]
fn test_rgba() {
let rgba: RGBA = (1.0, 0.5, -1.0, 2.0).into();
assert_eq!(rgba, (255, 127, 0, 255).into());
let rgba: RGBA = "FF00FF00".into();
assert_eq!(rgba, (255, 0, 255, 0).into());
}
#[test]
fn test_line() {
let mut pic = Picture::new(512, 512);
pic.fill(&(1.0, 1.0, 1.0, 1.0).into());
pic.thick_line(0, 0, 512, 512, &(1.0, 0.0, 0.0, 1.0).into(), 4.0);
pic.thick_line(0, 0, 256, 512, &(1.0, 0.0, 0.0, 1.0).into(), 4.0);
pic.thick_line(0, 256, 512, 256, &(1.0, 0.0, 0.0, 1.0).into(), 4.0);
pic.thick_line(512, 0, 0, 512, &(1.0, 0.0, 0.0, 1.0).into(), 1.0);
pic.thick_line(0, 256, 512, 256, &(1.0, 0.0, 0.0, 1.0).into(), 1.0);
pic.thick_line(256, 0, 256, 512, &(1.0, 0.0, 0.0, 1.0).into(), 1.0);
// plot chars
let mut i = 0;
for c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'x', 'm'].iter() {
pic.stroke_letter(100 + i * 14, 100, *c, 10.0, &"000000FF".into());
i += 1;
}
pic.stroke_string(100, 200, "12x55mm", 10.0, &"E6E6E6FF".into());
pic.save("test.png").unwrap();
}
}
|
pub mod term_selector;
pub mod term_scorer;
use term::Term;
use schema::FieldRef;
use query::term_selector::TermSelector;
use query::term_scorer::TermScorer;
#[derive(Debug, PartialEq)]
pub enum Query {
All {
score: f64,
},
None,
Term {
field: FieldRef,
term: Term,
scorer: TermScorer,
},
MultiTerm {
field: FieldRef,
term_selector: TermSelector,
scorer: TermScorer,
},
Conjunction {
queries: Vec<Query>,
},
Disjunction {
queries: Vec<Query>,
},
DisjunctionMax {
queries: Vec<Query>,
},
Filter {
query: Box<Query>,
filter: Box<Query>
},
Exclude {
query: Box<Query>,
exclude: Box<Query>
},
}
impl Query {
pub fn new_all() -> Query {
Query::All {
score: 1.0f64,
}
}
pub fn new_conjunction(queries: Vec<Query>) -> Query {
match queries.len() {
0 => Query::None,
1 => {
// Single query, unpack it from queries array and return it
for query in queries {
return query;
}
unreachable!();
}
_ => {
Query::Conjunction {
queries: queries,
}
}
}
}
pub fn new_disjunction(queries: Vec<Query>) -> Query {
match queries.len() {
0 => Query::None,
1 => {
// Single query, unpack it from queries array and return it
for query in queries {
return query;
}
unreachable!();
}
_ => {
Query::Disjunction {
queries: queries,
}
}
}
}
pub fn new_disjunction_max(queries: Vec<Query>) -> Query {
match queries.len() {
0 => Query::None,
1 => {
// Single query, unpack it from queries array and return it
for query in queries {
return query;
}
unreachable!();
}
_ => {
Query::DisjunctionMax {
queries: queries,
}
}
}
}
pub fn boost(&mut self, add_boost: f64) {
if add_boost == 1.0f64 {
// This boost query won't have any effect
return;
}
match *self {
Query::All{ref mut score} => {
*score *= add_boost;
},
Query::None => (),
Query::Term{ref mut scorer, ..} => {
scorer.boost *= add_boost;
}
Query::MultiTerm{ref mut scorer, ..} => {
scorer.boost *= add_boost;
}
Query::Conjunction{ref mut queries} => {
for query in queries {
query.boost(add_boost);
}
}
Query::Disjunction{ref mut queries} => {
for query in queries {
query.boost(add_boost);
}
}
Query::DisjunctionMax{ref mut queries} => {
for query in queries {
query.boost(add_boost);
}
}
Query::Filter{ref mut query, ..} => {
query.boost(add_boost);
}
Query::Exclude{ref mut query, ..} => {
query.boost(add_boost);
}
}
}
}
|
//! Advanced
fn main() {
let war = 10;
println!("war is {}", war);
// war = 20;
// 03.rs:7:5: 7:13 error: re-assignment of immutable variable `war`
// 03.rs:7 war = 20;
//
// 고칠수없는 변수의 값을 고쳤다는뜻.
// Rust는 변수선언을 하면 기본적으로 immutable임
println!("war never changes");
println!("");
let mut p = 10;
println!("p was {}", p);
p = 20;
println!("But now p is {}", p);
}
|
extern crate sdl2;
extern crate rand;
pub mod objparse;
use objparse::{Model, Face, Vertex};
use sdl2::event::{Event};
use sdl2::rect::{Point};
use sdl2::pixels::{Color};
use sdl2::render::{Renderer};
use std::time::{Instant, Duration};
use std::thread::{sleep};
static WIDTH : u32 = 500;
static HEIGHT : u32 = 500;
static TITLE : &'static str = "Pixels";
static FPS : u8 = 15;
fn triangle() -> Model {
let faces = vec![Face { verts: vec![1, 2, 3] }];
let verts = vec![
Vertex {x:10., y:70., z:0.},
Vertex {x:50., y:160., z:0.},
Vertex {x:70., y:80., z:0.}];
let triangle : Model = Model {
verts: verts,
faces: faces,
};
triangle
}
fn triangles() -> Model {
let faces = vec![
Face { verts: vec![1, 2, 3] },
Face { verts: vec![4, 5, 6] },
Face { verts: vec![7, 8, 9] },
];
let verts = vec![
Vertex {x:10., y:70., z:0.},
Vertex {x:50., y:160., z:0.},
Vertex {x:70., y:80., z:0.},
Vertex {x:180., y:50., z:0.},
Vertex {x:150., y:1., z:0.},
Vertex {x:70., y:180., z:0.},
Vertex {x:180., y:150., z:0.},
Vertex {x:120., y:160., z:0.},
Vertex {x:130., y:180., z:0.},
];
let triangles : Model = Model {
verts: verts,
faces: faces,
};
triangles
}
fn draw_line(mut x0: i32, mut y0: i32,
mut x1: i32, mut y1: i32,
renderer: &mut Renderer, color: Color) {
renderer.set_draw_color(color);
let dx = (x1-x0).abs();
let dy = (y1-y0).abs();
let steep = if dx < dy { true } else { false };
// TODO(Lito): Why is it so hard to write a swap function?
if steep { // transpose the whole drawing across x = y
let mut tmp_x = x0;
x0 = y0;
y0 = tmp_x;
tmp_x = x1;
x1 = y1;
y1 = tmp_x;
}
if x0 > x1 { let mut tmp = x0; x0 = x1; x1 = tmp; tmp = y0; y0 = y1; y1 = tmp; }
// assert!(x1 > x0, "x0:{}, x1:{}", x0, x1);
for x in x0..x1 {
let t = (x-x0) as f32 / (x1-x0) as f32;
let y = y0 as f32 * (1.-t) + y1 as f32 * t;
let p = if steep {
Point::new(y.round() as i32, x) // transposed
} else {
Point::new(x, y.round() as i32)
};
renderer.draw_point(p);
}
}
fn draw(model: &Model, width: u32, height: u32, image: &mut Renderer) {
let white = Color::RGB(255, 255, 255);
let red = Color::RGB(255, 0, 0);
draw_faces(model, image);
}
fn draw_xy_line_between_verts(v1: Vertex, v2: Vertex, r: &mut Renderer, c: Color) {
draw_line(v1.x.round() as i32, v1.y.round() as i32,
v2.x.round() as i32, v2.y.round() as i32, r, c);
}
fn draw_wireframe_triangle(v0: Vertex, v1: Vertex, v2: Vertex, image: &mut Renderer, color: Color) {
draw_xy_line_between_verts(v0, v1, image, color);
draw_xy_line_between_verts(v1, v2, image, color);
draw_xy_line_between_verts(v2, v0, image, color);
}
fn draw_filled_triangle(mut v0: Vertex, mut v1: Vertex, mut v2: Vertex,
image: &mut Renderer, color: Color) {
image.set_draw_color(color);
// Bubble sort verts
if v0.y > v1.y { let tmp = v0; v0 = v1; v1 = tmp; }
if v0.y > v2.y { let tmp = v0; v0 = v2; v2 = tmp; }
if v1.y > v2.y { let tmp = v1; v1 = v2; v2 = tmp; }
let triangle_height = v2.y - v0.y;
let y0 = v0.y.round() as i32;
let y1 = v1.y.round() as i32;
let y2 = v2.y.round() as i32;
for y in (y0+1)..(y1+1) {
let segment_height = v1.y - v0.y + 1.;
let alpha : f64 = (y as f64 - v0.y)/triangle_height;
let beta : f64 = (y as f64 - v0.y)/segment_height; // careful: div 0
let mut A = (v0.x + (v2.x-v0.x)*alpha).round() as i32;
let mut B = (v0.x + (v1.x-v0.x)*beta ).round() as i32;
// draw lines between edges
if A > B { let tmp = A; A = B; B = tmp; }
for x in A..(B+1) {
let p = Point::new(x, y);
image.draw_point(p);
}
}
for y in (y1+1)..(y2+1) {
let segment_height = v2.y - v1.y + 1.;
let alpha : f64 = (y as f64 - v0.y)/triangle_height;
let beta : f64 = (y as f64 - v1.y)/segment_height; // careful: div 0
let mut A = (v0.x + (v2.x-v0.x)*alpha).round() as i32;
let mut B = (v1.x + (v2.x-v1.x)*beta ).round() as i32;
// draw lines between edges
if A > B { let tmp = A; A = B; B = tmp; }
for x in A..(B+1) {
let p = Point::new(x, y);
image.draw_point(p);
}
}
}
fn draw_faces(model: &Model, image: &mut Renderer) {
for face in &model.faces {
let white = Color::RGB(255,255,255);
let green = Color::RGB(0,255,0);
let random_color = Color::RGB(rand::random::<u8>(),
rand::random::<u8>(),
rand::random::<u8>());
let v0 = model.verts[face.verts[0]-1];
let v1 = model.verts[face.verts[1]-1];
let v2 = model.verts[face.verts[2]-1];
draw_filled_triangle(v0, v1, v2, image, random_color);
// draw_wireframe_triangle(v0, v1, v2, image, green);
}
}
fn main() {
let FRAMETIME : Duration = Duration::from_millis(1000/FPS as u64);
let ctx = sdl2::init().unwrap();
let video_ctx = ctx.video().unwrap();
let scale = 1;
let window_width = WIDTH * scale;
let window_height = HEIGHT * scale;
let window = match video_ctx.window(TITLE, window_width, window_height)
.position_centered().opengl().build() {
Ok(window) => window,
Err(err) => panic!("failed to create window: {}", err)
};
let mut renderer = match window.renderer().build() {
Ok(renderer) => renderer,
Err(err) => panic!("failed to create renderer: {}", err)
};
renderer.set_draw_color(Color::RGB(0,0,0));
renderer.clear();
let mut starman : Model = objparse::load("./model.obj");
starman.scale(90., -90., 90.);
starman.shift(240.,190.,0.);
let mut medamaude : Model = objparse::load("./medamaude.obj");
medamaude.scale(500., -500., 500.);
medamaude.shift(100.,0.,0.);
let mut cube : Model = objparse::load("./cube.obj");
let mut triangles = triangles();
draw(&starman, window_width, window_height, &mut renderer);
renderer.present();
let mut events = ctx.event_pump().unwrap();
'main : loop {
let start_time = Instant::now();
for event in events.poll_iter() {
match event {
// Handle keys here
Event::Quit{..} => break 'main,
_ => continue
}
};
// TODO(Lito): Is there overhead in making an Instant::now twice?
// How about making a bunch of Durations?
let time_elapsed = Instant::now().duration_since(start_time);
// Ok, this is absurd, but sure:
let sleep_time : Duration =
// TODO(Lito): This will break if drawing or framerate goes slower
// than 1 fps.
if time_elapsed.subsec_nanos() > FRAMETIME.subsec_nanos() {
println!("rendered slow! {:?} milliseconds", time_elapsed.subsec_nanos() / 1000000);
Duration::new(0,0)
} else {
FRAMETIME - time_elapsed
};
// Don't max out the CPU!
sleep(sleep_time);
}
}
|
//vim: tw=80
use std::future::Future;
use std::task::Poll;
use std::pin::Pin;
use futures::channel::oneshot;
use futures::{future, stream, StreamExt, FutureExt, TryFutureExt};
#[cfg(feature = "tokio")]
use std::rc::Rc;
use tokio;
#[cfg(feature = "tokio")]
use tokio::runtime::current_thread;
use futures_locks::*;
// Create a MutexWeak and then upgrade it to Mutex
#[test]
fn mutex_weak_some() {
let mutex = Mutex::<u32>::new(0);
let mutex_weak = Mutex::downgrade(&mutex);
assert!(mutex_weak.upgrade().is_some())
}
// Create a MutexWeak and drop the mutex so that MutexWeak::upgrade return None
#[test]
fn mutex_weak_none() {
let mutex = Mutex::<u32>::new(0);
let mutex_weak = Mutex::downgrade(&mutex);
drop(mutex);
assert!(mutex_weak.upgrade().is_none())
}
// Compare Mutexes if it point to the same value
#[test]
fn mutex_eq_ptr_true() {
let mutex = Mutex::<u32>::new(0);
let mutex_other = mutex.clone();
assert!(Mutex::ptr_eq(&mutex, &mutex_other));
}
// Compare Mutexes if it point to the same value
#[test]
fn mutex_eq_ptr_false() {
let mutex = Mutex::<u32>::new(0);
let mutex_other = Mutex::<u32>::new(0);
assert!(!Mutex::ptr_eq(&mutex, &mutex_other));
}
// When a pending Mutex gets dropped, it should drain its channel and relinquish
// ownership if a message was found. If not, deadlocks may result.
#[tokio::test]
async fn drop_before_poll() {
future::poll_fn(|cx| {
let mutex = Mutex::<u32>::new(0);
let mut fut1 = mutex.lock();
let guard1 = Pin::new(&mut fut1).poll(cx); // fut1 immediately gets ownership
assert!(guard1.is_ready());
let mut fut2 = mutex.lock();
assert!(Pin::new(&mut fut2).poll(cx).is_pending());
drop(guard1); // ownership transfers to fut2
drop(fut1);
drop(fut2); // relinquish ownership
let mut fut3 = mutex.lock();
let guard3 = Pin::new(&mut fut3).poll(cx); // fut3 immediately gets ownership
assert!(guard3.is_ready());
Poll::Ready(())
}).await
}
// // Mutably dereference a uniquely owned Mutex
#[test]
fn get_mut() {
let mut mutex = Mutex::<u32>::new(42);
*mutex.get_mut().unwrap() += 1;
assert_eq!(*mutex.get_mut().unwrap(), 43);
}
// Cloned Mutexes cannot be deferenced
#[test]
fn get_mut_cloned() {
let mut mutex = Mutex::<u32>::new(42);
let _clone = mutex.clone();
assert!(mutex.get_mut().is_none());
}
// Acquire an uncontested Mutex. poll immediately returns Async::Ready
#[tokio::test]
async fn lock_uncontested() {
let mutex = Mutex::<u32>::new(0);
let guard = mutex.lock().await;
let result = *guard + 5;
assert_eq!(result, 5);
}
// Pend on a Mutex held by another task in the same tokio Reactor. poll returns
// Async::NotReady. Later, it gets woken up without involving the OS.
#[tokio::test]
async fn lock_contested() {
let mutex = Mutex::<u32>::new(0);
let (tx0, rx0) = oneshot::channel::<()>();
let (tx1, rx1) = oneshot::channel::<()>();
let task0 = mutex.lock()
.then(move |mut guard| {
*guard += 5;
rx0.map_err(|_| {drop(guard);})
});
let task1 = mutex.lock().map(|guard| *guard);
// Readying task2 before task1 causes Tokio to poll the latter even
// though it's not ready
let task2 = rx1.map(|_| tx0.send(()).unwrap());
let task3 = async move {
tx1.send(()).unwrap();
};
let result = future::join4(task0, task1, task2, task3).await;
assert_eq!(result, (Ok(()), 5, (), ()));
}
// A single Mutex is contested by tasks in multiple threads
#[tokio::test]
async fn lock_multithreaded() {
let mutex = Mutex::<u32>::new(0);
let mtx_clone0 = mutex.clone();
let mtx_clone1 = mutex.clone();
let mtx_clone2 = mutex.clone();
let mtx_clone3 = mutex.clone();
let fut1 = stream::iter(0..1000).for_each(move |_| {
mtx_clone0.lock().map(|mut guard| { *guard += 2 })
});
let fut2 = stream::iter(0..1000).for_each(move |_| {
mtx_clone1.lock().map(|mut guard| { *guard += 3 })
});
let fut3 = stream::iter(0..1000).for_each(move |_| {
mtx_clone2.lock().map(|mut guard| { *guard += 5 })
});
let fut4 = stream::iter(0..1000).for_each(move |_| {
mtx_clone3.lock().map(|mut guard| { *guard += 7 })
});
future::join4(fut1, fut2, fut3, fut4).await;
assert_eq!(mutex.try_unwrap().expect("try_unwrap"), 17_000);
}
// Mutexes should be acquired in the order that their Futures are waited upon.
#[tokio::test]
async fn lock_order() {
let mutex = Mutex::<Vec<u32>>::new(vec![]);
let fut2 = mutex.lock().map(|mut guard| guard.push(2));
let fut1 = mutex.lock().map(|mut guard| guard.push(1));
fut1.then(|_| fut2).await;
assert_eq!(mutex.try_unwrap().unwrap(), vec![1, 2]);
}
// Acquire an uncontested Mutex with try_lock
#[test]
fn try_lock_uncontested() {
let mutex = Mutex::<u32>::new(5);
let guard = mutex.try_lock().unwrap();
assert_eq!(5, *guard);
}
// Try and fail to acquire a contested Mutex with try_lock
#[test]
fn try_lock_contested() {
let mutex = Mutex::<u32>::new(0);
let _guard = mutex.try_lock().unwrap();
assert!(mutex.try_lock().is_err());
}
#[test]
fn try_unwrap_multiply_referenced() {
let mtx = Mutex::<u32>::new(0);
let _mtx2 = mtx.clone();
assert!(mtx.try_unwrap().is_err());
}
#[cfg(feature = "tokio")]
#[test]
fn with_err() {
let mtx = Mutex::<i32>::new(-5);
let mut rt = current_thread::Runtime::new().unwrap();
let r = rt.block_on(async {
mtx.with(|guard| {
if *guard > 0 {
future::ok(*guard)
} else {
future::err("Whoops!")
}
}).unwrap().await
});
assert_eq!(r, Err("Whoops!"));
}
#[cfg(feature = "tokio")]
#[test]
fn with_ok() {
let mtx = Mutex::<i32>::new(5);
let mut rt = current_thread::Runtime::new().unwrap();
let r = rt.block_on(async move {
mtx.with(|guard| {
futures::future::ok::<i32, ()>(*guard)
}).unwrap().await
});
assert_eq!(r, Ok(5));
}
// Mutex::with should work with multithreaded Runtimes as well as
// single-threaded Runtimes.
// https://github.com/asomers/futures-locks/issues/5
#[cfg(feature = "tokio")]
#[tokio::test]
async fn with_threadpool() {
let mtx = Mutex::<i32>::new(5);
let r = mtx.with(|guard| {
futures::future::ok::<i32, ()>(*guard)
}).unwrap().await;
assert!(r.is_ok());
assert_eq!(r, Ok(5));
}
#[cfg(feature = "tokio")]
#[test]
fn with_local_ok() {
// Note: Rc is not Send
let mtx = Mutex::<Rc<i32>>::new(Rc::new(5));
let mut rt = current_thread::Runtime::new().unwrap();
let r = rt.block_on(async move {
mtx.with_local(|guard| {
futures::future::ok::<i32, ()>(**guard)
}).await
});
assert_eq!(r, Ok(5));
}
|
// This file is part of Substrate.
// Copyright (C) 2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Testing utils for staking. Provides some common functions to setup staking state, such as
//! bonding validators, nominators, and generating different types of solutions.
use crate::Module as Staking;
use crate::*;
use frame_benchmarking::account;
use frame_system::RawOrigin;
use rand_chacha::{
rand_core::{RngCore, SeedableRng},
ChaChaRng,
};
use sp_io::hashing::blake2_256;
use sp_npos_elections::*;
const SEED: u32 = 0;
/// Grab a funded user.
pub fn create_funded_user<T: Trait>(
string: &'static str,
n: u32,
balance_factor: u32,
) -> T::AccountId {
let user = account(string, n, SEED);
let balance = T::Currency::minimum_balance() * balance_factor.into();
T::Currency::make_free_balance_be(&user, balance);
// ensure T::CurrencyToVote will work correctly.
T::Currency::issue(balance);
user
}
/// Create a stash and controller pair.
pub fn create_stash_controller<T: Trait>(
n: u32,
balance_factor: u32,
destination: RewardDestination<T::AccountId>,
) -> Result<(T::AccountId, T::AccountId), &'static str> {
let stash = create_funded_user::<T>("stash", n, balance_factor);
let controller = create_funded_user::<T>("controller", n, balance_factor);
let controller_lookup: <T::Lookup as StaticLookup>::Source =
T::Lookup::unlookup(controller.clone());
let amount = T::Currency::minimum_balance() * (balance_factor / 10).max(1).into();
Staking::<T>::bond(
RawOrigin::Signed(stash.clone()).into(),
controller_lookup,
amount,
destination,
)?;
return Ok((stash, controller))
}
/// Create a stash and controller pair, where the controller is dead, and payouts go to controller.
/// This is used to test worst case payout scenarios.
pub fn create_stash_and_dead_controller<T: Trait>(
n: u32,
balance_factor: u32,
destination: RewardDestination<T::AccountId>,
) -> Result<(T::AccountId, T::AccountId), &'static str> {
let stash = create_funded_user::<T>("stash", n, balance_factor);
// controller has no funds
let controller = create_funded_user::<T>("controller", n, 0);
let controller_lookup: <T::Lookup as StaticLookup>::Source =
T::Lookup::unlookup(controller.clone());
let amount = T::Currency::minimum_balance() * (balance_factor / 10).max(1).into();
Staking::<T>::bond(
RawOrigin::Signed(stash.clone()).into(),
controller_lookup,
amount,
destination,
)?;
return Ok((stash, controller))
}
/// create `max` validators.
pub fn create_validators<T: Trait>(
max: u32,
balance_factor: u32,
) -> Result<Vec<<T::Lookup as StaticLookup>::Source>, &'static str> {
let mut validators: Vec<<T::Lookup as StaticLookup>::Source> = Vec::with_capacity(max as usize);
for i in 0..max {
let (stash, controller) =
create_stash_controller::<T>(i, balance_factor, RewardDestination::Staked)?;
let validator_prefs = ValidatorPrefs { commission: Perbill::from_percent(50) };
Staking::<T>::validate(RawOrigin::Signed(controller).into(), validator_prefs)?;
let stash_lookup: <T::Lookup as StaticLookup>::Source = T::Lookup::unlookup(stash);
validators.push(stash_lookup);
}
Ok(validators)
}
/// This function generates validators and nominators who are randomly nominating
/// `edge_per_nominator` random validators (until `to_nominate` if provided).
///
/// Parameters:
/// - `validators`: number of bonded validators
/// - `nominators`: number of bonded nominators.
/// - `edge_per_nominator`: number of edge (vote) per nominator.
/// - `randomize_stake`: whether to randomize the stakes.
/// - `to_nominate`: if `Some(n)`, only the first `n` bonded validator are voted upon. Else, all of
/// them are considered and `edge_per_nominator` random validators are voted for.
///
/// Return the validators choosen to be nominated.
pub fn create_validators_with_nominators_for_era<T: Trait>(
validators: u32,
nominators: u32,
edge_per_nominator: usize,
randomize_stake: bool,
to_nominate: Option<u32>,
) -> Result<Vec<<T::Lookup as StaticLookup>::Source>, &'static str> {
let mut validators_stash: Vec<<T::Lookup as StaticLookup>::Source> =
Vec::with_capacity(validators as usize);
let mut rng = ChaChaRng::from_seed(SEED.using_encoded(blake2_256));
// Create validators
for i in 0..validators {
let balance_factor = if randomize_stake { rng.next_u32() % 255 + 10 } else { 100u32 };
let (v_stash, v_controller) =
create_stash_controller::<T>(i, balance_factor, RewardDestination::Staked)?;
let validator_prefs = ValidatorPrefs { commission: Perbill::from_percent(50) };
Staking::<T>::validate(RawOrigin::Signed(v_controller.clone()).into(), validator_prefs)?;
let stash_lookup: <T::Lookup as StaticLookup>::Source =
T::Lookup::unlookup(v_stash.clone());
validators_stash.push(stash_lookup.clone());
}
let to_nominate = to_nominate.unwrap_or(validators_stash.len() as u32) as usize;
let validator_choosen = validators_stash[0..to_nominate].to_vec();
// Create nominators
for j in 0..nominators {
let balance_factor = if randomize_stake { rng.next_u32() % 255 + 10 } else { 100u32 };
let (_n_stash, n_controller) = create_stash_controller::<T>(
u32::max_value() - j,
balance_factor,
RewardDestination::Staked,
)?;
// Have them randomly validate
let mut available_validators = validator_choosen.clone();
let mut selected_validators: Vec<<T::Lookup as StaticLookup>::Source> =
Vec::with_capacity(edge_per_nominator);
for _ in 0..validators.min(edge_per_nominator as u32) {
let selected = rng.next_u32() as usize % available_validators.len();
let validator = available_validators.remove(selected);
selected_validators.push(validator);
}
Staking::<T>::nominate(
RawOrigin::Signed(n_controller.clone()).into(),
selected_validators,
)?;
}
ValidatorCount::put(validators);
Ok(validator_choosen)
}
/// Build a _really bad_ but acceptable solution for election. This should always yield a solution
/// which has a less score than the seq-phragmen.
pub fn get_weak_solution<T: Trait>(
do_reduce: bool,
) -> (Vec<ValidatorIndex>, CompactAssignments, ElectionScore, ElectionSize) {
let mut backing_stake_of: BTreeMap<T::AccountId, BalanceOf<T>> = BTreeMap::new();
// self stake
<Validators<T>>::iter().for_each(|(who, _p)| {
*backing_stake_of.entry(who.clone()).or_insert_with(|| Zero::zero()) +=
<Module<T>>::slashable_balance_of(&who)
});
// elect winners. We chose the.. least backed ones.
let mut sorted: Vec<T::AccountId> = backing_stake_of.keys().cloned().collect();
sorted.sort_by_key(|x| backing_stake_of.get(x).unwrap());
let winners: Vec<T::AccountId> =
sorted.iter().rev().cloned().take(<Module<T>>::validator_count() as usize).collect();
let mut staked_assignments: Vec<StakedAssignment<T::AccountId>> = Vec::new();
// you could at this point start adding some of the nominator's stake, but for now we don't.
// This solution must be bad.
// add self support to winners.
winners.iter().for_each(|w| {
staked_assignments.push(StakedAssignment {
who: w.clone(),
distribution: vec![(
w.clone(),
<T::CurrencyToVote as Convert<BalanceOf<T>, u64>>::convert(
<Module<T>>::slashable_balance_of(&w),
) as ExtendedBalance,
)],
})
});
if do_reduce {
reduce(&mut staked_assignments);
}
// helpers for building the compact
let snapshot_validators = <Module<T>>::snapshot_validators().unwrap();
let snapshot_nominators = <Module<T>>::snapshot_nominators().unwrap();
let nominator_index = |a: &T::AccountId| -> Option<NominatorIndex> {
snapshot_nominators
.iter()
.position(|x| x == a)
.and_then(|i| <usize as TryInto<NominatorIndex>>::try_into(i).ok())
};
let validator_index = |a: &T::AccountId| -> Option<ValidatorIndex> {
snapshot_validators
.iter()
.position(|x| x == a)
.and_then(|i| <usize as TryInto<ValidatorIndex>>::try_into(i).ok())
};
let stake_of = |who: &T::AccountId| -> VoteWeight {
<T::CurrencyToVote as Convert<BalanceOf<T>, u64>>::convert(
<Module<T>>::slashable_balance_of(who),
)
};
// convert back to ratio assignment. This takes less space.
let low_accuracy_assignment =
assignment_staked_to_ratio_normalized(staked_assignments).expect("Failed to normalize");
// re-calculate score based on what the chain will decode.
let score = {
let staked = assignment_ratio_to_staked::<_, OffchainAccuracy, _>(
low_accuracy_assignment.clone(),
stake_of,
);
let support_map =
build_support_map::<T::AccountId>(winners.as_slice(), staked.as_slice()).unwrap();
evaluate_support::<T::AccountId>(&support_map)
};
// compact encode the assignment.
let compact = CompactAssignments::from_assignment(
low_accuracy_assignment,
nominator_index,
validator_index,
)
.unwrap();
// winners to index.
let winners = winners
.into_iter()
.map(|w| snapshot_validators.iter().position(|v| *v == w).unwrap().try_into().unwrap())
.collect::<Vec<ValidatorIndex>>();
let size = ElectionSize {
validators: snapshot_validators.len() as ValidatorIndex,
nominators: snapshot_nominators.len() as NominatorIndex,
};
(winners, compact, score, size)
}
/// Create a solution for seq-phragmen. This uses the same internal function as used by the offchain
/// worker code.
pub fn get_seq_phragmen_solution<T: Trait>(
do_reduce: bool,
) -> (Vec<ValidatorIndex>, CompactAssignments, ElectionScore, ElectionSize) {
let iters = offchain_election::get_balancing_iters::<T>();
let sp_npos_elections::ElectionResult { winners, assignments } =
<Module<T>>::do_phragmen::<OffchainAccuracy>(iters).unwrap();
offchain_election::prepare_submission::<T>(
assignments,
winners,
do_reduce,
T::MaximumBlockWeight::get(),
)
.unwrap()
}
/// Returns a solution in which only one winner is elected with just a self vote.
pub fn get_single_winner_solution<T: Trait>(
winner: T::AccountId,
) -> Result<(Vec<ValidatorIndex>, CompactAssignments, ElectionScore, ElectionSize), &'static str> {
let snapshot_validators = <Module<T>>::snapshot_validators().unwrap();
let snapshot_nominators = <Module<T>>::snapshot_nominators().unwrap();
let val_index =
snapshot_validators.iter().position(|x| *x == winner).ok_or("not a validator")?;
let nom_index =
snapshot_nominators.iter().position(|x| *x == winner).ok_or("not a nominator")?;
let stake = <Staking<T>>::slashable_balance_of(&winner);
let stake =
<T::CurrencyToVote as Convert<BalanceOf<T>, VoteWeight>>::convert(stake) as ExtendedBalance;
let val_index = val_index as ValidatorIndex;
let nom_index = nom_index as NominatorIndex;
let winners = vec![val_index];
let compact = CompactAssignments { votes1: vec![(nom_index, val_index)], ..Default::default() };
let score = [stake, stake, stake * stake];
let size = ElectionSize {
validators: snapshot_validators.len() as ValidatorIndex,
nominators: snapshot_nominators.len() as NominatorIndex,
};
Ok((winners, compact, score, size))
}
/// get the active era.
pub fn current_era<T: Trait>() -> EraIndex {
<Module<T>>::current_era().unwrap_or(0)
}
/// initialize the first era.
pub fn init_active_era() {
ActiveEra::put(ActiveEraInfo { index: 1, start: None })
}
/// Create random assignments for the given list of winners. Each assignment will have
/// MAX_NOMINATIONS edges.
pub fn create_assignments_for_offchain<T: Trait>(
num_assignments: u32,
winners: Vec<<T::Lookup as StaticLookup>::Source>,
) -> Result<
(Vec<(T::AccountId, ExtendedBalance)>, Vec<Assignment<T::AccountId, OffchainAccuracy>>),
&'static str,
> {
let ratio = OffchainAccuracy::from_rational_approximation(1, MAX_NOMINATIONS);
let assignments: Vec<Assignment<T::AccountId, OffchainAccuracy>> = <Nominators<T>>::iter()
.take(num_assignments as usize)
.map(|(n, t)| Assignment {
who: n,
distribution: t.targets.iter().map(|v| (v.clone(), ratio)).collect(),
})
.collect();
ensure!(assignments.len() == num_assignments as usize, "must bench for `a` assignments");
let winners =
winners.into_iter().map(|v| (<T::Lookup as StaticLookup>::lookup(v).unwrap(), 0)).collect();
Ok((winners, assignments))
}
|
extern crate td_rredis as redis;
use std::error;
use std::fmt;
use std::io;
use std::hash::Hash;
use std::str::{from_utf8, Utf8Error};
use std::collections::{HashMap, HashSet};
use std::convert::From;
use redis::RedisResult;
fn test_get() -> redis::RedisResult<()> {
let client = redis::Client::open("redis://127.0.0.1/").unwrap();
let con = client.get_connection().unwrap();
redis::cmd("DEL").arg("foo").execute(&con);
for x in 0..600 {
redis::cmd("SADD").arg("foo").arg(x).execute(&con);
}
Ok(())
}
fn main() {
let _ = test_get();
} |
use anyhow::{Context, Result};
use regex::Regex;
use structopt::StructOpt;
/// Remove the log files emitted in Sightglass runs.
#[derive(StructOpt, Debug)]
#[structopt(name = "clean")]
pub struct CleanCommand {}
impl CleanCommand {
pub fn execute(&self) -> Result<()> {
// Remove log files.
let log_file_regex = Regex::new(r"^(stdout|stderr)\-\w+\-\d+-\d+.log$").unwrap();
for entry in std::env::current_dir()?.read_dir()? {
let entry = entry?;
// Only consider files, not dirs or symlinks.
if !entry.file_type()?.is_file() {
continue;
}
let path = entry.path();
// If it doesn't have a file name, it definitely isn't a log file.
let name = match path.file_name().and_then(|n| n.to_str()) {
None => continue,
Some(n) => n,
};
// If it doesn't match our log file regex, it isn't a log file.
if !log_file_regex.is_match(name) {
continue;
}
// Okay! It's one of our log files!
log::info!("Removing log file: {}", path.display());
std::fs::remove_file(&path)
.with_context(|| format!("failed to remove {}", path.display()))?;
}
Ok(())
}
}
|
fn main() {
let low = 109165;
let high = 576723;
println!("{}", (low..high).fold(0, |count, num| count + if valid_num(num) { 1 } else { 0 }));
}
fn valid_num(num: u32) -> bool {
let mut has_double = false;
let multiples = [10,100,1000,10000,100000];
for tens in multiples.iter() {
let cur_digit = (num / tens) % 10;
let prev_digit = (num / (tens / 10)) % 10;
if cur_digit > prev_digit {
return false;
}
if tens == &10 {
has_double = has_double || (
cur_digit == prev_digit &&
cur_digit != ((num / (tens*10)) % 10));
} else if tens == &100000 {
has_double = has_double || (
cur_digit == prev_digit &&
cur_digit != ((num / (tens/100)) % 10));
} else {
has_double = has_double || (
cur_digit == prev_digit &&
cur_digit != ((num / (tens*10)) % 10) &&
cur_digit != ((num / (tens/100)) % 10)
);
}
}
return has_double;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_inc() {
assert_eq!(valid_num(223450), false);
}
#[test]
fn no_double() {
assert_eq!(valid_num(123789), false);
}
#[test]
fn no_longer_valid() {
assert_eq!(valid_num(111111), false);
}
#[test]
fn end_big_group() {
assert_eq!(valid_num(123444), false);
}
#[test]
fn begin_big_group() {
assert_eq!(valid_num(444567), false);
}
#[test]
fn is_valid() {
assert_eq!(valid_num(112233), true);
}
#[test]
fn big_group_valid() {
assert_eq!(valid_num(111122), true);
}
}
|
/*
Conversion from quaternions to Euler rotation sequences.
From: http://bediyap.com/programming/convert-quaternion-to-euler-rotations/
*/
use crate::{DQuat, Quat};
/// Euler rotation sequences.
///
/// The angles are applied starting from the right.
/// E.g. XYZ will first apply the z-axis rotation.
///
/// YXZ can be used for yaw (y-axis), pitch (x-axis), roll (z-axis).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EulerRot {
/// Intrinsic three-axis rotation ZYX
ZYX,
/// Intrinsic three-axis rotation ZXY
ZXY,
/// Intrinsic three-axis rotation YXZ
YXZ,
/// Intrinsic three-axis rotation YZX
YZX,
/// Intrinsic three-axis rotation XYZ
XYZ,
/// Intrinsic three-axis rotation XZY
XZY,
}
impl Default for EulerRot {
/// Default `YXZ` as yaw (y-axis), pitch (x-axis), roll (z-axis).
fn default() -> Self {
Self::YXZ
}
}
/// Conversion from quaternion to euler angles.
pub(crate) trait EulerFromQuaternion<Q: Copy>: Sized + Copy {
type Output;
/// Compute the angle of the first axis (X-x-x)
fn first(self, q: Q) -> Self::Output;
/// Compute then angle of the second axis (x-X-x)
fn second(self, q: Q) -> Self::Output;
/// Compute then angle of the third axis (x-x-X)
fn third(self, q: Q) -> Self::Output;
/// Compute all angles of a rotation in the notation order
fn convert_quat(self, q: Q) -> (Self::Output, Self::Output, Self::Output) {
(self.first(q), self.second(q), self.third(q))
}
}
/// Conversion from euler angles to quaternion.
pub(crate) trait EulerToQuaternion<T>: Copy {
type Output;
/// Create the rotation quaternion for the three angles of this euler rotation sequence.
fn new_quat(self, u: T, v: T, w: T) -> Self::Output;
}
macro_rules! impl_from_quat {
($t:ident, $quat:ident) => {
impl EulerFromQuaternion<$quat> for EulerRot {
type Output = $t;
fn first(self, q: $quat) -> $t {
use crate::$t::math;
use EulerRot::*;
match self {
ZYX => math::atan2(
2.0 * (q.x * q.y + q.w * q.z),
q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
),
ZXY => math::atan2(
-2.0 * (q.x * q.y - q.w * q.z),
q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
),
YXZ => math::atan2(
2.0 * (q.x * q.z + q.w * q.y),
q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
),
YZX => math::atan2(
-2.0 * (q.x * q.z - q.w * q.y),
q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
),
XYZ => math::atan2(
-2.0 * (q.y * q.z - q.w * q.x),
q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
),
XZY => math::atan2(
2.0 * (q.y * q.z + q.w * q.x),
q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
),
}
}
fn second(self, q: $quat) -> $t {
use crate::$t::math;
use EulerRot::*;
match self {
ZYX => math::asin_clamped(-2.0 * (q.x * q.z - q.w * q.y)),
ZXY => math::asin_clamped(2.0 * (q.y * q.z + q.w * q.x)),
YXZ => math::asin_clamped(-2.0 * (q.y * q.z - q.w * q.x)),
YZX => math::asin_clamped(2.0 * (q.x * q.y + q.w * q.z)),
XYZ => math::asin_clamped(2.0 * (q.x * q.z + q.w * q.y)),
XZY => math::asin_clamped(-2.0 * (q.x * q.y - q.w * q.z)),
}
}
fn third(self, q: $quat) -> $t {
use crate::$t::math;
use EulerRot::*;
match self {
ZYX => math::atan2(
2.0 * (q.y * q.z + q.w * q.x),
q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
),
ZXY => math::atan2(
-2.0 * (q.x * q.z - q.w * q.y),
q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
),
YXZ => math::atan2(
2.0 * (q.x * q.y + q.w * q.z),
q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
),
YZX => math::atan2(
-2.0 * (q.y * q.z - q.w * q.x),
q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
),
XYZ => math::atan2(
-2.0 * (q.x * q.y - q.w * q.z),
q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
),
XZY => math::atan2(
2.0 * (q.x * q.z + q.w * q.y),
q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
),
}
}
}
// End - impl EulerFromQuaternion
};
}
macro_rules! impl_to_quat {
($t:ty, $quat:ident) => {
impl EulerToQuaternion<$t> for EulerRot {
type Output = $quat;
#[inline(always)]
fn new_quat(self, u: $t, v: $t, w: $t) -> $quat {
use EulerRot::*;
#[inline(always)]
fn rot_x(a: $t) -> $quat {
$quat::from_rotation_x(a)
}
#[inline(always)]
fn rot_y(a: $t) -> $quat {
$quat::from_rotation_y(a)
}
#[inline(always)]
fn rot_z(a: $t) -> $quat {
$quat::from_rotation_z(a)
}
match self {
ZYX => rot_z(u) * rot_y(v) * rot_x(w),
ZXY => rot_z(u) * rot_x(v) * rot_y(w),
YXZ => rot_y(u) * rot_x(v) * rot_z(w),
YZX => rot_y(u) * rot_z(v) * rot_x(w),
XYZ => rot_x(u) * rot_y(v) * rot_z(w),
XZY => rot_x(u) * rot_z(v) * rot_y(w),
}
.normalize()
}
}
// End - impl EulerToQuaternion
};
}
impl_from_quat!(f32, Quat);
impl_from_quat!(f64, DQuat);
impl_to_quat!(f32, Quat);
impl_to_quat!(f64, DQuat);
|
pub use hooks::NO_CONFIG_FILE_FOUND_ERROR_CODE;
use std::collections::HashMap;
mod hooks;
pub fn get_root_directory_path<F>(
run_command: F,
target_directory: Option<&str>,
) -> Result<Option<String>, Option<String>>
where
F: Fn(
&str,
Option<&str>,
bool,
Option<&HashMap<String, String>>,
) -> Result<Option<String>, Option<String>>,
{
run_command(
"git rev-parse --show-toplevel",
target_directory,
false,
None,
)
}
fn get_hooks_directory<F>(
run_command: F,
root_directory: &str,
) -> Result<Option<String>, Option<String>>
where
F: Fn(
&str,
Option<&str>,
bool,
Option<&HashMap<String, String>>,
) -> Result<Option<String>, Option<String>>,
{
run_command(
"git rev-parse --git-path hooks",
Some(root_directory),
false,
None,
)
}
pub fn setup_hooks<F, G>(
run_command: F,
write_file: G,
root_directory_path: &str,
hook_file_skip_list: &[&str],
) -> Result<(), String>
where
F: Fn(
&str,
Option<&str>,
bool,
Option<&HashMap<String, String>>,
) -> Result<Option<String>, Option<String>>,
G: Fn(&str, &str, bool) -> Result<(), String>,
{
let hooks_directory = match get_hooks_directory(&run_command, root_directory_path) {
Ok(Some(path)) => path,
_ => return Err(String::from("Failure determining git hooks directory")),
};
hooks::create_hook_files(
write_file,
root_directory_path,
&hooks_directory,
hook_file_skip_list,
)
}
#[cfg(test)]
#[path = "git_test.rs"]
mod git_tests;
|
extern crate exonum;
extern crate exonum_configuration;
extern crate queue_constructor;
use exonum::helpers::{self, fabric::NodeBuilder};
use exonum_configuration as configuration;
fn main() {
exonum::crypto::init();
helpers::init_logger().unwrap();
let node = NodeBuilder::new()
.with_service(Box::new(configuration::ServiceFactory))
.with_service(Box::new(queue_constructor::ServiceFactory));
node.run();
}
|
use serde::Deserialize;
use std::fmt::{Display, Error, Formatter};
/// Modifier for interactive commands,
/// specifying the amount of normalization in the output.
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Rewrite {
AsIs,
Instantiated,
HeadNormal,
Simplified,
Normalised,
}
impl Default for Rewrite {
fn default() -> Self {
Rewrite::Simplified
}
}
/// Modifier for the interactive computation command,
/// specifying the mode of computation and result display.
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum ComputeMode {
DefaultCompute,
IgnoreAbstract,
UseShowInstance,
}
impl Default for ComputeMode {
fn default() -> Self {
ComputeMode::DefaultCompute
}
}
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Comparison {
CmpEq,
CmpLeq,
}
impl Display for Comparison {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
f.write_str(match self {
Comparison::CmpEq => "==",
Comparison::CmpLeq => "<=",
})
}
}
/// An extension of [`Comparison`](self::Comparison) to `>=`.
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum CompareDirection {
DirEq,
DirLeq,
DirGeq,
}
impl From<Comparison> for CompareDirection {
fn from(from: Comparison) -> Self {
match from {
Comparison::CmpEq => CompareDirection::DirEq,
Comparison::CmpLeq => CompareDirection::DirLeq,
}
}
}
/// Polarity for equality and subtype checking.
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Polarity {
/// monotone
Covariant,
/// antitone
Contravariant,
/// no information (mixed variance)
Invariant,
/// constant
Nonvariant,
}
impl Display for Polarity {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
f.write_str(match self {
Polarity::Covariant => "+",
Polarity::Contravariant => "-",
Polarity::Invariant => "*",
Polarity::Nonvariant => "_",
})
}
}
/// Modifier for interactive commands,
/// specifying whether safety checks should be ignored.
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum UseForce {
/// Ignore additional checks, like termination/positivity...
WithForce,
/// Don't ignore any checks.
WithoutForce,
}
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Remove {
Remove,
Keep,
}
/// Is the highlighting "token-based", i.e. based only on
/// information from the lexer?
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum TokenBased {
TokenBased,
NotOnlyTokenBased,
}
impl Default for TokenBased {
fn default() -> Self {
TokenBased::NotOnlyTokenBased
}
}
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Hiding {
YesOverlap,
NoOverlap,
Hidden,
NotHidden,
}
/// A function argument can be relevant or irrelevant.
/// See "Agda.TypeChecking.Irrelevance".
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Relevance {
/// The argument is (possibly) relevant at compile-time.
Relevant,
/// The argument may never flow into evaluation position.
/// Therefore, it is irrelevant at run-time.
/// It is treated relevantly during equality checking.
NonStrict,
/// The argument is irrelevant at compile- and runtime.
Irrelevant,
}
/// Cohesion modalities
/// see "Brouwer's fixed-point theorem in real-cohesive homotopy type theory" (arXiv:1509.07584)
/// types are now given an additional topological layer which the modalities interact with.
#[derive(Deserialize, Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Cohesion {
/// Same points, discrete topology, idempotent comonad, box - like.
Flat,
/// Identity modality.
Continuous,
/// Same points, codiscrete topology, idempotent monad, diamond-like.
Sharp,
/// Single point space, artificially added for Flat left-composition.
Squash,
}
|
/* Version de l'alogo avec la preuve rand faite à la Schnorr et les cartes en struct*/
extern crate curve25519_dalek;
extern crate rand_core;
extern crate rand;
extern crate sha2;
use rand_core::OsRng;
use curve25519_dalek::constants;
use curve25519_dalek::ristretto::RistrettoPoint;
use curve25519_dalek::scalar::Scalar;
use rand::seq::SliceRandom;
use rand::thread_rng;
use rand::Rng;
use std::convert::TryInto;
use sha2::Sha512;
/* Struct du vecteur c*/
struct Chiffre {
x : RistrettoPoint,
y : RistrettoPoint,
}
struct Carte {
couleur : u16,
valeur : u16,
}
/* Chaque struct Zk contient tous les éléments que le vérifieur a besoin */
struct Zkrand {
g : RistrettoPoint,
pkc : RistrettoPoint,
g1 : RistrettoPoint,
g2 : RistrettoPoint,
pk1 : Vec<RistrettoPoint>,
pk2 : Vec<RistrettoPoint>,
y1 : Vec<RistrettoPoint>,
y2 : Vec<RistrettoPoint>,
z : Vec<Scalar>,
c : Vec<Scalar>,
}
struct Zktheta {
theta : RistrettoPoint,
y : RistrettoPoint,
z : Scalar,
g : RistrettoPoint,
}
struct Zkpi0 {
id : Carte,
pk : RistrettoPoint,
ch : Chiffre,
t1 : RistrettoPoint,
t2 : RistrettoPoint,
z : Scalar,
g : RistrettoPoint,
}
struct Zkpij {
b : bool,
g1 : RistrettoPoint,
g2 : RistrettoPoint,
pk1 : RistrettoPoint,
pk2 : Vec<RistrettoPoint>,
y1 : Vec<RistrettoPoint>,
y2 : Vec<RistrettoPoint>,
z : Vec<Scalar>,
c : Vec<Scalar>,
}
/* Structure permettant de suivre le bon déroulement du jeu */
struct State {
alpha : u16,
suit : u16,
u : Vec<Vec<usize>>,
}
/* Fonction qui crée le deck de cartes */
fn deck() -> Vec <Carte> {
let mut deck : Vec <Carte> = Vec::new();
for i in 0..52 {
let j = i % 13;
let k = i / 13;
let carte = Carte { couleur : k+1, valeur : j+1};
deck.push(carte);
}
deck
}
/* Fonction qui choisit aléatoirement un générateur g*/
fn init() -> RistrettoPoint {
let mut rng = OsRng;
let g = RistrettoPoint::random(&mut rng);
g
}
/* Fonction de génération des clés publiques en choississant aléatoirement une clé secrète */
fn keygen(g : RistrettoPoint) -> (Scalar, RistrettoPoint){
let mut rng = OsRng;
let sk : Scalar = Scalar::random(&mut rng);
let pk : RistrettoPoint = g * sk;
(sk,pk)
}
/* Fonction permettant de transformer les cartes qui sont des entiers en Scalar pour pouvoir faire des opérations avec des RistrettoPoint */
fn fromcarte_to_nb(carte: &Carte) -> Scalar {
let nb = carte.couleur * 100 + carte.valeur;
let s : Scalar = Scalar::from(nb);
s
}
/* Fonction qui va mélanger le deck de cartes et distribuer les cartes à la fin */
fn gkeygen(mut ch : Vec <Chiffre> ,chiffre : &mut Vec<Chiffre>, sk : &Vec <Scalar>, g : &RistrettoPoint, pkc : &RistrettoPoint) {
let mut rng = thread_rng();
let mut rng2 = OsRng;
let mut nums : Vec<usize> = (0..52).collect();
let mut zk_r = Vec::new();
for _j in 1..5 {
// shuffle permet de mélanger tous les nombres de la variable nums aléatoirement
nums.shuffle(&mut rng);
let mut r : Vec<Scalar> = Vec::new();
for _i in 0..52 {
let ri : Scalar = Scalar::random(&mut rng2);
r.push(ri);
}
rand(&mut ch,&nums,r,&mut zk_r,&g,&pkc);
}
for i in 0..4 {
if verirand(&zk_r[i]) == 0 {
eprintln!("Erreur : Vérification de la valeur de r fausse");
}
}
let b = &constants::RISTRETTO_BASEPOINT_POINT;
let mut theta : Vec <Vec<RistrettoPoint>> = vec![vec![*b; 52];4];
let mut piij : Vec<Zktheta>= Vec::new();
for j in 0..4 {
caltheta(&mut theta,&ch,sk[j],j,&mut piij);
}
for _i in 0..4 {
*chiffre = calci(&ch,&theta,&piij);
}
}
// Fonction qui permet de mélanger le deck avec aussi la preuve de rand
fn rand(ch : &mut Vec<Chiffre>, nums : &Vec<usize>, r : Vec<Scalar>, zk_r : &mut Vec<Vec<Zkrand>>, g : &RistrettoPoint, pkc : &RistrettoPoint) {
let mut ch2 : Vec <Chiffre> = Vec::new();
for k in 0..52 {
let c = Chiffre {x: ch[nums[k]].x + r[k] * g, y: ch[nums[k]].y + r[k] * pkc};
ch2.push(c);
}
let zkr = zkrand(&ch,&ch2,&nums,r,&g,&pkc);
zk_r.push(zkr);
*ch = ch2;
}
/* Fonction qui effectue la preuve rand jusqu'au moment des calculs du vérifieur */
fn zkrand(che : &Vec<Chiffre>, chs : &Vec<Chiffre>, nums : &Vec<usize>, r : Vec<Scalar>, g : &RistrettoPoint, pkc : &RistrettoPoint) -> Vec<Zkrand> {
let mut zkr = Vec::new();
for i in 0..52{
let mut rng = OsRng;
let mut indice = 53usize;
let b = &constants::RISTRETTO_BASEPOINT_POINT;
let zero = Scalar::zero();
let mut pk1 : Vec<RistrettoPoint> = vec![*b;52];
let mut pk2 : Vec<RistrettoPoint> = vec![*b;52];
let mut y1 : Vec<RistrettoPoint> = vec![*b;52];
let mut y2 : Vec<RistrettoPoint> = vec![*b;52];
let mut c : Vec<Scalar> = vec![zero;52];
let mut z : Vec<Scalar> = vec![zero;52];
let mut som : Scalar = Scalar::zero();
let ra : Scalar = Scalar::random(&mut rng);
for k in 0..52{
if i == nums[k] {
y1[k] = ra * g;
y2[k] = ra * pkc;
indice = k;
pk1[k] = chs[k].x;
pk2[k] = chs[k].y;
} else {
z[k]= Scalar::random(&mut rng);
c[k] = Scalar::random(&mut rng);
y1[k] = z[k] * g - c[k] * (chs[k].x - che[i].x);
y2[k] = z[k] * pkc - c[k] * (chs[k].y - che[i].y);
pk1[k] = chs[k].x;
pk2[k] = chs[k].y;
}
}
let mut s = Scalar::zero();
for i in 0..52 {
let t = Scalar::hash_from_bytes::<Sha512>(y1[i].compress().as_bytes()) + Scalar::hash_from_bytes::<Sha512>(y2[i].compress().as_bytes());
s = s + t;
}
s = Scalar::hash_from_bytes::<Sha512>(s.as_bytes());
if indice != 53 {
for i in 0..52{
som = som + c[i];
}
c[indice] = s - som;
z[indice] = ra + r[indice] * c[indice];
}
let pij = Zkrand{g : *g, pkc : *pkc, g1 : che[i].x, g2 : che[i].y, pk1 : pk1, pk2 : pk2, y1 : y1, y2 : y2, z : z, c : c};
zkr.push(pij);
}
zkr
}
/* Fonction qui permet au vérifieur de vérifier si la preuve rand est accepter */
fn verirand(zkr : &Vec<Zkrand>) -> u8 {
for i in 0..52{
let mut s = Scalar::zero();
for j in 0..52 {
let t = Scalar::hash_from_bytes::<Sha512>(zkr[i].y1[j].compress().as_bytes()) + Scalar::hash_from_bytes::<Sha512>(zkr[i].y2[j].compress().as_bytes());
s = s + t;
}
s = Scalar::hash_from_bytes::<Sha512>(s.as_bytes());
let mut som = Scalar::zero();
for j in 0..52{
if (zkr[i].z[j] * zkr[i].g != zkr[i].y1[j] + zkr[i].c[j] * (zkr[i].pk1[j] - zkr[i].g1)) {
println!("chemin n°1");
return 0
}
if (zkr[i].z[j] * zkr[i].pkc != zkr[i].y2[j] + zkr[i].c[j] * (zkr[i].pk2[j] - zkr[i].g2)) {
println!("chemin n°2");
return 0
}
som = som + zkr[i].c[j];
}
if som != s {
println!("chemin n°3");
return 0
}
}
return 1
}
// Fonction de calcul des theta avec aussi la preuve ZK sur les theta
fn caltheta(theta : &mut Vec <Vec<RistrettoPoint>> , ch : &Vec<Chiffre> , sk : Scalar , n : usize, piij : &mut Vec<Zktheta>) {
let mut i = 0;
let mut j = 0;
while i < 52 {
if i < 13 * n || 13 * (n+1) - 1 < i {
let th = ch [i].x * sk;
theta[n][j] = th;
let pij = zktheta(&th,&sk,&ch[i].x);
piij.push(pij);
}
i += 1;
j += 1;
}
}
/* Fonction qui effectue la preuve des theta jusqu'au moment des calculs du vérifieur */
fn zktheta(theta : &RistrettoPoint, sk : &Scalar, g : &RistrettoPoint) -> Zktheta {
let mut rng = OsRng;
let r : Scalar = Scalar::random(&mut rng);
let y = r * g;
let b = Scalar::hash_from_bytes::<Sha512>(g.compress().as_bytes());
let z = r + sk * b;
let pij = Zktheta{theta: *theta, y: y, z: z, g: *g};
pij
// Retourne dans une struct toutes les valeurs nécessaire pour la vérification
}
/* Fonction qui permet au vérifieur de vérifier si la preuve des theta est accepter */
fn veritheta(zk : &Zktheta) -> u8 {
let b = Scalar::hash_from_bytes::<Sha512>(zk.g.compress().as_bytes());
if zk.z * zk.g == zk.y + b * zk.theta {
return 1
} else {
return 0
}
}
/* Fonction qui fait en sorte que dans chaque chiffré il ne reste qu'une clé secrète correspondant au joueur à qui appartient la carte */
fn calci(ch : &Vec<Chiffre> , theta : &Vec<Vec<RistrettoPoint>> , piij : &Vec<Zktheta>) -> Vec<Chiffre> {
let mut ci : Vec <Chiffre> = Vec::new();
let mut ind = vec![0usize; 3];
for l in 0..4 {
for i in 13*l..13*(l+1) {
let mut indice = 0;
if l == 0 {
indice = 1;
}
let mut the = theta[indice][i];
for j in 0..piij.len(){
if piij[j].theta == theta[indice][i] {
ind[0] = j;
}
}
let mut e = 1;
for k in 1..4 {
if k != indice && k != l {
the = the + theta[k][i];
for j in 0..piij.len(){
if piij[j].theta == theta[k][i] {
ind[e] = j;
e += 1;
}
}
}
}
for i in 0..3 {
if veritheta(&piij[ind[i]]) == 0{
eprintln!("Erreur : Vérification de la valeur de theta fausse");
}
}
let res = ch[i].y - the;
let c = Chiffre {x: ch[i].x, y: res};
ci.push(c);
}
}
ci
}
/* Fonction qui permet de déchiffrer les cartes une par une */
fn dec(ch : &Vec<Chiffre>, sk : &Scalar, deck : &Vec<Carte>, n : usize, g : &RistrettoPoint) -> Carte {
let valeur = ch[n].y - (sk * ch[n].x);
let mut card = Carte {couleur : 0, valeur : 0};
for k in 0..52 {
let carte = Carte {couleur : deck[k].couleur, valeur : deck[k].valeur};
let nb = fromcarte_to_nb(&carte);
if valeur == g * nb{
card.couleur = carte.couleur;
card.valeur = carte.valeur;
break;
}
}
card
}
// Fonction qui permet d'afficher les mains des quatre joueurs afin de vérifier le bon déroulement du jeu
fn get_hand(deck : &Vec<Carte> , ch : &Vec<Chiffre> , sk : &Scalar , n : usize, g : &RistrettoPoint) {
let mut decksor : Vec<Carte> = Vec::new();
for i in 13*n..13*(n+1) {
decksor.push(dec(&ch,&sk,&deck,i,&g));
}
println!("Cartes du Joueur n°{} :",n+1);
affichage(&decksor,13);
println!();
}
/* Fonction d'affichage de n cartes */
fn affichage(deck : &Vec<Carte>, n : usize){
for i in 0..n {
print!("{} , {}",deck[i].couleur,deck[i].valeur);
}
}
/* Fonction de jeu où à chaque exécution une carte est jouée */
fn play(n : &usize, sk : &Scalar, pk : &Vec<RistrettoPoint>, chiffre : &Vec<Chiffre>, state : &State, state2 : &mut State, deck : &Vec<Carte>, tour : &usize, g : &RistrettoPoint, jt : &mut Vec<usize>) -> (usize,Carte,Zkpi0,Vec<Zkpij>,Vec<usize>) {
let mut rng = thread_rng();
let mut t = rng.gen_range(0..jt.len());
/* boucle while qui fait en sorte que la carte que le joueur veut jouer n'a pas été déjà jouée ou avec laquelle il a déjà tenté de jouer ce tour-ci */
while (ine(&state.u[*n],&jt[t]) == 1){
jt.remove(t);
t = rng.gen_range(0..jt.len());
}
state2.u[*n][*tour] = jt[t].try_into().unwrap();
let valeur = dec(&chiffre,&sk,&deck,jt[t],&g);
println!("joueur n°{:?} : {},{}",*n+1,valeur.couleur,valeur.valeur);
if state.alpha == 4 {
state2.alpha = 1;
state2.suit = valeur.couleur;
} else {
state2.alpha = state.alpha + 1;
state2.suit = state.suit;
}
let pi0 = zkpi0(&valeur,&pk[*n],&g,&chiffre[jt[t]],&sk);
let mut l = Vec::new();
for i in 0..52 {
if deck[i].couleur != state2.suit {
l.push(i);
}
}
let mut pij : Vec<Zkpij> = Vec::new();
let zero = Scalar::zero();
let b = &constants::RISTRETTO_BASEPOINT_POINT;
for j in 13*n..13*(n+1){
if state2.suit == valeur.couleur {
let pi = Zkpij{b : false, g1 : *g, g2 : chiffre[j].x, pk1 : pk[*n], pk2 : vec![*b;39], y1 : vec![*b;39], y2 : vec![*b;39], z : vec![zero;39], c : vec![zero;39]};
pij.push(pi);
continue;
}
if ine(&state.u[*n],&j) == 1 {
let pi = Zkpij{b : false, g1 : *g, g2 : chiffre[j].x, pk1 : pk[*n], pk2 : vec![*b;39], y1 : vec![*b;39], y2 : vec![*b;39], z : vec![zero;39], c : vec![zero;39]};
pij.push(pi);
continue;
} else {
let carte = dec(&chiffre,&sk,&deck,j,&g);
let pi = zkpij(&deck,&l,&sk,&pk[*n],&g,&chiffre[j],carte);
pij.push(pi);
}
}
(t,valeur,pi0,pij,l)
}
/* Fonction qui effectue la preuve pi0 jusqu'au moment des calculs du vérifieur */
fn zkpi0(id : &Carte, pk : &RistrettoPoint, g : &RistrettoPoint, ch : &Chiffre, sk : &Scalar) -> Zkpi0 {
let mut rng = OsRng;
let r : Scalar = Scalar::random(&mut rng);
let t1 = r * g;
let t2 = r * ch.x;
let mut c = Scalar::hash_from_bytes::<Sha512>(t1.compress().as_bytes()) + Scalar::hash_from_bytes::<Sha512>(t2.compress().as_bytes());
c = Scalar::hash_from_bytes::<Sha512>(c.as_bytes());
let z = r + sk * c;
let carte = Carte{couleur : id.couleur,valeur : id.valeur};
let ch1 = Chiffre{x : ch.x, y : ch.y};
let pi0 = Zkpi0{id : carte, pk : *pk, ch : ch1, t1 : t1, t2 : t2, z : z, g : *g};
pi0
// Valeurs à mettre dans le struct : la carte id, la clé publique pk, le chiffre ch, t1, t2, z, g
}
/* Fonction qui permet au vérifieur de vérifier si la preuve rand est accepter */
fn veripi0(zk : Zkpi0) -> u8 {
let pk2 = zk.ch.y - fromcarte_to_nb(&zk.id) * zk.g;
let mut c = Scalar::hash_from_bytes::<Sha512>(zk.t1.compress().as_bytes()) + Scalar::hash_from_bytes::<Sha512>(zk.t2.compress().as_bytes());
c = Scalar::hash_from_bytes::<Sha512>(c.as_bytes());
if (zk.z * zk.g == zk.t1 + c * zk.pk) && (zk.z * zk.ch.x == zk.t2 + c * pk2) {
return 1
} else {
return 0
}
}
/* Fonction qui vérifie si une carte n'a pas déjà été jouée. Si c'est le cas elle retourne 1 */
fn ine(v : &Vec<usize>, j : &usize) -> u8{
let k : usize = *j;
if v.is_empty() {
return 0
}
for i in 0..v.len() {
if k == v[i].into() {
return 1
}
}
return 0
}
/* Fonction qui effectue la preuve pij jusqu'au moment des calculs du vérifieur */
fn zkpij(deck : &Vec<Carte>, l : &Vec<usize>, sk : &Scalar, pk : &RistrettoPoint, g : &RistrettoPoint, ch : &Chiffre, id : Carte) -> Zkpij {
let mut rng = OsRng;
let mut indice = 39usize;
let b = &constants::RISTRETTO_BASEPOINT_POINT;
let zero = Scalar::zero();
let mut pk2 = Vec::new();
let mut y1 : Vec<RistrettoPoint> = vec![*b;39];
let mut y2 : Vec<RistrettoPoint> = vec![*b;39];
let mut c : Vec<Scalar> = vec![zero;39];
let mut z : Vec<Scalar> = vec![zero;39];
let mut som : Scalar = Scalar::zero();
let r : Scalar = Scalar::random(&mut rng);
for k in 0..39{
if (deck[l[k]].couleur == id.couleur) && (deck[l[k]].valeur == id.valeur) {
y1[k] = r * g;
y2[k] = r * ch.x;
indice = k;
pk2.push(ch.y);
} else {
z[k]= Scalar::random(&mut rng);
c[k] = Scalar::random(&mut rng);
y1[k] = z[k] * g - c[k] * pk;
y2[k] = z[k] * ch.x - c[k] * ch.y;
pk2.push(ch.y + fromcarte_to_nb(&deck[l[k]]) * g);
}
}
let mut s = Scalar::zero();
for i in 0..39 {
let t = Scalar::hash_from_bytes::<Sha512>(y1[i].compress().as_bytes()) + Scalar::hash_from_bytes::<Sha512>(y2[i].compress().as_bytes());
s = s + t;
}
s = Scalar::hash_from_bytes::<Sha512>(s.as_bytes());
if indice != 39 {
//println!("indice {:?}",indice);
for i in 0..39{
som = som + c[i];
}
c[indice] = s - som;
z[indice] = r + sk * c[indice];
}
// Valeurs à retourner : g1, g2, pk1, pk2, y1, y2, z, c, l
let pij = Zkpij{b : true, g1 : *g, g2 : ch.x, pk1 : *pk, pk2 : pk2, y1 : y1, y2 : y2, z : z, c : c};
pij
}
/* Fonction qui permet au vérifieur de vérifier si la preuve rand est accepter */
fn veripij(pij : &Zkpij, deck : &Vec<Carte>, l : &Vec<usize>) -> u8 {
let mut s = Scalar::zero();
for i in 0..39 {
let t = Scalar::hash_from_bytes::<Sha512>(pij.y1[i].compress().as_bytes()) + Scalar::hash_from_bytes::<Sha512>(pij.y2[i].compress().as_bytes());
s = s + t;
}
s = Scalar::hash_from_bytes::<Sha512>(s.as_bytes());
let mut som = Scalar::zero();
for i in 0..39{
let pk2 = pij.pk2[i] - fromcarte_to_nb(&deck[l[i]]) * pij.g1;
if (pij.z[i] * pij.g1 != pij.y1[i] + pij.c[i] * pij.pk1) {
println!("chemin n°1");
return 0
}
if (pij.z[i] * pij.g2 != pij.y2[i] + pij.c[i] * pk2) {
println!("chemin n°2");
return 0
}
som = som + pij.c[i];
}
if som != s {
println!("chemin n°3");
return 0
}
return 1
}
/* Fonction qui permet au vérifieur de vérifier si la carte que le joueur tente de jouer est jouable */
fn verif(n : &usize, state : &State, state2 : &State, deck : &Vec<Carte>, tour : &usize, t : &usize, carte : &Carte, pi0 : Zkpi0, pij : &Vec<Zkpij>, l : Vec<usize>, jt : &mut Vec<usize>) -> u8 {
/* Les quatre premières vérifications permettent de vérifier si il n'y a pas de problème dans state ou state2 */
let mut i = 0;
while i < 4 {
if i == *n {
i += 1;
continue;
}
for j in 0..13 {
if state.u[i][j] != state2.u[i][j] {
return 0;
}
}
i += 1;
}
for i in 0..*tour {
if jt[*t] == state.u[*n][i] || state.u[*n][i] != state2.u[*n][i] || jt[*t] != state2.u[*n][*tour] {
return 0;
}
}
if (state.alpha == 4||state.alpha == 0) && (state2.alpha != 1||state2.suit != carte.couleur) {
return 0;
}
if state.alpha != 4 && state.suit != 0 && (state2.alpha != state.alpha + 1||state2.suit != state.suit) {
return 0;
}
/* Vérifie si la carte est associée au bon joueur */
if veripi0(pi0) == 0 {
return 0
}
/* Vérifie si le joueur a une carte de la couleur demandée si la carte qu'il veut jouer n'est pas de la bonne couleur */
if (state2.suit != carte.couleur){
for j in 0..13 {
if pij[j].b == true {
if veripij(&pij[j],&deck,&l) == 0 {
jt.remove(*t);
return 0
}
}
}
}
return 1;
}
/* Fonction qui permet de copier les éléments de state2 dans state */
fn copy(state : &mut State, state2 : &State) {
state.alpha = state2.alpha;
state.suit = state2.suit;
for i in 0..4 {
for j in 0..13 {
state.u[i][j] = state2.u[i][j];
}
}
}
fn main() {
let deck : Vec <Carte> = deck();
let g = init();
let mut pk = Vec::new();
let mut sk = Vec::new();
for _i in 0..4 {
let (a,b) = keygen(g);
sk.push(a);
pk.push(b);
}
let mut pkc : RistrettoPoint = pk[0];// pkc est la somme des 4 clés publiques
for i in 1..4{
pkc = pkc + pk[i];
}
let mut ch : Vec <Chiffre> = Vec::new();// ch correspnd au vecteur c dans le papier
let mut chiffre : Vec<Chiffre> = Vec::new();// chiffre correspnd au vecteur c dans le papier
for i in 0..52 {
let carte = Carte {couleur :deck[i].couleur , valeur :deck[i].valeur};
let c : RistrettoPoint = pkc + g * fromcarte_to_nb(&carte);
let d = Chiffre {x: g, y: c};
let e = Chiffre {x: g, y: c};
ch.push(d);
chiffre.push(e);
}
gkeygen(ch,&mut chiffre,&sk,&g,&pkc);
for n in 0..4 {
get_hand(&deck,&chiffre,&sk[n],n,&g);
}
let mut state = State {alpha : 4, suit : 0, u : vec! [vec![53; 13];4]};
let mut state2 = State {alpha : 0, suit : 0, u : vec! [vec![53; 13];4]};
let mut pre = 0;
for tour in 0..13 {
println!("tour n°{}",tour+1);
let mut best = Carte {couleur : 0, valeur : 0};
let mut pl = 0;
for n in 0..4 {
println!("Joueur n°{} :",pre+1);
let mut jt : Vec<usize> = (13*n..13*(n+1)).collect();
let mut veri = 0;
while veri == 0{
let (t,carte,pi0,pij,l) = play(&pre,&sk[pre],&pk,&chiffre,&state,&mut state2,&deck,&tour,&g,&mut jt);
veri = verif(&pre,&state,&state2,&deck,&tour,&t,&carte,pi0,&pij,l,&mut jt);
/* Vérifications pour savoir au prochain tour quel va être le joueur à jouer en premier */
if n == 0 {
best = carte;
continue;
}
if veri == 0 {
continue;
}
if carte.couleur == best.couleur && carte.valeur > best.valeur {
best = carte;
pl = pre;
continue;
}
/* On suppose ici que la couleur Pique qui est la couleur dominante, est égale à 4 */
if carte.couleur == 4 && carte.couleur != best.couleur {
best = carte;
pl = pre;
continue;
}
}
copy(&mut state,&state2);
pre = (pre+1)%4;
println!();
}
pre = pl;
}
}
|
use hacspec_lib::*;
use hacspec_p256::*;
use hacspec_sha256::*;
#[derive(Debug)]
pub enum Error {
InvalidScalar,
InvalidSignature,
}
pub type P256PublicKey = Affine;
pub type P256SecretKey = P256Scalar;
pub type P256Signature = (P256Scalar, P256Scalar); // (r, s)
pub type P256SignatureResult = Result<P256Signature, Error>;
pub type P256VerifyResult = Result<(), Error>;
type CheckResult = Result<(), Error>;
type ArithmeticResult = Result<Affine, Error>;
fn check_scalar_zero(r: P256Scalar) -> CheckResult {
if r.equal(P256Scalar::ZERO()) {
CheckResult::Err(Error::InvalidScalar)
} else {
CheckResult::Ok(())
}
}
fn ecdsa_point_mul_base(x: P256Scalar) -> ArithmeticResult {
match p256_point_mul_base(x) {
AffineResult::Ok(s) => ArithmeticResult::Ok(s),
AffineResult::Err(_) => ArithmeticResult::Err(Error::InvalidScalar),
}
}
fn ecdsa_point_mul(k: P256Scalar, p: Affine) -> ArithmeticResult {
match p256_point_mul(k, p) {
AffineResult::Ok(s) => ArithmeticResult::Ok(s),
AffineResult::Err(_) => ArithmeticResult::Err(Error::InvalidScalar),
}
}
fn ecdsa_point_add(p: Affine, q: Affine) -> ArithmeticResult {
match point_add(p, q) {
AffineResult::Ok(s) => ArithmeticResult::Ok(s),
AffineResult::Err(_) => ArithmeticResult::Err(Error::InvalidScalar),
}
}
fn sign(payload: &ByteSeq, sk: P256SecretKey, nonce: P256Scalar) -> P256SignatureResult {
check_scalar_zero(nonce)?;
let (k_x, _k_y) = ecdsa_point_mul_base(nonce)?;
let r = P256Scalar::from_byte_seq_be(&k_x.to_byte_seq_be());
check_scalar_zero(r)?;
let payload_hash = hash(payload);
let payload_hash = P256Scalar::from_byte_seq_be(&payload_hash);
let rsk = r * sk;
let hash_rsk = payload_hash + rsk;
let nonce_inv = nonce.inv();
let s = nonce_inv * hash_rsk;
P256SignatureResult::Ok((r, s))
}
pub fn ecdsa_p256_sha256_sign(
payload: &ByteSeq,
sk: P256SecretKey,
nonce: P256Scalar,
) -> P256SignatureResult {
sign(payload, sk, nonce)
}
fn verify(payload: &ByteSeq, pk: P256PublicKey, signature: P256Signature) -> P256VerifyResult {
// signature = (r, s) must be in [1, n-1] because they are Scalars
let (r, s) = signature;
let payload_hash = hash(payload);
let payload_hash = P256Scalar::from_byte_seq_be(&payload_hash);
let s_inv = s.inv();
// R' = (h * s1) * G + (r * s1) * pubKey
let u1 = payload_hash * s_inv;
let u1 = ecdsa_point_mul_base(u1)?;
let u2 = r * s_inv;
let u2 = ecdsa_point_mul(u2, pk)?;
let (x, _y) = ecdsa_point_add(u1, u2)?;
let x = P256Scalar::from_byte_seq_be(&x.to_byte_seq_be());
if x == r {
P256VerifyResult::Ok(())
} else {
P256VerifyResult::Err(Error::InvalidSignature)
}
}
pub fn ecdsa_p256_sha256_verify(
payload: &ByteSeq,
pk: P256PublicKey,
signature: P256Signature,
) -> P256VerifyResult {
verify(payload, pk, signature)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn self_test() {
let sk = P256Scalar::from_hex(
"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550",
);
let pk = (
P256FieldElement::from_hex(
"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
),
P256FieldElement::from_hex(
"B01CBD1C01E58065711814B583F061E9D431CCA994CEA1313449BF97C840AE0A",
),
);
let msg = ByteSeq::from_public_slice(b"hacspec ecdsa p256 sha256 self test");
let nonce = P256Scalar::from_be_bytes(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
let signature = match sign(&msg, sk, nonce) {
Ok(s) => s,
Err(_) => panic!("Error signing"),
};
assert!(verify(&msg, pk, signature).is_ok());
}
#[test]
fn kat_sign() {
let pk = (
P256FieldElement::from_hex(
"2927b10512bae3eddcfe467828128bad2903269919f7086069c8c4df6c732838",
),
P256FieldElement::from_hex(
"c7787964eaac00e5921fb1498a60f4606766b3d9685001558d1a974e7341513e",
),
);
let msg = ByteSeq::from_hex("313233343030");
let sig = (
P256Scalar::from_hex(
"2ba3a8be6b94d5ec80a6d9d1190a436effe50d85a1eee859b8cc6af9bd5c2e18",
),
P256Scalar::from_hex(
"b329f479a2bbd0a5c384ee1493b1f5186a87139cac5df4087c134b49156847db",
),
);
assert!(verify(&msg, pk, sig).is_ok());
}
}
|
use crate::message::SOH;
use crate::data_dictionary::*;
use crate::quickfix_errors::*;
pub fn validate_tag(msg: &str, dict: &DataDictionary) -> Result<(), SessionLevelRejectErr> {
// validate that tag is correct according to data_dictionary
// and value is in permissible range
// get the message type
let msg_type = get_message_type(msg).unwrap();
for tag_value_str in msg.split(SOH) {
let tag_and_val: Vec<&str> = tag_value_str.split('=').collect();
let tag = match tag_and_val[0].parse::<u32>() {
Ok(t) => t,
Err(e) => {
return Err(SessionLevelRejectErr::parse_err(Some(Box::new(e))));
}
};
match dict.check_tag_for_message(tag, msg_type) {
Ok(_) => Ok(()),
Err(e) => Err(e),
};
}
Ok(())
}
pub fn validate_checksum(message: &str) -> Result<(), SessionLevelRejectErr> {
let tag_vec: Vec<&str> = message.split(SOH).collect();
let recvd_checksum_field: Vec<&str> = tag_vec[tag_vec.len() - 1].split('=').collect();
if !recvd_checksum_field[0].starts_with("10=") {
return Err(SessionLevelRejectErr::required_tag_missing_err());
}
let mut calc_checksum = 0u32;
for tag in tag_vec {
calc_checksum = calc_checksum + tag.as_bytes().len() as u32 + 1;
}
let check_str = format!("{:0>3}", calc_checksum % 256);
if check_str != recvd_checksum_field[1] {
return Err(SessionLevelRejectErr::invalid_checksum());
}
Ok(())
}
pub fn validate_bodylength(message: &str) -> Result<(), SessionLevelRejectErr> {
let mut body_len: u32 = 0;
let all_tags: Vec<&str> = message.split(SOH).collect();
for tag in &all_tags[2..all_tags.len() - 1] {
// adding 1 for SOH character
body_len = body_len + (*tag).len() as u32 + 1;
}
let received_body_len = get_body_length(message)?;
if received_body_len == body_len {
return Ok(());
}
return Err(SessionLevelRejectErr::invalid_body_len_err());
}
pub fn get_message_type(msg_str: &str) -> Option<&str> {
for tag_value in msg_str.split(SOH) {
if tag_value.starts_with("35") {
let tag_value_str: Vec<&str> = tag_value.split('=').collect();
return Some(tag_value_str[1]);
}
}
return None;
}
pub fn get_begin_str(msg_str: &str) -> Option<&str> {
for tag_value in msg_str.split(SOH) {
if tag_value.starts_with("8=") {
let tag_value_str: Vec<&str> = tag_value.split('=').collect();
return Some(tag_value_str[1]);
}
}
return None;
}
pub fn get_body_length(msg_str: &str) -> Result<u32, SessionLevelRejectErr> {
for tag_value in msg_str.split(SOH) {
if tag_value.starts_with("9=") {
let tag_value_str: Vec<&str> = tag_value.split('=').collect();
match tag_value_str[1].parse::<u32>() {
Ok(num) => return Ok(num),
Err(e) => {
return Err(SessionLevelRejectErr::parse_err(Some(Box::new(e))));
}
}
}
}
// tag not found, raise error
Err(SessionLevelRejectErr::required_tag_missing_err())
}
// 8=FIX.4.2|9=156|35=D|34=124|49=ABC_DEFG04|52=20100208-18:51:42|56=CCG|115=XYZ|11=NF 0015/02082010|54=2|38=1000|55=RRC|40=2|44=55.36|59=0|1=ABC123ZYX|21=1|207=N|47=A|9487=CO|10=050|
|
use executor::*;
use std::fs::File;
use std::io::Write;
use std::path::Path;
const BUILTIN_RULES : &'static str = "\
# The rules
rule C_COMPILER
command = clang $cflags -c $in -o $out
";
fn dump_target(f: &mut File, target_name: &str, target: &Target) {
f.write_fmt(format_args!("# Target: {}\n", target_name)).unwrap();
match target.target_type {
TargetType::Executable(exclude_from_all, ref sources) => {
for source in sources {
f.write_fmt(format_args!("build build/{}/{}.o: C_COMPILER {}\n cflags={}\n\n",
target_name, source, source, "")).unwrap();
}
},
TargetType::ImportedExecutable => { /* These has no impact for code generation */ },
_ => unimplemented!(),
}
}
pub fn dump_to_ninja_file(context: &Context, filename: &str) {
let mut f = File::create(Path::new(filename)).unwrap();
f.write_fmt(format_args!("{}", BUILTIN_RULES)).unwrap();
for (target_name, target) in &context.targets {
dump_target(&mut f, &target_name, &target);
}
}
|
#![no_std]
use nrf52832_hal as hal;
pub use display_interface;
pub use display_interface_spi;
pub use st7789;
pub mod animated_st7789;
pub mod backlight;
pub mod battery_controller;
pub mod button;
pub mod cst816s;
pub mod lcd;
pub mod motor_controller;
pub mod watchdog;
|
use artell_domain::artist::{
ArtistId, ArtistRepository, {Artist, Error as ArtistDomainError},
};
pub struct Params {
pub name: String,
pub email: String,
pub status_msg: String,
pub description: String,
pub instagram: String,
pub twitter: String,
}
#[derive(Error, Debug)]
pub enum Error {
#[error("violate artist domain invariance rule. {0}")]
ArtistDomainInvarianceViolation(#[from] ArtistDomainError),
#[error(transparent)]
Others(#[from] anyhow::Error),
}
/// TODO
/// 認証
pub async fn admin_add_artist(
params: Params,
artist_repo: impl ArtistRepository,
) -> Result<ArtistId, Error> {
let Params {
name,
email,
status_msg,
description,
instagram,
twitter,
} = params;
let artist = Artist::new(name, email, status_msg, description, instagram, twitter)?;
let artist_id = artist.id;
artist_repo.save(artist).await?;
Ok(artist_id)
}
|
use actix::prelude::*;
use actix_web::{dev::Body, http::StatusCode, web::HttpResponse, ResponseError};
use diesel::prelude::*;
use diesel::sql_types::Integer;
use failure_derive::Fail;
use serde::Deserialize;
use crate::db::models::{NewHistory, Song};
use crate::db::schema::songs;
use crate::db::DbExecutor;
use crate::songs::{HistoryEntry, TopSong};
pub struct Recognize {
pub song_ids: Vec<i32>,
pub user_id: Option<i32>,
}
pub struct GetHistory {
pub user_id: Option<i32>,
}
pub struct GetMostPopular {
pub limit: u32,
}
/// Send empty vector to disable filtering.
#[derive(Deserialize)]
pub struct GetAllSongs {
pub genres: Vec<String>,
pub artists: Vec<String>,
#[serde(default)]
pub featured: Option<bool>,
}
pub struct EditSong {
pub song: Song,
}
#[derive(Deserialize, Insertable)]
#[table_name = "songs"]
pub struct AddSong {
pub artist: String,
pub title: String,
pub genre: String,
pub url: String,
}
pub struct GetAllGenres;
pub struct GetAllArtists;
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "Song was not found")]
NotFound,
#[fail(display = "Database error: {}", _0)]
DbError(#[cause] diesel::result::Error),
}
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse<Body> {
match self {
Error::DbError(_) => HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR),
Error::NotFound => HttpResponse::new(StatusCode::NOT_FOUND),
}
}
}
impl From<diesel::result::Error> for Error {
fn from(f: diesel::result::Error) -> Self {
Error::DbError(f)
}
}
impl Message for Recognize {
type Result = Result<Vec<Song>, Error>;
}
impl Handler<Recognize> for DbExecutor {
type Result = Result<Vec<Song>, Error>;
fn handle(&mut self, msg: Recognize, _: &mut Self::Context) -> Self::Result {
use super::schema::history::dsl::history;
use super::schema::songs::dsl::songs;
let mut sgs = Vec::new();
for song_id in &msg.song_ids {
sgs.push(songs.find(song_id).first(&self.0)?);
}
let history_entry = NewHistory {
song_id: msg.song_ids[0],
user_id: msg.user_id,
matched_at: chrono::offset::Utc::now().naive_utc(),
};
diesel::insert_into(history)
.values(&history_entry)
.execute(&self.0)?;
Ok(sgs)
}
}
impl Message for GetHistory {
type Result = Result<Vec<HistoryEntry>, Error>;
}
impl Handler<GetHistory> for DbExecutor {
type Result = Result<Vec<HistoryEntry>, Error>;
fn handle(&mut self, msg: GetHistory, _: &mut Self::Context) -> Self::Result {
use super::schema::history::dsl::{history, matched_at, song_id, user_id};
use super::schema::songs::dsl::{artist, genre, songs, title, url};
let entries = if let Some(uid) = msg.user_id {
history
.filter(user_id.eq(uid))
.inner_join(songs)
.select((song_id, artist, title, genre, url, matched_at))
.load::<HistoryEntry>(&self.0)?
} else {
history
.inner_join(songs)
.select((song_id, artist, title, genre, url, matched_at))
.load::<HistoryEntry>(&self.0)?
};
Ok(entries)
}
}
impl Message for GetMostPopular {
type Result = Result<Vec<TopSong>, Error>;
}
impl Handler<GetMostPopular> for DbExecutor {
type Result = Result<Vec<TopSong>, Error>;
fn handle(&mut self, msg: GetMostPopular, _: &mut Self::Context) -> Self::Result {
use super::schema::songs::dsl::{featured, songs};
let mut featured_songs = songs
.filter(featured.eq(true))
.load::<Song>(&self.0)?
.into_iter()
.map(|s| TopSong {
id: s.id,
artist: s.artist,
title: s.title,
genre: s.genre,
url: s.url,
cnt: 0,
})
.collect::<Vec<_>>();
let limit = (msg.limit as usize).saturating_sub(featured_songs.len());
let mut entries = diesel::sql_query(
"SELECT id, artist, title, genre, url, (
SELECT count(song_id) FROM history WHERE songs.id = song_id
) cnt
FROM songs
WHERE featured = FALSE
ORDER BY cnt DESC
LIMIT ?;",
)
.bind::<Integer, _>(limit as i32)
.load::<TopSong>(&self.0)?;
featured_songs.append(&mut entries);
Ok(featured_songs)
}
}
impl Message for GetAllSongs {
type Result = Result<Vec<Song>, Error>;
}
impl Handler<GetAllSongs> for DbExecutor {
type Result = Result<Vec<Song>, Error>;
fn handle(&mut self, msg: GetAllSongs, _: &mut Self::Context) -> Self::Result {
use super::schema::songs::dsl::{artist, featured, genre, songs};
let mut query = songs.into_boxed();
if !msg.artists.is_empty() {
query = query.filter(artist.eq_any(msg.artists));
}
if !msg.genres.is_empty() {
query = query.filter(genre.eq_any(msg.genres));
}
if let Some(is_featured) = msg.featured {
query = query.filter(featured.eq(is_featured));
}
Ok(query.load(&self.0)?)
}
}
impl Message for EditSong {
type Result = Result<(), Error>;
}
impl Handler<EditSong> for DbExecutor {
type Result = Result<(), Error>;
fn handle(&mut self, msg: EditSong, _: &mut Self::Context) -> Self::Result {
match msg.song.save_changes::<Song>(&self.0) {
Ok(_) => Ok(()),
Err(diesel::result::Error::NotFound) => Err(Error::NotFound),
Err(e) => Err(Error::DbError(e)),
}
}
}
impl Message for AddSong {
type Result = Result<Song, Error>;
}
impl Handler<AddSong> for DbExecutor {
type Result = Result<Song, Error>;
fn handle(&mut self, msg: AddSong, _: &mut Self::Context) -> Self::Result {
use super::schema::songs::dsl::{id, songs};
diesel::insert_into(songs).values(&msg).execute(&self.0)?;
Ok(songs.order(id.desc()).first(&self.0)?)
}
}
impl Message for GetAllGenres {
type Result = Result<Vec<String>, Error>;
}
impl Handler<GetAllGenres> for DbExecutor {
type Result = Result<Vec<String>, Error>;
fn handle(&mut self, _msg: GetAllGenres, _: &mut Self::Context) -> Self::Result {
use super::schema::songs::dsl::{genre, songs};
let entries = songs.select(genre).distinct().load(&self.0)?;
Ok(entries)
}
}
impl Message for GetAllArtists {
type Result = Result<Vec<String>, Error>;
}
impl Handler<GetAllArtists> for DbExecutor {
type Result = Result<Vec<String>, Error>;
fn handle(&mut self, _msg: GetAllArtists, _: &mut Self::Context) -> Self::Result {
use super::schema::songs::dsl::{artist, songs};
let entries = songs.select(artist).distinct().load(&self.0)?;
Ok(entries)
}
}
|
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
// This file was auto-created by LmcpGen. Modifications will be overwritten.
use avtas::lmcp::{Error, ErrorType, Lmcp, LmcpSubscription, SrcLoc, Struct, StructInfo};
use std::fmt::Debug;
#[derive(Clone, Debug, Default)]
#[repr(C)]
pub struct GraphEdge {
pub edge_id: i64,
pub start_node: i64,
pub end_node: i64,
pub waypoints: Vec<Box<::afrl::cmasi::location3d::Location3DT>>,
}
impl PartialEq for GraphEdge {
fn eq(&self, _other: &GraphEdge) -> bool {
true
&& &self.edge_id == &_other.edge_id
&& &self.start_node == &_other.start_node
&& &self.end_node == &_other.end_node
&& &self.waypoints == &_other.waypoints
}
}
impl LmcpSubscription for GraphEdge {
fn subscription() -> &'static str { "uxas.messages.route.GraphEdge" }
}
impl Struct for GraphEdge {
fn struct_info() -> StructInfo {
StructInfo {
exist: 1,
series: 5931053054693474304u64,
version: 4,
struct_ty: 2,
}
}
}
impl Lmcp for GraphEdge {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
let mut pos = 0;
{
let x = Self::struct_info().ser(buf)?;
pos += x;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.edge_id.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.start_node.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.end_node.ser(r)?;
pos += writeb;
}
{
let r = get!(buf.get_mut(pos ..));
let writeb: usize = self.waypoints.ser(r)?;
pos += writeb;
}
Ok(pos)
}
fn deser(buf: &[u8]) -> Result<(GraphEdge, usize), Error> {
let mut pos = 0;
let (si, u) = StructInfo::deser(buf)?;
pos += u;
if si == GraphEdge::struct_info() {
let mut out: GraphEdge = Default::default();
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.edge_id = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.start_node = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (i64, usize) = Lmcp::deser(r)?;
out.end_node = x;
pos += readb;
}
{
let r = get!(buf.get(pos ..));
let (x, readb): (Vec<Box<::afrl::cmasi::location3d::Location3DT>>, usize) = Lmcp::deser(r)?;
out.waypoints = x;
pos += readb;
}
Ok((out, pos))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
let mut size = 15;
size += self.edge_id.size();
size += self.start_node.size();
size += self.end_node.size();
size += self.waypoints.size();
size
}
}
pub trait GraphEdgeT: Debug + Send {
fn as_uxas_messages_route_graph_edge(&self) -> Option<&GraphEdge> { None }
fn as_mut_uxas_messages_route_graph_edge(&mut self) -> Option<&mut GraphEdge> { None }
fn edge_id(&self) -> i64;
fn edge_id_mut(&mut self) -> &mut i64;
fn start_node(&self) -> i64;
fn start_node_mut(&mut self) -> &mut i64;
fn end_node(&self) -> i64;
fn end_node_mut(&mut self) -> &mut i64;
fn waypoints(&self) -> &Vec<Box<::afrl::cmasi::location3d::Location3DT>>;
fn waypoints_mut(&mut self) -> &mut Vec<Box<::afrl::cmasi::location3d::Location3DT>>;
}
impl Clone for Box<GraphEdgeT> {
fn clone(&self) -> Box<GraphEdgeT> {
if let Some(x) = GraphEdgeT::as_uxas_messages_route_graph_edge(self.as_ref()) {
Box::new(x.clone())
} else {
unreachable!()
}
}
}
impl Default for Box<GraphEdgeT> {
fn default() -> Box<GraphEdgeT> { Box::new(GraphEdge::default()) }
}
impl PartialEq for Box<GraphEdgeT> {
fn eq(&self, other: &Box<GraphEdgeT>) -> bool {
if let (Some(x), Some(y)) =
(GraphEdgeT::as_uxas_messages_route_graph_edge(self.as_ref()),
GraphEdgeT::as_uxas_messages_route_graph_edge(other.as_ref())) {
x == y
} else {
false
}
}
}
impl Lmcp for Box<GraphEdgeT> {
fn ser(&self, buf: &mut[u8]) -> Result<usize, Error> {
if let Some(x) = GraphEdgeT::as_uxas_messages_route_graph_edge(self.as_ref()) {
x.ser(buf)
} else {
unreachable!()
}
}
fn deser(buf: &[u8]) -> Result<(Box<GraphEdgeT>, usize), Error> {
let (si, _) = StructInfo::deser(buf)?;
if si == GraphEdge::struct_info() {
let (x, readb) = GraphEdge::deser(buf)?;
Ok((Box::new(x), readb))
} else {
Err(error!(ErrorType::InvalidStructInfo))
}
}
fn size(&self) -> usize {
if let Some(x) = GraphEdgeT::as_uxas_messages_route_graph_edge(self.as_ref()) {
x.size()
} else {
unreachable!()
}
}
}
impl GraphEdgeT for GraphEdge {
fn as_uxas_messages_route_graph_edge(&self) -> Option<&GraphEdge> { Some(self) }
fn as_mut_uxas_messages_route_graph_edge(&mut self) -> Option<&mut GraphEdge> { Some(self) }
fn edge_id(&self) -> i64 { self.edge_id }
fn edge_id_mut(&mut self) -> &mut i64 { &mut self.edge_id }
fn start_node(&self) -> i64 { self.start_node }
fn start_node_mut(&mut self) -> &mut i64 { &mut self.start_node }
fn end_node(&self) -> i64 { self.end_node }
fn end_node_mut(&mut self) -> &mut i64 { &mut self.end_node }
fn waypoints(&self) -> &Vec<Box<::afrl::cmasi::location3d::Location3DT>> { &self.waypoints }
fn waypoints_mut(&mut self) -> &mut Vec<Box<::afrl::cmasi::location3d::Location3DT>> { &mut self.waypoints }
}
#[cfg(test)]
pub mod tests {
use super::*;
use quickcheck::*;
impl Arbitrary for GraphEdge {
fn arbitrary<G: Gen>(_g: &mut G) -> GraphEdge {
GraphEdge {
edge_id: Arbitrary::arbitrary(_g),
start_node: Arbitrary::arbitrary(_g),
end_node: Arbitrary::arbitrary(_g),
waypoints: Vec::<::afrl::cmasi::location3d::Location3D>::arbitrary(_g).into_iter().map(|x| Box::new(x) as Box<::afrl::cmasi::location3d::Location3DT>).collect(),
}
}
}
quickcheck! {
fn serializes(x: GraphEdge) -> Result<TestResult, Error> {
use std::u16;
if x.waypoints.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
Ok(TestResult::from_bool(sx == x.size()))
}
fn roundtrips(x: GraphEdge) -> Result<TestResult, Error> {
use std::u16;
if x.waypoints.len() > (u16::MAX as usize) { return Ok(TestResult::discard()); }
let mut buf: Vec<u8> = vec![0; x.size()];
let sx = x.ser(&mut buf)?;
let (y, sy) = GraphEdge::deser(&buf)?;
Ok(TestResult::from_bool(sx == sy && x == y))
}
}
}
|
#![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 AppProperties {
#[serde(rename = "applicationId", default, skip_serializing_if = "Option::is_none")]
pub application_id: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subdomain: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppSkuInfo {
pub name: app_sku_info::Name,
}
pub mod app_sku_info {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
F1,
S1,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct App {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AppProperties>,
pub sku: AppSkuInfo,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppPatch {
#[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<AppProperties>,
}
#[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 ErrorDetails {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppListResult {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<App>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplay>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplay {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationInputs {
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppNameAvailabilityInfo {
#[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")]
pub name_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<app_name_availability_info::Reason>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
pub mod app_name_availability_info {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Reason {
Invalid,
AlreadyExists,
}
}
|
#![feature(try_trait)]
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate gl;
mod gl_shaders;
mod gl_buffer;
mod gl_framebuffer;
mod gl_vertex_array;
mod gl_texture;
mod gl_err;
mod shader;
mod gl_render;
pub use gl_shaders::AttribInfo;
pub use gl_shaders::UniformInfo;
pub use gl_shaders::GlShader;
pub use gl_shaders::GlShaderUniform;
pub use gl_buffer::GlBufferRaw;
pub use gl_buffer::GlBufferElementType;
pub use gl_buffer::GlBuffer;
pub use gl_buffer::GlIndexBuffer;
pub use gl_framebuffer::GlFramebuffer;
pub use gl_vertex_array::GlVertexArray;
pub use gl_vertex_array::GlVertexArrayTmp;
pub use gl_vertex_array::HasGlVertexArrayHandle;
pub use gl_texture::GlTexture;
pub use gl_render::RenderTarget;
pub use gl_render::render;
pub use gl_render::render_indexed;
pub use gl_render::clear;
pub use gl_err::validate_gl;
pub use gl_err::GlError;
pub use shader::Shader;
|
use futures_01::future::Future as Future01;
use futures_01::stream::Stream as Stream01;
use futures_01::Poll as Poll01;
use futures_util::compat::Compat;
use futures_util::stream::Stream;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio_02::time::Sleep as Delay2;
use tokio_stream::wrappers::IntervalStream;
pub use tokio_02::time::Instant;
pub use tokio_timer_02::Error;
pub use crate::timeout::Timeout;
struct PhantomError<S, E> {
phantom: PhantomData<fn() -> E>,
inner: S,
}
impl<S, E> PhantomError<S, E> {
fn get_mut(&mut self) -> &mut S {
&mut self.inner
}
fn get(&self) -> &S {
&self.inner
}
}
impl<S, E> futures_util::stream::Stream for PhantomError<S, E>
where
S: Stream + Unpin,
{
type Item = Result<S::Item, E>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> std::task::Poll<Option<Self::Item>> {
let inner = Pin::into_inner(self);
let stream = Pin::new(&mut inner.inner);
match stream.poll_next(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(Some(val)) => Poll::Ready(Some(Ok(val))),
Poll::Ready(None) => Poll::Ready(None),
}
}
}
impl<F, E> std::future::Future for PhantomError<F, E>
where
F: std::future::Future + Unpin,
{
type Output = Result<F::Output, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> std::task::Poll<Self::Output> {
let inner = Pin::into_inner(self);
let stream = Pin::new(&mut inner.inner);
match stream.poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(val) => Poll::Ready(Ok(val)),
}
}
}
pub struct Interval(Compat<PhantomError<IntervalStream, tokio_timer_02::Error>>);
impl Interval {
pub fn new_interval(duration: std::time::Duration) -> Self {
Interval(Compat::new(PhantomError {
inner: IntervalStream::new(tokio_02::time::interval(duration)),
phantom: PhantomData,
}))
}
}
impl Stream01 for Interval {
type Item = tokio_02::time::Instant;
type Error = tokio_timer_02::Error;
fn poll(&mut self) -> Poll01<Option<Self::Item>, Self::Error> {
self.0.poll()
}
}
pub struct Delay {
inner: Compat<PhantomError<Pin<Box<Delay2>>, tokio_timer_02::Error>>,
}
impl Delay {
pub fn new(instant: Instant) -> Delay {
Delay {
inner: Compat::new(PhantomError {
inner: Box::pin(tokio_02::time::sleep_until(instant)),
phantom: PhantomData,
}),
}
}
pub fn deadline(&self) -> Instant {
self.inner.get_ref().get().deadline()
}
pub fn reset(&mut self, deadline: Instant) {
self.inner.get_mut().get_mut().as_mut().reset(deadline)
}
}
impl Future01 for Delay {
type Item = ();
type Error = tokio_timer_02::Error;
fn poll(&mut self) -> Poll01<Self::Item, Self::Error> {
self.inner.poll()
}
}
|
use crate::chunk::ChunkGridCoordinate;
use math::random::Seed;
use std::num::Wrapping;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct WorldSeed(pub Seed);
impl WorldSeed {
pub fn new() -> Self {
Self(Seed::new())
}
pub fn to_chunk_seed(&self, coords: ChunkGridCoordinate) -> ChunkSeed {
ChunkSeed::new(&self.0, coords)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ChunkSeed(pub Seed);
impl ChunkSeed {
pub fn new(seed: &Seed, coords: ChunkGridCoordinate) -> Self {
// https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function
let k1 = Wrapping(coords.x as u64);
let k2 = Wrapping(coords.z as u64);
let value = Wrapping(((k1 + k2) * (k1 + k2 + Wrapping(1))).0 / 2) + k2;
let seed = Wrapping(seed.0 as u64);
Self(Seed(((seed + value).0 & 0xffffffff) as u32))
}
}
|
mod opening;
pub mod puzzle;
pub mod reverse_amazon_search;
pub(crate) mod tree;
/// Analysis methods for paco sako. This can be used to analyze a game and
/// give information about interesting moments. E.g. missed opportunities.
use serde::Serialize;
use crate::{
determine_all_threats, BoardPosition, DenseBoard, Hand, PacoAction, PacoBoard, PacoError,
PieceType, PlayerColor,
};
#[derive(Serialize, PartialEq, Eq, Debug)]
pub struct ReplayData {
notation: Vec<HalfMove>,
opening: String,
}
/// Represents a single line in the sidebar, like "g2>Pf3>Pe4>Pd5>d6".
/// This would be represented as [g2>Pf3][>Pe4][>Pd5][>d6].
/// Where each section also points to the action index to jump there easily.
#[derive(Serialize, PartialEq, Eq, Debug)]
pub struct HalfMove {
move_number: u32,
current_player: PlayerColor,
actions: Vec<HalfMoveSection>,
metadata: HalfMoveMetadata,
}
/// Represents a single section in a half move. Like [g2>Pf3].
#[derive(Serialize, PartialEq, Eq, Debug)]
pub struct HalfMoveSection {
action_index: usize,
label: String,
}
#[derive(Serialize, PartialEq, Eq, Debug)]
pub struct HalfMoveMetadata {
gives_sako: bool,
missed_paco: bool,
/// If you make a move that ends with yourself in Ŝako even if you didn't start there.
gives_opponent_paco_opportunity: bool,
}
/// Metadata with all flags set to false.
impl Default for HalfMoveMetadata {
fn default() -> Self {
HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
}
}
/// A notation atom roughly corresponds to a Sako.Action but carries more metadata.
#[derive(Debug, Clone)]
pub(crate) enum NotationAtom {
StartMoveSinge {
mover: PieceType,
at: BoardPosition,
},
StartMoveUnion {
mover: PieceType,
partner: PieceType,
at: BoardPosition,
},
ContinueChain {
exchanged: PieceType,
at: BoardPosition,
},
EndMoveCalm {
at: BoardPosition,
},
EndMoveFormUnion {
partner: PieceType,
at: BoardPosition,
},
Promote {
to: PieceType,
},
}
impl NotationAtom {
fn is_place(&self) -> bool {
matches!(
self,
NotationAtom::ContinueChain { .. }
| NotationAtom::EndMoveCalm { .. }
| NotationAtom::EndMoveFormUnion { .. }
)
}
fn is_lift(&self) -> bool {
matches!(
self,
NotationAtom::StartMoveSinge { .. } | NotationAtom::StartMoveUnion { .. }
)
}
}
impl ToString for NotationAtom {
fn to_string(&self) -> String {
match self {
NotationAtom::StartMoveSinge { mover, at } => format!("{}{}", letter(mover), at),
NotationAtom::StartMoveUnion { mover, partner, at } => {
format!("{}{}{}", force_letter(mover), force_letter(partner), at)
}
NotationAtom::ContinueChain { exchanged, at } => {
format!(">{}{}", force_letter(exchanged), at)
}
NotationAtom::EndMoveCalm { at } => format!(">{}", at),
NotationAtom::EndMoveFormUnion { partner, at } => {
format!("x{}{}", letter(partner), at)
}
NotationAtom::Promote { to } => format!("={}", letter(to)),
}
}
}
/// Turns a piece type into a letter, where Pawn is left out.
fn letter(piece: &PieceType) -> &str {
match piece {
PieceType::Pawn => "",
PieceType::Knight => "N",
PieceType::Bishop => "B",
PieceType::Rook => "R",
PieceType::Queen => "Q",
PieceType::King => "K",
}
}
/// Turns a piece type into a letter, where Pawn is printed as "P".
/// I'm calling it "force" because it feels like the "-f" variant of letter.
fn force_letter(piece: &PieceType) -> &str {
match piece {
PieceType::Pawn => "P",
_ => letter(piece),
}
}
// Applies an action and returns information about what happened.
fn apply_action_semantically(
board: &mut DenseBoard,
action: PacoAction,
) -> Result<NotationAtom, PacoError> {
match action {
PacoAction::Lift(_) => {
board.execute(action)?;
match board.lifted_piece {
Hand::Empty => Err(PacoError::LiftEmptyPosition),
Hand::Single { piece, position } => Ok(NotationAtom::StartMoveSinge {
mover: piece,
at: position,
}),
Hand::Pair {
piece,
partner,
position,
} => Ok(NotationAtom::StartMoveUnion {
mover: piece,
partner,
at: position,
}),
}
}
PacoAction::Place(at) => {
// Remember the opponents piece that is at the target position.
let &partner = board.opponent_pieces().get(at.0 as usize).unwrap();
board.execute(action)?;
match board.lifted_piece {
Hand::Empty => {
if let Some(partner) = partner {
Ok(NotationAtom::EndMoveFormUnion { partner, at })
} else {
Ok(NotationAtom::EndMoveCalm { at })
}
}
Hand::Single { piece, position } => Ok(NotationAtom::ContinueChain {
exchanged: piece,
at: position,
}),
Hand::Pair { .. } => Err(PacoError::PlacePairFullPosition),
}
}
PacoAction::Promote(to) => {
board.execute(action)?;
Ok(NotationAtom::Promote { to })
}
}
}
/// Turns a list of notation atoms into a list of sections.
/// the initial 2-move is combined into a single section.
fn squash_notation_atoms(initial_index: usize, atoms: Vec<NotationAtom>) -> Vec<HalfMoveSection> {
let mut result: Vec<HalfMoveSection> = Vec::new();
let mut already_squashed = false;
// Stores the king's original position to detect castling.
let mut potentially_castling = None;
'atom_loop: for (i, atom) in atoms.iter().enumerate() {
if let NotationAtom::StartMoveSinge {
mover: PieceType::King,
at,
} = atom
{
potentially_castling = Some(*at);
}
if potentially_castling.is_some() && atom.is_place() {
if let NotationAtom::EndMoveCalm { at } = atom {
// This can never happen when the result is empty, so we can unwrap.
let last = result.last_mut().unwrap();
let from = potentially_castling.unwrap().0 as i8;
let to = at.0 as i8;
if to - from == 2 {
last.label = "0-0".to_string();
last.action_index = i + initial_index + 1;
already_squashed = true;
continue 'atom_loop;
}
if to - from == -2 {
last.label = "0-0-0".to_string();
last.action_index = i + initial_index + 1;
already_squashed = true;
continue 'atom_loop;
}
}
// Otherwise, we just continue, this is a regular King movement.
}
if !already_squashed && atom.is_place() {
// This can never happen when the result is empty, so we can unwrap.
let last = result.last_mut().unwrap();
last.label.push_str(&atom.to_string());
last.action_index = i + initial_index + 1;
already_squashed = true;
} else if atom.is_lift() && i >= 1 {
result.push(HalfMoveSection {
action_index: i + initial_index + 1,
label: format!(":{}", atom.to_string()),
});
} else {
result.push(HalfMoveSection {
action_index: i + initial_index + 1,
label: atom.to_string(),
});
}
}
result
}
pub fn history_to_replay_notation(
initial_board: DenseBoard,
actions: &[PacoAction],
) -> Result<ReplayData, PacoError> {
let mut half_moves = Vec::with_capacity(actions.len() / 2);
let mut initial_index = 0;
let mut move_count = 1;
let mut current_player = initial_board.controlling_player();
let mut current_half_move = HalfMove {
move_number: move_count,
current_player,
actions: Vec::new(),
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
},
};
let mut board = initial_board.clone();
let mut giving_sako_before_move = is_sako(&board, board.controlling_player())?;
let mut in_sako_before_move = is_sako(&board, board.controlling_player().other())?;
// Pick moves off the stack and add them to the current half move.
// This vector collects notation atoms and then gets turned into a HalfMove
// when the current player changes. (Or game is over)
let mut notations = Vec::new();
for (action_index, &action) in actions.iter().enumerate() {
let notation = apply_action_semantically(&mut board, action)?;
notations.push(notation);
if board.controlling_player() != current_player || board.victory_state.is_over() {
// analyze situation, finalize half move, change color
let giving_sako_after_move = is_sako(&board, current_player)?;
let in_sako_after_move = is_sako(&board, current_player.other())?;
current_half_move.metadata = HalfMoveMetadata {
gives_sako: giving_sako_after_move,
missed_paco: giving_sako_before_move && !board.victory_state().is_over(),
gives_opponent_paco_opportunity: !in_sako_before_move && in_sako_after_move,
};
current_half_move.actions =
squash_notation_atoms(initial_index, std::mem::take(&mut notations));
half_moves.push(current_half_move);
if board.controlling_player() == PlayerColor::White {
move_count += 1;
}
current_player = board.controlling_player();
initial_index = action_index + 1;
current_half_move = HalfMove {
move_number: move_count,
current_player,
actions: Vec::new(),
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
},
};
giving_sako_before_move = in_sako_after_move;
in_sako_before_move = giving_sako_after_move
}
}
Ok(ReplayData {
notation: half_moves,
opening: opening::classify_opening(&initial_board, actions)?,
})
}
pub fn is_sako(board: &DenseBoard, for_player: PlayerColor) -> Result<bool, PacoError> {
// If the game is already over, we don't need to check for ŝako.
if board.victory_state().is_over() {
return Ok(false);
}
let mut board = board.clone();
if board.required_action.is_promote() {
board.execute(PacoAction::Promote(PieceType::Queen))?;
}
board.controlling_player = for_player;
let threats = determine_all_threats(&board)?;
for (pos, _) in threats
.iter()
.enumerate()
.filter(|(_, is_threatened)| is_threatened.0)
{
// Check if the opponents king is on this square.
let piece = board.opponent_pieces().get(pos).unwrap();
if piece == &Some(PieceType::King) {
return Ok(true);
}
}
Ok(false)
}
// Test module
#[cfg(test)]
mod tests {
use crate::fen;
use super::*;
#[test]
fn empty_list() {
let replay =
history_to_replay_notation(DenseBoard::new(), &[]).expect("Error in input data");
assert_eq!(replay.notation, vec![]);
}
#[test]
fn notation_compile_simple_move() {
let replay = history_to_replay_notation(
DenseBoard::new(),
&[
PacoAction::Lift("d2".try_into().unwrap()),
PacoAction::Place("d4".try_into().unwrap()),
],
)
.expect("Error in input data");
assert_eq!(
replay.notation,
vec![HalfMove {
move_number: 1,
current_player: PlayerColor::White,
actions: vec![HalfMoveSection {
action_index: 2,
label: "d2>d4".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
}]
);
}
#[test]
fn chain_and_union_move() {
let replay = history_to_replay_notation(
DenseBoard::new(),
&[
PacoAction::Lift("e2".try_into().unwrap()),
PacoAction::Place("e4".try_into().unwrap()),
PacoAction::Lift("d7".try_into().unwrap()),
PacoAction::Place("d5".try_into().unwrap()),
PacoAction::Lift("e4".try_into().unwrap()),
PacoAction::Place("d5".try_into().unwrap()),
PacoAction::Lift("d8".try_into().unwrap()),
PacoAction::Place("d5".try_into().unwrap()),
PacoAction::Place("d4".try_into().unwrap()),
],
)
.expect("Error in input data");
assert_eq!(
replay.notation,
vec![
HalfMove {
move_number: 1,
current_player: PlayerColor::White,
actions: vec![HalfMoveSection {
action_index: 2,
label: "e2>e4".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
HalfMove {
move_number: 1,
current_player: PlayerColor::Black,
actions: vec![HalfMoveSection {
action_index: 4,
label: "d7>d5".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
HalfMove {
move_number: 2,
current_player: PlayerColor::White,
actions: vec![HalfMoveSection {
action_index: 6,
label: "e4xd5".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
HalfMove {
move_number: 2,
current_player: PlayerColor::Black,
actions: vec![
HalfMoveSection {
action_index: 8,
label: "Qd8>Pd5".to_string(),
},
HalfMoveSection {
action_index: 9,
label: ">d4".to_string(),
},
],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
}
]
);
}
#[test]
fn start_move_with_promotion() {
let setup = "rnbqkbn1/pppppp2/5p2/5p2/8/8/PPPPPPPC/RNBQKBNR b 0 AHah - -";
let initial_board = fen::parse_fen(setup).unwrap();
let replay = history_to_replay_notation(
initial_board,
&[
PacoAction::Lift("h2".try_into().unwrap()),
PacoAction::Place("h8".try_into().unwrap()),
PacoAction::Promote(PieceType::Knight),
PacoAction::Lift("h1".try_into().unwrap()),
PacoAction::Place("h8".try_into().unwrap()),
PacoAction::Place("g6".try_into().unwrap()),
],
)
.expect("Error in input data");
assert_eq!(
replay.notation,
vec![
HalfMove {
move_number: 1,
current_player: PlayerColor::Black,
actions: vec![HalfMoveSection {
action_index: 2,
label: "RPh2>h8".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
HalfMove {
move_number: 2,
current_player: PlayerColor::White,
actions: vec![
HalfMoveSection {
action_index: 3,
label: "=N".to_string(),
},
HalfMoveSection {
action_index: 5,
label: ":Rh1>Nh8".to_string(),
},
HalfMoveSection {
action_index: 6,
label: ">g6".to_string(),
},
],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
]
);
}
#[test]
fn test_castling_notation() {
let setup = "r3kbnr/ppp2ppp/2n5/1B1pp3/1PP1P1bq/5N2/P2P1PPP/RNBQK2R w 0 AHah - -";
let initial_board = fen::parse_fen(setup).unwrap();
let replay = history_to_replay_notation(
initial_board,
&[
PacoAction::Lift("e1".try_into().unwrap()),
PacoAction::Place("g1".try_into().unwrap()),
PacoAction::Lift("e8".try_into().unwrap()),
PacoAction::Place("c8".try_into().unwrap()),
PacoAction::Lift("g1".try_into().unwrap()),
PacoAction::Place("h1".try_into().unwrap()),
PacoAction::Lift("c8".try_into().unwrap()),
PacoAction::Place("d7".try_into().unwrap()),
],
)
.expect("Error in input data");
assert_eq!(
replay.notation,
vec![
HalfMove {
move_number: 1,
current_player: PlayerColor::White,
actions: vec![HalfMoveSection {
action_index: 2,
label: "0-0".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
HalfMove {
move_number: 1,
current_player: PlayerColor::Black,
actions: vec![HalfMoveSection {
action_index: 4,
label: "0-0-0".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
HalfMove {
move_number: 2,
current_player: PlayerColor::White,
actions: vec![HalfMoveSection {
action_index: 6,
label: "Kg1>h1".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
HalfMove {
move_number: 2,
current_player: PlayerColor::Black,
actions: vec![HalfMoveSection {
action_index: 8,
label: "Kc8>d7".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: false,
}
},
]
);
}
// Moves a pinned piece out of the way, giving the opponent a chance to paco.
#[test]
fn gives_opponent_paco_opportunity() {
let setup = "r1bqkbnr/ppp1pppp/2n5/1B1p4/3PP3/8/PPP2PPP/RNBQK1NR b 0 AHah - -";
let initial_board = fen::parse_fen(setup).unwrap();
let replay = history_to_replay_notation(
initial_board,
&[
PacoAction::Lift("c6".try_into().unwrap()),
PacoAction::Place("d4".try_into().unwrap()),
],
)
.expect("Error in input data");
assert_eq!(
replay.notation,
vec![HalfMove {
move_number: 1,
current_player: PlayerColor::Black,
actions: vec![HalfMoveSection {
action_index: 2,
label: "Nc6xd4".to_string(),
},],
metadata: HalfMoveMetadata {
gives_sako: false,
missed_paco: false,
gives_opponent_paco_opportunity: true,
}
},]
);
}
// TODO: Add an integration test were we test all games that were ever played.
}
|
static MAX_HEALTH: i32 = 100;
static GAME_NAME: &'static str = "Monster Attack";
fn main() {
}
|
use bitflags;
use std::path::PathBuf;
use std::{ffi::OsStr, fs};
pub struct Config {
pub files: Vec<PathBuf>,
pub print_flags: PrintFlags,
}
impl Config {
pub fn new(input_path: PathBuf, print_flags: PrintFlags, do_file: bool) -> Result<Config, &'static str> {
let mut config = Config {
files: Vec::new(),
print_flags,
};
if input_path.exists() == false {
return Err("Filepath given does not exist.");
}
match (input_path.is_dir(), do_file) {
(true, true) => {
return Err("Passed -f or --file but gave a directory filepath.");
}
(true, false) => {
fn take_in_gml_files(directory_path: &PathBuf, config: &mut Config) {
let gml_name = OsStr::new("gml");
for entry in
fs::read_dir(directory_path).expect(&format!("Error reading directory {:?}.", directory_path))
{
let entry = entry.expect(&format!("Error reading file"));
let path = entry.path();
if path.is_dir() == false {
if path.extension() == Some(gml_name) {
config.load_file_path(path);
}
} else {
take_in_gml_files(&path, config);
}
}
}
take_in_gml_files(&input_path, &mut config);
}
(false, true) => {
config.load_file_path(input_path);
}
(false, false) => {
return Err("Did not pass -f but gave a filepath. Pass -f for files.");
}
};
Ok(config)
}
pub fn load_file_path(&mut self, path: PathBuf) {
self.files.push(path);
}
}
bitflags::bitflags! {
pub struct PrintFlags: u8 {
const OVERWRITE = 0b001;
const LOGS = 0b010;
const LOG_AST = 0b100;
}
}
|
///// chapter 2 "using variables and types"
///// program section:
//
fn main() {
let health = 32;
let y = &health;
println!("{}", y);
// let tricks = 10;
// let reftricks = &mut tricks;
let mut score1 = 0;
// let score2 = &score;
let score3 = &mut score1;
println!("{}", score3);
*score3 = 5;
println!("{}", score3);
// let score4 = &mut score;
}
///// output should be:
/*
32
0
5
*/// end of output
|
#[doc = "Register `RTCCR` reader"]
pub type R = crate::R<RTCCR_SPEC>;
#[doc = "Register `RTCCR` writer"]
pub type W = crate::W<RTCCR_SPEC>;
#[doc = "Field `CAL` reader - Calibration value"]
pub type CAL_R = crate::FieldReader;
#[doc = "Field `CAL` writer - Calibration value"]
pub type CAL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>;
#[doc = "Field `CCO` reader - Calibration Clock Output"]
pub type CCO_R = crate::BitReader;
#[doc = "Field `CCO` writer - Calibration Clock Output"]
pub type CCO_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ASOE` reader - Alarm or second output enable"]
pub type ASOE_R = crate::BitReader<ASOE_A>;
#[doc = "Alarm or second output enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ASOE_A {
#[doc = "0: Disabled"]
Disabled = 0,
#[doc = "1: Setting this bit outputs either the RTC Alarm pulse signal or the Second pulse signal on the TAMPER pin depending on the ASOS bit"]
Enabled = 1,
}
impl From<ASOE_A> for bool {
#[inline(always)]
fn from(variant: ASOE_A) -> Self {
variant as u8 != 0
}
}
impl ASOE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ASOE_A {
match self.bits {
false => ASOE_A::Disabled,
true => ASOE_A::Enabled,
}
}
#[doc = "Disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ASOE_A::Disabled
}
#[doc = "Setting this bit outputs either the RTC Alarm pulse signal or the Second pulse signal on the TAMPER pin depending on the ASOS bit"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ASOE_A::Enabled
}
}
#[doc = "Field `ASOE` writer - Alarm or second output enable"]
pub type ASOE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ASOE_A>;
impl<'a, REG, const O: u8> ASOE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(ASOE_A::Disabled)
}
#[doc = "Setting this bit outputs either the RTC Alarm pulse signal or the Second pulse signal on the TAMPER pin depending on the ASOS bit"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(ASOE_A::Enabled)
}
}
#[doc = "Field `ASOS` reader - Alarm or second output selection"]
pub type ASOS_R = crate::BitReader<ASOS_A>;
#[doc = "Alarm or second output selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ASOS_A {
#[doc = "0: RTC Alarm pulse output selected"]
Alarm = 0,
#[doc = "1: RTC Second pulse output selected"]
Second = 1,
}
impl From<ASOS_A> for bool {
#[inline(always)]
fn from(variant: ASOS_A) -> Self {
variant as u8 != 0
}
}
impl ASOS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ASOS_A {
match self.bits {
false => ASOS_A::Alarm,
true => ASOS_A::Second,
}
}
#[doc = "RTC Alarm pulse output selected"]
#[inline(always)]
pub fn is_alarm(&self) -> bool {
*self == ASOS_A::Alarm
}
#[doc = "RTC Second pulse output selected"]
#[inline(always)]
pub fn is_second(&self) -> bool {
*self == ASOS_A::Second
}
}
#[doc = "Field `ASOS` writer - Alarm or second output selection"]
pub type ASOS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ASOS_A>;
impl<'a, REG, const O: u8> ASOS_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "RTC Alarm pulse output selected"]
#[inline(always)]
pub fn alarm(self) -> &'a mut crate::W<REG> {
self.variant(ASOS_A::Alarm)
}
#[doc = "RTC Second pulse output selected"]
#[inline(always)]
pub fn second(self) -> &'a mut crate::W<REG> {
self.variant(ASOS_A::Second)
}
}
impl R {
#[doc = "Bits 0:6 - Calibration value"]
#[inline(always)]
pub fn cal(&self) -> CAL_R {
CAL_R::new((self.bits & 0x7f) as u8)
}
#[doc = "Bit 7 - Calibration Clock Output"]
#[inline(always)]
pub fn cco(&self) -> CCO_R {
CCO_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - Alarm or second output enable"]
#[inline(always)]
pub fn asoe(&self) -> ASOE_R {
ASOE_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Alarm or second output selection"]
#[inline(always)]
pub fn asos(&self) -> ASOS_R {
ASOS_R::new(((self.bits >> 9) & 1) != 0)
}
}
impl W {
#[doc = "Bits 0:6 - Calibration value"]
#[inline(always)]
#[must_use]
pub fn cal(&mut self) -> CAL_W<RTCCR_SPEC, 0> {
CAL_W::new(self)
}
#[doc = "Bit 7 - Calibration Clock Output"]
#[inline(always)]
#[must_use]
pub fn cco(&mut self) -> CCO_W<RTCCR_SPEC, 7> {
CCO_W::new(self)
}
#[doc = "Bit 8 - Alarm or second output enable"]
#[inline(always)]
#[must_use]
pub fn asoe(&mut self) -> ASOE_W<RTCCR_SPEC, 8> {
ASOE_W::new(self)
}
#[doc = "Bit 9 - Alarm or second output selection"]
#[inline(always)]
#[must_use]
pub fn asos(&mut self) -> ASOS_W<RTCCR_SPEC, 9> {
ASOS_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 = "RTC clock calibration register (BKP_RTCCR)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rtccr::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 [`rtccr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RTCCR_SPEC;
impl crate::RegisterSpec for RTCCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rtccr::R`](R) reader structure"]
impl crate::Readable for RTCCR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rtccr::W`](W) writer structure"]
impl crate::Writable for RTCCR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RTCCR to value 0"]
impl crate::Resettable for RTCCR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use lspower::lsp::{self, notification::Notification};
use serde::{Deserialize, Serialize};
use strum_macros::{Display, EnumIter};
#[derive(EnumIter)]
pub enum LspServerCommand {
CompositionInitialize,
SetMeasurementFilter,
AddFieldFilter,
RemoveFieldFilter,
AddTagValueFilter,
RemoveTagValueFilter,
GetFunctionList,
}
impl TryFrom<String> for LspServerCommand {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
match value.as_str() {
"fluxComposition/initialize" => {
Ok(LspServerCommand::CompositionInitialize)
}
"fluxComposition/setMeasurementFilter" => {
Ok(LspServerCommand::SetMeasurementFilter)
}
"fluxComposition/addFieldFilter" => {
Ok(LspServerCommand::AddFieldFilter)
}
"fluxComposition/addTagValueFilter" => {
Ok(LspServerCommand::AddTagValueFilter)
}
"fluxComposition/removeFieldFilter" => {
Ok(LspServerCommand::RemoveFieldFilter)
}
"fluxComposition/removeTagValueFilter" => {
Ok(LspServerCommand::RemoveTagValueFilter)
}
"getFunctionList" => {
Ok(LspServerCommand::GetFunctionList)
}
_ => Err(format!(
"Received unknown value for LspServerCommand: {}",
value
)),
}
}
}
impl From<LspServerCommand> for String {
fn from(value: LspServerCommand) -> Self {
match value {
LspServerCommand::CompositionInitialize => {
"fluxComposition/initialize".into()
}
LspServerCommand::SetMeasurementFilter => {
"fluxComposition/setMeasurementFilter".into()
}
LspServerCommand::AddFieldFilter => {
"fluxComposition/addFieldFilter".into()
}
LspServerCommand::AddTagValueFilter => {
"fluxComposition/addTagValueFilter".into()
}
LspServerCommand::RemoveFieldFilter => {
"fluxComposition/removeFieldFilter".into()
}
LspServerCommand::RemoveTagValueFilter => {
"fluxComposition/removeTagValueFilter".into()
}
LspServerCommand::GetFunctionList => {
"getFunctionList".into()
}
}
}
}
pub struct ClientCommandNotification;
impl Notification for ClientCommandNotification {
type Params = lsp::ShowMessageRequestParams;
const METHOD: &'static str = "window/showMessageRequest";
}
#[derive(Debug)]
pub enum LspClientCommand {
UpdateComposition,
CompositionDropped,
CompositionNotFound,
ExecuteCommandFailed,
AlreadyExists,
}
impl ToString for LspClientCommand {
fn to_string(&self) -> String {
match &self {
LspClientCommand::UpdateComposition => {
"fluxComposition/compositionState".into()
}
LspClientCommand::CompositionDropped => {
"fluxComposition/compositionEnded".into()
}
LspClientCommand::CompositionNotFound => {
"fluxComposition/compositionNotFound".into()
}
LspClientCommand::ExecuteCommandFailed => {
"fluxComposition/executeCommandFailed".into()
}
LspClientCommand::AlreadyExists => {
"fluxComposition/alreadyInitialized".into()
}
}
}
}
#[derive(Debug, Display)]
pub enum LspMessageActionItem {
CompositionRange,
CompositionState,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompositionInitializeParams {
pub text_document: lsp::TextDocumentIdentifier,
pub bucket: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub measurement: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fields: Option<Vec<String>>,
#[deprecated(
since = "0.8.36",
note = "tag filters are no longer supported"
)]
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tag_values: Option<Vec<(String, String)>>,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ValueFilterParams {
pub text_document: lsp::TextDocumentIdentifier,
pub value: String,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TagValueFilterParams {
pub text_document: lsp::TextDocumentIdentifier,
pub tag: String,
pub value: String,
}
|
pub struct Ray3 {
origin: Vec3<f32>;
direction: Vec3<f32>;
} |
use std::env;
use std::path::Path;
use tantivy::collector::TopDocs;
use tantivy::query::QueryParser;
use tantivy::schema::*;
use tantivy::schema::{Schema, STORED, TEXT};
use tantivy::{Index, ReloadPolicy};
fn create_schema() -> Schema {
let mut schema_builder = Schema::builder();
schema_builder.add_text_field("title", TEXT | STORED);
schema_builder.add_u64_field("id", FAST | STORED);
schema_builder.build()
}
fn main() -> tantivy::Result<()> {
let args: Vec<String> = env::args().collect();
let mut search_string = "diary";
if args.len() == 2 {
search_string = &args[1];
}
println!("search string = {}", search_string);
let index_path = Path::new("/tmp/tantivy/idxbs");
let index = Index::open_in_dir(&index_path).unwrap(); //ok
let schema = create_schema();
let title = schema.get_field("title").unwrap();
// let id: Field = schema.get_field("id").unwrap();
let reader = index
.reader_builder()
.reload_policy(ReloadPolicy::OnCommit)
.try_into()?;
let searcher = reader.searcher();
let query_parser = QueryParser::for_index(&index, vec![title]);
let query = query_parser.parse_query(search_string)?;
let top_docs = searcher.search(&query, &TopDocs::with_limit(10))?;
for (_score, doc_address) in top_docs {
let retrieved_doc = searcher.doc(doc_address)?;
println!("{}", schema.to_json(&retrieved_doc));
}
Ok(())
}
|
pub mod routes;
pub mod config;
pub mod logging;
pub mod catchers;
pub mod server; |
mod buf;
mod key;
mod node;
mod interpolator;
mod search;
#[cfg(test)]
mod tests;
use {
std::{
ops::Index,
marker::PhantomData
},
buf::Buffer,
search::search,
};
pub use {
key::{
TrackKey,
TrackKeyDistance,
},
node::TrackNode,
interpolator::TrackInterpolator,
};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
Overflow,
KeyNotInRange,
KeyIsNotInInnerRange,
}
type Key<I> = <I as TrackInterpolator>::Key;
type KeyDistance<I> = <Key<I> as TrackKey>::Distance;
type Data<I> = <I as TrackInterpolator>::Data;
type NotAlignedData<I> = <I as TrackInterpolator>::NotAlignedData;
type Node<I> = TrackNode<Key<I>, Data<I>, NotAlignedData<I>>;
type NotAlignedNode<I> = node::NotAlignedNode::<Key<I>, Data<I>, NotAlignedData<I>>;
type Output<I> = <I as TrackInterpolator>::Output;
type TrackRange = (usize, usize);
struct NearbyNodes<I: TrackInterpolator> {
begin_index: usize,
begin_key: Key<I>,
end_index: usize,
end_key: Key<I>
}
pub struct Track<I: TrackInterpolator> {
interpolator: I,
ranges: Buffer<TrackRange>,
buf: Buffer<Node<I>>,
aligned_step: KeyDistance<I>,
next_step: KeyDistance<I>,
key_start: Key<I>,
key_end: Key<I>,
}
impl<I: TrackInterpolator> Track<I> {
pub fn new(interpolator: I, track_size: usize, aligned_step: KeyDistance<I>) -> Self {
assert!(track_size > 1);
Self {
interpolator,
ranges: Buffer::new(track_size - 1),
buf: Buffer::new(track_size),
aligned_step: aligned_step.clone(),
next_step: aligned_step,
key_start: Key::<I>::default(),
key_end: Key::<I>::default(),
}
}
pub fn key_start(&self) -> &Key<I> {
&self.key_start
}
pub fn key_end(&self) -> &Key<I> {
&self.key_end
}
pub fn reset_track(&mut self, new_key_start: Key<I>) -> buf::Truncated<Node<I>> {
self.ranges.clear();
self.key_start = new_key_start.clone();
self.next_step = self.aligned_step.clone();
self.key_end = new_key_start;
self.buf.clear()
}
pub fn interpolate(&mut self, key: &Key<I>) -> Result<Output<I>> {
if *key < self.key_start || *key >= self.key_end {
return Err(Error::KeyNotInRange);
}
let range_index = self.range_index(key);
let nodes = self.find_nearby_nodes_in_range(range_index, key);
let output = self.interpolator.interpolate(
key,
nodes.begin_key,
&self.buf[nodes.begin_index],
nodes.end_key,
&self.buf[nodes.end_index]
);
Ok(output)
}
pub fn truncate_back(&mut self, key: &Key<I>) {
// If `key` is behind the `self.key_start` -- distance will be negative.
// Negative distance might cause too big `range_index`.
//
// Also, those key value is meaningless for `truncate_back`
if !self.is_forward_key(&key) || self.ranges.len() < 2 {
return;
}
let old_begin = self.ranges.first().unwrap().0;
let range_index = self.range_index(&key);
let removed_ranges = self.ranges.truncate_back(range_index);
let removed_ranges = removed_ranges.len();
self.key_start = self.increase_key_by_step(&self.key_start, removed_ranges);
let (begin, _) = self.ranges.first().unwrap();
self.buf.truncate_back(
self.wrap_buf_index(
*begin, old_begin
)
);
}
pub fn cancel_forward(&mut self, key: &Key<I>) -> buf::Truncated<Node<I>> {
if *key <= self.key_start {
return self.reset_track(
Key::<I>::default()
);
} else if *key > self.key_end || self.is_empty() {
return buf::Truncated::empty(&mut self.buf)
}
let index;
let mut range_index;
if *key == self.key_end {
range_index = self.ranges.len() - 1;
let (_, end) = self.ranges.last_mut().unwrap();
*end -= 1;
index = *end;
} else {
range_index = self.range_index(key);
let nearby_nodes = self.find_nearby_nodes_in_range(range_index, key);
let mut node_index = nearby_nodes.begin_index;
let finded_key = nearby_nodes.begin_key;
if *key == finded_key {
node_index -= 1;
}
index = node_index;
if *key == self.range_index_to_key(range_index) {
range_index -= 1;
}
self.ranges.truncate_forward(range_index);
self.ranges.last_mut().unwrap().1 = index;
}
let (begin, end) = self.ranges.last().unwrap();
if begin == end {
if self.ranges.len() > 1 {
self.ranges.truncate_forward(range_index - 1);
} else {
self.ranges.clear();
}
}
match self.buf[index] {
TrackNode::Aligned(_) => {
self.next_step = self.aligned_step.clone();
self.key_end = self.increase_key_by_step(&self.key_start, self.ranges.len());
},
TrackNode::NotAligned(ref node) => {
let range_index = self.range_index(&node.key);
let nearest_aligned_key = self.increase_key_by_step(
&self.key_start,
range_index
);
self.key_end = node.key.clone();
let key_distance = nearest_aligned_key.distance(&self.key_end);
self.next_step = self.aligned_step.clone() - key_distance;
}
};
self.buf.truncate_forward(index)
}
pub fn push_aligned(&mut self, node: Data<I>) -> Result<()> {
if self.is_empty() {
self.buf.try_push(node.into()).unwrap();
return Ok(());
}
if self.ranges.is_empty() {
debug_assert!(matches![self.node_end().unwrap(), Node::<I>::Aligned(_)]);
self.buf.try_push(node.into()).unwrap();
self.ranges.try_push((0, 1)).unwrap();
} else {
self.push_helper(node.into())?;
}
self.key_end = self.key_end.add_distance(&self.next_step);
self.next_step = self.aligned_step.clone();
Ok(())
}
pub fn insert_not_aligned<Handler>(
&mut self,
key: Key<I>,
node: NotAlignedData<I>,
mut handler: Handler
) -> Result<()>
where
Handler: FnMut(&mut Node<I>)
{
if !self.is_key_in_inner_range(&key) {
return Err(Error::KeyIsNotInInnerRange);
}
let mut canceled_nodes = self.cancel_forward(&key);
let nearest_canceled_node = canceled_nodes.nth(0).unwrap().clone();
for node in canceled_nodes {
handler(node)
}
let (canceled_node, canceled_key) = match nearest_canceled_node {
Node::<I>::Aligned(ref data) => {
let node = data.clone();
let key = self.key_end.add_distance(&self.next_step);
(node, key)
},
Node::<I>::NotAligned(ref data) => {
let node = data.canceled_node().clone();
let key = data.canceled_key().clone();
(node, key)
}
};
let node_key = key.clone();
let not_aligned_node = NotAlignedNode::<I> {
node,
key,
canceled_node,
canceled_key,
phantom: PhantomData
};
if self.ranges.is_empty() {
debug_assert!(matches![self.node_end().unwrap(), Node::<I>::Aligned(_)]);
self.buf.try_push(not_aligned_node.into()).unwrap();
self.ranges.try_push((0, 1)).unwrap();
} else {
self.push_helper(not_aligned_node.into())?;
}
let key_distance = self.key_end.distance(&node_key);
self.next_step = self.next_step.clone() - key_distance;
self.key_end = node_key;
Ok(())
}
fn push_helper(&mut self, node: Node<I>) -> Result<()> {
match self.node_end().unwrap() {
Node::<I>::Aligned(_) => {
self.try_push(node)?;
let (_, last_end) = self.ranges.last().unwrap();
let new_begin = *last_end;
let new_end = new_begin + 1;
self.ranges.try_push((new_begin, new_end)).unwrap();
},
Node::<I>::NotAligned(_) => {
self.try_push(node)?;
let (_, last_end) = self.ranges.last_mut().unwrap();
*last_end += 1;
}
}
Ok(())
}
fn try_push(&mut self, node: Node::<I>) -> Result<()> {
if let Err(buf::Error::Overflow(node)) = self.buf.try_push(node) {
self.force_push(node)?;
}
Ok(())
}
fn force_push(&mut self, node: Node::<I>) -> Result<()> {
debug_assert!(!self.ranges.is_empty());
if self.ranges.len() == 1 {
self.buf.grow();
self.buf.try_push(node).unwrap();
Ok(())
} else {
Err(Error::Overflow)
}
}
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
pub fn node_start(&self) -> Option<&Node<I>> {
self.buf.first()
}
pub fn node_end(&self) -> Option<&Node<I>> {
self.buf.last()
}
fn find_nearby_nodes_in_range(&self, range_index: usize, key: &Key<I>) -> NearbyNodes<I> {
let range = self.ranges[range_index];
let begin_key = self.range_index_to_key(range_index);
let end_key = match self.buf[range.1] {
Node::<I>::Aligned(_) => begin_key.add_distance(&self.aligned_step),
Node::<I>::NotAligned(ref node) => node.key.clone()
};
assert!(begin_key <= *key && *key <= end_key);
let range_adapter = TrackRangeAdapter::<I>::new(
&self.buf,
range,
begin_key,
end_key.clone()
);
let (begin_index, begin_key) = search(&range_adapter, range.0, range.1, key);
let end_index = begin_index + 1;
let begin_key = begin_key.clone();
let end_key = match self.buf[end_index] {
Node::<I>::Aligned(_) => end_key,
Node::<I>::NotAligned(ref node) => node.key.clone()
};
NearbyNodes::<I> {
begin_index,
begin_key,
end_index,
end_key
}
}
fn is_key_in_inner_range(&self, key: &Key<I>) -> bool {
self.key_start < *key && * key < self.key_end
}
fn is_forward_key(&self, key: &Key<I>) -> bool {
self.key_start <= *key
}
fn range_index(&self, key: &Key<I>) -> usize {
self.key_start.distance(key)
.div_floor(&self.aligned_step)
}
fn increase_key_by_step(&self, key: &Key<I>, steps: usize) -> Key<I> {
key.add_distance(
&self.aligned_step.scale(steps)
)
}
fn range_index_to_key(&self, range_index: usize) -> Key<I> {
assert!(range_index < self.ranges.len());
self.increase_key_by_step(&self.key_start, range_index)
}
fn wrap_buf_index(&self, buf_index: usize, begin_index: usize) -> usize {
assert!(buf_index >= begin_index);
let index = buf_index - begin_index;
self.buf.wrap_raw_index(index)
}
}
struct TrackRangeAdapter<'b, I: TrackInterpolator> {
buf: &'b Buffer<Node<I>>,
range: TrackRange,
left_key: Key<I>,
right_key: Key<I>
}
impl<'b, I: TrackInterpolator> TrackRangeAdapter<'b, I> {
fn new(
buf: &'b Buffer<Node<I>>,
range: TrackRange,
left_key: Key<I>,
right_key: Key<I>
) -> Self {
Self {
buf,
range,
left_key,
right_key
}
}
}
impl<'b, I: TrackInterpolator> Index<usize> for TrackRangeAdapter<'b, I> {
type Output = Key<I>;
fn index(&self, index: usize) -> &Self::Output {
if index == self.range.0 {
&self.left_key
} else if index == self.range.1 {
&self.right_key
} else {
match self.buf[index] {
TrackNode::NotAligned(ref node) => &node.key,
TrackNode::Aligned(_) => panic!("unexpected aligned node")
}
}
}
} |
use super::*;
pick! {
if #[cfg(target_feature="sse2")] {
#[derive(Default, Clone, Copy, PartialEq, Eq)]
#[repr(C, align(16))]
pub struct i64x2 { sse: m128i }
} else if #[cfg(target_feature="simd128")] {
use core::arch::wasm32::*;
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct i64x2 { simd: v128 }
impl Default for i64x2 {
fn default() -> Self {
Self::splat(0)
}
}
impl PartialEq for i64x2 {
fn eq(&self, other: &Self) -> bool {
u64x2_all_true(i64x2_eq(self.simd, other.simd))
}
}
impl Eq for i64x2 { }
} else {
#[derive(Default, Clone, Copy, PartialEq, Eq)]
#[repr(C, align(16))]
pub struct i64x2 { arr: [i64;2] }
}
}
int_uint_consts!(i64, 2, i64x2, i64x2, i64a2, const_i64_as_i64x2, 128);
unsafe impl Zeroable for i64x2 {}
unsafe impl Pod for i64x2 {}
impl Add for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn add(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="sse2")] {
Self { sse: add_i64_m128i(self.sse, rhs.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: i64x2_add(self.simd, rhs.simd) }
} else {
Self { arr: [
self.arr[0].wrapping_add(rhs.arr[0]),
self.arr[1].wrapping_add(rhs.arr[1]),
]}
}
}
}
}
impl Sub for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn sub(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="sse2")] {
Self { sse: sub_i64_m128i(self.sse, rhs.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: i64x2_sub(self.simd, rhs.simd) }
} else {
Self { arr: [
self.arr[0].wrapping_sub(rhs.arr[0]),
self.arr[1].wrapping_sub(rhs.arr[1]),
]}
}
}
}
}
//we should try to implement this on sse2
impl Mul for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn mul(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="simd128")] {
Self { simd: i64x2_mul(self.simd, rhs.simd) }
} else {
let arr1: [i64; 2] = cast(self);
let arr2: [i64; 2] = cast(rhs);
cast([
arr1[0].wrapping_mul(arr2[0]),
arr1[1].wrapping_mul(arr2[1]),
])
}
}
}
}
impl Add<i64> for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn add(self, rhs: i64) -> Self::Output {
self.add(Self::splat(rhs))
}
}
impl Sub<i64> for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn sub(self, rhs: i64) -> Self::Output {
self.sub(Self::splat(rhs))
}
}
impl Mul<i64> for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn mul(self, rhs: i64) -> Self::Output {
self.mul(Self::splat(rhs))
}
}
impl Add<i64x2> for i64 {
type Output = i64x2;
#[inline]
#[must_use]
fn add(self, rhs: i64x2) -> Self::Output {
i64x2::splat(self).add(rhs)
}
}
impl Sub<i64x2> for i64 {
type Output = i64x2;
#[inline]
#[must_use]
fn sub(self, rhs: i64x2) -> Self::Output {
i64x2::splat(self).sub(rhs)
}
}
impl Mul<i64x2> for i64 {
type Output = i64x2;
#[inline]
#[must_use]
fn mul(self, rhs: i64x2) -> Self::Output {
i64x2::splat(self).mul(rhs)
}
}
impl BitAnd for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn bitand(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="sse2")] {
Self { sse: bitand_m128i(self.sse, rhs.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: v128_and(self.simd, rhs.simd) }
} else {
Self { arr: [
self.arr[0].bitand(rhs.arr[0]),
self.arr[1].bitand(rhs.arr[1]),
]}
}
}
}
}
impl BitOr for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn bitor(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="sse2")] {
Self { sse: bitor_m128i(self.sse, rhs.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: v128_or(self.simd, rhs.simd) }
} else {
Self { arr: [
self.arr[0].bitor(rhs.arr[0]),
self.arr[1].bitor(rhs.arr[1]),
]}
}
}
}
}
impl BitXor for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn bitxor(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="sse2")] {
Self { sse: bitxor_m128i(self.sse, rhs.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: v128_xor(self.simd, rhs.simd) }
} else {
Self { arr: [
self.arr[0].bitxor(rhs.arr[0]),
self.arr[1].bitxor(rhs.arr[1]),
]}
}
}
}
}
macro_rules! impl_shl_t_for_i64x2 {
($($shift_type:ty),+ $(,)?) => {
$(impl Shl<$shift_type> for i64x2 {
type Output = Self;
/// Shifts all lanes by the value given.
#[inline]
#[must_use]
fn shl(self, rhs: $shift_type) -> Self::Output {
pick! {
if #[cfg(target_feature="sse2")] {
let shift = cast([rhs as u64, 0]);
Self { sse: shl_all_u64_m128i(self.sse, shift) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: i64x2_shl(self.simd, rhs as u32) }
} else {
let u = rhs as u64;
Self { arr: [
self.arr[0] << u,
self.arr[1] << u,
]}
}
}
}
})+
};
}
impl_shl_t_for_i64x2!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128);
macro_rules! impl_shr_t_for_i64x2 {
($($shift_type:ty),+ $(,)?) => {
$(impl Shr<$shift_type> for i64x2 {
type Output = Self;
/// Shifts all lanes by the value given.
#[inline]
#[must_use]
fn shr(self, rhs: $shift_type) -> Self::Output {
pick! {
if #[cfg(target_feature="simd128")] {
Self { simd: i64x2_shr(self.simd, rhs as u32) }
} else {
let u = rhs as u64;
let arr: [i64; 2] = cast(self);
cast([
arr[0] >> u,
arr[1] >> u,
])
}
}
}
})+
};
}
impl_shr_t_for_i64x2!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128);
impl CmpEq for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn cmp_eq(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="sse4.1")] {
Self { sse: cmp_eq_mask_i64_m128i(self.sse, rhs.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: i64x2_eq(self.simd, rhs.simd) }
} else {
let s: [i64;2] = cast(self);
let r: [i64;2] = cast(rhs);
cast([
if s[0] == r[0] { -1_i64 } else { 0 },
if s[1] == r[1] { -1_i64 } else { 0 },
])
}
}
}
}
impl CmpGt for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn cmp_gt(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="sse4.2")] {
Self { sse: cmp_gt_mask_i64_m128i(self.sse, rhs.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: i64x2_gt(self.simd, rhs.simd) }
} else {
let s: [i64;2] = cast(self);
let r: [i64;2] = cast(rhs);
cast([
if s[0] > r[0] { -1_i64 } else { 0 },
if s[1] > r[1] { -1_i64 } else { 0 },
])
}
}
}
}
impl CmpLt for i64x2 {
type Output = Self;
#[inline]
#[must_use]
fn cmp_lt(self, rhs: Self) -> Self::Output {
pick! {
if #[cfg(target_feature="sse4.2")] {
Self { sse: !cmp_gt_mask_i64_m128i(self.sse, rhs.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: i64x2_lt(self.simd, rhs.simd) }
} else {
let s: [i64;2] = cast(self);
let r: [i64;2] = cast(rhs);
cast([
if s[0] < r[0] { -1_i64 } else { 0 },
if s[1] < r[1] { -1_i64 } else { 0 },
])
}
}
}
}
impl i64x2 {
#[inline]
#[must_use]
pub fn blend(self, t: Self, f: Self) -> Self {
pick! {
if #[cfg(target_feature="sse4.1")] {
Self { sse: blend_varying_i8_m128i(f.sse, t.sse, self.sse) }
} else if #[cfg(target_feature="simd128")] {
Self { simd: v128_bitselect(t.simd, f.simd, self.simd) }
} else {
generic_bit_blend(self, t, f)
}
}
}
#[inline]
#[must_use]
pub fn round_float(self) -> f64x2 {
let arr: [i64; 2] = cast(self);
cast([arr[0] as f64, arr[1] as f64])
}
pub fn to_array(self) -> [i64; 2] {
cast(self)
}
}
|
// Copyright 2017 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::thread;
use std::time::Duration;
use std::sync::{Arc, RwLock};
use adapters::NetToChainAdapter;
use chain;
use core::core::hash::{Hash, Hashed};
use p2p::{self, Peer, NetAdapter};
use types::Error;
use util::LOGGER;
/// Starts the syncing loop, just spawns two threads that loop forever
pub fn run_sync(
adapter: Arc<NetToChainAdapter>,
p2p_server: Arc<p2p::Server>,
chain: Arc<chain::Chain>,
) {
let a_inner = adapter.clone();
let p2p_inner = p2p_server.clone();
let c_inner = chain.clone();
let _ = thread::Builder::new()
.name("body_sync".to_string())
.spawn(move || {
loop {
if a_inner.is_syncing() {
body_sync(p2p_inner.clone(), c_inner.clone());
} else {
thread::sleep(Duration::from_secs(5));
}
}
});
let _ = thread::Builder::new()
.name("header_sync".to_string())
.spawn(move || {
loop {
if adapter.is_syncing() {
header_sync(adapter.clone(), p2p_server.clone(), chain.clone());
} else {
thread::sleep(Duration::from_secs(5));
}
}
});
}
fn body_sync(
p2p_server: Arc<p2p::Server>,
chain: Arc<chain::Chain>,
) {
debug!(LOGGER, "block_sync: loop");
let header_head = chain.get_header_head().unwrap();
let block_header = chain.head_header().unwrap();
let mut hashes = vec![];
if header_head.total_difficulty > block_header.total_difficulty {
let mut current = chain.get_block_header(&header_head.last_block_h);
while let Ok(header) = current {
if header.hash() == block_header.hash() {
break;
}
hashes.push(header.hash());
current = chain.get_block_header(&header.previous);
}
}
hashes.reverse();
let hashes_to_get = hashes
.iter()
.filter(|x| !chain.get_block(&x).is_ok())
.take(10)
.cloned()
.collect::<Vec<_>>();
if hashes_to_get.len() > 0 {
debug!(
LOGGER,
"block_sync: requesting blocks ({}/{}), {:?}",
block_header.height,
header_head.height,
hashes_to_get,
);
for hash in hashes_to_get.clone() {
let peer = if hashes_to_get.len() < 100 {
p2p_server.most_work_peer()
} else {
p2p_server.random_peer()
};
if let Some(peer) = peer {
let peer = peer.read().unwrap();
if let Err(e) = peer.send_block_request(hash) {
debug!(LOGGER, "block_sync: error requesting block: {:?}, {:?}", hash, e);
}
}
}
thread::sleep(Duration::from_secs(1));
} else {
thread::sleep(Duration::from_secs(5));
}
}
pub fn header_sync(
adapter: Arc<NetToChainAdapter>,
p2p_server: Arc<p2p::Server>,
chain: Arc<chain::Chain>,
) {
debug!(LOGGER, "header_sync: loop");
let difficulty = adapter.total_difficulty();
if let Some(peer) = p2p_server.most_work_peer() {
let peer = peer.clone();
let p = peer.read().unwrap();
let peer_difficulty = p.info.total_difficulty.clone();
if peer_difficulty > difficulty {
debug!(
LOGGER,
"header_sync: difficulty {} vs {}",
peer_difficulty,
difficulty,
);
let _ = request_headers(
peer.clone(),
chain.clone(),
);
}
}
thread::sleep(Duration::from_secs(30));
}
/// Request some block headers from a peer to advance us
fn request_headers(
peer: Arc<RwLock<Peer>>,
chain: Arc<chain::Chain>,
) -> Result<(), Error> {
let locator = get_locator(chain)?;
let peer = peer.read().unwrap();
debug!(
LOGGER,
"Sync: Asking peer {} for more block headers, locator: {:?}",
peer.info.addr,
locator,
);
let _ = peer.send_header_request(locator);
Ok(())
}
fn get_locator(chain: Arc<chain::Chain>) -> Result<Vec<Hash>, Error> {
let tip = chain.get_header_head()?;
// TODO - is this necessary?
// go back to earlier header height to ensure we do not miss a header
let height = if tip.height > 5 {
tip.height - 5
} else {
0
};
let heights = get_locator_heights(height);
debug!(LOGGER, "Sync: locator heights: {:?}", heights);
let mut locator = vec![];
let mut current = chain.get_block_header(&tip.last_block_h);
while let Ok(header) = current {
if heights.contains(&header.height) {
locator.push(header.hash());
}
current = chain.get_block_header(&header.previous);
}
debug!(LOGGER, "Sync: locator: {:?}", locator);
Ok(locator)
}
// current height back to 0 decreasing in powers of 2
fn get_locator_heights(height: u64) -> Vec<u64> {
let mut current = height.clone();
let mut heights = vec![];
while current > 0 {
heights.push(current);
let next = 2u64.pow(heights.len() as u32);
current = if current > next {
current - next
} else {
0
}
}
heights.push(0);
heights
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_get_locator_heights() {
assert_eq!(get_locator_heights(0), vec![0]);
assert_eq!(get_locator_heights(1), vec![1, 0]);
assert_eq!(get_locator_heights(2), vec![2, 0]);
assert_eq!(get_locator_heights(3), vec![3, 1, 0]);
assert_eq!(get_locator_heights(10), vec![10, 8, 4, 0]);
assert_eq!(get_locator_heights(100), vec![100, 98, 94, 86, 70, 38, 0]);
assert_eq!(
get_locator_heights(1000),
vec![1000, 998, 994, 986, 970, 938, 874, 746, 490, 0]
);
// check the locator is still a manageable length, even for large numbers of headers
assert_eq!(
get_locator_heights(10000),
vec![10000, 9998, 9994, 9986, 9970, 9938, 9874, 9746, 9490, 8978, 7954, 5906, 1810, 0]
);
}
}
|
//! Error module with all error used by soft
#![allow(missing_docs)]
error_chain!{
types {
Error, ErrorKind, ResultExt, Result;
}
links {}
foreign_links {
Io(::std::io::Error);
AppDirs(::app_dirs::AppDirsError);
SystemTime(::std::time::SystemTimeError);
Int(::std::num::ParseIntError);
}
errors {
InvalidCommand(c: String) {
description("parsed command is invalid")
display("invalid command: {}", c)
}
InvalidLogin {
description("user name or password is invalid")
display("user name or password is invalid")
}
NotConnected {
description("client is not logged in server")
display("client is not logged in server")
}
InvalidUserDB {
description("provided user database is invalid")
display("provided user database is invalid")
}
}
}
|
use std::fs::{DirBuilder, File, Metadata, OpenOptions};
use std::io::{self, Error, ErrorKind};
use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
use std::os::unix::prelude::OpenOptionsExt;
use std::path::Path;
// of course we can also write "file & 0o040 != 0", but this makes the intent explicit
enum Op {
Read = 4,
Write = 2,
Exec = 1,
}
enum Category {
Owner = 2,
Group = 1,
World = 0,
}
fn mode(who: Category, what: Op) -> u32 {
(what as u32) << (3 * who as u32)
}
pub fn secure_open(path: impl AsRef<Path>, check_parent_dir: bool) -> io::Result<File> {
let mut open_options = OpenOptions::new();
open_options.read(true);
secure_open_impl(path.as_ref(), &mut open_options, check_parent_dir, false)
}
pub fn secure_open_cookie_file(path: impl AsRef<Path>) -> io::Result<File> {
let mut open_options = OpenOptions::new();
open_options
.read(true)
.write(true)
.create(true)
.mode(mode(Category::Owner, Op::Write) | mode(Category::Owner, Op::Read));
secure_open_impl(path.as_ref(), &mut open_options, true, true)
}
fn checks(path: &Path, meta: Metadata) -> io::Result<()> {
let error = |msg| Error::new(ErrorKind::PermissionDenied, msg);
let path_mode = meta.permissions().mode();
if meta.uid() != 0 {
Err(error(format!("{} must be owned by root", path.display())))
} else if meta.gid() != 0 && (path_mode & mode(Category::Group, Op::Write) != 0) {
Err(error(format!(
"{} cannot be group-writable",
path.display()
)))
} else if path_mode & mode(Category::World, Op::Write) != 0 {
Err(error(format!(
"{} cannot be world-writable",
path.display()
)))
} else {
Ok(())
}
}
// Open `path` with options `open_options`, provided that it is "secure".
// "Secure" means that it passes the `checks` function above.
// If `check_parent_dir` is set, also check that the parent directory is "secure" also.
// If `create_parent_dirs` is set, create the path to the file if it does not already exist.
fn secure_open_impl(
path: &Path,
open_options: &mut OpenOptions,
check_parent_dir: bool,
create_parent_dirs: bool,
) -> io::Result<File> {
let error = |msg| Error::new(ErrorKind::PermissionDenied, msg);
if check_parent_dir || create_parent_dirs {
if let Some(parent_dir) = path.parent() {
// if we should create parent dirs and it does not yet exist, create it
if create_parent_dirs && !parent_dir.exists() {
DirBuilder::new()
.recursive(true)
.mode(
mode(Category::Owner, Op::Write)
| mode(Category::Owner, Op::Read)
| mode(Category::Owner, Op::Exec)
| mode(Category::Group, Op::Exec)
| mode(Category::World, Op::Exec),
)
.create(parent_dir)?;
}
if check_parent_dir {
let parent_meta = std::fs::metadata(parent_dir)?;
checks(parent_dir, parent_meta)?;
}
} else {
return Err(error(format!(
"{} has no valid parent directory",
path.display()
)));
}
}
let file = open_options.open(path)?;
let meta = file.metadata()?;
checks(path, meta)?;
Ok(file)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn secure_open_is_predictable() {
// /etc/hosts should be readable and "secure" (if this test fails, you have been compromised)
assert!(std::fs::File::open("/etc/hosts").is_ok());
assert!(secure_open("/etc/hosts", false).is_ok());
// /var/log/utmp should be readable, but not secure (writeable by group other than root)
assert!(std::fs::File::open("/var/log/wtmp").is_ok());
assert!(secure_open("/var/log/wtmp", false).is_err());
// /etc/shadow should not be readable
assert!(std::fs::File::open("/etc/shadow").is_err());
assert!(secure_open("/etc/shadow", false).is_err());
}
#[test]
fn test_secure_open_cookie_file() {
assert!(secure_open_cookie_file("/etc/hosts").is_err());
}
}
|
#[doc = "Register `DDRCTRL_PERFLPR1` reader"]
pub type R = crate::R<DDRCTRL_PERFLPR1_SPEC>;
#[doc = "Register `DDRCTRL_PERFLPR1` writer"]
pub type W = crate::W<DDRCTRL_PERFLPR1_SPEC>;
#[doc = "Field `LPR_MAX_STARVE` reader - LPR_MAX_STARVE"]
pub type LPR_MAX_STARVE_R = crate::FieldReader<u16>;
#[doc = "Field `LPR_MAX_STARVE` writer - LPR_MAX_STARVE"]
pub type LPR_MAX_STARVE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>;
#[doc = "Field `LPR_XACT_RUN_LENGTH` reader - LPR_XACT_RUN_LENGTH"]
pub type LPR_XACT_RUN_LENGTH_R = crate::FieldReader;
#[doc = "Field `LPR_XACT_RUN_LENGTH` writer - LPR_XACT_RUN_LENGTH"]
pub type LPR_XACT_RUN_LENGTH_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bits 0:15 - LPR_MAX_STARVE"]
#[inline(always)]
pub fn lpr_max_starve(&self) -> LPR_MAX_STARVE_R {
LPR_MAX_STARVE_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 24:31 - LPR_XACT_RUN_LENGTH"]
#[inline(always)]
pub fn lpr_xact_run_length(&self) -> LPR_XACT_RUN_LENGTH_R {
LPR_XACT_RUN_LENGTH_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:15 - LPR_MAX_STARVE"]
#[inline(always)]
#[must_use]
pub fn lpr_max_starve(&mut self) -> LPR_MAX_STARVE_W<DDRCTRL_PERFLPR1_SPEC, 0> {
LPR_MAX_STARVE_W::new(self)
}
#[doc = "Bits 24:31 - LPR_XACT_RUN_LENGTH"]
#[inline(always)]
#[must_use]
pub fn lpr_xact_run_length(&mut self) -> LPR_XACT_RUN_LENGTH_W<DDRCTRL_PERFLPR1_SPEC, 24> {
LPR_XACT_RUN_LENGTH_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 = "DDRCTRL low priority read CAM register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrctrl_perflpr1::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 [`ddrctrl_perflpr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DDRCTRL_PERFLPR1_SPEC;
impl crate::RegisterSpec for DDRCTRL_PERFLPR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ddrctrl_perflpr1::R`](R) reader structure"]
impl crate::Readable for DDRCTRL_PERFLPR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ddrctrl_perflpr1::W`](W) writer structure"]
impl crate::Writable for DDRCTRL_PERFLPR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DDRCTRL_PERFLPR1 to value 0x0f00_007f"]
impl crate::Resettable for DDRCTRL_PERFLPR1_SPEC {
const RESET_VALUE: Self::Ux = 0x0f00_007f;
}
|
use flatbuffers::EndianScalar;
use std::cell::{RefCell, RefMut};
use std::ffi::OsString;
use std::net::SocketAddr;
use flatbuffers::FlatBufferBuilder;
use thread_local::ThreadLocal;
use crate::base::{finalize_request, response_or_error};
use crate::client::tcp_client::TcpClient;
use crate::generated::*;
use crate::storage::ROOT_INODE;
use fuser::FileAttr;
use std::ops::Add;
use std::time::{Duration, SystemTime};
fn to_fuse_file_type(file_type: FileKind) -> fuser::FileType {
match file_type {
FileKind::File => fuser::FileType::RegularFile,
FileKind::Directory => fuser::FileType::Directory,
FileKind::Symlink => fuser::FileType::Symlink,
FileKind::DefaultValueNotAType => unreachable!(),
}
}
pub fn decode_fast_read_response_inplace(response: &mut Vec<u8>) -> Result<&Vec<u8>, ErrorCode> {
let value = response.pop().unwrap().from_little_endian() as i8;
let p = &value as *const i8 as *const ErrorCode;
let error_code = unsafe { *p };
if error_code == ErrorCode::DefaultValueNotAnError {
Ok(response)
} else {
Err(error_code)
}
}
pub struct StatFS {
pub block_size: u32,
pub max_name_length: u32,
}
fn metadata_to_fuse_fileattr(metadata: &FileMetadataResponse) -> FileAttr {
FileAttr {
ino: metadata.inode(),
size: metadata.size_bytes(),
blocks: metadata.size_blocks(),
atime: SystemTime::UNIX_EPOCH.add(Duration::new(
metadata.last_access_time().seconds() as u64,
metadata.last_access_time().nanos() as u32,
)),
mtime: SystemTime::UNIX_EPOCH.add(Duration::new(
metadata.last_modified_time().seconds() as u64,
metadata.last_modified_time().nanos() as u32,
)),
ctime: SystemTime::UNIX_EPOCH.add(Duration::new(
metadata.last_metadata_modified_time().seconds() as u64,
metadata.last_metadata_modified_time().nanos() as u32,
)),
crtime: SystemTime::UNIX_EPOCH,
kind: to_fuse_file_type(metadata.kind()),
perm: metadata.mode(),
nlink: metadata.hard_links(),
uid: metadata.user_id(),
gid: metadata.group_id(),
rdev: metadata.device_id(),
flags: 0,
blksize: metadata.block_size(),
}
}
pub struct NodeClient {
tcp_client: TcpClient,
response_buffer: ThreadLocal<RefCell<Vec<u8>>>,
request_builder: ThreadLocal<RefCell<FlatBufferBuilder<'static>>>,
}
impl NodeClient {
pub fn new(server_ip_port: SocketAddr) -> NodeClient {
NodeClient {
tcp_client: TcpClient::new(server_ip_port),
response_buffer: ThreadLocal::new(),
request_builder: ThreadLocal::new(),
}
}
fn get_or_create_builder(&self) -> RefMut<FlatBufferBuilder<'static>> {
let mut builder = self
.request_builder
.get_or(|| RefCell::new(FlatBufferBuilder::new()))
.borrow_mut();
builder.reset();
return builder;
}
fn get_or_create_buffer(&self) -> RefMut<Vec<u8>> {
return self
.response_buffer
.get_or(|| RefCell::new(vec![]))
.borrow_mut();
}
fn send_receive_raw<'b>(
&self,
request: &[u8],
buffer: &'b mut Vec<u8>,
) -> Result<&'b mut Vec<u8>, ErrorCode> {
self.tcp_client
.send_and_receive_length_prefixed(request, buffer.as_mut())
.map_err(|_| ErrorCode::Uncategorized)?;
Ok(buffer)
}
fn send<'b>(
&self,
request: &[u8],
buffer: &'b mut Vec<u8>,
) -> Result<GenericResponse<'b>, ErrorCode> {
self.tcp_client
.send_and_receive_length_prefixed(request, buffer.as_mut())
.map_err(|_| ErrorCode::Uncategorized)?;
return response_or_error(buffer);
}
pub fn filesystem_ready(&self) -> Result<(), ErrorCode> {
let mut builder = self.get_or_create_builder();
let request_builder = FilesystemReadyRequestBuilder::new(&mut builder);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(
&mut builder,
RequestType::FilesystemReadyRequest,
finish_offset,
);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
pub fn fsck(&self) -> Result<(), ErrorCode> {
let mut builder = self.get_or_create_builder();
let request_builder = FilesystemCheckRequestBuilder::new(&mut builder);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(
&mut builder,
RequestType::FilesystemCheckRequest,
finish_offset,
);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
Ok(())
}
pub fn mkdir(
&self,
parent: u64,
name: &str,
uid: u32,
gid: u32,
mode: u16,
) -> Result<FileAttr, ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_name = builder.create_string(name);
let mut request_builder = MkdirRequestBuilder::new(&mut builder);
request_builder.add_parent(parent);
request_builder.add_name(builder_name);
request_builder.add_uid(uid);
request_builder.add_gid(gid);
request_builder.add_mode(mode);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::MkdirRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let metadata = response
.response_as_file_metadata_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(metadata_to_fuse_fileattr(&metadata));
}
pub fn lookup(&self, parent: u64, name: &str, context: UserContext) -> Result<u64, ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_name = builder.create_string(name);
let mut request_builder = LookupRequestBuilder::new(&mut builder);
request_builder.add_parent(parent);
request_builder.add_name(builder_name);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::LookupRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let inode_response = response
.response_as_inode_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(inode_response.inode());
}
pub fn create(
&self,
parent: u64,
name: &str,
uid: u32,
gid: u32,
mode: u16,
kind: FileKind,
) -> Result<FileAttr, ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_name = builder.create_string(name);
let mut request_builder = CreateRequestBuilder::new(&mut builder);
request_builder.add_parent(parent);
request_builder.add_name(builder_name);
request_builder.add_uid(uid);
request_builder.add_gid(gid);
request_builder.add_mode(mode);
request_builder.add_kind(kind);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::CreateRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let metadata = response
.response_as_file_metadata_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(metadata_to_fuse_fileattr(&metadata));
}
pub fn statfs(&self) -> Result<StatFS, ErrorCode> {
let mut builder = self.get_or_create_builder();
let request_builder = FilesystemInformationRequestBuilder::new(&mut builder);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(
&mut builder,
RequestType::FilesystemInformationRequest,
finish_offset,
);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let info = response
.response_as_filesystem_information_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(StatFS {
block_size: info.block_size(),
max_name_length: info.max_name_length(),
});
}
pub fn getattr(&self, inode: u64) -> Result<FileAttr, ErrorCode> {
let mut builder = self.get_or_create_builder();
let mut request_builder = GetattrRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::GetattrRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let metadata = response
.response_as_file_metadata_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(metadata_to_fuse_fileattr(&metadata));
}
pub fn getxattr(
&self,
inode: u64,
key: &str,
context: UserContext,
) -> Result<Vec<u8>, ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_key = builder.create_string(key);
let mut request_builder = GetXattrRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_key(builder_key);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::GetXattrRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let data = response
.response_as_read_response()
.ok_or(ErrorCode::BadResponse)?
.data();
return Ok(data.to_vec());
}
pub fn listxattr(&self, inode: u64) -> Result<Vec<String>, ErrorCode> {
let mut builder = self.get_or_create_builder();
let mut request_builder = ListXattrsRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::ListXattrsRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let xattrs_response = response
.response_as_xattrs_response()
.ok_or(ErrorCode::BadResponse)?;
let xattrs = xattrs_response.xattrs();
let mut attrs = vec![];
for i in 0..xattrs.len() {
let attr = xattrs.get(i);
attrs.push(attr.to_string());
}
return Ok(attrs);
}
pub fn setxattr(
&self,
inode: u64,
key: &str,
value: &[u8],
context: UserContext,
) -> Result<(), ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_key = builder.create_string(key);
let builder_value = builder.create_vector_direct(value);
let mut request_builder = SetXattrRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_key(builder_key);
request_builder.add_value(builder_value);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::SetXattrRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
Ok(())
}
pub fn removexattr(
&self,
inode: u64,
key: &str,
context: UserContext,
) -> Result<(), ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_key = builder.create_string(key);
let mut request_builder = RemoveXattrRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_key(builder_key);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::RemoveXattrRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
Ok(())
}
pub fn utimens(
&self,
inode: u64,
atime: Option<Timestamp>,
mtime: Option<Timestamp>,
context: UserContext,
) -> Result<(), ErrorCode> {
assert_ne!(inode, ROOT_INODE);
let mut builder = self.get_or_create_builder();
let mut request_builder = UtimensRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
if let Some(ref atime) = atime {
request_builder.add_atime(atime);
}
if let Some(ref mtime) = mtime {
request_builder.add_mtime(mtime);
}
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::UtimensRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
pub fn chmod(&self, inode: u64, mode: u32, context: UserContext) -> Result<(), ErrorCode> {
if inode == ROOT_INODE {
return Err(ErrorCode::OperationNotPermitted);
}
let mut builder = self.get_or_create_builder();
let mut request_builder = ChmodRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_mode(mode);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::ChmodRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
pub fn chown(
&self,
inode: u64,
uid: Option<u32>,
gid: Option<u32>,
context: UserContext,
) -> Result<(), ErrorCode> {
assert_ne!(inode, ROOT_INODE);
let mut builder = self.get_or_create_builder();
let mut request_builder = ChownRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
let uid_struct;
let gid_struct;
if let Some(uid) = uid {
uid_struct = OptionalUInt::new(uid);
request_builder.add_uid(&uid_struct);
}
if let Some(gid) = gid {
gid_struct = OptionalUInt::new(gid);
request_builder.add_gid(&gid_struct);
}
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::ChownRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
pub fn hardlink(
&self,
inode: u64,
new_parent: u64,
new_name: &str,
context: UserContext,
) -> Result<FileAttr, ErrorCode> {
assert_ne!(inode, ROOT_INODE);
let mut builder = self.get_or_create_builder();
let builder_new_name = builder.create_string(new_name);
let mut request_builder = HardlinkRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_new_parent(new_parent);
request_builder.add_new_name(builder_new_name);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::HardlinkRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let metadata = response
.response_as_file_metadata_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(metadata_to_fuse_fileattr(&metadata));
}
pub fn rename(
&self,
parent: u64,
name: &str,
new_parent: u64,
new_name: &str,
context: UserContext,
) -> Result<(), ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_name = builder.create_string(name);
let builder_new_name = builder.create_string(new_name);
let mut request_builder = RenameRequestBuilder::new(&mut builder);
request_builder.add_parent(parent);
request_builder.add_name(builder_name);
request_builder.add_new_parent(new_parent);
request_builder.add_new_name(builder_new_name);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::RenameRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
pub fn readlink(&self, inode: u64) -> Result<Vec<u8>, ErrorCode> {
assert_ne!(inode, ROOT_INODE);
let mut builder = self.get_or_create_builder();
let mut request_builder = ReadRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_offset(0);
// TODO: this just tries to read a value longer than the longest link.
// instead we should be using a special readlink message
request_builder.add_read_size(999_999);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::ReadRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send_receive_raw(builder.finished_data(), &mut buffer)?;
decode_fast_read_response_inplace(response).map(Clone::clone)
}
pub fn read<F: FnOnce(Result<&[u8], ErrorCode>)>(
&self,
inode: u64,
offset: u64,
size: u32,
callback: F,
) {
assert_ne!(inode, ROOT_INODE);
let mut builder = self.get_or_create_builder();
let mut request_builder = ReadRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_offset(offset);
request_builder.add_read_size(size);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::ReadRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
match self.send_receive_raw(builder.finished_data(), &mut buffer) {
Ok(response) => match decode_fast_read_response_inplace(response) {
Ok(data) => {
callback(Ok(data));
return;
}
Err(e) => {
callback(Err(e));
return;
}
},
Err(e) => {
callback(Err(e));
return;
}
};
}
pub fn read_to_vec(&self, inode: u64, offset: u64, size: u32) -> Result<Vec<u8>, ErrorCode> {
assert_ne!(inode, ROOT_INODE);
let mut builder = self.get_or_create_builder();
let mut request_builder = ReadRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_offset(offset);
request_builder.add_read_size(size);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::ReadRequest, finish_offset);
let mut buffer = Vec::with_capacity((size + 1) as usize);
self.send_receive_raw(builder.finished_data(), &mut buffer)?;
decode_fast_read_response_inplace(&mut buffer)?;
Ok(buffer)
}
pub fn readdir(&self, inode: u64) -> Result<Vec<(u64, OsString, fuser::FileType)>, ErrorCode> {
let mut builder = self.get_or_create_builder();
let mut request_builder = ReaddirRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::ReaddirRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
let mut result = vec![];
let listing_response = response
.response_as_directory_listing_response()
.ok_or(ErrorCode::BadResponse)?;
let entries = listing_response.entries();
for i in 0..entries.len() {
let entry = entries.get(i);
result.push((
entry.inode(),
OsString::from(entry.name()),
to_fuse_file_type(entry.kind()),
));
}
return Ok(result);
}
pub fn truncate(&self, inode: u64, length: u64, context: UserContext) -> Result<(), ErrorCode> {
assert_ne!(inode, ROOT_INODE);
let mut builder = self.get_or_create_builder();
let mut request_builder = TruncateRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_new_length(length);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::TruncateRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
pub fn write(&self, inode: u64, data: &[u8], offset: u64) -> Result<u32, ErrorCode> {
let mut builder = self.get_or_create_builder();
let data_offset = builder.create_vector_direct(data);
let mut request_builder = WriteRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
request_builder.add_offset(offset);
request_builder.add_data(data_offset);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::WriteRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
return Ok(response
.response_as_written_response()
.ok_or(ErrorCode::BadResponse)?
.bytes_written());
}
pub fn fsync(&self, inode: u64) -> Result<(), ErrorCode> {
let mut builder = self.get_or_create_builder();
let mut request_builder = FsyncRequestBuilder::new(&mut builder);
request_builder.add_inode(inode);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::FsyncRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
pub fn unlink(&self, parent: u64, name: &str, context: UserContext) -> Result<(), ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_name = builder.create_string(name);
let mut request_builder = UnlinkRequestBuilder::new(&mut builder);
request_builder.add_parent(parent);
request_builder.add_name(builder_name);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::UnlinkRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
pub fn rmdir(&self, parent: u64, name: &str, context: UserContext) -> Result<(), ErrorCode> {
let mut builder = self.get_or_create_builder();
let builder_name = builder.create_string(name);
let mut request_builder = RmdirRequestBuilder::new(&mut builder);
request_builder.add_parent(parent);
request_builder.add_name(builder_name);
request_builder.add_context(&context);
let finish_offset = request_builder.finish().as_union_value();
finalize_request(&mut builder, RequestType::RmdirRequest, finish_offset);
let mut buffer = self.get_or_create_buffer();
let response = self.send(builder.finished_data(), &mut buffer)?;
response
.response_as_empty_response()
.ok_or(ErrorCode::BadResponse)?;
return Ok(());
}
}
|
use rand::{thread_rng, Rng};
use crate::{common::BetContext, common::Environment};
pub(crate) fn is_broke(context: &BetContext) -> bool {
context.total_money == 0
}
pub(crate) fn reach_goal(context: &BetContext) -> bool {
context.total_money >= context.start_money * 2
}
pub(crate) fn should_end(context: &BetContext) -> bool {
is_broke(context) || reach_goal(context)
}
pub(crate) fn bet_result(env: &Environment, bet_amount: u64) -> Option<u64> {
let win = thread_rng().gen_bool(env.win_rate);
if win {
Some((bet_amount as f64 * env.return_ratio) as u64)
} else {
None
}
}
|
use std::borrow::Cow;
use std::io::Write;
use std::mem;
use byteorder::{ByteOrder, WriteBytesExt};
use nom::*;
use errors::{PcapError, Result};
use pcapng::blocks::timestamp::{self, Timestamp};
use pcapng::options::{pad_to, parse_options, Opt, Options};
use pcapng::{Block, BlockType};
use traits::WriteTo;
pub const BLOCK_TYPE: u32 = 0x0000_0006;
pub const EPB_FLAGS: u16 = 2;
pub const EPB_HASH: u16 = 3;
pub const EPB_DROPCOUNT: u16 = 4;
bitflags! {
pub struct Flags: u32 {
const INBOUND = 1;
const OUTBOUND = 2;
const UNICAST = 1 << 2;
const MULTICAST = 2 << 2;
const BROADCAST = 3 << 2;
const PROMISCUOUS = 4 << 2;
const FCS_LEN_MASK = 0xF << 5;
const CRC_ERROR = 1 << 24;
const PACKET_TOO_LONG = 1 << 25;
const PACKET_TOO_SHORT = 1 << 26;
const WRONG_INTER_FRAME_GAP = 1 << 27;
const UNALIGNED_FRAME = 1 << 28;
const START_FRAME_DELIMITER = 1 << 29;
const PREAMBLE_ERROR = 1 << 30;
const SYMBOL_ERROR = 1 << 31;
}
}
/// This option is a 32-bit flags word containing link-layer information.
pub fn epb_flags<'a, T: ByteOrder>(flags: Flags) -> Opt<'a> {
Opt::u32::<T>(EPB_FLAGS, flags.bits())
}
pub const HASH_ALGO_2S_COMPLEMENT: u8 = 0;
pub const HASH_ALGO_XOR: u8 = 1;
pub const HASH_ALGO_CRC32: u8 = 2;
pub const HASH_ALGO_MD5: u8 = 3;
pub const HASH_ALGO_SHA1: u8 = 4;
/// This option contains a hash of the packet.
pub fn epb_hash<'a, T: AsRef<[u8]>>(algorithm: u8, hash: T) -> Opt<'a> {
let mut buf = vec![algorithm];
buf.write_all(hash.as_ref()).unwrap();
Opt::new(EPB_HASH, buf)
}
/// This option is a 64-bit integer value specifying the number of packets lost
pub fn epb_dropcount<'a, T: ByteOrder>(count: u64) -> Opt<'a> {
Opt::u64::<T>(EPB_DROPCOUNT, count)
}
/// An Enhanced Packet Block is the standard container for storing the packets coming from the network.
#[derive(Clone, Debug, PartialEq)]
pub struct EnhancedPacket<'a> {
/// the interface this packet comes from
pub interface_id: u32,
/// the number of units of time that have elapsed since 1970-01-01 00:00:00 UTC.
pub timestamp: Timestamp,
/// number of octets captured from the packet.
pub captured_len: u32,
/// actual length of the packet when it was transmitted on the network.
pub original_len: u32,
/// the data coming from the network, including link-layer headers.
pub data: Cow<'a, [u8]>,
/// optionally, a list of options
pub options: Options<'a>,
}
impl<'a> EnhancedPacket<'a> {
pub fn block_type() -> BlockType {
BlockType::EnhancedPacket
}
pub fn size(&self) -> usize {
self.options.iter().fold(
mem::size_of::<u32>() * 3
+ mem::size_of::<Timestamp>()
+ pad_to::<u32>(self.data.len()),
|size, opt| size + opt.size(),
)
}
pub fn parse(buf: &'a [u8], endianness: Endianness) -> Result<(&'a [u8], Self)> {
parse_enhanced_packet(buf, endianness).map_err(|err| PcapError::from(err).into())
}
pub fn flags<T: ByteOrder>(&self) -> Option<Flags> {
self.options
.iter()
.find(|opt| opt.code == EPB_FLAGS && opt.value.len() == mem::size_of::<u32>())
.map(|opt| Flags::from_bits_truncate(T::read_u32(&opt.value)))
}
pub fn hash(&self) -> Vec<(u8, &[u8])> {
self.options
.iter()
.filter(|opt| opt.code == EPB_HASH && opt.value.len() > 0)
.map(|opt| (opt.value[0], &opt.value[1..]))
.collect()
}
pub fn dropcount<T: ByteOrder>(&self) -> Option<u64> {
self.options
.iter()
.find(|opt| opt.code == EPB_DROPCOUNT && opt.value.len() == mem::size_of::<u64>())
.map(|opt| T::read_u64(&opt.value))
}
}
/// 0 1 2 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +---------------------------------------------------------------+
/// 0 | Block Type = 0x00000006 |
/// +---------------------------------------------------------------+
/// 4 | Block Total Length |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 8 | Interface ID |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 12 | Timestamp (High) |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 16 | Timestamp (Low) |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 20 | Captured Packet Length |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 24 | Original Packet Length |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// 28 / /
/// / Packet Data /
/// / variable length, padded to 32 bits /
/// / /
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// / /
/// / Options (variable) /
/// / /
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Block Total Length |
/// +---------------------------------------------------------------+
named_args!(parse_enhanced_packet(endianness: Endianness)<EnhancedPacket>,
dbg_dmp!(do_parse!(
interface_id: u32!(endianness) >>
timestamp_hi: u32!(endianness) >>
timestamp_lo: u32!(endianness) >>
captured_len: u32!(endianness) >>
original_len: u32!(endianness) >>
data: take!(pad_to::<u32>(captured_len as usize)) >>
options: apply!(parse_options, endianness) >>
(
EnhancedPacket {
interface_id,
timestamp: timestamp::new(timestamp_hi, timestamp_lo),
captured_len,
original_len,
data: Cow::from(&data[..captured_len as usize]),
options,
}
)
))
);
impl<'a> WriteTo for EnhancedPacket<'a> {
fn write_to<T: ByteOrder, W: Write>(&self, w: &mut W) -> Result<usize> {
w.write_u32::<T>(self.interface_id)?;
self.timestamp.write_to::<T, _>(w)?;
w.write_u32::<T>(self.captured_len)?;
w.write_u32::<T>(self.original_len)?;
w.write_all(&self.data)?;
let padded_len = pad_to::<u32>(self.data.len()) - self.data.len();
if padded_len > 0 {
w.write_all(&vec![0; padded_len])?;
}
self.options.write_to::<T, _>(w)?;
Ok(self.size())
}
}
impl<'a> Block<'a> {
pub fn is_enhanced_packet(&self) -> bool {
self.ty == BLOCK_TYPE
}
pub fn as_enhanced_packet(&'a self, endianness: Endianness) -> Option<EnhancedPacket<'a>> {
if self.is_enhanced_packet() {
EnhancedPacket::parse(&self.body, endianness)
.map(|(_, packet)| packet)
.map_err(|err| {
warn!("fail to parse enhanced packet: {:?}", err);
hexdump!(self.body);
err
})
.ok()
} else {
None
}
}
}
#[cfg(test)]
pub mod tests {
use byteorder::LittleEndian;
use super::*;
use pcapng::Block;
pub const LE_ENHANCED_PACKET: &[u8] = b"\x06\x00\x00\x00\
\x64\x00\x00\x00\
\x00\x00\x00\x00\
\x6A\x72\x05\x00\xC1\x6A\x96\x80\
\x42\x00\x00\x00\
\x42\x00\x00\x00\
\x8C\x85\x90\x0B\xCB\x9E\x20\x4E\x71\xFC\x92\x14\x08\x00\x45\x00\
\x00\x34\xE8\xA8\x40\x00\xEF\x06\xC1\x0B\x11\xA7\xC0\x80\x0A\x06\
\x05\xE2\x01\xBB\xC8\xF3\x0A\x30\x41\xDC\xD0\x4D\x17\xA5\x80\x10\
\x01\x3F\xC7\xDC\x00\x00\x01\x01\x05\x0A\xD0\x4D\x17\xA4\xD0\x4D\
\x17\xA5\x00\x00\
\x64\x00\x00\x00";
lazy_static! {
static ref ENHANCED_PACKET: EnhancedPacket<'static> = EnhancedPacket {
interface_id: 0,
timestamp: 0x05726a80966ac1,
captured_len: 66,
original_len: 66,
data: Cow::from(
&b"\x8C\x85\x90\x0B\xCB\x9E\x20\x4E\x71\xFC\x92\x14\x08\x00\x45\x00\
\x00\x34\xE8\xA8\x40\x00\xEF\x06\xC1\x0B\x11\xA7\xC0\x80\x0A\x06\
\x05\xE2\x01\xBB\xC8\xF3\x0A\x30\x41\xDC\xD0\x4D\x17\xA5\x80\x10\
\x01\x3F\xC7\xDC\x00\x00\x01\x01\x05\x0A\xD0\x4D\x17\xA4\xD0\x4D\
\x17\xA5"[..]
),
options: vec![],
};
}
#[test]
fn test_parse() {
let (remaining, block) = Block::parse(LE_ENHANCED_PACKET, Endianness::Little).unwrap();
assert_eq!(remaining, b"");
assert_eq!(block.ty, BLOCK_TYPE);
assert_eq!(block.size(), LE_ENHANCED_PACKET.len());
let enhanced_packet = block.as_enhanced_packet(Endianness::Little).unwrap();
assert_eq!(enhanced_packet, *ENHANCED_PACKET);
}
#[test]
fn test_write() {
let mut buf = vec![];
let wrote = ENHANCED_PACKET
.write_to::<LittleEndian, _>(&mut buf)
.unwrap();
assert_eq!(wrote, ENHANCED_PACKET.size());
assert_eq!(
buf.as_slice(),
&LE_ENHANCED_PACKET[8..LE_ENHANCED_PACKET.len() - 4]
);
}
#[test]
fn test_options() {
let packet = EnhancedPacket {
interface_id: 0,
timestamp: 0,
captured_len: 0,
original_len: 0,
data: Cow::from(&[][..]),
options: vec![
epb_flags::<LittleEndian>(Flags::INBOUND | Flags::UNICAST),
epb_hash(HASH_ALGO_CRC32, [0xEC, 0x1D, 0x87, 0x97]),
epb_hash(
HASH_ALGO_MD5,
[
0x45, 0x6E, 0xC2, 0x17, 0x7C, 0x10, 0x1E, 0x3C, 0x2E, 0x99, 0x6E, 0xC2,
0x9A, 0x3D, 0x50, 0x8E,
],
),
epb_dropcount::<LittleEndian>(123),
],
};
let mut buf = vec![];
assert_eq!(packet.write_to::<LittleEndian, _>(&mut buf).unwrap(), 76);
let (_, packet) = EnhancedPacket::parse(&buf, Endianness::Little).unwrap();
assert_eq!(
packet.flags::<LittleEndian>().unwrap(),
Flags::INBOUND | Flags::UNICAST
);
assert_eq!(
packet.hash(),
vec![
(HASH_ALGO_CRC32, &[0xEC, 0x1D, 0x87, 0x97][..]),
(
HASH_ALGO_MD5,
&[
0x45, 0x6E, 0xC2, 0x17, 0x7C, 0x10, 0x1E, 0x3C, 0x2E, 0x99, 0x6E, 0xC2,
0x9A, 0x3D, 0x50, 0x8E,
][..],
),
]
);
assert_eq!(packet.dropcount::<LittleEndian>().unwrap(), 123);
}
}
|
pub mod api;
pub mod common;
pub mod connection;
pub mod error;
pub mod http;
pub use connection::*;
|
// Problem 38 - Pandigital multiples
//
// Take the number 192 and multiply it by each of 1, 2, and 3:
//
// 192 × 1 = 192
// 192 × 2 = 384
// 192 × 3 = 576
//
// By concatenating each product we get the 1 to 9 pandigital, 192384576. We will
// call 192384576 the concatenated product of 192 and (1,2,3)
//
// The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and
// 5, giving the pandigital, 918273645, which is the concatenated product of 9 and
// (1,2,3,4,5).
//
// What is the largest 1 to 9 pandigital 9-digit number that can be formed as the
// concatenated product of an integer with (1,2, ... , n) where n > 1?
fn main() {
println!("{}", solution());
}
fn solution() -> usize {
let mut largest = 0.to_string();
for n in 1..10_000 {
let mut nstr = n.to_string();
for k in 2..10 {
nstr.push_str(&(n*k).to_string());
if nstr.len() >= 9 {
break;
}
}
if nstr.len() == 9 && nstr > largest && is_pandigital(nstr.clone()) {
largest = nstr;
}
}
largest.parse().unwrap()
}
fn is_pandigital(s: String) -> bool {
let mut chars = s.chars().collect::<Vec<char>>();
chars.sort();
let sorted = chars.iter().cloned().collect::<String>();
sorted == "123456789"
}
|
// Copyright (c) 2016, <daggerbot@gmail.com>
// This software is available under the terms of the zlib license.
// See COPYING.md for more information.
use std::mem;
/// Gets some associated data.
pub trait Get<T> {
fn get (&self) -> T;
}
impl<T: Clone> Get<T> for T {
fn get (&self) -> T {
self.clone()
}
}
/// Gets a resource's implementation.
pub trait GetProvider {
type Provider;
fn provider (&self) -> &Self::Provider;
}
/// Gets a reference to some associated data.
pub trait GetRef<T> {
fn get_ref (&self) -> &T;
}
impl<T> GetRef<T> for T {
fn get_ref (&self) -> &T {
self
}
}
/// Compares two ranges of bytes from pointers for equality.
pub unsafe fn memeq<T> (lhs: *const T, rhs: *const T) -> bool {
let mut l = lhs as usize;
let mut r = rhs as usize;
let mut rem = mem::size_of::<T>();
while rem > 0 {
if *(l as *const u8) != *(r as *const u8) {
return false;
}
l += 1;
r += 1;
rem -= 1;
}
true
}
|
//! Hello world server.
//!
//! A simple client that opens a TCP stream, writes "hello world\n", and closes
//! the connection.
//!
//! You can test this out by running:
//!
//! ncat -l 6142
//! nc.exe -l -p 6142 -t -e cmd.exe
//!
//! And then in another terminal run:
//!
//! cargo run --example hello_world
/*
* cd C:\Users\むずでょ\source\repos\practice-rust\tokio
* cargo check --example ep2-created-stream
* cargo build --example ep2-created-stream
* cargo run --example ep2-created-stream
*
* [Hello World!](https://tokio.rs/docs/getting-started/hello-world/)
* [tokio 0.2.3](https://docs.rs/crate/tokio/0.2.3)
*/
use futures::executor::block_on;
use std::net::SocketAddr;
async fn connect() {
// Sleep 3 seconds.
println!("Info | Please wait 1 seconds.");
std::thread::sleep(std::time::Duration::from_secs(1));
// let addr: SocketAddr = "localhost:3000".parse().unwrap(); // v4 or v6?
let addr: SocketAddr = "127.0.0.1:3000".parse().unwrap();
println!("Host | {}", &addr);
// https://docs.rs/tokio-tcp/0.1.2/src/tokio_tcp/stream.rs.html#49-58
match tokio::net::TcpStream::connect(&addr).await {
Ok(_stream) => {
// Following snippets come here...
println!("Info | Connect end.");
}
Err(e) => println!("{:?}", e),
};
}
#[tokio::main]
async fn main() {
println!("Info | Please wait 1 seconds.");
std::thread::sleep(std::time::Duration::from_secs(1));
// syncronized.
block_on(connect());
// asyncronized.
// tokio::spawn(connect());
// Sleep 9 seconds.
println!("Info | Please wait 3 seconds.");
std::thread::sleep(std::time::Duration::from_secs(3));
println!("Info | Finished.");
}
|
// ユーザの記事
pub struct DomainUserArticle {
id: i32,
// 記事タイトル
title: String,
// 記事URL
url: String,
}
impl DomainUserArticle {
pub fn new(id: i32, title: String, url: String) -> DomainUserArticle {
DomainUserArticle {
id,
title,
url,
}
}
pub fn id(&self) -> &i32 {
&self.id
}
pub fn title(&self) -> &str {
&self.title
}
pub fn url(&self) -> &str {
&self.url
}
} |
// Debug module used to compare my cpu with Nintendulator's log of the nestest rom
#![allow(dead_code)]
use crate::cpu::{AddrMode, Cpu, OPTABLE};
impl<'a> Cpu<'a> {
/// Gets the operand addr without changing the program counter. Used in trace module
fn operand_addr_peek(&mut self, mode: AddrMode, pc: u16) -> u16 {
match mode {
AddrMode::None | AddrMode::Imp => 0,
AddrMode::Imm | AddrMode::Rel => pc,
AddrMode::Zp0 => self.mem_read(pc) as u16,
AddrMode::Zpx => {
let base = self.mem_read(pc);
base.wrapping_add(self.x()) as u16
}
AddrMode::Zpy => {
let base = self.mem_read(pc);
base.wrapping_add(self.y()) as u16
}
AddrMode::Abs | AddrMode::Ind => self.mem_read_word(pc),
AddrMode::Abx => {
let base = self.mem_read_word(pc);
base.wrapping_add(self.x() as u16)
}
AddrMode::AbxW => {
let base = self.mem_read_word(pc);
base.wrapping_add(self.x() as u16)
}
AddrMode::Aby => {
let base = self.mem_read_word(pc);
base.wrapping_add(self.y() as u16)
}
AddrMode::AbyW => {
let base = self.mem_read_word(pc);
base.wrapping_add(self.y() as u16)
}
AddrMode::Izx => {
let base = self.mem_read(pc);
let ptr = base.wrapping_add(self.x());
let lo = self.mem_read(ptr as u16);
let hi = self.mem_read(ptr.wrapping_add(1) as u16);
u16::from_le_bytes([lo, hi])
}
AddrMode::Izy => {
let ptr = self.mem_read(pc);
let lo = self.mem_read(ptr as u16);
let hi = self.mem_read(ptr.wrapping_add(1) as u16);
u16::from_le_bytes([lo, hi]).wrapping_add(self.y() as u16)
}
AddrMode::IzyW => {
let ptr = self.mem_read(pc);
let lo = self.mem_read(ptr as u16);
let hi = self.mem_read(ptr.wrapping_add(1) as u16);
u16::from_le_bytes([lo, hi]).wrapping_add(self.y() as u16)
}
}
}
}
/// Traces execution of the NES
pub fn trace(cpu: &mut Cpu) -> String {
let code = cpu.mem_read(cpu.pc());
let ins = *OPTABLE.get(&code).unwrap();
let begin = cpu.pc();
let mut hex_dump = vec![code];
let (mem_addr, stored_value) = match ins.mode {
AddrMode::Imm | AddrMode::None | AddrMode::Imp => (0, 0),
_ => {
let addr = cpu.operand_addr_peek(ins.mode, begin + 1);
(addr, cpu.mem_read(addr))
}
};
let tmp = match ins.mode {
AddrMode::None | AddrMode::Imp => match ins.opcode {
0x0a | 0x4a | 0x2a | 0x6a => "A ".to_string(),
_ => String::from(""),
},
AddrMode::Imm
| AddrMode::Zp0
| AddrMode::Zpx
| AddrMode::Zpy
| AddrMode::Izx
| AddrMode::Izy
| AddrMode::IzyW
| AddrMode::Rel => {
let address: u8 = cpu.mem_read(begin + 1);
hex_dump.push(address);
match ins.mode {
AddrMode::Imm => format!("#${:02x}", address),
AddrMode::Zp0 => format!("${:02x} = {:02x}", mem_addr, stored_value),
AddrMode::Zpx => format!(
"${:02x},X @ {:02x} = {:02x}",
address, mem_addr, stored_value
),
AddrMode::Zpy => format!(
"${:02x},Y @ {:02x} = {:02x}",
address, mem_addr, stored_value
),
AddrMode::Izx => format!(
"(${:02x},X) @ {:02x} = {:04x} = {:02x}",
address,
(address.wrapping_add(cpu.x())),
mem_addr,
stored_value
),
AddrMode::Izy | AddrMode::IzyW => format!(
"(${:02x}),Y = {:04x} @ {:04x} = {:02x}",
address,
(mem_addr.wrapping_sub(cpu.y() as u16)),
mem_addr,
stored_value
),
AddrMode::Rel => {
// assuming local jumps: BNE, BVS, etc....
let address: usize =
(begin as usize + 2).wrapping_add((address as i8) as usize);
format!("${:04x}", address)
}
_ => panic!(
"unexpected addressing mode {:?} has ops-len 2. code {:02x}",
ins.mode, ins.opcode
),
}
}
AddrMode::Abs
| AddrMode::Abx
| AddrMode::AbxW
| AddrMode::Aby
| AddrMode::AbyW
| AddrMode::Ind => {
let address_lo = cpu.mem_read(begin + 1);
let address_hi = cpu.mem_read(begin + 2);
hex_dump.push(address_lo);
hex_dump.push(address_hi);
let address = cpu.mem_read_word(begin + 1);
match ins.mode {
AddrMode::Ind | AddrMode::Abs
if (ins.opcode == 0x4C) | (ins.opcode == 0x20) | (ins.opcode == 0x6C) =>
{
if ins.opcode == 0x6C {
//jmp indirect
let jmp_addr = if address & 0x00FF == 0x00FF {
let lo = cpu.mem_read(address);
let hi = cpu.mem_read(address & 0xFF00);
(hi as u16) << 8 | (lo as u16)
} else {
cpu.mem_read_word(address)
};
format!("(${:04x}) = {:04x}", address, jmp_addr)
} else {
format!("${:04x}", address)
}
}
AddrMode::Abs => format!("${:04x} = {:02x}", mem_addr, stored_value),
AddrMode::Abx | AddrMode::AbxW => format!(
"${:04x},X @ {:04x} = {:02x}",
address, mem_addr, stored_value
),
AddrMode::Aby | AddrMode::AbyW => format!(
"${:04x},Y @ {:04x} = {:02x}",
address, mem_addr, stored_value
),
_ => panic!(
"unexpected addressing mode {:?} has ops-len 3. code {:02x}",
ins.mode, ins.opcode
),
}
}
};
let hex_str = hex_dump
.iter()
.map(|x| format!("{:02x}", x))
.collect::<Vec<String>>()
.join(" ");
let asm_str = format!("{:04x} {:8} {: >4} {}", begin, hex_str, ins.mnemonic, tmp)
.trim()
.to_string();
format!(
"{:47} A:{:02x} X:{:02x} Y:{:02x} P:{:02x} SP:{:02x} CYC:{}",
asm_str,
cpu.a(),
cpu.x(),
cpu.y(),
cpu.p(),
cpu.s(),
cpu.cycles()
)
.to_ascii_uppercase()
}
|
fn main() {
// イミュータブルな束縛を作っておく。
let x = 1;
// `&値` で参照がとれる。
let y: &isize = &x;
// ミュータブルな束縛を作っておく。
let mut a = 1;
// `&mut 値`でミュータブルな参照がとれる。値もミュータブルである必要がある。
let b = &mut a;
// `*参照 = 値`で代入できる。これは`&mut`型ならいつでも可能。
*b = 2;
// bの参照先が書き変わっている。aは一定の条件を満たしている(Copyな)ため参照外しができる。
println!("result is {}", *b); // => 2
println!("result is {}", *y); // => 1
} |
// SPDX-FileCopyrightText: 2020-2021 HH Partners
//
// SPDX-License-Identifier: MIT
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CreationInfo {
/// https://spdx.github.io/spdx-spec/2-document-creation-information/#27-license-list-version
#[serde(skip_serializing_if = "Option::is_none", default)]
pub license_list_version: Option<String>,
/// https://spdx.github.io/spdx-spec/2-document-creation-information/#28-creator
pub creators: Vec<String>,
/// https://spdx.github.io/spdx-spec/2-document-creation-information/#29-created
pub created: DateTime<Utc>,
/// https://spdx.github.io/spdx-spec/2-document-creation-information/#210-creator-comment
#[serde(skip_serializing_if = "Option::is_none", default)]
#[serde(rename = "comment")]
pub creator_comment: Option<String>,
}
impl Default for CreationInfo {
fn default() -> Self {
Self {
license_list_version: None,
creators: vec![
"Person: Jane Doe ()".into(),
"Organization: ExampleCodeInspect ()".into(),
"Tool: LicenseFind-1.0".into(),
],
created: chrono::offset::Utc::now(),
creator_comment: None,
}
}
}
|
use std::io::{BufReader, BufRead, Write};
use std::process::{ChildStdin, ChildStdout, Command, Stdio};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Satisfiability {
Sat,
Unsat,
Unknown,
}
#[derive(Debug)]
pub struct Z3 {
z3_stdin: ChildStdin,
z3_stdout: BufReader<ChildStdout>,
}
impl Z3 {
pub fn new() -> Z3 {
let z3 = Command::new("z3")
.args(&["-in"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("Failed to spawn Z3 process");
Z3 {
z3_stdin: z3.stdin.expect("Failed to open stdin to Z3"),
z3_stdout: BufReader::new(z3.stdout.expect("Failed to open stdout to Z3")),
}
}
pub fn input(&mut self, input: &str) {
writeln!(self.z3_stdin, "{}", input).expect("Failed to send input to Z3 process");
}
pub fn check_sat(&mut self) -> Satisfiability {
writeln!(self.z3_stdin, "(check-sat)").expect("Failed to check_sat");
let sat = self.read_line();
match &*sat {
"sat" => Satisfiability::Sat,
"unsat" => Satisfiability::Unsat,
"unknown" => Satisfiability::Unknown,
_ => panic!("Unknown value for satisfiability: {}", sat),
}
}
pub fn eval(&mut self, expr: String) -> String {
writeln!(self.z3_stdin, "(eval {})", expr).expect("Failed to eval");
self.read_line()
}
pub fn read_line(&mut self) -> String {
let mut buf = String::new();
self.z3_stdout.read_line(&mut buf).expect("Failed to read line from Z3 process");
buf.trim().to_string()
}
}
|
//! This example demonstrates using the [`JsonTable::collapse`] function
//! to greatly improve the readability of a [`JsonTable`].
use json_to_table::json_to_table;
fn main() {
let json = serde_json::json!({
"key1": "value1",
"key2": {
"key1": 123,
"key2": [1, 2, 3, 4, 5],
},
"key3": [
{"key": 123.3},
2,
"asd"
],
});
let mut table = json_to_table(&json);
table.collapse();
println!("{table}");
}
|
use ::*;
/// Remoes all line segments that can't possibly be part of a cycle.
pub fn prune<P, I, S: 'static>(segments: I, epsilon: f32, only_starts: bool) -> Vec<PathSegment<S>>
where
I: IntoIterator<Item = P>,
P: Into<smallvec::SmallVec<[Point<S>; 2]>>,
{
let mut dual_qt = util::populate(segments, epsilon);
loop {
let made_progress = prune_one_iter(&mut dual_qt, epsilon, only_starts);
if !made_progress {
break;
}
}
dual_qt.into_iter().collect()
}
fn prune_one_iter<S: 'static>(dual_qt: &mut DualQuadTree<S>, epsilon: f32, only_starts: bool) -> bool {
let mut made_progress = false;
let mut to_remove = vec![];
for (id, path) in dual_qt.iter() {
let (start, end) = (path.first(), path.last());
let a = dual_qt.has_forward_neighbor(id, start, epsilon);
let b = || dual_qt.has_backward_neighbor(id, start, epsilon);
let c = dual_qt.has_backward_neighbor(id, end, epsilon);
let d = || dual_qt.has_forward_neighbor(id, end, epsilon);
let should_be_kept = (a || (!only_starts && b())) && (c || (!only_starts && d()));
if !should_be_kept {
to_remove.push(id);
}
}
for id in to_remove {
dual_qt.remove(id);
made_progress = true;
}
made_progress
}
|
fn main() {
let i = 3;
{
let borrow1 = &i;
println!("borrow1: {}", borrow1);
}
{
let borrow2 = &i;
println!("borrow2: {}", borrow2);
}
}
|
mod config;
mod model;
mod raft_network;
mod raft_storage;
use std::sync::Arc;
use clap;
use tokio;
use tokio::join;
#[tokio::main]
pub async fn main() {
let matches = clap::App::new("Simple RAFT experiment")
.version("1.1.1.1.1.1.1")
.author("monoid")
.arg(
clap::Arg::with_name("config")
.long("config")
.required(true)
.takes_value(true),
)
.arg(
clap::Arg::with_name("self")
.long("self")
.required(true)
.takes_value(true),
)
.get_matches();
let path = matches
.value_of("config")
.expect("YAML config path expected");
let conf = config::load_config(&path).expect("Valid YAML config expected");
let node_self = matches.value_of("self").expect("self name expected");
eprintln!(
"HTTP port: {}, RAFT port: {}",
conf.http_port, conf.raft_port
);
eprintln!("Self: {}", node_self);
eprintln!("Nodes:");
for n in &conf.nodes {
eprintln!("{}", n);
}
let config = conf.raft_config.validate();
eprintln!("Raft config: {:?}", config);
let node_id = node_self.parse().unwrap();
let storage = memstore::MemStore::new(node_id);
let network = Arc::new(raft_network::RaftRouter::with_nodes(&conf.nodes));
let network1 = network.clone();
let raft = async_raft::Raft::new(
node_id,
Arc::new(config.expect("Expected valid config")),
network,
Arc::new(storage),
);
let raft = Arc::new(raft);
let raft1 = raft.clone();
join!(
raft_network::network_server_endpoint(raft1, network1, conf.http_port),
raft.initialize((0u64..conf.nodes.len() as u64).collect::<_>())
)
.1
.expect("Result");
}
|
extern crate hllvm;
use hllvm::{ir, target, support};
fn build_module(context: &ir::Context) -> ir::Module {
let mut module = ir::Module::new("mymodule", context);
let int8 = ir::IntegerType::new(8, &context);
let stru = ir::StructType::new(&[&int8.as_ref()], false, context);
let func_ty = ir::FunctionType::new(&stru.as_ref(), &[], false);
{
let mut func = module.get_or_insert_function("my_func", &func_ty, &[]);
let mut block = ir::Block::new(&context);
block.append(ir::ReturnInst::new(None, context).as_ref().as_ref());
func.append(&mut block);
}
module
}
fn main() {
let context = ir::Context::new();
let module = build_module(&context);
module.dump();
let stdout = support::FileOutputStream::stdout(false);
let target = target::Registry::get().targets().find(|t| t.name() == "x86-64").expect("doesn't support X86-64");
target::Compilation::new(&target)
.compile(module, &stdout, target::FileType::Assembly);
}
|
use super::keys::*;
use super::trie_node::TrieNode;
use super::{NibbleVec, SubTrie, SubTrieMut, SubTrieResult};
impl<'a, V> SubTrie<'a, V> {
/// Look up the value for the given key, which should be an extension of this subtrie's key.
///
/// The key may be any borrowed form of the trie's key type, but TrieKey on the borrowed
/// form *must* match those for the key type
pub fn get<K: TrieKey + ?Sized>(&self, key: &K) -> SubTrieResult<&V> {
subtrie_get(&self.prefix, self.node, key)
}
/// Move the view to a subkey. The new view will be looking at the original key with
/// the encoding of this subkey appended.
pub fn to_subkey<K: TrieKey + ?Sized>(self, subkey: &K) -> Option<SubTrie<'a, V>> {
self.to_subkey_nv(&subkey.encode())
}
/// Move the view to a subkey, specified directly by its `NibbleVec` encoding.
/// The input view is consumed.
pub fn to_subkey_nv(self, subkey: &NibbleVec) -> Option<SubTrie<'a, V>> {
match self {
SubTrie {prefix, node} =>
node.get(subkey).map(|node|
SubTrie {
prefix: prefix.join(subkey),
node
})
}
}
}
fn subtrie_get<'a, K: TrieKey + ?Sized, V>(
prefix: &NibbleVec,
node: &'a TrieNode<V>,
key: &K,
) -> SubTrieResult<&'a V> {
let key_enc = key.encode();
match match_keys(0, prefix, &key_enc) {
KeyMatch::Full => Ok(node.value()),
KeyMatch::FirstPrefix => Ok(node
.get(&stripped(key_enc, prefix))
.and_then(TrieNode::value)),
_ => Err(()),
}
}
impl<'a, V> SubTrieMut<'a, V> {
/// Mutable reference to the node's value.
pub fn value_mut(&mut self) -> Option<&mut V> {
self.node.value_mut()
}
/// Look up the value for the given key, which should be an extension of this subtrie's key.
///
/// The key may be any borrowed form of the trie's key type, but TrieKey on the borrowed
/// form *must* match those for the key type
pub fn get<K: TrieKey + ?Sized>(&self, key: &K) -> SubTrieResult<&V> {
subtrie_get(&self.prefix, &*self.node, key)
}
/// Move the view to a subkey. The new view will be looking at the original key with
/// the encoding of this subkey appended.
pub fn to_subkey<K: TrieKey + ?Sized>(self, subkey: &K) -> Option<SubTrieMut<'a, V>> {
self.to_subkey_nv(&subkey.encode())
}
/// Move the view to a subkey, specified directly by its `NibbleVec` encoding.
/// The input view is consumed.
pub fn to_subkey_nv(self, subkey: &NibbleVec) -> Option<SubTrieMut<'a, V>> {
match self {
SubTrieMut {length, prefix, node} =>
node.get_mut(subkey).map(move |node|
SubTrieMut {
length,
prefix: prefix.join(subkey),
node
})
}
}
/// Insert a value in this subtrie. The key should be an extension of this subtrie's key.
pub fn insert<K: TrieKey + ?Sized>(&mut self, key: &K, value: V) -> SubTrieResult<V> {
let key_enc = key.encode();
let previous = match match_keys(0, &self.prefix, &key_enc) {
KeyMatch::Full => self.node.replace_value(value),
KeyMatch::FirstPrefix => self
.node
.insert(stripped(key_enc, &self.prefix), value),
_ => {
return Err(());
}
};
if previous.is_none() {
*self.length += 1;
}
Ok(previous)
}
/// Remove a value from this subtrie. The key should be an extension of this subtrie's key.
pub fn remove<K: TrieKey + ?Sized>(&mut self, key: &K) -> SubTrieResult<V> {
self.remove_nv(&key.encode())
}
/// Remove a value from this subtrie. The key should be an extension of this subtrie's key.
pub fn remove_nv(&mut self, key: &NibbleVec) -> SubTrieResult<V> {
let removed = match match_keys(0, &self.prefix, key) {
KeyMatch::Full => self.node.take_value(),
KeyMatch::FirstPrefix => self.node.remove(key),
_ => {
return Err(());
}
};
if removed.is_some() {
*self.length -= 1;
}
Ok(removed)
}
}
fn stripped(mut key: NibbleVec, prefix: &NibbleVec) -> NibbleVec {
key.split(prefix.len())
}
|
extern crate quick_xml;
use quick_xml::{XmlWriter, Element, Event};
use quick_xml::error::Error as XmlError;
use std::collections::HashMap;
use toxml::ToXml;
/// Types and functions for
/// [iTunes](https://help.apple.com/itc/podcasts_connect/#/itcb54353390) extensions.
pub mod itunes;
/// Types and functions for [Dublin Core](http://dublincore.org/documents/dces/) extensions.
pub mod dublincore;
/// A map of extension namespace prefixes to local names to elements.
pub type ExtensionMap = HashMap<String, HashMap<String, Vec<Extension>>>;
/// A namespaced extension such as iTunes or Dublin Core.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Extension {
/// The qualified name of the extension element.
pub name: String,
/// The content of the extension element.
pub value: Option<String>,
/// The attributes for the extension element.
pub attrs: HashMap<String, String>,
/// The children of the extension element. This is a map of local names to child
/// elements.
pub children: HashMap<String, Vec<Extension>>,
}
impl ToXml for Extension {
fn to_xml<W: ::std::io::Write>(&self, writer: &mut XmlWriter<W>) -> Result<(), XmlError> {
let element = Element::new(&self.name);
try!(writer.write(Event::Start({
let mut element = element.clone();
element.extend_attributes(&self.attrs);
element
})));
if let Some(value) = self.value.as_ref() {
try!(writer.write(Event::Text(Element::new(value))));
}
for extensions in self.children.values() {
for extension in extensions {
try!(extension.to_xml(writer));
}
}
writer.write(Event::End(element))
}
}
/// Get a reference to the value for the first extension with the specified key.
pub fn get_extension_value<'a>(map: &'a HashMap<String, Vec<Extension>>,
key: &str)
-> Option<&'a str> {
map.get(key).and_then(|v| v.first()).and_then(|ext| ext.value.as_ref()).map(|s| s.as_str())
}
/// Remove and return the value for the first extension with the specified key.
pub fn remove_extension_value(map: &mut HashMap<String, Vec<Extension>>,
key: &str)
-> Option<String> {
map.remove(key).map(|mut v| v.remove(0)).and_then(|ext| ext.value)
}
/// Get a reference to all values for the extensions with the specified key.
pub fn get_extension_values<'a>(map: &'a HashMap<String, Vec<Extension>>,
key: &str)
-> Option<Vec<&'a str>> {
map.get(key).map(|v| {
v.iter().filter_map(|ext| ext.value.as_ref().map(|s| s.as_str())).collect::<Vec<_>>()
})
}
/// Remove and return all values for the extensions with the specified key.
pub fn remove_extension_values(map: &mut HashMap<String, Vec<Extension>>,
key: &str)
-> Option<Vec<String>> {
map.remove(key).map(|v| v.into_iter().filter_map(|ext| ext.value).collect::<Vec<_>>())
}
|
use std::sync::Arc;
use chrono::{Duration, FixedOffset, Timelike, Utc};
use eyre::Report;
use image::{png::PngEncoder, ColorType, ImageEncoder};
use plotters::{
prelude::{
AreaSeries, BitMapBackend, ChartBuilder, Circle, EmptyElement, IntoDrawingArea,
IntoSegmentedCoord, PointSeries, Rectangle, SegmentValue, SeriesLabelPosition,
},
style::{Color, RGBColor, ShapeStyle, BLACK, GREEN, RED, WHITE},
};
use plotters_backend::FontStyle;
use rosu_v2::prelude::{GameMode, OsuError, Score, User};
use twilight_model::application::{
command::CommandOptionChoice,
interaction::{
application_command::{CommandDataOption, CommandOptionValue},
ApplicationCommand,
},
};
use crate::{
commands::{
osu::{get_user, get_user_and_scores, ProfileGraphFlags, ScoreArgs, UserArgs},
parse_discord, parse_mode_option, MyCommand, MyCommandOption,
},
core::{commands::CommandData, Context},
database::UserConfig,
embeds::{Author, EmbedBuilder, EmbedData, Footer, GraphEmbed},
error::{Error, GraphError},
util::{
constants::{
common_literals::{DISCORD, MODE, NAME},
GENERAL_ISSUE, HUISMETBENEN_ISSUE, OSU_API_ISSUE, OSU_BASE,
},
numbers::{with_comma_float, with_comma_int},
osu::flag_url,
CountryCode, InteractionExt, MessageBuilder, MessageExt,
},
BotResult,
};
use super::{
option_discord, option_mode, option_name, player_snipe_stats, profile, sniped,
ProfileGraphParams,
};
async fn graph(ctx: Arc<Context>, data: CommandData<'_>, args: GraphArgs) -> BotResult<()> {
let GraphArgs { config, kind } = args;
let mode = config.mode.unwrap_or(GameMode::STD);
let name = match config.into_username() {
Some(name) => name,
None => return super::require_link(&ctx, &data).await,
};
let user_args = UserArgs::new(name.as_str(), mode);
let tuple_option = match kind {
GraphKind::MedalProgression => medals_graph(&ctx, &data, &name, &user_args).await?,
GraphKind::PlaycountReplays { flags } => {
if flags.is_empty() {
return data.error(&ctx, ":clown:").await;
}
playcount_replays_graph(&ctx, &data, &name, &user_args, flags).await?
}
GraphKind::RankProgression => rank_graph(&ctx, &data, &name, &user_args).await?,
GraphKind::ScoreTime { tz } => {
// Handle distinctly because it has a footer due to the timezone
let tuple_option = score_time_graph(&ctx, &data, &name, user_args, tz).await?;
let (user, graph, tz) = match tuple_option {
Some(tuple) => tuple,
None => return Ok(()),
};
let author = {
let stats = user.statistics.as_ref().expect("no statistics on user");
let text = format!(
"{name}: {pp}pp (#{global} {country}{national})",
name = user.username,
pp = with_comma_float(stats.pp),
global = with_comma_int(stats.global_rank.unwrap_or(0)),
country = user.country_code,
national = stats.country_rank.unwrap_or(0)
);
let url = format!("{OSU_BASE}users/{}/{}", user.user_id, user.mode);
let icon = flag_url(user.country_code.as_str());
Author::new(text).url(url).icon_url(icon)
};
let footer = Footer::new(format!("Considering timezone UTC{tz}"));
let embed = EmbedBuilder::new()
.author(author)
.footer(footer)
.image("attachment://graph.png")
.build();
let builder = MessageBuilder::new().embed(embed).file("graph.png", graph);
data.create_message(&ctx, builder).await?;
return Ok(());
}
GraphKind::Sniped => sniped_graph(&ctx, &data, &name, &user_args).await?,
GraphKind::SnipeCount => snipe_count_graph(&ctx, &data, &name, &user_args).await?,
GraphKind::Top { order } => top_graph(&ctx, &data, &name, user_args, order).await?,
};
let (user, graph) = match tuple_option {
Some(tuple) => tuple,
None => return Ok(()),
};
let embed = GraphEmbed::new(&user).into_builder().build();
let builder = MessageBuilder::new().embed(embed).file("graph.png", graph);
data.create_message(&ctx, builder).await?;
Ok(())
}
const W: u32 = 1350;
const H: u32 = 711;
const LEN: usize = (W * H) as usize;
async fn medals_graph(
ctx: &Context,
data: &CommandData<'_>,
name: &str,
user_args: &UserArgs<'_>,
) -> BotResult<Option<(User, Vec<u8>)>> {
let mut user = match get_user(ctx, user_args).await {
Ok(user) => user,
Err(OsuError::NotFound) => {
let content = format!("Could not find user `{name}`");
data.error(ctx, content).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
};
if let Some(ref mut medals) = user.medals {
medals.sort_unstable_by_key(|medal| medal.achieved_at);
}
let bytes = match super::medals::stats::graph(user.medals.as_ref().unwrap(), W, H) {
Ok(Some(graph)) => graph,
Ok(None) => {
let content = format!("`{name}` does not have any medals");
let builder = MessageBuilder::new().embed(content);
data.create_message(ctx, builder).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, GENERAL_ISSUE).await;
warn!("{:?}", Report::new(err));
return Ok(None);
}
};
Ok(Some((user, bytes)))
}
async fn playcount_replays_graph(
ctx: &Context,
data: &CommandData<'_>,
name: &str,
user_args: &UserArgs<'_>,
flags: ProfileGraphFlags,
) -> BotResult<Option<(User, Vec<u8>)>> {
let mut user = match get_user(ctx, user_args).await {
Ok(user) => user,
Err(OsuError::NotFound) => {
let content = format!("Could not find user `{name}`");
data.error(ctx, content).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
};
let params = ProfileGraphParams::new(ctx, &mut user)
.width(W)
.height(H)
.flags(flags);
let bytes = match profile::graphs(params).await {
Ok(Some(graph)) => graph,
Ok(None) => {
let content = format!("`{name}` does not have enough playcount data points");
let builder = MessageBuilder::new().embed(content);
data.create_message(ctx, builder).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, GENERAL_ISSUE).await;
warn!("{:?}", Report::new(err));
return Ok(None);
}
};
Ok(Some((user, bytes)))
}
async fn rank_graph(
ctx: &Context,
data: &CommandData<'_>,
name: &str,
user_args: &UserArgs<'_>,
) -> BotResult<Option<(User, Vec<u8>)>> {
let user = match get_user(ctx, user_args).await {
Ok(user) => user,
Err(OsuError::NotFound) => {
let content = format!("Could not find user `{name}`");
data.error(ctx, content).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
};
fn draw_graph(user: &User) -> Result<Option<Vec<u8>>, GraphError> {
let mut buf = vec![0; LEN * 3];
let history = match user.rank_history {
Some(ref history) if history.is_empty() => return Ok(None),
Some(ref history) => history,
None => return Ok(None),
};
let history_len = history.len();
let mut min = u32::MAX;
let mut max = 0;
let mut min_idx = 0;
let mut max_idx = 0;
for (i, &rank) in history.iter().enumerate() {
if rank < min {
min = rank;
min_idx = i;
if rank > max {
max = rank;
max_idx = i;
}
} else if rank > max {
max = rank;
max_idx = i;
}
}
let y_label_area_size = if max > 1_000_000 {
75
} else if max > 10_000 {
65
} else if max > 100 {
50
} else {
40
};
let (min, max) = (-(max as i32), -(min as i32));
{
let root = BitMapBackend::with_buffer(&mut buf, (W, H)).into_drawing_area();
let background = RGBColor(19, 43, 33);
root.fill(&background)?;
let style: fn(RGBColor) -> ShapeStyle = |color| ShapeStyle {
color: color.to_rgba(),
filled: false,
stroke_width: 1,
};
let mut chart = ChartBuilder::on(&root)
.x_label_area_size(40)
.y_label_area_size(y_label_area_size)
.margin(10)
.margin_left(6)
.build_cartesian_2d(0_u32..history_len.saturating_sub(1) as u32, min..max)?;
chart
.configure_mesh()
.disable_y_mesh()
.x_labels(20)
.x_desc("Days ago")
.x_label_formatter(&|x| format!("{}", 90 - *x))
.y_label_formatter(&|y| format!("{}", -*y))
.y_desc("Rank")
.label_style(("sans-serif", 15, &WHITE))
.bold_line_style(&WHITE.mix(0.3))
.axis_style(RGBColor(7, 18, 14))
.axis_desc_style(("sans-serif", 16, FontStyle::Bold, &WHITE))
.draw()?;
let data = (0..).zip(history.iter().map(|rank| -(*rank as i32)));
let area_style = RGBColor(2, 186, 213).mix(0.7).filled();
let border_style = style(RGBColor(0, 208, 138)).stroke_width(3);
let series = AreaSeries::new(data, min, area_style).border_style(border_style);
chart.draw_series(series)?;
let max_coords = (min_idx as u32, max);
let circle = Circle::new(max_coords, 9_u32, style(GREEN));
chart
.draw_series(std::iter::once(circle))?
.label(format!("Peak: #{}", with_comma_int(-max)))
.legend(|(x, y)| Circle::new((x, y), 5_u32, style(GREEN)));
let min_coords = (max_idx as u32, min);
let circle = Circle::new(min_coords, 9_u32, style(RED));
chart
.draw_series(std::iter::once(circle))?
.label(format!("Worst: #{}", with_comma_int(-min)))
.legend(|(x, y)| Circle::new((x, y), 5_u32, style(RED)));
let position = if min_idx <= 70 {
SeriesLabelPosition::UpperRight
} else if max_idx > 70 {
SeriesLabelPosition::UpperLeft
} else {
SeriesLabelPosition::LowerRight
};
chart
.configure_series_labels()
.border_style(BLACK.stroke_width(2))
.background_style(&RGBColor(192, 192, 192))
.position(position)
.legend_area_size(13)
.label_font(("sans-serif", 15, FontStyle::Bold))
.draw()?;
}
// Encode buf to png
let mut png_bytes: Vec<u8> = Vec::with_capacity(LEN);
let png_encoder = PngEncoder::new(&mut png_bytes);
png_encoder.write_image(&buf, W, H, ColorType::Rgb8)?;
Ok(Some(png_bytes))
}
let bytes = match draw_graph(&user) {
Ok(Some(graph)) => graph,
Ok(None) => {
let content = format!("`{name}` has no available rank data :(");
let _ = data.error(ctx, content).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, GENERAL_ISSUE).await;
warn!("{:?}", Report::new(err));
return Ok(None);
}
};
Ok(Some((user, bytes)))
}
async fn score_time_graph(
ctx: &Context,
data: &CommandData<'_>,
name: &str,
user_args: UserArgs<'_>,
tz: Option<FixedOffset>,
) -> BotResult<Option<(User, Vec<u8>, FixedOffset)>> {
let score_args = ScoreArgs::top(100);
let (user, scores) = match get_user_and_scores(ctx, user_args, &score_args).await {
Ok(tuple) => tuple,
Err(OsuError::NotFound) => {
let content = format!("Could not find user `{name}`");
data.error(ctx, content).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
};
fn draw_graph(scores: &[Score], tz: &FixedOffset) -> Result<Vec<u8>, GraphError> {
let mut hours = [0_u32; 24];
for score in scores {
hours[score.created_at.with_timezone(tz).hour() as usize] += 1;
}
let max = hours.iter().max().copied().unwrap_or(0);
let mut buf = vec![0; LEN * 3];
{
let root = BitMapBackend::with_buffer(&mut buf, (W, H)).into_drawing_area();
let background = RGBColor(19, 43, 33);
root.fill(&background)?;
let mut chart = ChartBuilder::on(&root)
.x_label_area_size(40)
.y_label_area_size(40)
.margin(5)
.build_cartesian_2d((0_u32..23_u32).into_segmented(), 0u32..max + 1)?;
chart
.configure_mesh()
.disable_x_mesh()
.x_labels(24)
.x_desc("Hour of the day")
.y_desc("# of plays set")
.label_style(("sans-serif", 15, &WHITE))
.bold_line_style(&WHITE.mix(0.3))
.axis_style(RGBColor(7, 18, 14))
.axis_desc_style(("sans-serif", 16, FontStyle::Bold, &WHITE))
.draw()?;
let counts = ScoreHourCounts::new(hours);
chart.draw_series(counts)?;
}
// Encode buf to png
let mut png_bytes: Vec<u8> = Vec::with_capacity(LEN);
let png_encoder = PngEncoder::new(&mut png_bytes);
png_encoder.write_image(&buf, W, H, ColorType::Rgb8)?;
Ok(png_bytes)
}
let tz = tz.unwrap_or_else(|| CountryCode::from(user.country_code.clone()).timezone());
let bytes = match draw_graph(&scores, &tz) {
Ok(graph) => graph,
Err(err) => {
let _ = data.error(ctx, GENERAL_ISSUE).await;
warn!("{:?}", Report::new(err));
return Ok(None);
}
};
Ok(Some((user, bytes, tz)))
}
async fn sniped_graph(
ctx: &Context,
data: &CommandData<'_>,
name: &str,
user_args: &UserArgs<'_>,
) -> BotResult<Option<(User, Vec<u8>)>> {
let user = match get_user(ctx, user_args).await {
Ok(user) => user,
Err(OsuError::NotFound) => {
let content = format!("Could not find user `{name}`");
data.error(ctx, content).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
};
let (sniper, snipee) = if ctx.contains_country(user.country_code.as_str()) {
let now = Utc::now();
let sniper_fut =
ctx.clients
.custom
.get_national_snipes(&user, true, now - Duration::weeks(8), now);
let snipee_fut =
ctx.clients
.custom
.get_national_snipes(&user, false, now - Duration::weeks(8), now);
match tokio::try_join!(sniper_fut, snipee_fut) {
Ok((mut sniper, snipee)) => {
sniper.retain(|score| score.sniped.is_some());
(sniper, snipee)
}
Err(err) => {
let _ = data.error(ctx, HUISMETBENEN_ISSUE).await;
return Err(err.into());
}
}
} else {
let content = format!(
"`{}`'s country {} is not supported :(",
user.username, user.country_code
);
data.error(ctx, content).await?;
return Ok(None);
};
let bytes = match sniped::graphs(user.username.as_str(), &sniper, &snipee, W, H) {
Ok(Some(graph)) => graph,
Ok(None) => {
let content =
format!("`{name}` was neither sniped nor sniped other people in the last 8 weeks");
let builder = MessageBuilder::new().embed(content);
data.create_message(ctx, builder).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, GENERAL_ISSUE).await;
warn!("{:?}", Report::new(err));
return Ok(None);
}
};
Ok(Some((user, bytes)))
}
async fn snipe_count_graph(
ctx: &Context,
data: &CommandData<'_>,
name: &str,
user_args: &UserArgs<'_>,
) -> BotResult<Option<(User, Vec<u8>)>> {
let user = match get_user(ctx, user_args).await {
Ok(user) => user,
Err(OsuError::NotFound) => {
let content = format!("Could not find user `{name}`");
data.error(ctx, content).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
};
let player = if ctx.contains_country(user.country_code.as_str()) {
let player_fut = ctx
.clients
.custom
.get_snipe_player(&user.country_code, user.user_id);
match player_fut.await {
Ok(counts) => counts,
Err(err) => {
let report = Report::new(err).wrap_err("failed to retrieve snipe player");
warn!("{report:?}");
let content = format!("`{name}` has never had any national #1s");
let builder = MessageBuilder::new().embed(content);
data.create_message(ctx, builder).await?;
return Ok(None);
}
}
} else {
let content = format!(
"`{}`'s country {} is not supported :(",
user.username, user.country_code
);
data.error(ctx, content).await?;
return Ok(None);
};
let graph_result =
player_snipe_stats::graphs(&player.count_first_history, &player.count_sr_spread, W, H);
let bytes = match graph_result {
Ok(graph) => graph,
Err(err) => {
let _ = data.error(ctx, GENERAL_ISSUE).await;
warn!("{:?}", Report::new(err));
return Ok(None);
}
};
Ok(Some((user, bytes)))
}
struct ScoreHourCounts {
hours: [u32; 24],
idx: usize,
}
impl ScoreHourCounts {
fn new(hours: [u32; 24]) -> Self {
Self { hours, idx: 0 }
}
}
impl Iterator for ScoreHourCounts {
type Item = Rectangle<(SegmentValue<u32>, u32)>;
fn next(&mut self) -> Option<Self::Item> {
let count = *self.hours.get(self.idx)?;
let hour = self.idx as u32;
self.idx += 1;
let top_left = (SegmentValue::Exact(hour), count);
let bot_right = (SegmentValue::Exact(hour + 1), 0);
let style = RGBColor(2, 186, 213).mix(0.8).filled();
let mut rect = Rectangle::new([top_left, bot_right], style);
rect.set_margin(0, 0, 2, 2);
Some(rect)
}
}
async fn top_graph(
ctx: &Context,
data: &CommandData<'_>,
name: &str,
user_args: UserArgs<'_>,
order: GraphTopOrder,
) -> BotResult<Option<(User, Vec<u8>)>> {
let mode = user_args.mode;
let score_args = ScoreArgs::top(100);
let (user, mut scores) = match get_user_and_scores(ctx, user_args, &score_args).await {
Ok(tuple) => tuple,
Err(OsuError::NotFound) => {
let content = format!("Could not find user `{name}`");
data.error(ctx, content).await?;
return Ok(None);
}
Err(err) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
};
if scores.is_empty() {
let content = "User's top scores are empty";
data.error(ctx, content).await?;
return Ok(None);
}
let caption = format!(
"{name}'{genitive} top {mode}scores",
name = user.username,
genitive = if user.username.ends_with('s') {
""
} else {
"s"
},
mode = match mode {
GameMode::STD => "",
GameMode::TKO => "taiko ",
GameMode::CTB => "ctb ",
GameMode::MNA => "mania ",
}
);
let graph_result = match order {
GraphTopOrder::Date => top_graph_date(caption, &mut scores).await,
GraphTopOrder::Index => top_graph_index(caption, &scores).await,
};
let bytes = match graph_result {
Ok(graph) => graph,
Err(err) => {
let _ = data.error(ctx, GENERAL_ISSUE).await;
warn!("{:?}", Report::new(err));
return Ok(None);
}
};
Ok(Some((user, bytes)))
}
async fn top_graph_date(caption: String, scores: &mut [Score]) -> Result<Vec<u8>, GraphError> {
let max = scores.first().and_then(|s| s.pp).unwrap_or(0.0);
let max_adj = max + 5.0;
let min = scores.last().and_then(|s| s.pp).unwrap_or(0.0);
let min_adj = (min - 5.0).max(0.0);
scores.sort_unstable_by_key(|s| s.created_at);
let dates: Vec<_> = scores.iter().map(|s| s.created_at).collect();
let first = dates[0];
let last = dates[dates.len() - 1];
let len = (W * H) as usize;
let mut buf = vec![0; len * 3];
{
let root = BitMapBackend::with_buffer(&mut buf, (W, H)).into_drawing_area();
let background = RGBColor(19, 43, 33);
root.fill(&background)?;
let caption_style = ("sans-serif", 25_i32, FontStyle::Bold, &WHITE);
let mut chart = ChartBuilder::on(&root)
.x_label_area_size(40_i32)
.y_label_area_size(60_i32)
.margin_top(5_i32)
.margin_right(15_i32)
.caption(caption, caption_style)
.build_cartesian_2d(first..last, min_adj..max_adj)?;
chart
.configure_mesh()
.disable_x_mesh()
.y_label_formatter(&|pp| format!("{pp:.0}pp"))
.x_label_formatter(&|date| format!("{}", date.format("%F")))
.label_style(("sans-serif", 16_i32, &WHITE))
.bold_line_style(&WHITE.mix(0.3))
.axis_style(RGBColor(7, 18, 14))
.axis_desc_style(("sans-serif", 16_i32, FontStyle::Bold, &WHITE))
.draw()?;
let point_style = RGBColor(2, 186, 213).mix(0.7).filled();
// let border_style = RGBColor(30, 248, 178).mix(0.9).filled();
let border_style = WHITE.mix(0.9).stroke_width(1);
let iter = scores.iter().filter_map(|s| Some((s.created_at, s.pp?)));
let series = PointSeries::of_element(iter, 3_i32, point_style, &|coord, size, style| {
EmptyElement::at(coord) + Circle::new((0, 0), size, style)
});
chart
.draw_series(series)?
.label(format!("Max: {max}pp"))
.legend(|coord| EmptyElement::at(coord));
let iter = scores.iter().filter_map(|s| Some((s.created_at, s.pp?)));
let series = PointSeries::of_element(iter, 3_i32, border_style, &|coord, size, style| {
EmptyElement::at(coord) + Circle::new((0, 0), size, style)
});
chart
.draw_series(series)?
.label(format!("Min: {min}pp"))
.legend(|coord| EmptyElement::at(coord));
chart
.configure_series_labels()
.border_style(WHITE.mix(0.6).stroke_width(1))
.background_style(RGBColor(7, 23, 17))
.position(SeriesLabelPosition::MiddleLeft)
.legend_area_size(0_i32)
.label_font(("sans-serif", 16_i32, FontStyle::Bold, &WHITE))
.draw()?;
}
// Encode buf to png
let mut png_bytes: Vec<u8> = Vec::with_capacity(len);
let png_encoder = PngEncoder::new(&mut png_bytes);
png_encoder.write_image(&buf, W, H, ColorType::Rgb8)?;
Ok(png_bytes)
}
async fn top_graph_index(caption: String, scores: &[Score]) -> Result<Vec<u8>, GraphError> {
let max = scores.first().and_then(|s| s.pp).unwrap_or(0.0);
let max_adj = max + 5.0;
let min = scores.last().and_then(|s| s.pp).unwrap_or(0.0);
let min_adj = (min - 5.0).max(0.0);
let len = (W * H) as usize;
let mut buf = vec![0; len * 3];
{
let root = BitMapBackend::with_buffer(&mut buf, (W, H)).into_drawing_area();
let background = RGBColor(19, 43, 33);
root.fill(&background)?;
let caption_style = ("sans-serif", 25_i32, FontStyle::Bold, &WHITE);
let mut chart = ChartBuilder::on(&root)
.x_label_area_size(40_i32)
.y_label_area_size(60_i32)
.margin_top(5_i32)
.margin_right(15_i32)
.caption(caption, caption_style)
.build_cartesian_2d(1..scores.len(), min_adj..max_adj)?;
chart
.configure_mesh()
.y_label_formatter(&|pp| format!("{pp:.0}pp"))
.label_style(("sans-serif", 16_i32, &WHITE))
.bold_line_style(&WHITE.mix(0.3))
.axis_style(RGBColor(7, 18, 14))
.axis_desc_style(("sans-serif", 16_i32, FontStyle::Bold, &WHITE))
.draw()?;
let area_style = RGBColor(2, 186, 213).mix(0.7).filled();
let border_style = RGBColor(0, 208, 138).stroke_width(3);
let iter = (1..).zip(scores).filter_map(|(i, s)| Some((i, s.pp?)));
let series = AreaSeries::new(iter, 0.0, area_style).border_style(border_style);
chart
.draw_series(series)?
.label(format!("Max: {max}pp"))
.legend(|coord| EmptyElement::at(coord));
let iter = (1..)
.zip(scores)
.filter_map(|(i, s)| Some((i, s.pp?)))
.take(0);
let series = AreaSeries::new(iter, 0.0, &WHITE).border_style(&WHITE);
chart
.draw_series(series)?
.label(format!("Min: {min}pp"))
.legend(|coord| EmptyElement::at(coord));
chart
.configure_series_labels()
.border_style(WHITE.mix(0.6).stroke_width(1))
.background_style(RGBColor(7, 23, 17))
.position(SeriesLabelPosition::UpperRight)
.legend_area_size(0_i32)
.label_font(("sans-serif", 16_i32, FontStyle::Bold, &WHITE))
.draw()?;
}
// Encode buf to png
let mut png_bytes: Vec<u8> = Vec::with_capacity(len);
let png_encoder = PngEncoder::new(&mut png_bytes);
png_encoder.write_image(&buf, W, H, ColorType::Rgb8)?;
Ok(png_bytes)
}
struct GraphArgs {
config: UserConfig,
kind: GraphKind,
}
enum GraphKind {
MedalProgression,
PlaycountReplays { flags: ProfileGraphFlags },
RankProgression,
ScoreTime { tz: Option<FixedOffset> },
Sniped,
SnipeCount,
Top { order: GraphTopOrder },
}
enum GraphTopOrder {
Date,
Index,
}
impl Default for GraphTopOrder {
fn default() -> Self {
Self::Index
}
}
pub async fn slash_graph(ctx: Arc<Context>, mut command: ApplicationCommand) -> BotResult<()> {
let (subcommand, mut options) = command
.data
.options
.pop()
.and_then(|option| match option.value {
CommandOptionValue::SubCommand(options) => Some((option.name, options)),
_ => None,
})
.ok_or(Error::InvalidCommandOptions)?;
let mut config = ctx.user_config(command.user_id()?).await?;
let kind = match subcommand.as_str() {
"medals" => GraphKind::MedalProgression,
"playcount_replays" => {
let badges = check_show_hide_option(&mut options, "badges")?;
let playcount = check_show_hide_option(&mut options, "playcount")?;
let replays = check_show_hide_option(&mut options, "replays")?;
let mut flags = ProfileGraphFlags::default();
if !badges {
flags.remove(ProfileGraphFlags::BADGES);
}
if !playcount {
flags.remove(ProfileGraphFlags::PLAYCOUNT);
}
if !replays {
flags.remove(ProfileGraphFlags::REPLAYS);
}
GraphKind::PlaycountReplays { flags }
}
"rank" => GraphKind::RankProgression,
"score_time" => {
let mut tz = None;
if let Some(idx) = options.iter().position(|option| option.name == "timezone") {
match options.swap_remove(idx).value {
CommandOptionValue::String(value) => match value.parse::<i32>() {
Ok(value) => tz = Some(FixedOffset::east(value * 3600)),
Err(_) => return Err(Error::InvalidCommandOptions),
},
_ => return Err(Error::InvalidCommandOptions),
}
}
GraphKind::ScoreTime { tz }
}
"sniped" => GraphKind::Sniped,
"snipe_count" => GraphKind::SnipeCount,
"top" => {
let mut order = None;
if let Some(idx) = options.iter().position(|option| option.name == "order") {
match options.swap_remove(idx).value {
CommandOptionValue::String(value) => match value.as_str() {
"date" => order = Some(GraphTopOrder::Date),
"index" => order = Some(GraphTopOrder::Index),
_ => return Err(Error::InvalidCommandOptions),
},
_ => return Err(Error::InvalidCommandOptions),
}
}
GraphKind::Top {
order: order.unwrap_or_default(),
}
}
_ => return Err(Error::InvalidCommandOptions),
};
for option in options {
match option.value {
CommandOptionValue::String(value) => match option.name.as_str() {
NAME => config.osu = Some(value.into()),
MODE => config.mode = parse_mode_option(&value),
_ => return Err(Error::InvalidCommandOptions),
},
CommandOptionValue::User(value) => match option.name.as_str() {
DISCORD => match parse_discord(&ctx, value).await? {
Ok(osu) => config.osu = Some(osu),
Err(content) => return command.error(&ctx, content).await,
},
_ => return Err(Error::InvalidCommandOptions),
},
_ => return Err(Error::InvalidCommandOptions),
}
}
graph(ctx, command.into(), GraphArgs { config, kind }).await
}
fn check_show_hide_option(options: &mut Vec<CommandDataOption>, name: &str) -> BotResult<bool> {
if let Some(idx) = options.iter().position(|o| o.name == name) {
match options.swap_remove(idx).value {
CommandOptionValue::String(value) => match value.as_str() {
"show" => return Ok(true),
"hide" => return Ok(false),
_ => return Err(Error::InvalidCommandOptions),
},
_ => return Err(Error::InvalidCommandOptions),
}
}
Ok(true)
}
fn timezones() -> Vec<CommandOptionChoice> {
vec![
CommandOptionChoice::String {
name: "UTC-12".to_owned(),
value: "-12".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-11".to_owned(),
value: "-11".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-10".to_owned(),
value: "-10".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-9".to_owned(),
value: "-9".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-8".to_owned(),
value: "-8".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-7".to_owned(),
value: "-7".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-6".to_owned(),
value: "-6".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-5".to_owned(),
value: "-5".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-4".to_owned(),
value: "-4".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-3".to_owned(),
value: "-3".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-2".to_owned(),
value: "-2".to_owned(),
},
CommandOptionChoice::String {
name: "UTC-1".to_owned(),
value: "-1".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+0".to_owned(),
value: "0".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+1".to_owned(),
value: "1".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+2".to_owned(),
value: "2".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+3".to_owned(),
value: "3".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+4".to_owned(),
value: "4".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+5".to_owned(),
value: "5".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+6".to_owned(),
value: "6".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+7".to_owned(),
value: "7".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+8".to_owned(),
value: "8".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+9".to_owned(),
value: "9".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+10".to_owned(),
value: "10".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+11".to_owned(),
value: "11".to_owned(),
},
CommandOptionChoice::String {
name: "UTC+12".to_owned(),
value: "12".to_owned(),
},
]
}
fn show_hide() -> Vec<CommandOptionChoice> {
vec![
CommandOptionChoice::String {
name: "Show".to_owned(),
value: "show".to_owned(),
},
CommandOptionChoice::String {
name: "Hide".to_owned(),
value: "hide".to_owned(),
},
]
}
pub fn define_graph() -> MyCommand {
let medals = MyCommandOption::builder("medals", "Display a user's medal progress over time")
.subcommand(vec![option_name(), option_discord()]);
let playcount_description = "Specify if the playcount curve should be included";
let playcount =
MyCommandOption::builder("playcount", playcount_description).string(show_hide(), false);
let replays =
MyCommandOption::builder("replays", "Specify if the replay curve should be included")
.string(show_hide(), false);
let badges = MyCommandOption::builder("badges", "Specify if the badges should be included")
.string(show_hide(), false);
let playcount_replays_description = "Display a user's playcount and replays watched over time";
let playcount_replays =
MyCommandOption::builder("playcount_replays", playcount_replays_description).subcommand(
vec![option_name(), option_discord(), playcount, replays, badges],
);
let rank = MyCommandOption::builder("rank", "Display a user's rank progression over time")
.subcommand(vec![option_mode(), option_name(), option_discord()]);
let timezone =
MyCommandOption::builder("timezone", "Specify a timezone").string(timezones(), false);
let score_time_description = "Display at what times a user set their top scores";
let score_time_options = vec![option_mode(), timezone, option_name(), option_discord()];
let score_time = MyCommandOption::builder("score_time", score_time_description)
.subcommand(score_time_options);
let sniped = MyCommandOption::builder("sniped", "Display sniped users of the past 8 weeks")
.subcommand(vec![option_name(), option_discord()]);
let snipe_count_description = "Display how a user's national #1 count progressed";
let snipe_count = MyCommandOption::builder("snipe_count", snipe_count_description)
.subcommand(vec![option_name(), option_discord()]);
let order_choices = vec![
CommandOptionChoice::String {
name: "Date".to_owned(),
value: "date".to_owned(),
},
CommandOptionChoice::String {
name: "Index".to_owned(),
value: "index".to_owned(),
},
];
let order_description = "Choose by which order the scores should be sorted, defaults to index";
let order = MyCommandOption::builder("order", order_description).string(order_choices, false);
let options = vec![option_mode(), option_name(), order, option_discord()];
let top = MyCommandOption::builder("top", "Display a user's top scores pp").subcommand(options);
let subcommands = vec![
medals,
playcount_replays,
rank,
score_time,
sniped,
snipe_count,
top,
];
MyCommand::new("graph", "Display graphs about some data").options(subcommands)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.