text stringlengths 8 4.13M |
|---|
//! A Rust wrapper around Python's linecache. We can't just emulate it because
//! PEP 302 `__loader__`s and ipython shoving stuff into it and oh god oh god oh
//! god Python is complicated.
use crate::python;
/// Wrapper around Python's linecache.
#[derive(Default)]
pub struct LineCacher {}
impl LineCacher {
/// Get the source code line for the given file.
pub fn get_source_line(&mut self, filename: &str, line_number: usize) -> String {
if line_number == 0 {
return String::new();
}
python::get_source_line(filename, line_number).unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use pyo3::prelude::*;
use rusty_fork::rusty_fork_test;
use std::io::Write;
rusty_fork_test! {
/// The linecache can read files.
#[test]
fn linecacher_from_file() {
pyo3::prepare_freethreaded_python();
let mut cache = LineCacher::default();
// Non-existent file
assert_eq!(cache.get_source_line("/no/such/file", 1), "");
let mut f = tempfile::NamedTempFile::new().unwrap();
f.as_file_mut().write_all(b"abc\ndef\r\nghijk").unwrap();
let path = f.path().as_os_str().to_str().unwrap();
// 0 line number
assert_eq!(cache.get_source_line(path, 0), "");
// Too high line number
assert_eq!(cache.get_source_line(path, 4), "");
// Present line numbers
assert_eq!(cache.get_source_line(path, 1), "abc\n");
assert_eq!(cache.get_source_line(path, 2), "def\n");
assert_eq!(cache.get_source_line(path, 3), "ghijk\n");
}
/// The linecache can read random crap shoved into the linecache module.
#[test]
fn linecacher_from_arbitrary_source() {
pyo3::prepare_freethreaded_python();
let mut cache = LineCacher::default();
Python::with_gil(|py| {
let blah = vec!["arr\n", "boo"];
let linecache = PyModule::import(py, "linecache")?;
linecache
.getattr("cache")?.set_item("blah", (8, 0, blah, "blah"))?;
Ok::<(), PyErr>(())
}).unwrap();
assert_eq!(cache.get_source_line("blah", 1), "arr\n");
assert_eq!(cache.get_source_line("blah", 2), "boo");
}
}
}
|
use crate::core::io::Io;
use std::path::Path;
use std::fs::read;
const _ROM_SIZE: usize = 32768;
const TITLE_START: usize = 0x134;
const TITLE_END: usize = 0x142;
// const LICENSEE_CODE_START: usize = 0x144;
// const LICENSEE_CODE_END: usize = 0x145;
// const SGB_FLAG: usize = 0x146;
const CARTRIDGE_TYPE: usize = 0x147;
// const ROM_SIZE_ADDR: usize = 0x148;
// const RAM_SIZE_ADDR: usize = 0x149;
// const DESTINATION_CODE: usize = 0x14A;
pub enum BankMode {
RamBank = 0,
RomBank = 1,
}
pub enum Cartridge {
NoMbc {
rom: Vec<u8>,
title: String,
},
Mbc1 {
rom: Vec<u8>,
rombank: u8,
title: String,
ram: Vec<u8>,
rambank: u8,
ram_enabled: bool,
mode: BankMode,
},
}
impl Cartridge {
pub fn _no_cartridge() -> Self {
Cartridge::NoMbc {
rom: vec![0; _ROM_SIZE],
title: "NO CARTRIDGE".to_string(),
}
}
pub fn from_path(path: &Path) -> Self {
let bin = read(path).unwrap();
let title = String::from_utf8(bin[TITLE_START..TITLE_END]
.to_vec())
.unwrap();
let ramsize = match bin[0x149] {
0 => 0,
1 => 16*1024, // 16kbit
2 => 64*1024, // 64kbit
3 => 256*1024, // 256kbit
4 => 1024*1024, // 1Mbit
_ => panic!(),
};
match bin[CARTRIDGE_TYPE] {
// No MBC(ROM only)
0x00 => Cartridge::NoMbc {
rom: bin,
title: title,
},
0x01 => Cartridge::Mbc1 {
rom: bin,
rombank: 1,
title: title,
ram: vec![0; ramsize],
rambank: 0,
ram_enabled: false,
mode: BankMode::RomBank,
},
_ => unimplemented!("can't load: mbc type={}", bin[CARTRIDGE_TYPE]),
}
}
}
impl Io for Cartridge {
fn read8(&self, addr: usize) -> u8 {
match self {
Cartridge::NoMbc { rom, .. } => match addr {
0x0000 ..= 0x7FFF => rom[addr],
_ => panic!(),
},
Cartridge::Mbc1 { rom, rombank, ram, rambank, .. } => match addr {
0x0000 ..= 0x3FFF => rom[addr],
0x4000 ..= 0x7FFF => rom[addr+0x4000*(*rombank as usize - 1)],
0xA000 ..= 0xBFFF => ram[addr-0xA000+0x2000*(*rambank as usize)],
_ => panic!(),
},
}
}
fn write8(&mut self, addr: usize, data: u8) {
match self {
Cartridge::NoMbc { rom, .. } => match addr {
0x0000 ..= 0x7FFF => rom[addr] = data,
_ => panic!(),
},
Cartridge::Mbc1 { rombank, ram, rambank, ram_enabled, mode, .. } => match addr {
0x0000 ..= 0x1FFF => *ram_enabled = data&0x0F == 0x0A,
0x2000 ..= 0x3FFF => *rombank = data&0x1F,
0x4000 ..= 0x5FFF => match mode {
BankMode::RamBank => *rambank = data&0x03,
BankMode::RomBank => *rombank |= (data&0x03) << 5,
}
0x6000 ..= 0x7FFF => match data&0x01 == 0x00 {
true => *mode = BankMode::RomBank,
false => *mode = BankMode::RamBank,
},
0xA000 ..= 0xBFFF => if *ram_enabled {
match mode {
BankMode::RamBank => ram[addr-0xA000+0x2000*(*rambank as usize)] = data,
BankMode::RomBank => ram[addr-0xA000] = data,
}
},
_ => panic!(),
},
}
}
} |
//! AIZU ONLINE JUDGEの回答用ライブラリ。
pub mod itp1_1;
pub mod itp1_2;
pub mod itp1_3;
pub mod itp1_4;
pub mod itp1_5;
pub mod itp1_6;
pub mod itp1_7;
pub mod itp1_8;
pub mod itp1_9;
pub mod itp1_10;
pub mod itp1_11; |
extern crate cgmath;
use cgmath::Vector3;
use cgmath::InnerSpace;
type Vec3 = Vector3<f32>;
use materials::Material;
pub struct Ray {
origin: Vec3,
direction: Vec3,
}
impl Ray {
pub fn new(a: Vec3, b: Vec3) -> Ray {
Ray {
origin: a,
direction: b,
}
}
pub fn point_at(&self, t: &f32) -> Vec3 {
self.origin + (*t) * self.direction
}
pub fn direction(&self) -> Vec3 {
self.direction
}
pub fn origin(&self) -> Vec3 {
self.origin
}
}
pub struct Sphere {
pub radius: f32,
pub center: Vec3,
pub material: Box<Material>
}
pub struct Hit<'a> {
t: f32,
pub p: Vec3,
pub normal: Vec3,
pub material: &'a Material
}
pub trait Hitable {
fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<Hit>;
}
// The basic function of a sphere centered at origin:
// x*x + y*y + z*z = R*R (radius)
// Spehere centered at (cx, cy, cz):
// (x-cx)*(x-cx) + (y-cy)*(y-cy) + (z-cz)*(z-cz) = R*R
// This is the same as
// dot((p-c), (p-c)) = R*R where p is a position vector we're comparing and
// c is the position vector of the center of the sphere.
// making the position vector a function of of t we get:
// t*t*dot(B,B) + 2*t*dot(B,A-C) + dot(A-C,A-C) - R*R = 0
// which is a basic quadratic function with 0/1/2 roots
// The roots are where the ray hits the sphere
impl Hitable for Sphere {
fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<Hit> {
// center to ray origin
let oc: Vec3 = ray.origin() - self.center;
let a = ray.direction().dot(ray.direction());
let b = 2.0 * oc.dot(ray.direction());
let c = oc.dot(oc) - self.radius * self.radius;
let discriminant = b * b - 4.0 * a * c;
if discriminant > 0.0 {
let plus: f32 = (-b + (b * b - 4.0 * a * c).sqrt()) / (2.0 * a);
let minus: f32 = (-b - (b * b - 4.0 * a * c).sqrt()) / (2.0 * a);
for temp in &[minus, plus] {
if temp < &t_max && temp > &t_min {
let point = ray.point_at(temp);
return Some(Hit {
t: *temp,
p: point,
normal: (point - self.center) / self.radius,
material: &*self.material
});
}
}
}
return None;
}
}
pub struct HitableList {
pub list: Vec<Box<Hitable>>,
}
impl Hitable for HitableList {
// Would be cool to do this with a map and a filter
fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> Option<Hit> {
let mut closest_so_far = t_max;
let mut result: Option<Hit> = None;
for obj in &self.list {
match obj.hit(&ray, t_min, closest_so_far) {
Some(hit) => {
closest_so_far = hit.t;
result = Some(hit);
}
None => {}
}
}
result
}
}
|
use runic::*;
use std::rc::Rc;
use std::cell::RefCell;
use std::error::Error;
use std::env;
use std::collections::HashMap;
use buffer::Buffer;
use res::Resources;
use lsp::LanguageServer;
use mode;
use winit::Event;
use regex::Regex;
use super::ConfigError;
#[derive(Debug,Clone,PartialEq,Eq,Hash)]
pub struct ClipstackId(pub char);
pub struct State {
pub bufs: Vec<Rc<RefCell<Buffer>>>,
pub res: Rc<RefCell<Resources>>,
pub last_buffer: usize,
pub current_buffer: usize,
pub clipstacks: HashMap<ClipstackId, Vec<String>>,
pub should_quit: bool,
pub language_servers: Vec<(Regex, Rc<RefCell<LanguageServer>>)>,
pub status_text: Option<String>
}
impl State {
pub fn buf(&self) -> Rc<RefCell<Buffer>> {
self.bufs[self.current_buffer].clone()
}
pub fn mutate_buf<R, F: FnOnce(&mut Buffer)->R>(&mut self, f: F) -> R {
f(&mut self.bufs[self.current_buffer].borrow_mut())
}
pub fn push_clip(&mut self, id: &ClipstackId, s: String) {
let mut stack = self.clipstacks.entry(id.clone()).or_insert(Vec::new());
stack.push(s);
}
pub fn top_clip(&self, id: &ClipstackId) -> Option<String> {
self.clipstacks.get(id).and_then(|sk| sk.last()).map(Clone::clone)
}
pub fn pop_clip(&mut self, id: &ClipstackId) -> Option<String> {
self.clipstacks.get_mut(id).and_then(|sk| sk.pop())
}
pub fn move_to_buffer(&mut self, ix: usize) {
self.last_buffer = self.current_buffer;
self.current_buffer = ix;
}
pub fn language_server_for_file_type(&mut self, file_ext: &str) -> Result<Option<Rc<RefCell<LanguageServer>>>, Box<Error>> {
for (ref test, ref lsp) in self.language_servers.iter() {
if test.is_match(file_ext) {
return Ok(Some(lsp.clone()));
}
}
if let Some(cfgs) = self.res.borrow().config.as_ref().and_then(|c| c.get("language-server")).and_then(|c| c.as_array()) {
for cfg in cfgs {
let test = Regex::new(cfg.get("file-extention").ok_or(ConfigError::Missing("language server file extention regex"))?.as_str().ok_or(ConfigError::Invalid("language server file extention regex"))?)?;
if test.is_match(file_ext) {
let lsp = Rc::new(RefCell::new(LanguageServer::new(&cfg)?));
self.language_servers.push((test, lsp.clone()));
return Ok(Some(lsp.clone()));
}
}
}
Ok(None)
}
}
use std::path::{Path, PathBuf};
pub struct TxdApp {
state: State,
last_err: Option<Box<Error>>,
mode: Box<mode::Mode>,
}
impl TxdApp {
pub fn init(mut rx: &mut RenderContext) -> TxdApp {
use std::fs::File;
use std::io::Read;
use toml::Value;
let (config, le) : (Option<Value>, Option<Box<Error>>) = match File::open("config.toml") {
Ok(mut f) => {
let mut config_text = String::new();
if let Err(e) = f.read_to_string(&mut config_text) {
(None, Some(Box::new(e)))
} else {
match config_text.parse::<Value>() {
Ok(v) => (Some(v), None),
Err(e) => (None, Some(Box::new(e)))
}
}
}
Err(e) => (None, Some(Box::new(e)))
};
if let Some(ref e) = le {
println!("config error {:?}", e);
}
let res = Rc::new(RefCell::new(Resources::new(rx, config).expect("create resources")));
let buf = Rc::new(RefCell::new(Buffer::new(res.clone())));
//env::args().nth(1).map_or_else(|| Buffer::new(res.clone()),
//|p| Buffer::load(Path::new(&p), res.clone()).expect("open file")) ));
let cmd = Rc::new(RefCell::new(Buffer::new(res.clone())));
{ cmd.borrow_mut().show_cursor = false; }
//println!("cd = {}, canoncd = {}", ::std::env::current_dir().unwrap().display(),
// ::std::env::current_dir().unwrap().canonicalize().unwrap().display());
TxdApp {
state: State {
bufs: vec![cmd, buf],
current_buffer: 1, last_buffer: 1,
clipstacks: HashMap::new(), res,
should_quit: false,
language_servers: Vec::new(),
status_text: None
},
mode: Box::new(mode::NormalMode::new()), last_err: le,
}
}
}
impl App for TxdApp {
fn event(&mut self, e: Event) -> bool {
match e {
Event::WindowEvent { event: we, .. } => {
let nxm = self.mode.event(we, &mut self.state);
match nxm {
Ok(Some(new_mode)) => { if self.last_err.is_some() { self.last_err = None; } self.mode = new_mode }
Ok(None) => {}
Err(err) => { println!("error: {}", err); self.last_err = Some(err); self.mode = Box::new(mode::NormalMode::new()); }
}
},
_ => { }
}
self.state.should_quit
}
fn paint(&mut self, rx: &mut RenderContext) {
for lsp in self.state.language_servers.iter() {
let st = &mut self.state.status_text;
lsp.1.borrow_mut().process_notifications(|n| {
match n["method"].as_str() {
Some("window/progress") => {
if n["params"].has_key("done") {
*st = None;
} else {
*st = Some(format!("{}: {}", n["params"]["title"], n["params"]["message"]));
}
},
Some(_) => println!("unknown notification {:?}", n),
None => println!("invalid notification {:?}", n)
}
});
}
rx.clear(Color::rgb(0.1, 0.1, 0.1));
let bnd = rx.bounds();
let res = self.state.res.borrow();
let mode_tag_tl = rx.new_text_layout(self.mode.status_tag(), &res.font, bnd.w, bnd.h).expect("create mode text layout");
let mtb = mode_tag_tl.bounds();
//draw buffer line
rx.set_color(Color::rgb(0.25, 0.22, 0.2));
rx.fill_rect(Rect::xywh(0.0, 0.0, bnd.w, mtb.h));
rx.set_color(Color::rgb(0.1, 0.44, 0.5));
rx.draw_text(Rect::xywh(4.0, 0.0, bnd.w, mtb.h), "txd", &res.font);
{
let mut x = 48.0;
for (i, b) in self.state.bufs.iter().enumerate() {
let tl = rx.new_text_layout(&format!("[{} {}]", i,
b.borrow().fs_loc.as_ref().map_or_else(|| String::from("*"),
|p| format!("{}", p.strip_prefix(::std::env::current_dir().unwrap().as_path()).unwrap_or(p).display()) ),
), &res.font, bnd.w, bnd.h).expect("create text layout");
if i == self.state.current_buffer {
rx.set_color(Color::rgb(0.80, 0.44, 0.1));
} else {
rx.set_color(Color::rgb(0.50, 0.44, 0.1));
}
rx.draw_text_layout(Point::xy(x, 0.0), &tl);
x += tl.bounds().w;
}
}
let buf_ = self.state.buf();
let mut buf = buf_.borrow_mut();
buf.paint(rx, Rect::xywh(4.0, 4.0 + mtb.h*1.1, bnd.w-4.0, bnd.h-mtb.h*3.2));
//draw status line
let status_y = bnd.h-mtb.h*2.2;
rx.set_color(Color::rgb(0.25, 0.22, 0.2));
rx.fill_rect(Rect::xywh(0.0, status_y-0.5, bnd.w, mtb.h));
rx.set_color(Color::rgb(0.4, 0.6, 0.0));
/*rx.draw_text(Rect::xywh(4.0, bnd.h-35.0, bnd.w, 18.0), self.mode.status_tag(), &res.font);*/
rx.draw_text_layout(Point::xy(4.0, status_y), &mode_tag_tl);
rx.set_color(Color::rgb(0.9, 0.4, 0.0));
rx.draw_text(Rect::xywh(100.0, status_y, bnd.w, 18.0),
&buf.fs_loc.as_ref().map_or_else(|| String::from("[new file]"),
|p| format!("{}", p.strip_prefix(::std::env::current_dir().unwrap().as_path()).unwrap_or(p).display()) ),
&res.font);
if let Some(ref s) = self.state.status_text {
rx.draw_text(Rect::xywh(600.0, status_y, bnd.w, 18.0), &s, &res.font);
}
rx.set_color(Color::rgb(0.0, 0.6, 0.4));
rx.draw_text(Rect::xywh(bnd.w-200.0, status_y, bnd.w, 18.0),
&format!("ln {} col {}", buf.cursor_line, buf.cursor_col),
&res.font);
if let Some(ref err) = self.last_err {
rx.set_color(Color::rgb(0.9, 0.2, 0.0));
rx.draw_text(Rect::xywh(4.0, status_y + mtb.h, bnd.w, 18.0),
&format!("error: {}", err),
&res.font);
}
//draw command line
if let Some(cmd) = self.mode.pending_command() {
rx.set_color(Color::rgb(0.8, 0.8, 0.8));
rx.draw_text(Rect::xywh(bnd.w-200.0, status_y + mtb.h, bnd.w, 28.0), cmd,
&res.font);
}
self.state.bufs[0].borrow_mut().paint(rx, Rect::xywh(4.0, status_y + mtb.h, bnd.w-200.0, 50.0));
}
}
|
use serde::{Deserialize, Serialize};
use super::auction_type::*;
use super::currency::*;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Deal {
pub id: String,
#[serde(rename(serialize = "flr", deserialize = "flr"))]
pub floor_price: Option<f64>,
#[serde(default)]
#[serde(rename(serialize = "flrcur", deserialize = "flrcur"))]
pub floor_price_currency: Currency,
#[serde(default)]
#[serde(rename(serialize = "at", deserialize = "at"))]
pub auction_type: Option<AuctionType>,
#[serde(rename(serialize = "wseat", deserialize = "wseat"))]
pub allowed_seats: Vec<String>,
#[serde(rename(serialize = "wadomain", deserialize = "wadomain"))]
pub allowed_advertiser_domain: Vec<String>,
pub ext: Option<DealExt>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct DealExt {}
|
use failure::Error;
use find_file_paths;
use git2::Repository;
use json_patch::merge;
use regex::Regex;
use serde_json::{self, Value};
use std::fs::File;
use std::path::{Path, PathBuf};
use tempfile::{self, TempDir};
use url::{ParseError, Url};
use walkdir::WalkDir;
use git;
pub enum ConfigDir {
File {
directory: PathBuf,
},
Git {
git_repo: Repository,
temp_dir: TempDir,
directory: PathBuf,
},
}
impl ConfigDir {
pub fn new(src: String, ssh_key_path: &Path) -> Result<ConfigDir, Error> {
let config_dir = if src.contains(".git") {
let git_url = git::GitUrl::new(&src);
let temp_dir = tempfile::tempdir()?;
let git_repo = git_url.clone(temp_dir.path(), Some(ssh_key_path))?;
let directory = match git_repo.workdir() {
Some(workdir) => workdir.join(git_url.internal_path),
None => bail!("No working directory found for git repository"),
};
Ok(ConfigDir::Git {
git_repo,
temp_dir,
directory,
})
} else {
match Url::parse(&src) {
Ok(url) => match url.scheme() {
"file" => ConfigDir::new(src.replacen("file://", "", 1), ssh_key_path),
scheme => bail!("URL scheme {} not yet supported", scheme),
},
Err(ParseError::RelativeUrlWithoutBase) => Ok(ConfigDir::File {
directory: PathBuf::from(src),
}),
Err(e) => Err(e.into()),
}
};
if let &Ok(ref config_dir) = &config_dir {
if !config_dir.directory().is_dir() {
bail!(
"{:?} either does not exist or is not a directory. It needs to be both",
config_dir.directory()
)
}
}
config_dir
}
pub fn directory(&self) -> &Path {
match *self {
ConfigDir::File { ref directory, .. } => directory,
ConfigDir::Git { ref directory, .. } => directory,
}
}
// TODO: Implement being able to re-checkout a git repo
pub fn refresh(&self) -> &Self {
match *self {
ConfigDir::File { .. } => {}
ConfigDir::Git { .. } => {}
}
self
}
pub fn find(&self, filter: Regex) -> Vec<Environment> {
fn find_env_type_data<'a>(types: &'a Vec<EnvironmentType>, name: &str) -> &'a Value {
types
.iter()
.find(|e| e.environment_type == name)
.map(|env| &env.config_data)
.unwrap_or(&Value::Null)
}
let environment_types =
ConfigDir::find_environment_types(self).collect::<Vec<EnvironmentType>>();
let global = find_env_type_data(&environment_types, "global");
ConfigDir::find_environments(self, filter)
.map(|mut environment| {
let parent = if let Some(ref env_type_name) = environment.environment_type {
find_env_type_data(&environment_types, env_type_name)
} else {
&Value::Null
};
let mut config_data = global.clone(); // Start with global
merge(&mut config_data, &parent); // Merge in an env type
merge(&mut config_data, &environment.config_data); // Merge with the actual config
environment.config_data = config_data;
environment
})
.collect()
}
fn find_environments(&self, filter: Regex) -> Box<Iterator<Item = Environment>> {
Box::new(
find_file_paths(self.directory(), filter)
.filter_map(|p| File::open(p).ok())
.filter_map(|f| serde_json::from_reader(f).ok())
.filter_map(|c: Config| c.as_environment()),
)
}
fn find_environment_types(&self) -> Box<Iterator<Item = EnvironmentType>> {
Box::new(
WalkDir::new(self.directory())
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.file_type().is_file())
.filter_map(|e| {
let path = e.path();
let env_type = path.file_stem().unwrap().to_string_lossy().into_owned();
File::open(&path)
.ok()
.and_then(|f| serde_json::from_reader(f).ok())
.and_then(|c: Config| c.as_environment_type())
.and_then(|mut e| {
e.environment_type = env_type;
Some(e)
})
}),
)
}
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Config {
Environment(Environment),
EnvironmentType(EnvironmentType),
}
impl Config {
fn as_environment(self) -> Option<Environment> {
match self {
Config::Environment(e) => Some(e),
_ => None,
}
}
fn as_environment_type(self) -> Option<EnvironmentType> {
match self {
Config::EnvironmentType(e) => Some(e),
_ => None,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct Environment {
pub environment: String,
pub environment_type: Option<String>,
pub config_data: Value,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct EnvironmentType {
environment_type: String,
config_data: Value,
}
#[cfg(test)]
mod tests {
use super::*;
use regex::RegexBuilder;
#[test]
fn test_basic_triple_merge() {
let global: Value = serde_json::from_str(r#"{"a": null}"#).unwrap();
let parent = serde_json::from_str(r#"{"a": 1}"#).unwrap();
let doc = serde_json::from_str(r#"{"a": 2}"#).unwrap();
let mut merged = global.clone();
merge(&mut merged, &parent);
merge(&mut merged, &doc);
let expected_json: Value = serde_json::from_str(r#"{"a": 2}"#).unwrap();
assert_eq!(merged, expected_json)
}
#[test]
fn test_complex_merge() {
let global: Value = Value::Null;
let parent = serde_json::from_str(r#"{"a": 1, "b": null, "c": 3, "d": 4}"#).unwrap();
let doc = serde_json::from_str(r#"{"a": null, "b": 2, "c": 4, "e": 5}"#).unwrap();
let mut merged = global.clone();
merge(&mut merged, &parent);
merge(&mut merged, &doc);
let expected_json: Value =
serde_json::from_str(r#"{"b": 2, "c": 4, "d": 4, "e": 5}"#).unwrap();
assert_eq!(merged, expected_json)
}
#[test]
fn test_find_all_configs() {
let config_dir = ConfigDir::new(
String::from("file://./tests/fixtures/configs"),
Path::new(""),
).unwrap();
let environments = config_dir.find(
RegexBuilder::new("config\\..+\\.json$")
.case_insensitive(true)
.build()
.unwrap(),
);
assert_eq!(environments.len(), 4)
}
#[test]
fn test_find_subset_configs() {
let config_dir = ConfigDir::new(
String::from("file://./tests/fixtures/configs"),
Path::new(""),
).unwrap();
let environments = config_dir.find(
RegexBuilder::new(r#"config\.test\d?\.json"#)
.case_insensitive(true)
.build()
.unwrap(),
);
assert_eq!(environments.len(), 2)
}
}
|
use super::*;
/**
Wrapper that allows consuming transformations on borrowed data
This is useful when you want a mutable interface wrapping a functional one.
# Example
```
use kai::*;
struct Foo {
v: Swap<Vec<i32>>
}
impl Foo {
fn keep_even(&mut self) {
self.v.hold(|v| v.into_iter().filter(|n| n % 2 == 0).collect());
}
}
let mut foo = Foo { v: vec![1, 2, 3, 4, 5].into() };
foo.keep_even();
assert_eq!(vec![2, 4], *foo.v);
```
*/
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Swap<T>(Option<T>);
impl<T> Swap<T> {
/// Create a new `Swap`
pub fn new(inner: T) -> Self {
Swap::from(inner)
}
/// Take the inner value, transform it, and put it back in place
pub fn hold<F>(&mut self, f: F)
where
F: FnOnce(T) -> T,
{
let res = f(self.0.take().unwrap());
self.0 = Some(res);
}
/// Take the inner value
pub fn into_inner(self) -> T {
self.0.unwrap()
}
}
impl<T> Deref for Swap<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.as_ref().unwrap()
}
}
impl<T> DerefMut for Swap<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.as_mut().unwrap()
}
}
impl<T> From<T> for Swap<T> {
fn from(inner: T) -> Self {
Swap(Some(inner))
}
}
impl<T> Default for Swap<T>
where
T: Default,
{
fn default() -> Self {
Swap::from(T::default())
}
}
impl<T> Debug for Swap<T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter) -> FmtResult {
<T as Debug>::fmt(self.0.as_ref().unwrap(), f)
}
}
impl<T> Display for Swap<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter) -> FmtResult {
<T as Display>::fmt(self.0.as_ref().unwrap(), f)
}
}
impl<T> AsRef<T> for Swap<T> {
fn as_ref(&self) -> &T {
self.0.as_ref().unwrap()
}
}
impl<T> std::borrow::Borrow<T> for Swap<T> {
fn borrow(&self) -> &T {
self.0.as_ref().unwrap()
}
}
|
use std::path::PathBuf;
use clap::Parser;
use once_cell::sync::Lazy;
use simple_ssr::App;
use tokio_util::task::LocalPoolHandle;
use warp::Filter;
// We spawn a local pool that is as big as the number of cpu threads.
static LOCAL_POOL: Lazy<LocalPoolHandle> = Lazy::new(|| LocalPoolHandle::new(num_cpus::get()));
/// A basic example
#[derive(Parser, Debug)]
struct Opt {
/// the "dist" created by trunk directory to be served for hydration.
#[structopt(short, long, parse(from_os_str))]
dir: PathBuf,
}
async fn render(index_html_s: &str) -> String {
let content = LOCAL_POOL
.spawn_pinned(move || async move {
let renderer = yew::ServerRenderer::<App>::new();
renderer.render().await
})
.await
.expect("the task has failed.");
// Good enough for an example, but developers should avoid the replace and extra allocation
// here in an actual app.
index_html_s.replace("<body>", &format!("<body>{}", content))
}
#[tokio::main]
async fn main() {
let opts = Opt::parse();
let index_html_s = tokio::fs::read_to_string(opts.dir.join("index.html"))
.await
.expect("failed to read index.html");
let html = warp::path::end().then(move || {
let index_html_s = index_html_s.clone();
async move { warp::reply::html(render(&index_html_s).await) }
});
let routes = html.or(warp::fs::dir(opts.dir));
println!("You can view the website at: http://localhost:8080/");
warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;
}
|
pub enum Mode {
Deploy,
EnemyTurn,
Select(Select),
Action(Action),
}
pub enum Select {
None,
Terrain,
Object,
Enemy,
Soldier
}
pub enum Action {
Move,
Fire,
Sprint,
UseItem,
HunkerDown,
Reload,
ChangeWeapon
} |
use nphysics::object::WorldObject;
use ncollide::events::ProximityEvent;
use ncollide::query::Proximity;
use specs::Join;
pub struct PhysicSystem;
impl<'a> ::specs::System<'a> for PhysicSystem {
type SystemData = (
::specs::ReadStorage<'a, ::component::Player>,
::specs::ReadStorage<'a, ::component::Momentum>,
::specs::ReadStorage<'a, ::component::Hook>,
::specs::WriteStorage<'a, ::component::PhysicBody>,
::specs::WriteStorage<'a, ::component::Contactor>,
::specs::WriteStorage<'a, ::component::Proximitor>,
::specs::Fetch<'a, ::resource::UpdateTime>,
::specs::FetchMut<'a, ::resource::PhysicWorld>,
::specs::Entities<'a>,
);
fn run(
&mut self,
(
players,
momentums,
hooks,
mut bodies,
mut contactors,
mut proximitors,
update_time,
mut physic_world,
entities,
): Self::SystemData,
) {
// TODO: use integrator to modify rigidbody
for (momentum, body, entity) in (&momentums, &mut bodies, &*entities).join() {
let body = body.get_mut(&mut physic_world);
let lin_vel = body.lin_vel();
let ang_vel = body.ang_vel();
body.clear_forces();
body.append_lin_force(-momentum.damping * lin_vel);
if players.get(entity).is_some() {
body.append_lin_force(
::CONFIG.player_gravity * ::na::Vector3::new(0.0, 0.0, -1.0),
);
}
if let Some(ref hook) = hooks.get(entity) {
if let Some(ref anchor) = hook.anchor {
let dir = (anchor.pos - body.position().translation.vector).normalize();
body.append_lin_force(hook.force * dir);
}
}
let direction_force = momentum.force * momentum.direction;
if let Some(pnt_to_com) = momentum.pnt_to_com {
let pnt_to_com = body.position().rotation * pnt_to_com;
body.append_force_wrt_point(direction_force, pnt_to_com);
} else {
body.append_lin_force(direction_force);
}
if let Some(ang_force) = momentum.ang_force {
body.append_ang_force(ang_force);
}
body.set_ang_vel_internal(momentum.ang_damping * ang_vel);
// TODO: assert everything is different from none before step
}
for contactor in (&mut contactors).join() {
contactor.contacts.clear();
}
for proximitor in (&mut proximitors).join() {
proximitor.intersections.clear();
}
let mut remaining_to_update = update_time.0;
while remaining_to_update > ::CONFIG.physic_min_step_time {
let step = remaining_to_update.min(::CONFIG.physic_max_step_time);
remaining_to_update -= step;
physic_world.step(step);
for (co1, co2, mut contact) in physic_world.collision_world().contacts() {
let (entity_1, entity_2) = match (&co1.data, &co2.data) {
(&WorldObject::RigidBody(w1), &WorldObject::RigidBody(w2)) => {
let e1 = physic_world.rigid_body(w1);
let e2 = physic_world.rigid_body(w2);
(
::component::PhysicBody::entity(e1),
::component::PhysicBody::entity(e2),
)
}
_ => unreachable!(),
};
if let Some(contactor) = contactors.get_mut(entity_1) {
contactor.contacts.push((entity_2, contact.clone()));
}
if let Some(contactor) = contactors.get_mut(entity_2) {
contact.flip();
contactor.contacts.push((entity_1, contact));
}
}
for event in physic_world.collision_world().proximity_events() {
if let &ProximityEvent {
co1,
co2,
new_status: Proximity::Intersecting,
..
} = event
{
let co1 = physic_world
.collision_world()
.collision_object(co1)
.map(|c| &c.data);
let co2 = physic_world
.collision_world()
.collision_object(co2)
.map(|c| &c.data);
if let (Some(co1), Some(co2)) = (co1, co2) {
// we can't just get e1 and e2 and check for each if there is a proximitor
// because the rigid body of eX may be involve in a proximity even if the
// proximitor is associated to eX sensor
match (co1, co2) {
(&WorldObject::Sensor(w1), &WorldObject::RigidBody(w2)) => {
let e1 = ::component::PhysicSensor::entity(physic_world.sensor(w1));
let e2 = ::component::PhysicBody::entity(physic_world.rigid_body(w2));
if let Some(proximitor) = proximitors.get_mut(e1) {
proximitor.intersections.push(e2);
}
}
(&WorldObject::RigidBody(w1), &WorldObject::Sensor(w2)) => {
let e1 = ::component::PhysicBody::entity(physic_world.rigid_body(w1));
let e2 = ::component::PhysicSensor::entity(physic_world.sensor(w2));
if let Some(proximitor) = proximitors.get_mut(e2) {
proximitor.intersections.push(e1);
}
}
_ => unreachable!(),
}
}
}
}
}
for (_, body) in (&players, &mut bodies).join() {
let body = body.get_mut(&mut physic_world);
body.set_ang_acc_scale(::na::zero());
body.set_ang_vel(::na::zero());
let mut pos = body.position().clone();
pos = ::na::Isometry3::new(
pos.translation.vector,
::na::Vector3::x() * ::std::f32::consts::FRAC_PI_2,
);
body.set_transformation(pos);
}
}
}
|
#![crate_name = "reforge_client"]
#![crate_type = "bin"]
#![feature(box_syntax)]
#![feature(rand)]
#![feature(core)]
#![feature(os)]
#![feature(io)]
#![feature(old_io)]
#![feature(alloc)]
#![feature(thread_sleep)]
#![feature(collections)]
#![feature(std_misc)]
extern crate bincode;
extern crate time;
extern crate rustc_serialize;
// Piston stuff
extern crate sdl2;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate graphics;
extern crate event;
extern crate input;
extern crate quack;
extern crate sdl2_mixer;
extern crate shader_version;
extern crate vecmath;
extern crate window;
use std::os;
use std::rc::Rc;
use std::cell::RefCell;
use std::path::Path;
use std::thread::{Builder, Thread};
use std::sync::mpsc::channel;
use sdl2_window::Sdl2Window;
use opengl_graphics::Gl;
use opengl_graphics::glyph_cache::GlyphCache;
use window::WindowSettings;
use asset_store::AssetStore;
use battle_state::BattleContext;
use battle_type::BattleType;
use client_battle_state::ClientBattleState;
use client_state::run_client_state_manager;
use login::LoginPacket;
use login_screen::LoginScreen;
use main_menu::{MainMenu, MainMenuSelection};
use net::{Client, OutPacket};
use star_map_gui::StarMapGui;
use tutorial_state::TutorialState;
// Server stuff
use net::Server;
use star_map_server::StarMapServer;
#[macro_use]
mod util;
mod ai;
mod asset_store;
mod battle_state;
mod battle_type;
mod client_battle_state;
mod client_state;
mod gui;
mod login;
mod login_screen;
mod main_menu;
mod module;
mod net;
mod sector_data;
mod sector_state;
mod ship;
mod sim;
mod sim_events;
mod sim_visuals;
mod space_gui;
mod sprite_sheet;
mod star_map_gui;
mod tutorial_state;
mod vec;
// server stuff
mod star_map_server;
#[cfg(feature = "client")]
fn main () {
let opengl = shader_version::OpenGL::_3_2;
// Create an SDL window.
let window = Sdl2Window::new(
opengl,
WindowSettings {
title: "Reforge".to_string(),
size: [1280, 720],
samples: 0,
fullscreen: false,
exit_on_esc: true,
}
);
// Initialize SDL mixer
sdl2::init(sdl2::INIT_AUDIO | sdl2::INIT_TIMER);
sdl2_mixer::init(sdl2_mixer::INIT_MP3 | sdl2_mixer::INIT_FLAC |
sdl2_mixer::INIT_MOD | sdl2_mixer::INIT_FLUIDSYNTH |
sdl2_mixer::INIT_MODPLUG | sdl2_mixer::INIT_OGG);
// TODO: 0x8010 is SDL_audio flag
sdl2_mixer::open_audio(sdl2_mixer::DEFAULT_FREQUENCY, 0x8010u16, 2, 1024).ok().expect("Failed to initialize SDL2 mixer");
sdl2_mixer::allocate_channels(512);
// Create GL device
let mut gl = Gl::new(opengl);
// Load our font
let mut glyph_cache = GlyphCache::new(&Path::new("content/fonts/8bit.ttf")).unwrap();
// Create the asset store
let asset_store = AssetStore::new();
// Wrap window in RefCell
let window = Rc::new(RefCell::new(window));
let music = sdl2_mixer::Music::from_file(&Path::new("content/audio/music/space.wav")).unwrap();
music.play(-1);
// Create main menu
let mut main_menu = MainMenu::new();
main_menu.run(&window, &mut gl, |window, gl, menu_bg, selection| {
match selection {
MainMenuSelection::Multiplayer => {
if let Some((username, password)) = LoginScreen::new().run(&window, gl, &mut glyph_cache, menu_bg) {
// Check for IP address in args
/*
let mut ip_address =
if os::args().len() > 1 {
os::args()[1].clone()
} else {
prisize!("IP Address: ");
String::from_str(
io::stdin().read_line()
.ok().expect("Failed to read IP address")
.trim_left()
)
};
ip_address.push_str(":30000"); // Add the port to the end of the address
*/
//let ip_address = String::from_str("localhost:30000");
let ip_address = String::from_str("104.131.129.181:30000");
// Start a local server
let mut server = Server::new();
let login_slot = server.create_slot();
let star_map_slot = server.create_slot();
let star_map_slot_id = star_map_slot.get_id();
let (star_map_account_sender, star_map_account_receiver) = channel();
Builder::new().name("server_master".to_string()).spawn(move || {
server.listen("localhost:30000");
});
Builder::new().name("login_server".to_string()).spawn(move || {
login::run_login_server(login_slot, star_map_slot_id, star_map_account_sender);
});
Builder::new().name("star_map_server".to_string()).spawn(move || {
let mut star_map_server = StarMapServer::new(star_map_slot);
star_map_server.run(star_map_account_receiver);
});
// Connect to server
let mut client = Client::new(ip_address.as_slice());
let mut packet = OutPacket::new();
packet.write(&LoginPacket{username: username, password: password});
client.send(&packet);
run_client_state_manager(&window, gl, &mut glyph_cache, &asset_store, client);
}
},
MainMenuSelection::Tutorial => {
// Create the tutorial state
let mut battle = TutorialState::new();
battle.run(&window, gl, &mut glyph_cache, &asset_store);
},
MainMenuSelection::Exit => {
},
}
});
sdl2_mixer::Music::halt();
sdl2_mixer::quit();
} |
use super::message::{Message, send_msg, send_prompt};
use std::path::PathBuf;
pub enum Arg {
S(SendArg),
R(RecvArg),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OverwriteStrategy {
Ask,
Rename,
Overwrite,
Skip,
}
#[derive(Debug, Default)]
pub struct SendArg {
pub expire: u8,
pub files: Option<Vec<PathBuf>>,
pub msg: Option<String>,
pub password: Option<String>,
}
#[derive(Debug, Default)]
pub struct RecvArg {
pub expire: u8,
pub dir: PathBuf,
pub overwrite: OverwriteStrategy,
pub password: Option<String>,
pub code: u16, // Port number
}
impl Default for OverwriteStrategy {
fn default() -> Self {
OverwriteStrategy::Ask
}
}
impl OverwriteStrategy {
// Ask the user for an overwrite strategy.
// Note that 'ask' is not in the options but still used as default.
pub fn ask() -> Self {
let input = send_prompt(Message::Prompt(
"Please choose: overwrite(o) | rename(r) | skip (s): ".to_string()));
match input.trim() {
"o" | "O" => return OverwriteStrategy::Overwrite,
"r" | "R" => return OverwriteStrategy::Rename,
"s" | "S" => return OverwriteStrategy::Skip,
_ => {
send_msg(Message::Status(format!("Unknown overwrite strategy chose")));
}
}
OverwriteStrategy::Ask
}
}
|
pub mod utils {}
|
extern crate sdl2;
use super::super::controller::player_controller::PlayerController;
use super::super::input::input::Input;
use super::super::network::socket::Socket;
use super::dropped_item;
use super::item;
use super::map::Map;
use super::player;
pub struct World {
map: Option<Map>,
items: Vec<dropped_item::DroppedItem>,
players: Vec<player::Player>,
player_controller: PlayerController,
}
impl World {
pub fn new() -> World {
World {
map: None,
items: vec![dropped_item::DroppedItem::new(
1,
1,
item::Item::new(
item::ItemType::Equipment,
"test!".to_owned(),
"This is a test item.".to_owned(),
),
)],
players: Vec::new(),
player_controller: PlayerController::new(0.25f32),
}
}
pub fn map(&self) -> &Option<Map> {
&self.map
}
pub fn items(&self) -> &Vec<dropped_item::DroppedItem> {
&self.items
}
pub fn players(&self) -> &Vec<player::Player> {
&self.players
}
pub fn players_mut(&mut self) -> &mut Vec<player::Player> {
&mut self.players
}
pub fn player_controller(&self) -> &PlayerController {
&self.player_controller
}
pub fn player_controller_mut(&mut self) -> &mut PlayerController {
&mut self.player_controller
}
pub fn update(&mut self, now: std::time::Instant, input: &Input, socket: &mut Socket) {
match &self.map {
Some(map) => {
self.player_controller.update(
now,
input,
map,
self.players.first_mut().unwrap(),
socket,
);
}
None => {}
}
}
pub fn add_player(&mut self, id: u64, color: (u8, u8, u8), x: i32, y: i32) {
self.players.push(player::Player::new(
id,
x,
y,
sdl2::pixels::Color::from(color),
));
}
pub fn remove_player(&mut self, id: u64) {
self.players.remove(
self.players
.iter()
.position(|player| player.id() == id)
.unwrap(),
);
}
pub fn init_map(&mut self, map: Map) {
self.map = Some(map);
}
}
|
use super::super::posting::mastodon::MastodonUpload;
pub struct Saramin {
// 공고 ID
pub id: u32,
// 회사명
pub company_name: String,
// 공고 제목
pub title: String,
// 링크
pub link: String,
// 경력
career: Option<String>,
// 학력
education: Option<String>,
// 근로형태
employment_type: Option<String>,
// 근무지
work_place: Option<String>,
// 임금
salary: Option<String>,
// 모집기한
deadline: Option<String>,
}
impl MastodonUpload for Saramin {
fn spoiler_text(&self) -> String {
self.title.clone()
}
fn status(&self) -> String {
let is_none = String::from("-");
format!(
r"🏢 {company_name}
⌛ {career}
🏫 {education}
💼 {employment_type}
🗺️ {work_place}
💰 {salary}
🕑 {deadline}
🔗 {link}",
company_name = &self.company_name,
career = &self.career.as_ref().unwrap_or(&is_none),
education = &self.education.as_ref().unwrap_or(&is_none),
employment_type = &self.employment_type.as_ref().unwrap_or(&is_none),
work_place = &self.work_place.as_ref().unwrap_or(&is_none),
salary = &self.salary.as_ref().unwrap_or(&is_none),
deadline = &self.deadline.as_ref().unwrap_or(&is_none),
link = &self.link
)
}
}
impl Saramin {
pub fn new(
id: u32, title: String, company_name: String, career: Option<String>,
education: Option<String>, employment_type: Option<String>, work_place: Option<String>,
salary: Option<String>, deadline: Option<String>, link: String,
) -> Saramin {
Saramin {
id,
title,
company_name,
career,
education,
employment_type,
work_place,
salary,
deadline,
link,
}
}
}
|
// SPDX-License-Identifier: Apache-2.0
use std::fmt;
use openssl::hash::{DigestBytes, MessageDigest};
#[derive(Copy, Clone, Debug)]
pub enum Kind {
Sha256,
Null,
}
impl fmt::Display for Kind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::Sha256 => "sha256",
Self::Null => "null",
};
write!(f, "{}", s)
}
}
impl From<Kind> for MessageDigest {
fn from(k: Kind) -> MessageDigest {
match k {
Kind::Sha256 => MessageDigest::sha256(),
Kind::Null => MessageDigest::null(),
}
}
}
#[derive(Copy, Clone, Debug)]
pub struct Measurement {
pub kind: Kind,
pub digest: DigestBytes,
}
|
use argh::FromArgs;
use assembly_pack::pki::core::PackIndexFile;
use std::{convert::TryFrom, fs::File, path::PathBuf};
#[derive(FromArgs)]
/// Show contents of a PKI file
struct Args {
/// print all pack files
#[argh(switch, short = 'p')]
pack_files: bool,
/// print all files
#[argh(switch, short = 'f')]
files: bool,
/// the PKI file
#[argh(positional)]
path: PathBuf,
}
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let args: Args = argh::from_env();
let file = File::open(&args.path)?;
let file = PackIndexFile::try_from(file)?;
if args.pack_files {
for pack in file.archives {
println!("{}", pack.path);
}
Ok(())
} else if args.files {
for (key, file_ref) in file.files {
let pack_index = file_ref.pack_file as usize;
match file.archives.get(pack_index) {
Some(pack_ref) => {
println!("{:>10} {:08x} {}", key, file_ref.category, pack_ref.path);
}
None => println!("Pack ID {} out of bounds", pack_index),
}
}
Ok(())
} else {
eprintln!("Please specify either `-f` or `-p`");
Ok(())
}
}
|
use std::cell::RefCell;
use std::rc::Rc;
use super::super::{Env, InterpreterError};
use super::super::super::Expr;
pub fn eq(args: &[Expr], _: Rc<RefCell<Env>>) -> Result<Expr, InterpreterError> {
if args.len() != 2 {
Err(InterpreterError::Usage("=".to_string(), args.to_vec()))
} else if args[0] == args[1] {
Ok(Expr::Symbol("t".to_string()))
} else {
Ok(Expr::Nil)
}
}
pub fn ne(args: &[Expr], _: Rc<RefCell<Env>>) -> Result<Expr, InterpreterError> {
if args.len() != 2 {
Err(InterpreterError::Usage("!=".to_string(), args.to_vec()))
} else if args[0] == args[1] {
Ok(Expr::Nil)
} else {
Ok(Expr::Symbol("t".to_string()))
}
}
macro_rules! arith_bfunc {
($name:ident, $sym:expr, $base:expr, $block:expr) => {
arith_bfunc!($name, $sym, $base, $block, $block);
};
($name:ident, $sym:expr, $base: expr, $ints:expr, $floats:expr) => {
pub fn $name(args: &[Expr], _: Rc<RefCell<Env>>) -> Result<Expr, InterpreterError> {
if args.len() == 0 {
Err(InterpreterError::Usage($sym.to_string(), args.to_vec()))
} else if args.iter().all(|expr| expr.to_integer().is_some()) {
Ok(Expr::Integer(args.iter()
.map(|expr| expr.to_integer().unwrap())
.fold($base as i64, $ints)))
} else if args.iter().all(|expr| expr.to_floating().is_some()) {
Ok(Expr::Floating(args.iter()
.map(|expr| expr.to_floating().unwrap())
.fold($base as f64, $floats)))
} else {
Err(InterpreterError::Usage($sym.to_string(), args.to_vec()))
}
}
};
}
arith_bfunc!(plus, "+", 0, |a, b| a + b);
arith_bfunc!(minus, "-", 0, |a, b| a - b);
arith_bfunc!(times, "*", 1, |a, b| a * b);
arith_bfunc!(div, "/", 1, |a, b| a / b);
pub fn pow(args: &[Expr], _: Rc<RefCell<Env>>) -> Result<Expr, InterpreterError> {
let err = InterpreterError::Usage("pow".to_string(), args.to_vec());
if args.len() != 2 {
Err(err)
} else {
args[0]
.to_floating()
.iter()
.cloned()
.zip(args[1]
.to_floating()
.iter()
.cloned())
.map(|(a, b)| a.powf(b))
.map(Expr::Floating)
.next()
.ok_or(err)
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use fidl_fuchsia_wlan_common as fidl_common;
use fidl_fuchsia_wlan_mlme as fidl_mlme;
type Ssid = Vec<u8>;
pub fn fake_bss_description(ssid: Ssid, rsn: Option<Vec<u8>>) -> fidl_mlme::BssDescription {
fidl_mlme::BssDescription {
bssid: [7, 1, 2, 77, 53, 8],
ssid,
bss_type: fidl_mlme::BssTypes::Infrastructure,
beacon_period: 100,
dtim_period: 100,
timestamp: 0,
local_time: 0,
cap: fidl_mlme::CapabilityInfo {
ess: false,
ibss: false,
cf_pollable: false,
cf_poll_req: false,
privacy: rsn.is_some(),
short_preamble: false,
spectrum_mgmt: false,
qos: false,
short_slot_time: false,
apsd: false,
radio_msmt: false,
delayed_block_ack: false,
immediate_block_ack: false,
},
basic_rate_set: vec![],
op_rate_set: vec![],
country: None,
rsn,
vendor_ies: None,
rcpi_dbmh: 0,
rsni_dbh: 0,
ht_cap: None,
ht_op: None,
vht_cap: None,
vht_op: None,
chan: fidl_common::WlanChan { primary: 1, secondary80: 0, cbw: fidl_common::Cbw::Cbw20 },
rssi_dbm: 0,
}
}
pub fn fake_unprotected_bss_description(ssid: Ssid) -> fidl_mlme::BssDescription {
fake_bss_description(ssid, None)
}
pub fn fake_vht_capabilities() -> fidl_mlme::VhtCapabilities {
fidl_mlme::VhtCapabilities {
vht_cap_info: fake_vht_capabilities_info(),
vht_mcs_nss: fake_vht_mcs_nss(),
}
}
pub fn fake_vht_capabilities_info() -> fidl_mlme::VhtCapabilitiesInfo {
fidl_mlme::VhtCapabilitiesInfo {
max_mpdu_len: fidl_mlme::MaxMpduLen::Octets7991 as u8,
supported_cbw_set: 0,
rx_ldpc: true,
sgi_cbw80: true,
sgi_cbw160: false,
tx_stbc: true,
rx_stbc: 2,
su_bfer: false,
su_bfee: false,
bfee_sts: 0,
num_sounding: 0,
mu_bfer: false,
mu_bfee: false,
txop_ps: false,
htc_vht: false,
max_ampdu_exp: 2,
link_adapt: fidl_mlme::VhtLinkAdaptation::NoFeedback as u8,
rx_ant_pattern: true,
tx_ant_pattern: true,
ext_nss_bw: 2,
}
}
pub fn fake_vht_mcs_nss() -> fidl_mlme::VhtMcsNss {
fidl_mlme::VhtMcsNss {
rx_max_mcs: [fidl_mlme::VhtMcs::Set0To9 as u8; 8],
rx_max_data_rate: 867,
max_nsts: 2,
tx_max_mcs: [fidl_mlme::VhtMcs::Set0To9 as u8; 8],
tx_max_data_rate: 867,
ext_nss_bw: false,
}
}
pub fn fake_vht_operation() -> fidl_mlme::VhtOperation {
fidl_mlme::VhtOperation {
vht_cbw: fidl_mlme::VhtCbw::Cbw8016080P80 as u8,
center_freq_seg0: 42,
center_freq_seg1: 0,
basic_mcs: fake_basic_vht_mcs_nss(),
}
}
pub fn fake_basic_vht_mcs_nss() -> fidl_mlme::BasicVhtMcsNss {
fidl_mlme::BasicVhtMcsNss { max_mcs: [fidl_mlme::VhtMcs::Set0To9 as u8; 8] }
}
pub fn fake_ht_capabilities() -> fidl_mlme::HtCapabilities {
fidl_mlme::HtCapabilities {
ht_cap_info: fake_ht_cap_info(),
ampdu_params: fake_ampdu_params(),
mcs_set: fake_supported_mcs_set(),
ht_ext_cap: fake_ht_ext_capabilities(),
txbf_cap: fake_txbf_capabilities(),
asel_cap: fake_asel_capability(),
}
}
pub fn fake_ht_cap_info() -> fidl_mlme::HtCapabilityInfo {
fidl_mlme::HtCapabilityInfo {
ldpc_coding_cap: false,
chan_width_set: fidl_mlme::ChanWidthSet::TwentyForty as u8,
sm_power_save: fidl_mlme::SmPowerSave::Disabled as u8,
greenfield: true,
short_gi_20: true,
short_gi_40: true,
tx_stbc: true,
rx_stbc: 1,
delayed_block_ack: false,
max_amsdu_len: fidl_mlme::MaxAmsduLen::Octets3839 as u8,
dsss_in_40: false,
intolerant_40: false,
lsig_txop_protect: false,
}
}
pub fn fake_ampdu_params() -> fidl_mlme::AmpduParams {
fidl_mlme::AmpduParams {
exponent: 0,
min_start_spacing: fidl_mlme::MinMpduStartSpacing::NoRestrict as u8,
}
}
pub fn fake_supported_mcs_set() -> fidl_mlme::SupportedMcsSet {
fidl_mlme::SupportedMcsSet {
rx_mcs_set: 0x01000000ff,
rx_highest_rate: 0,
tx_mcs_set_defined: true,
tx_rx_diff: false,
tx_max_ss: 1,
tx_ueqm: false,
}
}
pub fn fake_ht_ext_capabilities() -> fidl_mlme::HtExtCapabilities {
fidl_mlme::HtExtCapabilities {
pco: false,
pco_transition: fidl_mlme::PcoTransitionTime::PcoReserved as u8,
mcs_feedback: fidl_mlme::McsFeedback::McsNofeedback as u8,
htc_ht_support: false,
rd_responder: false,
}
}
pub fn fake_txbf_capabilities() -> fidl_mlme::TxBfCapability {
fidl_mlme::TxBfCapability {
implicit_rx: false,
rx_stag_sounding: false,
tx_stag_sounding: false,
rx_ndp: false,
tx_ndp: false,
implicit: false,
calibration: fidl_mlme::Calibration::CalibrationNone as u8,
csi: false,
noncomp_steering: false,
comp_steering: false,
csi_feedback: fidl_mlme::Feedback::FeedbackNone as u8,
noncomp_feedback: fidl_mlme::Feedback::FeedbackNone as u8,
comp_feedback: fidl_mlme::Feedback::FeedbackNone as u8,
min_grouping: fidl_mlme::MinGroup::MinGroupOne as u8,
csi_antennas: 1,
noncomp_steering_ants: 1,
comp_steering_ants: 1,
csi_rows: 1,
chan_estimation: 1,
}
}
pub fn fake_asel_capability() -> fidl_mlme::AselCapability {
fidl_mlme::AselCapability {
asel: false,
csi_feedback_tx_asel: false,
ant_idx_feedback_tx_asel: false,
explicit_csi_feedback: false,
antenna_idx_feedback: false,
rx_asel: false,
tx_sounding_ppdu: false,
}
}
pub fn fake_ht_operation() -> fidl_mlme::HtOperation {
fidl_mlme::HtOperation {
primary_chan: 36,
ht_op_info: fake_ht_op_info(),
basic_mcs_set: fake_supported_mcs_set(),
}
}
pub fn fake_ht_op_info() -> fidl_mlme::HtOperationInfo {
fidl_mlme::HtOperationInfo {
secondary_chan_offset: fidl_mlme::SecChanOffset::SecondaryAbove as u8,
sta_chan_width: fidl_mlme::StaChanWidth::Any as u8,
rifs_mode: false,
ht_protect: fidl_mlme::HtProtect::None as u8,
nongreenfield_present: true,
obss_non_ht: true,
center_freq_seg2: 0,
dual_beacon: false,
dual_cts_protect: false,
stbc_beacon: false,
lsig_txop_protect: false,
pco_active: false,
pco_phase: false,
}
}
|
extern crate quicr_core as quicr;
extern crate openssl;
extern crate rand;
#[macro_use]
extern crate slog;
#[macro_use]
extern crate assert_matches;
#[macro_use]
extern crate lazy_static;
extern crate bytes;
#[macro_use]
extern crate hex_literal;
extern crate byteorder;
use std::net::SocketAddrV6;
use std::{fmt, str};
use std::io::{self, Write};
use std::collections::VecDeque;
use openssl::pkey::{PKey, Private};
use openssl::rsa::Rsa;
use openssl::x509::X509;
use openssl::asn1::Asn1Time;
use slog::{Logger, Drain, KV};
use byteorder::{ByteOrder, BigEndian};
use quicr::*;
struct TestDrain;
impl Drain for TestDrain {
type Ok = ();
type Err = io::Error;
fn log(&self, record: &slog::Record, values: &slog::OwnedKVList) -> Result<(), io::Error> {
let mut vals = Vec::new();
values.serialize(&record, &mut TestSerializer(&mut vals))?;
record.kv().serialize(&record, &mut TestSerializer(&mut vals))?;
println!("{} {}{}", record.level(), record.msg(), str::from_utf8(&vals).unwrap());
Ok(())
}
}
struct TestSerializer<'a, W: 'a>(&'a mut W);
impl<'a, W> slog::Serializer for TestSerializer<'a, W>
where W: Write + 'a
{
fn emit_arguments(&mut self, key: slog::Key, val: &fmt::Arguments) -> slog::Result {
write!(self.0, ", {}: {}", key, val).unwrap();
Ok(())
}
}
fn logger() -> Logger {
Logger::root(TestDrain.fuse(), o!())
}
lazy_static! {
static ref KEY: PKey<Private> = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
static ref CERT: X509 = {
let mut cert = X509::builder().unwrap();
cert.set_pubkey(&KEY).unwrap();
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
cert.set_not_after(&Asn1Time::days_from_now(u32::max_value()).unwrap()).unwrap();
cert.sign(&KEY, openssl::hash::MessageDigest::sha256()).unwrap();
cert.build()
};
static ref LISTEN_KEYS: ListenKeys = ListenKeys::new(&mut rand::thread_rng());
}
struct Pair {
log: Logger,
server: TestEndpoint,
client: TestEndpoint,
time: u64,
// One-way
latency: u64,
}
impl Default for Pair {
fn default() -> Self {
Pair::new(Config { max_remote_uni_streams: 32, max_remote_bi_streams: 32, ..Config::default() },
Config::default())
}
}
impl Pair {
fn new(server_config: Config, client_config: Config) -> Self {
let log = logger();
let server_addr = "[::1]:42".parse().unwrap();
let server = Endpoint::new(
log.new(o!("side" => "Server")),
server_config,
Some(CertConfig {
private_key: &KEY,
cert: &CERT,
}),
Some(*LISTEN_KEYS)).unwrap();
let client_addr = "[::2]:7890".parse().unwrap();
let client = Endpoint::new(log.new(o!("side" => "Client")), client_config, None, None).unwrap();
Self {
log,
server: TestEndpoint::new(Side::Server, server, server_addr),
client: TestEndpoint::new(Side::Client, client, client_addr),
time: 0,
latency: 0,
}
}
/// Returns whether the connection is not idle
fn step(&mut self) -> bool {
self.drive_client();
self.drive_server();
let client_t = self.client.next_wakeup();
let server_t = self.server.next_wakeup();
if client_t == self.client.idle && server_t == self.server.idle { return false; }
if client_t < server_t {
if client_t != self.time {
self.time = self.time.max(client_t);
trace!(self.log, "advancing to {time} for client", time=self.time);
}
} else {
if server_t != self.time {
self.time = self.time.max(server_t);
trace!(self.log, "advancing to {time} for server", time=self.time);
}
}
true
}
/// Advance time until both connections are idle
fn drive(&mut self) { while self.step() {} }
fn drive_client(&mut self) {
trace!(self.log, "client running");
self.client.drive(&self.log, self.time, self.server.addr);
for packet in self.client.outbound.drain(..) {
self.server.inbound.push_back((self.time + self.latency, packet));
}
}
fn drive_server(&mut self) {
trace!(self.log, "server running");
self.server.drive(&self.log, self.time, self.client.addr);
for packet in self.server.outbound.drain(..) {
self.client.inbound.push_back((self.time + self.latency, packet));
}
}
fn connect(&mut self) -> (ConnectionHandle, ConnectionHandle) {
info!(self.log, "connecting");
let client_conn = self.client.connect(self.server.addr, ClientConfig {
accept_insecure_certs: true,
..ClientConfig::default()
}).unwrap();
self.drive();
let server_conn = if let Some(c) = self.server.accept() { c } else { panic!("server didn't connect"); };
assert_matches!(self.client.poll(), Some((conn, Event::Connected { .. })) if conn == client_conn);
(client_conn, server_conn)
}
}
struct TestEndpoint {
side: Side,
endpoint: Endpoint,
addr: SocketAddrV6,
idle: u64,
loss: u64,
close: u64,
conn: Option<ConnectionHandle>,
outbound: VecDeque<Box<[u8]>>,
inbound: VecDeque<(u64, Box<[u8]>)>,
}
impl TestEndpoint {
fn new(side: Side, endpoint: Endpoint, addr: SocketAddrV6) -> Self { Self {
side, endpoint, addr,
idle: u64::max_value(),
loss: u64::max_value(),
close: u64::max_value(),
conn: None,
outbound: VecDeque::new(),
inbound: VecDeque::new(),
}}
fn drive(&mut self, log: &Logger, now: u64, remote: SocketAddrV6) {
if let Some(conn) = self.conn {
if self.loss <= now {
trace!(log, "{side:?} {timer:?} timeout", side=self.side, timer=Timer::LossDetection);
self.loss = u64::max_value();
self.endpoint.timeout(now, conn, Timer::LossDetection);
}
if self.idle <= now {
trace!(log, "{side:?} {timer:?} timeout", side=self.side, timer=Timer::Idle);
self.idle = u64::max_value();
self.endpoint.timeout(now, conn, Timer::Idle);
}
if self.close <= now {
trace!(log, "{side:?} {timer:?} timeout", side=self.side, timer=Timer::Close);
self.close = u64::max_value();
self.endpoint.timeout(now, conn, Timer::Close);
}
}
while self.inbound.front().map_or(false, |x| x.0 <= now) {
self.endpoint.handle(now, remote, Vec::from(self.inbound.pop_front().unwrap().1).into());
}
while let Some(x) = self.endpoint.poll_io(now) { match x {
Io::Transmit { packet, .. } => {
self.outbound.push_back(packet);
}
Io::TimerStart { timer, time, connection } => {
self.conn = Some(connection);
trace!(log, "{side:?} {timer:?} start: {dt}", side=self.side, timer=timer, dt=(time - now));
match timer {
Timer::LossDetection => { self.loss = time; }
Timer::Idle => { self.idle = time; }
Timer::Close => { self.close = time; }
}
}
Io::TimerStop { timer, .. } => {
trace!(log, "{side:?} {timer:?} stop", side=self.side, timer=timer);
match timer {
Timer::LossDetection => { self.loss = u64::max_value(); }
Timer::Idle => { self.idle = u64::max_value(); }
Timer::Close => { self.close = u64::max_value(); }
}
}
}}
}
fn next_wakeup(&self) -> u64 {
self.idle.min(self.loss).min(self.close).min(self.inbound.front().map_or(u64::max_value(), |x| x.0))
}
}
impl ::std::ops::Deref for TestEndpoint {
type Target = Endpoint;
fn deref(&self) -> &Endpoint { &self.endpoint }
}
impl ::std::ops::DerefMut for TestEndpoint {
fn deref_mut(&mut self) -> &mut Endpoint { &mut self.endpoint }
}
#[test]
fn version_negotiate() {
let log = logger();
let client_addr = "[::2]:7890".parse().unwrap();
let mut server = Endpoint::new(
log.new(o!("peer" => "server")),
Config::default(),
Some(CertConfig {
private_key: &KEY,
cert: &CERT,
}),
Some(*LISTEN_KEYS)).unwrap();
server.handle(0, client_addr,
// Long-header packet with reserved version number
hex!("80 0a1a2a3a
11 00000000 00000000
00")[..].into());
let io = server.poll_io(0);
assert_matches!(io, Some(Io::Transmit { .. }));
if let Some(Io::Transmit { packet, .. }) = io {
assert!(packet[0] | 0x80 != 0);
assert!(&packet[1..14] == hex!("00000000 11 00000000 00000000"));
assert!(packet[14..].chunks(4).any(|x| BigEndian::read_u32(x) == VERSION));
}
assert_matches!(server.poll_io(0), None);
assert_matches!(server.poll(), None);
}
#[test]
fn lifecycle() {
let mut pair = Pair::default();
let (client_conn, _) = pair.connect();
assert_matches!(pair.client.poll(), Some((conn, Event::NewSessionTicket { .. })) if conn == client_conn);
const REASON: &[u8] = b"whee";
info!(pair.log, "closing");
pair.client.close(pair.time, client_conn, 42, REASON.into());
pair.drive();
assert_matches!(pair.server.poll(),
Some((_, Event::ConnectionLost { reason: ConnectionError::ApplicationClosed {
reason: ApplicationClose { error_code: 42, ref reason }
}})) if reason == REASON);
assert_matches!(pair.client.poll(), Some((conn, Event::NewSessionTicket { .. })) if conn == client_conn);
assert_matches!(pair.client.poll(), Some((conn, Event::ConnectionDrained)) if conn == client_conn);
}
#[test]
fn stateless_retry() {
let mut pair = Pair::new(Config { use_stateless_retry: true, ..Config::default() }, Config::default());
pair.connect();
}
#[test]
fn stateless_reset() {
let mut pair = Pair::default();
let (client_conn, _) = pair.connect();
assert_matches!(pair.client.poll(), Some((conn, Event::NewSessionTicket { .. })) if conn == client_conn);
pair.server.endpoint = Endpoint::new(
pair.log.new(o!("peer" => "server")),
Config::default(),
Some(CertConfig {
private_key: &KEY,
cert: &CERT,
}),
Some(*LISTEN_KEYS)).unwrap();
pair.client.ping(client_conn);
info!(pair.log, "resetting");
pair.drive();
assert_matches!(pair.client.poll(), Some((conn, Event::NewSessionTicket { .. })) if conn == client_conn);
assert_matches!(pair.client.poll(), Some((conn, Event::ConnectionLost { reason: ConnectionError::Reset })) if conn == client_conn);
}
#[test]
fn finish_stream() {
let mut pair = Pair::default();
let (client_conn, server_conn) = pair.connect();
let s = pair.client.open(client_conn, Directionality::Uni).unwrap();
const MSG: &[u8] = b"hello";
pair.client.write(client_conn, s, MSG).unwrap();
pair.client.finish(client_conn, s);
pair.drive();
assert_matches!(pair.client.poll(), Some((conn, Event::NewSessionTicket { .. })) if conn == client_conn);
assert_matches!(pair.client.poll(), Some((conn, Event::NewSessionTicket { .. })) if conn == client_conn);
assert_matches!(pair.client.poll(), Some((conn, Event::StreamFinished { stream })) if conn == client_conn && stream == s);
assert_matches!(pair.client.poll(), None);
assert_matches!(pair.server.poll(), Some((conn, Event::StreamReadable { stream, fresh: true })) if conn == server_conn && stream == s);
assert_matches!(pair.server.poll(), None);
assert_matches!(pair.server.read_unordered(server_conn, s), Ok((ref data, 0)) if data == MSG);
assert_matches!(pair.server.read_unordered(server_conn, s), Err(ReadError::Finished));
}
#[test]
fn reset_stream() {
let mut pair = Pair::default();
let (client_conn, server_conn) = pair.connect();
assert_matches!(pair.client.poll(), Some((conn, Event::NewSessionTicket { .. })) if conn == client_conn);
let s = pair.client.open(client_conn, Directionality::Uni).unwrap();
const MSG: &[u8] = b"hello";
pair.client.write(client_conn, s, MSG).unwrap();
pair.drive();
info!(pair.log, "resetting stream");
const ERROR: u16 = 42;
pair.client.reset(client_conn, s, ERROR);
pair.drive();
assert_matches!(pair.server.poll(), Some((conn, Event::StreamReadable { stream, fresh: true })) if conn == server_conn && stream == s);
assert_matches!(pair.server.poll(), None);
assert_matches!(pair.server.read_unordered(server_conn, s), Ok((ref data, 0)) if data == MSG);
assert_matches!(pair.server.read_unordered(server_conn, s), Err(ReadError::Reset { error_code: ERROR }));
assert_matches!(pair.client.poll(), Some((conn, Event::NewSessionTicket { .. })) if conn == client_conn);
assert_matches!(pair.client.poll(), None);
}
#[test]
fn stop_stream() {
let mut pair = Pair::default();
let (client_conn, server_conn) = pair.connect();
let s = pair.client.open(client_conn, Directionality::Uni).unwrap();
const MSG: &[u8] = b"hello";
pair.client.write(client_conn, s, MSG).unwrap();
pair.drive();
info!(pair.log, "stopping stream");
const ERROR: u16 = 42;
pair.server.stop_sending(server_conn, s, ERROR);
pair.drive();
assert_matches!(pair.server.poll(), Some((conn, Event::StreamReadable { stream, fresh: true })) if conn == server_conn && stream == s);
assert_matches!(pair.server.poll(), None);
assert_matches!(pair.server.read_unordered(server_conn, s), Ok((ref data, 0)) if data == MSG);
assert_matches!(pair.server.read_unordered(server_conn, s), Err(ReadError::Reset { error_code: 0 }));
assert_matches!(pair.client.write(client_conn, s, b"foo"), Err(WriteError::Stopped { error_code: ERROR }));
}
#[test]
fn reject_self_signed_cert() {
let mut pair = Pair::new(Config::default(), Config::default());
info!(pair.log, "connecting");
let client_conn = pair.client.connect(pair.server.addr, ClientConfig::default()).unwrap();
pair.drive();
assert_matches!(pair.client.poll(),
Some((conn, Event::ConnectionLost { reason: ConnectionError::TransportError {
error_code: TransportError::TLS_HANDSHAKE_FAILED
}})) if conn == client_conn);
}
#[test]
fn congestion() {
let mut pair = Pair::default();
let (client_conn, _) = pair.connect();
let initial_congestion_state = pair.client.get_congestion_state(client_conn);
let s = pair.client.open(client_conn, Directionality::Uni).unwrap();
loop {
match pair.client.write(client_conn, s, &[42; 1024]) {
Ok(n) => { assert!(n <= 1024); pair.drive_client(); }
Err(WriteError::Blocked) => { break; }
Err(e) => { panic!("unexpected write error: {}", e); }
}
}
pair.drive();
assert!(pair.client.get_congestion_state(client_conn) >= initial_congestion_state);
pair.client.write(client_conn, s, &[42; 1024]).unwrap();
}
#[test]
fn high_latency_handshake() {
let mut pair = Pair::default();
pair.latency = 200 * 1000;
let client_conn = pair.client.connect(pair.server.addr, ClientConfig { accept_insecure_certs: true, ..ClientConfig::default() }).unwrap();
pair.drive();
let server_conn = if let Some(c) = pair.server.accept() { c } else { panic!("server didn't connect"); };
assert_matches!(pair.client.poll(), Some((conn, Event::Connected { .. })) if conn == client_conn);
assert_eq!(pair.client.get_bytes_in_flight(client_conn), 0);
assert_eq!(pair.server.get_bytes_in_flight(server_conn), 0);
}
#[test]
fn zero_rtt() {
let mut pair = Pair::default();
let (c, _) = pair.connect();
let ticket = match pair.client.poll() {
Some((conn, Event::NewSessionTicket { ref ticket })) if conn == c => ticket.clone(),
e => panic!("unexpected poll result: {:?}", e),
};
info!(pair.log, "closing"; "ticket size" => ticket.len());
pair.client.close(pair.time, c, 42, (&[][..]).into());
pair.drive();
info!(pair.log, "resuming");
let cc = pair.client.connect(pair.server.addr,
ClientConfig {
accept_insecure_certs: true,
session_ticket: Some(&ticket),
..ClientConfig::default()
}).unwrap();
let s = pair.client.open(cc, Directionality::Uni).unwrap();
const MSG: &[u8] = b"Hello, 0-RTT!";
pair.client.write(cc, s, MSG).unwrap();
pair.drive();
assert!(pair.client.get_session_resumed(c));
let sc = if let Some(c) = pair.server.accept() { c } else { panic!("server didn't connect"); };
assert_matches!(pair.server.read_unordered(sc, s), Ok((ref data, 0)) if data == MSG);
}
|
#[path="../src/file.rs"]
mod file;
#[test]
fn is_valid_with_path_and_content() {
let file = file::FileResource {
path: "/home/john/hello.txt".to_string(),
content: "Foo".to_string()
};
assert_eq!(file.is_valid(), true);
}
#[test]
fn is_invalid_without_path() {
let file = file::FileResource {
path: "".to_string(),
content: "Foo".to_string()
};
assert_eq!(file.is_valid(), false);
}
#[test]
fn is_invalid_without_content() {
let file = file::FileResource {
path: "/home/john/hello.txt".to_string(),
content: "".to_string()
};
assert_eq!(file.is_valid(), false);
}
#[test]
fn returns_no_error_messages_if_valid() {
let file = file::FileResource {
path: "/home/john/hello.txt".to_string(),
content: "Foobar".to_string()
};
assert_eq!(file.error_messages().is_empty(), true);
}
#[test]
fn returns_error_message_if_path_is_missing() {
let file = file::FileResource {
path: "".into(),
content: "FooBar".into()
};
let messages = file.error_messages();
assert_eq!(messages.first(), Some(&"File: path is missing".to_string()));
}
#[test]
fn returns_error_message_if_content_is_missing() {
let file = file::FileResource {
path: "/home/john/hello.txt".into(),
content: "".into()
};
let messages = file.error_messages();
assert_eq!(messages.first(), Some(&"File: content is missing".to_string()));
}
#[test]
fn returns_a_hash_for_content() {
let file = file::FileResource {
path: "/home/john/hello.txt".into(),
content: "foobar".into()
};
assert_eq!(file.hash().len() > 0, true);
}
|
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the MIT License, <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
use errors::{SerializableError, WireError};
use futures::{self, Future};
use futures::stream::Empty;
use futures_cpupool::{CpuFuture, CpuPool};
use protocol::{LOOP_HANDLE, TarpcTransport};
use protocol::writer::Packet;
use serde::Serialize;
use std::io;
use std::net::ToSocketAddrs;
use tokio_proto::pipeline;
use tokio_proto::NewService;
use tokio_proto::server::{self, ServerHandle};
/// Start a Tarpc service listening on the given address.
pub fn listen<A, T>(addr: A, new_service: T) -> io::Result<ServerHandle>
where T: NewService<Req = Vec<u8>,
Resp = pipeline::Message<Packet, Empty<(), io::Error>>,
Error = io::Error> + Send + 'static,
A: ToSocketAddrs
{
let mut addrs = addr.to_socket_addrs()?;
let addr = if let Some(a) = addrs.next() {
a
} else {
return Err(io::Error::new(io::ErrorKind::AddrNotAvailable,
"`ToSocketAddrs::to_socket_addrs` returned an empty iterator."));
};
server::listen(LOOP_HANDLE.clone(), addr, move |stream| {
pipeline::Server::new(new_service.new_service()?, TarpcTransport::new(stream))
})
.wait()
}
/// Returns a future containing the serialized reply.
///
/// Because serialization can take a non-trivial
/// amount of cpu time, it is run on a thread pool.
#[doc(hidden)]
#[inline]
pub fn serialize_reply<T: Serialize + Send + 'static,
E: SerializableError>(result: Result<T, WireError<E>>)
-> SerializeFuture
{
POOL.spawn(futures::lazy(move || {
let packet = match Packet::serialize(&result) {
Ok(packet) => packet,
Err(e) => {
let err: Result<T, WireError<E>> =
Err(WireError::ServerSerialize(e.to_string()));
Packet::serialize(&err).unwrap()
}
};
futures::finished(pipeline::Message::WithoutBody(packet))
}))
}
#[doc(hidden)]
pub type SerializeFuture = CpuFuture<SerializedReply, io::Error>;
#[doc(hidden)]
pub type SerializedReply = pipeline::Message<Packet, Empty<(), io::Error>>;
lazy_static! {
static ref POOL: CpuPool = { CpuPool::new_num_cpus() };
}
|
#![allow(unused)]
use std::fs::File;
use std::io::prelude::*;
use std::fs::OpenOptions;
pub static CACHE_FILE: &'static str = "cache.txt";
pub fn create_cache_file() {
let try_file = File::open(CACHE_FILE);
match try_file {
Ok(file) => file,
Err(_) => File::create(CACHE_FILE).unwrap(),
};
}
pub fn read_status_file() -> String {
let mut file = File::open(CACHE_FILE).expect("unable to open file");
let mut contents = String::new();
file.read_to_string(&mut contents).expect(
"unable to read from file",
);
contents
}
pub fn write_status_file(content: &str) {
let mut file = OpenOptions::new().write(true).open(CACHE_FILE).unwrap();
file.write_all(content.as_bytes()).unwrap();
}
|
/*
* YNAB API Endpoints
*
* Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudget.com
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
/// DateFormat : The date format setting for the budget. In some cases the format will not be available and will be specified as null.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct DateFormat {
#[serde(rename = "format")]
pub format: String,
}
impl DateFormat {
/// The date format setting for the budget. In some cases the format will not be available and will be specified as null.
pub fn new(format: String) -> DateFormat {
DateFormat {
format,
}
}
}
|
use sudo_test::{Command, Env, User};
use crate::{Result, GROUPNAME, PASSWORD, SUDOERS_NO_LECTURE, USERNAME};
macro_rules! assert_snapshot {
($($tt:tt)*) => {
insta::with_settings!({
filters => vec![(r"[[:xdigit:]]{12}", "[host]")],
prepend_module_to_snapshot => false,
snapshot_path => "../../snapshots/sudoers/runas_alias",
}, {
insta::assert_snapshot!($($tt)*)
});
};
}
#[test]
fn runas_alias_works() -> Result<()> {
let env = Env([
"Runas_Alias OP = root, operator",
"root ALL=(ALL:ALL) NOPASSWD: ALL",
&format!("{USERNAME} ALL = (OP) ALL"),
])
.user(User(USERNAME).password(PASSWORD))
.build()?;
for user in ["root", USERNAME] {
Command::new("sudo")
.args(["-u", "root", "-S", "true"])
.as_user(user)
.stdin(PASSWORD)
.output(&env)?
.assert_success()?;
}
Command::new("sudo")
.args(["-S", "true"])
.as_user("root")
.output(&env)?
.assert_success()?;
Ok(())
}
#[test]
fn underscore() -> Result<()> {
let env = Env([
"Runas_Alias UNDER_SCORE = root, operator",
"root ALL=(ALL:ALL) NOPASSWD: ALL",
&format!("{USERNAME} ALL = (UNDER_SCORE) ALL"),
])
.user(User(USERNAME).password(PASSWORD))
.build()?;
for user in ["root", USERNAME] {
Command::new("sudo")
.args(["-u", "root", "-S", "true"])
.as_user(user)
.stdin(PASSWORD)
.output(&env)?
.assert_success()?;
}
Ok(())
}
#[test]
fn runas_alias_negation() -> Result<()> {
let env = Env([
"Runas_Alias OP = root, operator",
"root ALL = (ALL:ALL) NOPASSWD: ALL",
&format!("{USERNAME} ALL = (!OP) ALL"),
SUDOERS_NO_LECTURE,
])
.user(User(USERNAME).password(PASSWORD))
.build()?;
let output = Command::new("sudo")
.args(["-u", "root", "-S", "true"])
.as_user(USERNAME)
.stdin(PASSWORD)
.output(&env)?;
assert!(!output.status().success());
assert_eq!(Some(1), output.status().code());
let stderr = output.stderr();
if sudo_test::is_original_sudo() {
assert_snapshot!(stderr);
} else {
assert_contains!(
stderr,
format!("authentication failed: I'm sorry {USERNAME}. I'm afraid I can't do that")
);
}
Ok(())
}
#[test]
fn negation_on_user() -> Result<()> {
let env = Env([
"Runas_Alias OP = !root, operator",
"root ALL = (ALL:ALL) NOPASSWD: ALL",
&format!("{USERNAME} ALL = (OP) ALL"),
SUDOERS_NO_LECTURE,
])
.user(User(USERNAME).password(PASSWORD))
.build()?;
let output = Command::new("sudo")
.args(["-u", "root", "-S", "true"])
.as_user(USERNAME)
.stdin(PASSWORD)
.output(&env)?;
assert!(!output.status().success());
assert_eq!(Some(1), output.status().code());
let stderr = output.stderr();
if sudo_test::is_original_sudo() {
assert_snapshot!(stderr);
} else {
assert_contains!(
stderr,
format!("authentication failed: I'm sorry {USERNAME}. I'm afraid I can't do that")
);
}
Ok(())
}
#[test]
fn double_negation() -> Result<()> {
let env = Env([
"Runas_Alias OP = root, operator",
"root ALL=(ALL:ALL) NOPASSWD: ALL",
&format!("{USERNAME} ALL = (!!OP) ALL"),
])
.user(User(USERNAME).password(PASSWORD))
.build()?;
for user in ["root", USERNAME] {
Command::new("sudo")
.args(["-u", "root", "-S", "true"])
.as_user(user)
.stdin(PASSWORD)
.output(&env)?
.assert_success()?;
}
Ok(())
}
#[test]
fn when_specific_user_then_as_a_different_user_is_not_allowed() -> Result<()> {
let env = Env([
&format!("Runas_Alias OP = {USERNAME}, operator"),
"ALL ALL = (OP) ALL",
SUDOERS_NO_LECTURE,
])
.user(User(USERNAME).password(PASSWORD))
.user(User("ghost"))
.build()?;
let output = Command::new("sudo")
.args(["-u", "ghost", "-S", "true"])
.as_user(USERNAME)
.stdin(PASSWORD)
.output(&env)?;
assert!(!output.status().success());
assert_eq!(Some(1), output.status().code());
let stderr = output.stderr();
if sudo_test::is_original_sudo() {
assert_snapshot!(stderr);
} else {
assert_contains!(
stderr,
format!("authentication failed: I'm sorry {USERNAME}. I'm afraid I can't do that")
);
}
Ok(())
}
// Groupname
// Without the use of an alias it looks e.g. like this: "ALL ALL = (USERNAME:GROUPNAME) ALL"
// Even when 'Runas_Alias' contains both USERNAME and GROUPNAME, it depends on how the alias is referred to.
// e.g. (OP) only accepts the user, (:OP) only accepts the group and (OP:OP) accepts either user or group
// but not both together.
#[test]
fn alias_for_group() -> Result<()> {
let env = Env([
&format!("Runas_Alias OP = {GROUPNAME}"),
&format!("{USERNAME} ALL = (:OP) NOPASSWD: ALL"),
])
.user(User(USERNAME).password(PASSWORD))
.user(User("otheruser"))
.group(GROUPNAME)
.build()?;
Command::new("sudo")
.args(["-g", GROUPNAME, "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
Ok(())
}
#[test]
fn when_only_groupname_is_given_user_arg_fails() -> Result<()> {
let env = Env([
&format!("Runas_Alias OP = otheruser, {GROUPNAME}"),
&format!("{USERNAME} ALL = (:OP) NOPASSWD: ALL"),
SUDOERS_NO_LECTURE,
])
.user(User(USERNAME).password(PASSWORD))
.user(User("otheruser"))
.group(GROUPNAME)
.build()?;
Command::new("sudo")
.args(["-g", GROUPNAME, "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
let output = Command::new("sudo")
.args(["-u", "otheruser", "-S", "true"])
.as_user(USERNAME)
.stdin(PASSWORD)
.output(&env)?;
assert!(!output.status().success());
assert_eq!(Some(1), output.status().code());
let stderr = output.stderr();
if sudo_test::is_original_sudo() {
assert_snapshot!(stderr);
} else {
assert_contains!(
stderr,
format!("authentication failed: I'm sorry ferris. I'm afraid I can't do that")
);
}
Ok(())
}
#[test]
fn when_only_username_is_given_group_arg_fails() -> Result<()> {
let env = Env([
&format!("Runas_Alias OP = otheruser, {GROUPNAME}"),
&format!("{USERNAME} ALL = (OP) NOPASSWD: ALL"),
SUDOERS_NO_LECTURE,
])
.user(User(USERNAME).password(PASSWORD))
.user(User("otheruser"))
.group(GROUPNAME)
.build()?;
Command::new("sudo")
.args(["-u", "otheruser", "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
let output = Command::new("sudo")
.args(["-g", GROUPNAME, "-S", "true"])
.as_user(USERNAME)
.stdin(PASSWORD)
.output(&env)?;
assert!(!output.status().success());
assert_eq!(Some(1), output.status().code());
let stderr = output.stderr();
if sudo_test::is_original_sudo() {
assert_snapshot!(stderr);
} else {
assert_contains!(
stderr,
format!("authentication failed: I'm sorry ferris. I'm afraid I can't do that")
);
}
Ok(())
}
#[test]
fn user_and_group_works_when_one_is_passed_as_arg() -> Result<()> {
let env = Env([
&format!("Runas_Alias OP = otheruser, {GROUPNAME}"),
&format!("{USERNAME} ALL = (OP:OP) NOPASSWD: ALL"),
])
.user(User(USERNAME))
.user(User("otheruser"))
.group(GROUPNAME)
.build()?;
Command::new("sudo")
.args(["-u", "otheruser", "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
Command::new("sudo")
.args(["-g", GROUPNAME, "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
Ok(())
}
#[test]
fn user_and_group_succeeds_when_both_are_passed() -> Result<()> {
if sudo_test::is_original_sudo() {
// TODO: original sudo should pass this test after 1.9.14b2
return Ok(());
}
let env = Env([
&format!("Runas_Alias OP = otheruser, {GROUPNAME}"),
&format!("{USERNAME} ALL = (OP:OP) NOPASSWD: ALL"),
SUDOERS_NO_LECTURE,
])
.user(User(USERNAME).password(PASSWORD))
.user(User("otheruser"))
.group(GROUPNAME)
.build()?;
Command::new("sudo")
.args(["-u", "otheruser", "-g", GROUPNAME, "-S", "true"])
.as_user(USERNAME)
.stdin(PASSWORD)
.output(&env)?
.assert_success()?;
Ok(())
}
#[test]
fn different_aliases_user_and_group_works_when_one_is_passed_as_arg() -> Result<()> {
let env = Env([
&format!("Runas_Alias GROUPALIAS = {GROUPNAME}"),
("Runas_Alias USERALIAS = otheruser"),
&format!("{USERNAME} ALL = (USERALIAS:GROUPALIAS) NOPASSWD: ALL"),
])
.user(USERNAME)
.user("otheruser")
.group(GROUPNAME)
.build()?;
Command::new("sudo")
.args(["-u", "otheruser", "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
Command::new("sudo")
.args(["-g", GROUPNAME, "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
Ok(())
}
#[test]
fn different_aliases_user_and_group_succeeds_when_both_are_passed() -> Result<()> {
if sudo_test::is_original_sudo() {
// TODO: original sudo should pass this test after 1.9.14b2
return Ok(());
}
let env = Env([
&format!("Runas_Alias GROUPALIAS = {GROUPNAME}"),
("Runas_Alias USERALIAS = otheruser"),
&format!("{USERNAME} ALL = (USERALIAS:GROUPALIAS) NOPASSWD: ALL"),
SUDOERS_NO_LECTURE,
])
.user(User(USERNAME).password(PASSWORD))
.user(User("otheruser"))
.group(GROUPNAME)
.build()?;
Command::new("sudo")
.args(["-u", "otheruser", "-g", GROUPNAME, "-S", "true"])
.as_user(USERNAME)
.stdin(PASSWORD)
.output(&env)?
.assert_success()?;
Ok(())
}
#[test]
fn aliases_given_on_one_line_divided_by_colon() -> Result<()> {
let env = Env([
"Runas_Alias GROUPALIAS = ALL : USERALIAS = ALL",
"ALL ALL = (USERALIAS:GROUPALIAS) NOPASSWD: ALL",
])
.user(USERNAME)
.user("otheruser")
.group("ghost")
.build()?;
Command::new("sudo")
.args(["-u", "otheruser", "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
Command::new("sudo")
.args(["-g", "ghost", "true"])
.as_user(USERNAME)
.output(&env)?
.assert_success()?;
Ok(())
}
#[test]
#[ignore = "gh700"]
fn keywords() -> Result<()> {
for bad_keyword in super::KEYWORDS_ALIAS_BAD {
dbg!(bad_keyword);
let env = Env([
format!("Runas_Alias {bad_keyword} = root"),
format!("ALL ALL=({bad_keyword}) ALL"),
])
.build()?;
let output = Command::new("sudo").arg("true").output(&env)?;
assert_contains!(output.stderr(), "syntax error");
assert_eq!(*bad_keyword == "ALL", output.status().success());
}
for good_keyword in super::keywords_alias_good() {
dbg!(good_keyword);
let env = Env([
format!("Runas_Alias {good_keyword} = root"),
format!("ALL ALL=({good_keyword}) ALL"),
])
.build()?;
let output = Command::new("sudo").arg("true").output(&env)?;
let stderr = output.stderr();
assert!(stderr.is_empty(), "{}", stderr);
assert!(output.status().success());
}
Ok(())
}
|
use crate::protocol::Protocol;
use crate::protocol::ProtocolSet;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
pub const DEFAULT_UDP_PORT: u16 = 53;
pub const DEFAULT_TCP_PORT: u16 = 53;
pub const DEFAULT_DOT_PORT: u16 = 853;
pub const DEFAULT_DOH_PORT: u16 = 443;
pub const DEFAULT_MDNS_PORT: u16 = 5353;
pub const DEFAULT_TCP_DNSCRYPT_PORT: u16 = 443; // NOTE: 也许改为 5443 ?
pub const DEFAULT_UDP_DNSCRYPT_PORT: u16 = 443;
pub static ROOT_V4_SERVERS: [(&'static str, IpAddr); 13] = [
("a.root-servers.net", IpAddr::V4(Ipv4Addr::new(198, 41, 0, 4))), // 198.41.0.4
("b.root-servers.net", IpAddr::V4(Ipv4Addr::new(199, 9, 14, 201))), // 199.9.14.201
("c.root-servers.net", IpAddr::V4(Ipv4Addr::new(192, 33, 4, 12))), // 192.33.4.12
("d.root-servers.net", IpAddr::V4(Ipv4Addr::new(199, 7, 91, 13))), // 199.7.91.13
("e.root-servers.net", IpAddr::V4(Ipv4Addr::new(192, 203, 230, 10))), // 192.203.230.10
("f.root-servers.net", IpAddr::V4(Ipv4Addr::new(192, 5, 5, 241))), // 192.5.5.241
("g.root-servers.net", IpAddr::V4(Ipv4Addr::new(192, 112, 36, 4))), // 192.112.36.4
("h.root-servers.net", IpAddr::V4(Ipv4Addr::new(198, 97, 190, 53))), // 198.97.190.53
("i.root-servers.net", IpAddr::V4(Ipv4Addr::new(192, 36, 148, 17))), // 192.36.148.17
("j.root-servers.net", IpAddr::V4(Ipv4Addr::new(192, 58, 128, 30))), // 192.58.128.30
("k.root-servers.net", IpAddr::V4(Ipv4Addr::new(193, 0, 14, 129))), // 193.0.14.129
("l.root-servers.net", IpAddr::V4(Ipv4Addr::new(199, 7, 83, 42))), // 199.7.83.42
("m.root-servers.net", IpAddr::V4(Ipv4Addr::new(202, 12, 27, 33))), // 202.12.27.33
];
pub static ROOT_V6_SERVERS: [(&'static str, IpAddr); 13] = [
("a.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0503, 0xba3e, 0x0000, 0x0000, 0x0000, 0x0002, 0x0030))), // 2001:503:ba3e::2:30
("b.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0500, 0x0200, 0x0000, 0x0000, 0x0000, 0x0000, 0x000b))), // 2001:500:200::b
("c.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0500, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000, 0x000c))), // 2001:500:2::c
("d.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0500, 0x002d, 0x0000, 0x0000, 0x0000, 0x0000, 0x000d))), // 2001:500:2d::d
("e.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0500, 0x00a8, 0x0000, 0x0000, 0x0000, 0x0000, 0x000e))), // 2001:500:a8::e
("f.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0500, 0x002f, 0x0000, 0x0000, 0x0000, 0x0000, 0x000f))), // 2001:500:2f::f
("g.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0500, 0x0012, 0x0000, 0x0000, 0x0000, 0x0000, 0x0d0d))), // 2001:500:12::d0d
("h.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0500, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0053))), // 2001:500:1::53
("i.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x07fe, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0053))), // 2001:7fe::53
("j.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0503, 0x0c27, 0x0000, 0x0000, 0x0000, 0x0002, 0x0030))), // 2001:503:c27::2:30
("k.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x07fd, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001))), // 2001:7fd::1
("l.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0500, 0x009f, 0x0000, 0x0000, 0x0000, 0x0000, 0x0042))), // 2001:500:9f::42
("m.root-servers.net", IpAddr::V6(Ipv6Addr::new(0x2001, 0x0dc3, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0035))), // 2001:dc3::35
];
// pub struct NameServer2 {
// provider_name: &'static str,
// domain_name: &'static str,
// ip_addrs: &'static [std::net::IpAddr],
// udp_port: Option<u16>,
// tcp_port: Option<u16>,
// tls_port: Option<u16>,
// https_port: Option<u16>,
// // https_port: Option<u16>,
// dnscrypt_tcp_port: Option<u16>,
// dnscrypt_udp_port: Option<u16>,
// support_edns0: bool,
// support_ecs: bool,
// }
// Example:
// udp+tcp+tls+https://8.8.8.8?domain=dns.google&tcp_port=53
// udp+tcp+tls+https://8.8.4.4?domain=dns.google&tcp_port=53
// udp+tcp://1.1.1.1?domain=one.one.one.one
// udp+tcp://9.9.9.9
//
#[derive(Debug, Clone)]
pub struct NameServer {
domain: Option<String>,
protocol_set: ProtocolSet,
ip: std::net::IpAddr,
udp_port: Option<u16>,
tcp_port: Option<u16>,
tls_port: Option<u16>,
https_port: Option<u16>,
dnscrypt_udp_port: Option<u16>,
dnscrypt_tcp_port: Option<u16>,
}
impl NameServer {
pub fn new_default<A: Into<std::net::IpAddr>>(domain: Option<String>, ip: A) -> Self {
// NOTE: 默认使用 TCP ,而不是 UDP.
const DEFAULT_PROTOCOLS: [Protocol; 2] = [ Protocol::Tcp, Protocol::Udp, ];
let ip = ip.into();
NameServer {
domain,
protocol_set: ProtocolSet::new(&DEFAULT_PROTOCOLS).unwrap(),
ip,
udp_port: Some(DEFAULT_UDP_PORT),
tcp_port: Some(DEFAULT_TCP_PORT),
tls_port: None,
https_port: None,
dnscrypt_udp_port: None,
dnscrypt_tcp_port: None,
}
}
#[inline]
pub fn domain(&self) -> Option<&str> {
match self.domain {
Some(ref s) => Some(s),
None => None,
}
}
#[inline]
pub fn ip(&self) -> std::net::IpAddr {
self.ip
}
pub fn socket_addr_by(&self, protocol: Protocol) -> Option<std::net::SocketAddr> {
let port = match protocol {
Protocol::Udp => self.udp_port,
Protocol::Tcp => self.tcp_port,
Protocol::Tls => self.tls_port,
Protocol::Https => self.https_port,
Protocol::DNSCryptUdp => self.dnscrypt_udp_port,
Protocol::DNSCryptTcp => self.dnscrypt_tcp_port,
};
port.map(|port| std::net::SocketAddr::new(self.ip, port))
}
#[inline]
pub fn protocols(&self) -> ProtocolSet {
self.protocol_set
}
}
impl std::str::FromStr for NameServer {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.parse::<http::uri::Uri>() {
Ok(uri) => {
let protocols = match uri.scheme_str() {
Some(scheme) => {
let mut protocols = vec![];
for s in scheme.split('+') {
match s.to_lowercase().as_str() {
"udp" => protocols.push(Protocol::Udp),
"tcp" => protocols.push(Protocol::Tcp),
"tls" => protocols.push(Protocol::Tls),
"https" => protocols.push(Protocol::Https),
"dnscrypt-udp" => protocols.push(Protocol::DNSCryptUdp),
"dnscrypt-tcp" => protocols.push(Protocol::DNSCryptTcp),
_ => { },
}
}
protocols
},
None => {
vec![ Protocol::Tcp, Protocol::Udp, ]
},
};
let protocol_set = match ProtocolSet::new(&protocols) {
Ok(p) => p,
Err(e) => {
error!("{:?}", e);
return Err(());
},
};
let ip = match uri.host() {
Some(host) => {
match host.parse::<std::net::IpAddr>() {
Ok(ip) => ip,
Err(e) => {
let host_iter = if !host.contains(":") {
std::net::ToSocketAddrs::to_socket_addrs(&format!("{}:0", host))
} else {
std::net::ToSocketAddrs::to_socket_addrs(&host)
};
match host_iter {
Ok(mut iter) => {
match iter.next() {
Some(socket_addr) => socket_addr.ip(),
None => {
error!("No Host Ip.");
return Err(());
}
}
},
Err(e) => {
error!("No Host Ip.");
return Err(());
}
}
}
}
},
None => {
error!("No Host.");
return Err(());
}
};
let mut domain = None;
let mut tcp_port = None;
let mut udp_port = None;
let mut tls_port = None;
let mut https_port = None;
let mut dnscrypt_udp_port = None;
let mut dnscrypt_tcp_port = None;
match uri.query() {
Some(query) => {
for kv in query.split('&') {
let pair = kv.split('=').collect::<Vec<&str>>();
if pair.len() > 1 {
let key = pair[0];
let val = pair[1];
match key {
"domain" => {
if domain.is_none() {
domain = Some(val.to_string());
}
},
"tcp_port" => {
if tcp_port.is_none() {
if let Ok(port) = val.parse::<u16>() {
tcp_port = Some(port);
}
}
},
"udp_port" => {
if udp_port.is_none() {
if let Ok(port) = val.parse::<u16>() {
udp_port = Some(port);
}
}
},
"tls_port" => {
if tls_port.is_none() {
if let Ok(port) = val.parse::<u16>() {
tls_port = Some(port);
}
}
},
"https_port" => {
if https_port.is_none() {
if let Ok(port) = val.parse::<u16>() {
https_port = Some(port);
}
}
},
"dnscrypt_udp_port" => {
if dnscrypt_udp_port.is_none() {
if let Ok(port) = val.parse::<u16>() {
dnscrypt_udp_port = Some(port);
}
}
},
"dnscrypt_tcp_port" => {
if dnscrypt_tcp_port.is_none() {
if let Ok(port) = val.parse::<u16>() {
dnscrypt_tcp_port = Some(port);
}
}
},
_ => { },
}
}
}
},
None => {
}
}
for p in protocols.iter() {
match p {
Protocol::Udp => {
if udp_port.is_none() {
udp_port = Some(DEFAULT_UDP_PORT);
}
},
Protocol::Tcp => {
if tcp_port.is_none() {
tcp_port = Some(DEFAULT_TCP_PORT);
}
},
Protocol::Tls => {
if tls_port.is_none() {
tls_port = Some(DEFAULT_DOT_PORT);
}
},
Protocol::Https => {
if https_port.is_none() {
https_port = Some(DEFAULT_DOH_PORT);
}
},
Protocol::DNSCryptUdp => {
if dnscrypt_udp_port.is_none() {
dnscrypt_udp_port = Some(DEFAULT_UDP_DNSCRYPT_PORT);
}
},
Protocol::DNSCryptTcp => {
if dnscrypt_tcp_port.is_none() {
dnscrypt_tcp_port = Some(DEFAULT_TCP_DNSCRYPT_PORT);
}
},
}
}
Ok(NameServer {
domain,
protocol_set,
ip,
udp_port,
tcp_port,
tls_port,
https_port,
dnscrypt_udp_port,
dnscrypt_tcp_port,
})
},
Err(e) => {
error!("Parse NameServer URI Error: {:?}", e);
Err(())
}
}
}
}
// impl std::convert::TryFrom<http::uri::Uri> for NameServer {
// type Error = &'static str;
// fn try_from(uri: http::uri::Uri) -> Result<Self, Self::Error> {
// todo!()
// }
// }
// impl Into<http::uri::Uri> for NameServer {
// fn into(self) -> http::uri::Uri {
// todo!()
// }
// }
|
use crate::hittable::{aabb::Aabb, HitRecord, Hittable, Hittables};
use crate::material::MaterialType;
use crate::onb::Onb;
use crate::ray::{face_normal, Ray};
use crate::util::random_to_sphere;
use crate::vec::{vec3, Vec3};
use rand::rngs::SmallRng;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Sphere {
pub center: Vec3,
pub radius: f64,
pub mat: Arc<MaterialType>,
}
impl Sphere {
#[allow(dead_code)]
pub fn new(center: Vec3, radius: f64, mat: Arc<MaterialType>) -> Hittables {
Hittables::from(Sphere {
center: center,
radius: radius,
mat: mat,
})
}
}
impl Hittable for Sphere {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, _rng: &mut SmallRng) -> Option<HitRecord> {
let oc = ray.origin - self.center;
let a = ray.direction.length_squared();
let half_b = oc.dot(ray.direction);
let c = oc.length_squared() - self.radius * self.radius;
let discriminant = half_b * half_b - a * c;
if discriminant > 0.0 {
let root = f64::sqrt(discriminant);
let temp1 = (-half_b - root) / a;
if temp1 < t_max && temp1 > t_min {
let t = temp1;
let point = ray.at(temp1);
let normal = (point - self.center) / self.radius;
let (front_face, normal) = face_normal(ray, normal);
let (u, v) = get_sphere_uv(&normal);
return Some(HitRecord {
t: t,
u: u,
v: v,
point: point,
normal: normal,
front_face: front_face,
mat: self.mat.clone(),
});
}
let temp2 = (-half_b + root) / a;
if temp2 < t_max && temp2 > t_min {
let t = temp2;
let point = ray.at(temp2);
let normal = (point - self.center) / self.radius;
let (front_face, normal) = face_normal(ray, normal);
let (u, v) = get_sphere_uv(&normal);
return Some(HitRecord {
t: t,
u: u,
v: v,
point: point,
normal: normal,
front_face: front_face,
mat: self.mat.clone(),
});
}
}
return None;
}
fn bounding_box(&self, _time0: f64, _time1: f64) -> Option<Aabb> {
Some(Aabb {
minimum: self.center - vec3(self.radius, self.radius, self.radius),
maximum: self.center + vec3(self.radius, self.radius, self.radius),
})
}
fn pdf_value(&self, origin: Vec3, v: Vec3, rng: &mut SmallRng) -> f64 {
let ray = Ray {
origin: origin,
direction: v,
time: 0.0,
};
let hit = self.hit(&ray, 0.001, std::f64::INFINITY, rng);
match hit {
None => {
return 0.0;
}
Some(_) => {
let cos_theta_max = f64::sqrt(
1.0 * self.radius * self.radius / (self.center - origin).length_squared(),
);
let solid_angle = 2.0 * std::f64::consts::PI * (1.0 - cos_theta_max);
return 1.0 / solid_angle;
}
}
}
fn random(&self, origin: Vec3, rng: &mut SmallRng) -> Vec3 {
let direction = self.center - origin;
let dist_squared = direction.length_squared();
let uvw = Onb::new(&direction);
return uvw.local(&random_to_sphere(self.radius, dist_squared, rng));
}
}
#[derive(Debug, Clone)]
pub struct MovingSphere {
pub center0: Vec3,
pub center1: Vec3,
pub radius: f64,
pub time0: f64,
pub time1: f64,
pub mat: Arc<MaterialType>,
}
impl MovingSphere {
#[allow(dead_code)]
pub fn new(
center0: Vec3,
center1: Vec3,
t0: f64,
t1: f64,
radius: f64,
mat: Arc<MaterialType>,
) -> Hittables {
Hittables::from(MovingSphere {
center0: center0,
center1: center1,
time0: t0,
time1: t1,
radius: radius,
mat: mat,
})
}
pub fn center(&self, time: f64) -> Vec3 {
self.center0
+ ((time - self.time0) / (self.time1 - self.time0)) * (self.center1 - self.center0)
}
}
impl Hittable for MovingSphere {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, _rng: &mut SmallRng) -> Option<HitRecord> {
let oc = ray.origin - self.center(ray.time);
let a = ray.direction.length_squared();
let half_b = oc.dot(ray.direction);
let c = oc.length_squared() - self.radius * self.radius;
let discriminant = half_b * half_b - a * c;
if discriminant > 0.0 {
let root = f64::sqrt(discriminant);
let temp1 = (-half_b - root) / a;
if temp1 < t_max && temp1 > t_min {
let t = temp1;
let point = ray.at(temp1);
let normal = (point - self.center(ray.time)) / self.radius;
let (front_face, normal) = face_normal(ray, normal);
let (u, v) = get_sphere_uv(&normal);
return Some(HitRecord {
t: t,
u: u,
v: v,
point: point,
normal: normal,
front_face: front_face,
mat: self.mat.clone(),
});
}
let temp2 = (-half_b + root) / a;
if temp2 < t_max && temp2 > t_min {
let t = temp2;
let point = ray.at(temp2);
let normal = (point - self.center(ray.time)) / self.radius;
let (front_face, normal) = face_normal(ray, normal);
let (u, v) = get_sphere_uv(&normal);
return Some(HitRecord {
t: t,
u: u,
v: v,
point: point,
normal: normal,
front_face: front_face,
mat: self.mat.clone(),
});
}
}
return None;
}
fn bounding_box(&self, time0: f64, time1: f64) -> Option<Aabb> {
let box0 = Aabb {
minimum: self.center(time0) - vec3(self.radius, self.radius, self.radius),
maximum: self.center(time0) + vec3(self.radius, self.radius, self.radius),
};
let box1 = Aabb {
minimum: self.center(time1) - vec3(self.radius, self.radius, self.radius),
maximum: self.center(time1) + vec3(self.radius, self.radius, self.radius),
};
Some(Aabb::surrounding_box(box0, box1))
}
}
pub fn get_sphere_uv(p: &Vec3) -> (f64, f64) {
let theta = f64::acos(-p.y);
let phi = f64::atan2(-p.z, p.x) + std::f64::consts::PI;
let u = phi / (2.0 * std::f64::consts::PI);
let v = theta / std::f64::consts::PI;
(u, v)
}
|
extern crate pest;
#[macro_use]
extern crate pest_derive;
use anyhow::{Context, Result};
use pest::Parser;
use structopt::StructOpt;
#[derive(Parser)]
#[grammar = "adoc.pest"]
struct AdocParser;
#[derive(StructOpt)]
struct Cli {
#[structopt(parse(from_os_str))]
path: std::path::PathBuf,
}
fn main() -> Result<()> {
let args = Cli::from_args();
let path = args.path.clone();
let content = std::fs::read_to_string(&path)
.with_context(|| format!("could not read path: {:?}", path.display()))?;
let pairs = AdocParser::parse(Rule::adoc, &content)?;
for pair in pairs {
// A pair can be converted to an iterator of the tokens which make it up:
for inner_pair in pair.into_inner() {
match inner_pair.as_rule() {
Rule::p => println!("<p>{}</p>", inner_pair.as_str()),
_ => unreachable!()
};
}
}
Ok(())
}
|
/// EditTeamOption options for editing a team
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct EditTeamOption {
pub can_create_org_repo: Option<bool>,
pub description: Option<String>,
pub includes_all_repositories: Option<bool>,
pub name: String,
pub permission: Option<crate::edit_team_option::EditTeamOptionPermission>,
pub units: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(non_camel_case_types)]
pub enum EditTeamOptionPermission {
#[serde(rename = "read")]
Read,
#[serde(rename = "write")]
Write,
#[serde(rename = "admin")]
Admin,
}
impl Default for EditTeamOptionPermission {
fn default() -> Self {
EditTeamOptionPermission::Read
}
}
impl EditTeamOption {
/// Create a builder for this object.
#[inline]
pub fn builder() -> EditTeamOptionBuilder<crate::generics::MissingName> {
EditTeamOptionBuilder {
body: Default::default(),
_name: core::marker::PhantomData,
}
}
#[inline]
pub fn org_edit_team() -> EditTeamOptionPatchBuilder<crate::generics::MissingId, crate::generics::MissingName> {
EditTeamOptionPatchBuilder {
inner: Default::default(),
_param_id: core::marker::PhantomData,
_name: core::marker::PhantomData,
}
}
}
impl Into<EditTeamOption> for EditTeamOptionBuilder<crate::generics::NameExists> {
fn into(self) -> EditTeamOption {
self.body
}
}
impl Into<EditTeamOption> for EditTeamOptionPatchBuilder<crate::generics::IdExists, crate::generics::NameExists> {
fn into(self) -> EditTeamOption {
self.inner.body
}
}
/// Builder for [`EditTeamOption`](./struct.EditTeamOption.html) object.
#[derive(Debug, Clone)]
pub struct EditTeamOptionBuilder<Name> {
body: self::EditTeamOption,
_name: core::marker::PhantomData<Name>,
}
impl<Name> EditTeamOptionBuilder<Name> {
#[inline]
pub fn can_create_org_repo(mut self, value: impl Into<bool>) -> Self {
self.body.can_create_org_repo = Some(value.into());
self
}
#[inline]
pub fn description(mut self, value: impl Into<String>) -> Self {
self.body.description = Some(value.into());
self
}
#[inline]
pub fn includes_all_repositories(mut self, value: impl Into<bool>) -> Self {
self.body.includes_all_repositories = Some(value.into());
self
}
#[inline]
pub fn name(mut self, value: impl Into<String>) -> EditTeamOptionBuilder<crate::generics::NameExists> {
self.body.name = value.into();
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn permission(mut self, value: crate::edit_team_option::EditTeamOptionPermission) -> Self {
self.body.permission = Some(value.into());
self
}
#[inline]
pub fn units(mut self, value: impl Iterator<Item = impl Into<String>>) -> Self {
self.body.units = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
}
/// Builder created by [`EditTeamOption::org_edit_team`](./struct.EditTeamOption.html#method.org_edit_team) method for a `PATCH` operation associated with `EditTeamOption`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct EditTeamOptionPatchBuilder<Id, Name> {
inner: EditTeamOptionPatchBuilderContainer,
_param_id: core::marker::PhantomData<Id>,
_name: core::marker::PhantomData<Name>,
}
#[derive(Debug, Default, Clone)]
struct EditTeamOptionPatchBuilderContainer {
body: self::EditTeamOption,
param_id: Option<i64>,
}
impl<Id, Name> EditTeamOptionPatchBuilder<Id, Name> {
/// id of the team to edit
#[inline]
pub fn id(mut self, value: impl Into<i64>) -> EditTeamOptionPatchBuilder<crate::generics::IdExists, Name> {
self.inner.param_id = Some(value.into());
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn can_create_org_repo(mut self, value: impl Into<bool>) -> Self {
self.inner.body.can_create_org_repo = Some(value.into());
self
}
#[inline]
pub fn description(mut self, value: impl Into<String>) -> Self {
self.inner.body.description = Some(value.into());
self
}
#[inline]
pub fn includes_all_repositories(mut self, value: impl Into<bool>) -> Self {
self.inner.body.includes_all_repositories = Some(value.into());
self
}
#[inline]
pub fn name(mut self, value: impl Into<String>) -> EditTeamOptionPatchBuilder<Id, crate::generics::NameExists> {
self.inner.body.name = value.into();
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn permission(mut self, value: crate::edit_team_option::EditTeamOptionPermission) -> Self {
self.inner.body.permission = Some(value.into());
self
}
#[inline]
pub fn units(mut self, value: impl Iterator<Item = impl Into<String>>) -> Self {
self.inner.body.units = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for EditTeamOptionPatchBuilder<crate::generics::IdExists, crate::generics::NameExists> {
type Output = crate::team::Team;
const METHOD: http::Method = http::Method::PATCH;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/teams/{id}", id=self.inner.param_id.as_ref().expect("missing parameter id?")).into()
}
fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> {
use crate::client::Request;
Ok(req
.json(&self.inner.body))
}
}
|
use rusty_martian::read_input::read_input;
use rusty_martian::rover::Position;
use rusty_martian::simulation::Simulation;
fn main() {
let (grid, rovers, instructions) = read_input();
let mut simulation = Simulation::new(grid, rovers, instructions);
simulation.run();
for rover in simulation.rovers.iter() {
let Position(x, y, orientation) = rover.position;
if rover.lost {
println!("{} {} {:?} LOST", x, y, orientation);
} else {
println!("{} {} {:?}", x, y, orientation);
}
}
}
|
use http_file::*;
use http::*;
use handler_lib::*;
pub struct FileSystemHandler {
path: String,
fs: FileSystem,
}
impl FileSystemHandler {
pub fn new(path: &str) -> FileSystemHandler {
FileSystemHandler {
path: path.to_string(),
fs: FileSystem::new(path),
}
}
}
impl Handler for FileSystemHandler {
fn process(&mut self, req: Request, resp: &mut Response) {
self.fs.serve(&req.uri, resp);
}
fn duplicate(&self) -> Box<Handler> {
return Box::new(FileSystemHandler::new(&self.path));
}
}
pub struct FileHandler {
path: String,
fs: FileSystem,
}
impl FileHandler {
pub fn new(path: &str) -> FileHandler {
FileHandler {
path: path.to_string(),
fs: FileSystem::new(path),
}
}
}
impl Handler for FileHandler {
fn process(&mut self, _: Request, resp: &mut Response) {
self.fs.serve("", resp);
}
fn duplicate(&self) -> Box<Handler> {
return Box::new(FileHandler::new(&self.path));
}
}
|
/// Basic linear allocator.
pub struct IdAlloc<T> {
entries: Vec<Option<T>>,
empty_ids: Vec<usize>,
}
impl<T> IdAlloc<T> {
pub fn new() -> IdAlloc<T> {
IdAlloc {
entries: vec![],
empty_ids: vec![],
}
}
/// Get the entry with the given ID as mut.
pub fn get_mut(&mut self, id: usize) -> &mut T {
self.entries[id].as_mut().unwrap()
}
/// Get the entry with the given ID.
pub fn get(&self, id: usize) -> &T {
self.entries[id].as_ref().unwrap()
}
/// Store the given new_entry with a new ID. Returns (the stored entry, the entry's ID).
pub fn allocate(&mut self, new_entry: T) -> (&mut T, usize) {
if let Some(id) = self.empty_ids.pop() {
let entry = &mut self.entries[id];
*entry = Some(new_entry);
(entry.as_mut().unwrap(), id)
} else {
let id = self.entries.len();
self.entries.push(Some(new_entry));
(self.entries.last_mut().unwrap().as_mut().unwrap(), id)
}
}
/// Deallocate the entry with the given ID, freeing up the ID for later allocations.
pub fn deallocate(&mut self, id: usize) {
self.entries[id] = None;
self.empty_ids.push(id);
}
pub fn apply_to_all(&self, func: &mut FnMut(usize, &T)) {
for (id, ref opt_entry) in self.entries.iter().enumerate() {
if let &Some(ref entry) = *opt_entry {
func(id, entry);
}
}
}
pub fn apply_to_all_mut(&mut self, func: &mut FnMut(usize, &mut T)) {
for (id, ref mut opt_entry) in self.entries.iter_mut().enumerate() {
if let &mut Some(ref mut entry) = *opt_entry {
func(id, entry);
}
}
}
}
|
extern crate num;
use std::ops;
use std::vec;
use std::fmt;
pub trait Number<T>: Copy + num::Num + num::Bounded + num::NumCast + PartialOrd + Clone {}
impl<T> Number<T> for T where T: Copy
+ num::Num
+ num::Bounded
+ num::NumCast
+ PartialOrd
+ Clone {}
pub trait Vector<'a, T>
where &'a Self: ops::Mul<&'a Self, Output=T> + 'a,
T: Number<T>
{
fn dot(&'a self, other: &'a Self) -> T {
self*other
}
fn norm(&'a self) -> f64 {
(self.dot(self).to_f64().unwrap()).sqrt()
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Vec2<T> {
pub x: T,
pub y: T,
}
impl<T> Vec2<T>
where T: Number<T>
{
pub fn new(x: T, y: T) -> Vec2<T> {
Vec2 { x, y }
}
pub fn normalize(self) -> Vec2<f64> {
let norm = self.norm();
&self.to_f64()*(1./norm)
}
pub fn to_f64(&self) -> Vec2<f64> {
Vec2::<f64>{x: self.x.to_f64().unwrap(), y: self.y.to_f64().unwrap()}
}
}
impl<'a, T: 'a> Vector<'a, T> for Vec2<T> where T: Number<T> {}
impl<'a, 'b, T> ops::Add<&'b Vec2<T>> for Vec2<T>
where T: Number<T>
{
type Output = Vec2<T>;
fn add(self, other: &'b Vec2<T>) -> Vec2<T> {
Vec2::<T>{
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl<'a, 'b, T> ops::Sub<&'b Vec2<T>> for Vec2<T>
where T: Number<T>
{
type Output = Vec2<T>;
fn sub(self, other: &'b Vec2<T>) -> Vec2<T> {
Vec2::<T>{
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl<'a, T> ops::Mul<T> for &'a Vec2<T>
where T: Number<T>
{
type Output = Vec2<T>;
fn mul(self, scal: T) -> Vec2<T> {
Vec2::<T>{
x: self.x*scal,
y: self.y*scal,
}
}
}
impl<'a, 'b, T> ops::Mul<&'b Vec2<T>> for &'a Vec2<T>
where T: Number<T>
{
type Output = T;
fn mul(self, other: &'b Vec2<T>) -> T {
self.x*other.x + self.y*other.y
}
}
impl<T: fmt::Display> fmt::Display for Vec2<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Vec2(x: {}, y: {})", self.x, self.y)
}
}
impl<'a, T> From<&'a [T; 2]> for Vec2<T>
where T: Number<T>
{
fn from(vec: &'a [T; 2]) -> Self {
Vec2::<T>::new(vec[0].clone(), vec[1].clone())
}
}
// Vec3 impl
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Vec3<T>
{
pub x: T,
pub y: T,
pub z: T
}
impl<T> Vec3<T>
where T: Number<T>
{
pub fn new(x: T, y: T, z: T) -> Vec3<T> {
Vec3{x, y, z}
}
pub fn to_f64(&self) -> Option<Vec3<f64>> {
let x = self.x.to_f64()?;
let y = self.y.to_f64()?;
let z = self.z.to_f64()?;
Some(Vec3::<f64>{x, y, z})
}
pub fn to_i32(&self) -> Option<Vec3<i32>> {
let x = self.x.to_i32()?;
let y = self.y.to_i32()?;
let z = self.z.to_i32()?;
Some(Vec3::<i32>{x, y, z})
}
pub fn to_u32(&self) -> Option<Vec3<u32>> {
let x = self.x.to_u32()?;
let y = self.y.to_u32()?;
let z = self.z.to_u32()?;
Some(Vec3::<u32>{x, y, z})
}
pub fn normalize(self) -> Vec3<f64> {
let fself = self.to_f64().expect("Failed to convert vector to f64");
(&fself)*(1./self.norm())
}
pub fn cross(&self, other: &Vec3<T>) -> Vec3<T> {
let x = self.y*other.z - self.z*other.y;
let y = self.z*other.x - self.x*other.z;
let z = self.x*other.y - self.y*other.x;
Vec3::<T>{x, y, z}
}
}
impl<'a, T: 'a> Vector<'a, T> for Vec3<T> where T: Number<T> {}
impl<'a, 'b, T> ops::Add<&'b Vec3<T>> for &'a Vec3<T>
where T: Number<T>
{
type Output = Vec3<T>;
fn add(self, other: &'b Vec3<T>) ->Vec3<T> {
Vec3::<T>{
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z
}
}
}
impl<'a, 'b, T> ops::Sub<&'b Vec3<T>> for &'a Vec3<T>
where T: Number<T>
{
type Output = Vec3<T>;
fn sub(self, other: &'b Vec3<T>) -> Vec3<T> {
Vec3::<T>{
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z
}
}
}
impl<'a, T> ops::Mul<T> for &'a Vec3<T>
where T: Number<T>
{
type Output = Vec3<T>;
fn mul(self, scal: T) -> Vec3<T> {
Vec3::<T>{
x: self.x*scal,
y: self.y*scal,
z: self.z*scal
}
}
}
impl<'a, 'b, T> ops::Mul<&'b Vec3<T>> for &'a Vec3<T>
where T: Number<T>
{
type Output = T;
fn mul(self, other: &'b Vec3<T>) -> T {
self.x*other.x + self.y*other.y + self.z*other.z
}
}
impl<T: fmt::Display> fmt::Display for Vec3<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Vec3(x: {}, y: {}, z: {})", self.x, self.y, self.z)
}
}
impl<'a, T> From<&'a [T; 3]> for Vec3<T>
where T: Number<T>
{
fn from(vec: &'a [T; 3]) -> Self {
Vec3::<T>::new(vec[0].clone(), vec[1].clone(), vec[2].clone())
}
}
impl<T> Into<[T; 3]> for Vec3<T>
where T: Number<T>
{
fn into(self) -> [T; 3] {
let array: [T; 3] = [self.x, self.y, self.z];
array
}
}
// typedefs
pub type Vec3f = Vec3<f64>;
pub type Vec2f = Vec2<f64>;
pub type Vec2i = Vec2<i32>;
pub type Vec3i = Vec3<i32>;
#[cfg(test)]
mod test {
use super::*;
#[test]
fn from_array() {
assert_eq!(Vec3f{x: 1., y: 2., z: 3.}, Vec3f::from(&[1., 2., 3.]));
}
#[test]
fn into_array() {
let v = Vec3f::new(1., 2., 3.);
let a: [f64; 3] = v.into();
assert_eq!([1., 2., 3.], a);
}
#[test]
fn add() {
let first = Vec3f::new(1., 2., 3.);
let second = Vec3f::new(2., 3., 4.);
assert_eq!(&first + &second, Vec3f::new(3., 5., 7.));
}
#[test]
fn sub() {
let first = Vec3f::new(1., 2., 3.);
let second = Vec3f::new(2., 3., 4.);
assert_eq!(&first - &second, Vec3f::new(-1., -1., -1.));
}
#[test]
fn norm() {
assert_eq!(Vec3f::new(1., 1., 1.).norm(), (3. as f64).sqrt());
}
#[test]
fn normalize() {
assert_eq!(Vec3f::new(1., 1., 1.).normalize().norm(), 1 as f64);
}
#[test]
fn dot() {
let first = Vec2f::new(1., -1.);
let second = Vec2f::new(1., 1.);
assert_eq!(&first*&second, 0 as f64);
assert_eq!(first.dot(&second), 0 as f64);
}
#[test]
fn cross() {
let first = Vec3f::new(1.0, 2.0, 3.0);
let second = Vec3f::new(2.0, 3.0, 4.0);
assert_eq!(first.cross(&second).dot(&first), 0 as f64);
assert_eq!(first.cross(&second).dot(&second), 0 as f64);
assert_eq!(second.cross(&first), (&first.cross(&second))*(-1 as f64));
}
}
|
mod domain;
mod time;
pub use self::domain::run_domain_cli;
pub use self::time::run_time_cli;
|
#![allow(dead_code)]
use render::object::Object;
use nalgebra::geometry::{Quaternion, Point3, UnitQuaternion};
use nalgebra::Vector3;
pub struct GameObject{
// Id of the game object
pub id: u32,
// Name of the Game Object
pub name: String,
// Mesh
pub render_object: Option<Object>,
// Global position
pub position: Point3<f32>,
pub rotation: UnitQuaternion<f32>,
// Parent ID
pub childs: Vec<GameObject>,
pub tags: Vec<String>,
pub area: (i32, i32)
}
impl GameObject{
// Create new game object
pub fn new(id: u32, name: String) -> GameObject{
GameObject{
id: id,
name: name,
render_object: None,
position: Point3::new(0.0,0.0,0.0),
rotation: UnitQuaternion::from_quaternion(Quaternion::new(0.0,0.0,1.0,0.0)),
childs: vec![],
tags: vec![],
area: (0, 0)
}
}
pub fn add_child(&mut self, child: GameObject){
self.childs.push(child);
}
//Get go childs
pub fn get_childs(&mut self) -> Vec<&mut GameObject>{
let mut childs = vec![];
for x in &mut self.childs{
for x in x.get_childs(){
childs.push(x);
}
}
childs
}
// Set render object (render::object::Object)
pub fn set_render_object(&mut self, object: Object){
self.render_object = Some(object);
}
// Set global position
pub fn set_position(&mut self, position: Point3<f32>){
self.position = position;
}
pub fn set_rotation(&mut self, quat: Quaternion<f32>){
self.rotation = UnitQuaternion::from_quaternion(quat);
}
pub fn forward(&mut self) -> Vector3<f32>{
self.direction(Vector3::new(0.0, 0.0, -1.0))
}
pub fn right(&mut self) -> Vector3<f32>{
self.direction(Vector3::new(-1.0, 0.0, 0.0))
}
pub fn up(&mut self) -> Vector3<f32>{
self.direction(Vector3::new(0.0, 1.0, 0.0))
}
pub fn set_area(&mut self, area: (i32, i32)){
self.area = area;
}
pub fn direction(&mut self, vec: Vector3<f32>) -> Vector3<f32>{
use alga::linear::Transformation;
let mut point = vec;
let matrix = self.rotation.to_homogeneous();
point = matrix.transform_vector(&point);
point
}
pub fn update(&mut self){
// Update positions and other stuff, WIP
/*
match parent{
Some(ref x) => {
let delta_rot = x.local_rotation * self.local_rotation.inverse();
//self.global_position = x.global_position * self.local_position.coords;
}
None => {
//self.global_position = self.local_position
}
}*/
match self.render_object{
Some(ref mut x) => {
//x.position = x.position + self.global_position.coords;
x.calculate_transform(self.position, *self.rotation.quaternion())
}
None => {}
}
for x in &mut self.childs{
//let rotation = (self.rotation * x.rotation);
x.update();
}
}
}
pub struct GameObjectBuilder{
// Id of the game object
pub id: u32,
// Name of the Game Object
pub name: String,
// Mesh
pub render_object: Option<Object>,
// Global position
pub position: Point3<f32>,
// Rotation of the object releative to the parent's
pub rotation: UnitQuaternion<f32>,
// Parent ID
pub childs: Vec<GameObject>,
pub tags: Vec<String>,
pub area: (i32, i32)
}
impl GameObjectBuilder{
pub fn new() -> GameObjectBuilder{
GameObjectBuilder{
id: 0,
name: String::new(),
render_object: None,
position: Point3::new(0.0, 0.0, 0.0),
rotation: UnitQuaternion::from_quaternion(Quaternion::new(0.0,0.0,1.0,0.0)),
childs: vec![],
tags: vec![],
area: (0, 0)
}
}
pub fn with_id(self, id: u32) -> Self{
GameObjectBuilder{
id,
..self
}
}
pub fn with_name(self, name: String) -> Self{
GameObjectBuilder{
name,
..self
}
}
pub fn with_render_object(self, render_object: Object) -> Self{
GameObjectBuilder{
render_object: Some(render_object),
..self
}
}
pub fn with_position(self, position: Point3<f32>) -> Self{
GameObjectBuilder{
position,
..self
}
}
pub fn with_rotation(self, rotation: UnitQuaternion<f32>) -> Self{
GameObjectBuilder{
rotation,
..self
}
}
pub fn with_childs(self, childs: Vec<GameObject>) -> Self{
GameObjectBuilder{
childs,
..self
}
}
pub fn with_tags(self, tags: Vec<String>) -> Self{
GameObjectBuilder{
tags,
..self
}
}
pub fn with_area(self, area: (i32, i32)) -> Self{
GameObjectBuilder{
area,
..self
}
}
pub fn build(self) -> GameObject{
GameObject{
id: self.id,
name: self.name,
render_object: self.render_object,
position: self.position,
rotation: self.rotation,
childs: self.childs,
tags: self.tags,
area: self.area
}
}
}
|
use crate::blob::blob::responses::PutBlockListResponse;
use crate::blob::prelude::*;
use azure_core::headers::{add_optional_header, add_optional_header_ref};
use azure_core::prelude::*;
use bytes::Bytes;
#[derive(Debug, Clone)]
pub struct PutBlockListBuilder<'a> {
blob_client: &'a BlobClient,
block_list: &'a BlockList,
content_type: Option<ContentType<'a>>,
content_encoding: Option<ContentEncoding<'a>>,
content_language: Option<ContentLanguage<'a>>,
content_disposition: Option<ContentDisposition<'a>>,
content_md5: Option<BlobContentMD5>,
metadata: Option<&'a Metadata>,
access_tier: Option<AccessTier>,
// TODO: Support tags
lease_id: Option<&'a LeaseId>,
client_request_id: Option<ClientRequestId<'a>>,
timeout: Option<Timeout>,
}
impl<'a> PutBlockListBuilder<'a> {
pub(crate) fn new(blob_client: &'a BlobClient, block_list: &'a BlockList) -> Self {
Self {
blob_client,
block_list,
content_type: None,
content_encoding: None,
content_language: None,
content_disposition: None,
content_md5: None,
metadata: None,
access_tier: None,
lease_id: None,
client_request_id: None,
timeout: None,
}
}
setters! {
content_type: ContentType<'a> => Some(content_type),
content_encoding: ContentEncoding<'a> => Some(content_encoding),
content_language: ContentLanguage<'a> => Some(content_language),
content_disposition: ContentDisposition<'a> => Some(content_disposition),
content_md5: BlobContentMD5 => Some(content_md5),
metadata: &'a Metadata => Some(metadata),
access_tier: AccessTier => Some(access_tier),
lease_id: &'a LeaseId => Some(lease_id),
client_request_id: ClientRequestId<'a> => Some(client_request_id),
timeout: Timeout => Some(timeout),
}
pub async fn execute(
&self,
) -> Result<PutBlockListResponse, Box<dyn std::error::Error + Send + Sync>> {
let mut url = self.blob_client.url_with_segments(None)?;
url.query_pairs_mut().append_pair("comp", "blocklist");
self.timeout.append_to_url_query(&mut url);
trace!("url == {:?}", url);
let body = self.block_list.to_xml();
let body_bytes = Bytes::from(body);
// calculate the xml MD5. This can be made optional
// if needed, but i think it's best to calculate it.
let md5 = {
let hash = md5::compute(body_bytes.clone());
debug!("md5 hash: {:02X}", hash);
base64::encode(hash.0)
};
let (request, _url) = self.blob_client.prepare_request(
url.as_str(),
&http::Method::PUT,
&|mut request| {
request = request.header("Content-MD5", &md5);
request = add_optional_header(&self.content_type, request);
request = add_optional_header(&self.content_encoding, request);
request = add_optional_header(&self.content_language, request);
request = add_optional_header(&self.content_disposition, request);
request = add_optional_header(&self.content_md5, request);
request = add_optional_header(&self.metadata, request);
request = add_optional_header(&self.access_tier, request);
request = add_optional_header_ref(&self.lease_id, request);
request = add_optional_header(&self.client_request_id, request);
request
},
Some(body_bytes),
)?;
let response = self
.blob_client
.http_client()
.execute_request_check_status(request, http::StatusCode::CREATED)
.await?;
debug!("response.headers() == {:#?}", response.headers());
Ok(PutBlockListResponse::from_headers(response.headers())?)
}
}
|
use chrono::prelude::*;
use chrono_tz::Tz;
use crate::{
binary::{Encoder, ReadEx},
errors::Result,
types::{
SqlType, DateTimeType, Value, ValueRef,
column::{
column_data::{BoxColumnData, ColumnData}, list::List,
}
},
};
pub struct DateTime64ColumnData {
data: List<i64>,
params: (u32, Tz),
}
impl DateTime64ColumnData {
pub(crate) fn load<R: ReadEx>(
reader: &mut R,
size: usize,
precision: u32,
tz: Tz,
) -> Result<DateTime64ColumnData> {
let mut data = List::with_capacity(size);
unsafe {
data.set_len(size);
}
reader.read_bytes(data.as_mut())?;
Ok(DateTime64ColumnData {
data,
params: (precision, tz),
})
}
pub(crate) fn with_capacity(capacity: usize, precision: u32, timezone: Tz) -> Self {
DateTime64ColumnData {
data: List::with_capacity(capacity),
params: (precision, timezone),
}
}
}
impl ColumnData for DateTime64ColumnData {
fn sql_type(&self) -> SqlType {
let (precision, tz) = self.params;
SqlType::DateTime(DateTimeType::DateTime64(precision, tz))
}
fn save(&self, _encoder: &mut Encoder, _start: usize, _end: usize) {
unimplemented!()
}
fn len(&self) -> usize {
self.data.len()
}
fn push(&mut self, value: Value) {
let (precision, tz) = &self.params;
let time = DateTime::<Tz>::from(value);
let stamp = from_datetime(time.with_timezone(tz), *precision);
self.data.push(stamp)
}
fn at(&self, index: usize) -> ValueRef {
let value = self.data.at(index);
ValueRef::DateTime64(value, &self.params)
}
fn clone_instance(&self) -> BoxColumnData {
Box::new(Self {
data: self.data.clone(),
params: self.params,
})
}
unsafe fn get_internal(&self, pointers: &[*mut *const u8], level: u8, _props: u32) -> Result<()> {
assert_eq!(level, 0);
let (precision, tz) = &self.params;
*pointers[0] = self.data.as_ptr() as *const u8;
*pointers[1] = tz as *const Tz as *const u8;
*(pointers[2] as *mut usize) = self.len();
*(pointers[3] as *mut Option<u32>) = Some(*precision);
Ok(())
}
}
pub(crate) fn from_datetime<T: chrono::offset::TimeZone>(time: DateTime<T>, precision: u32) -> i64 {
let base10: i64 = 10;
let timestamp = time.timestamp_nanos();
timestamp / base10.pow(9 - precision)
}
#[inline(always)]
pub(crate) fn to_datetime(value: i64, precision: u32, tz: Tz) -> DateTime<Tz> {
let base10: i64 = 10;
let nano = if precision < 19 {
value * base10.pow(9 - precision)
} else {
0_i64
};
let sec = nano / 1_000_000_000;
let nsec = nano - sec * 1_000_000_000;
tz.timestamp(sec, nsec as u32)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_to_datetime() {
let expected = DateTime::parse_from_rfc3339("2019-01-01T00:00:00-00:00").unwrap();
let actual = to_datetime(1_546_300_800_000, 3, Tz::UTC);
assert_eq!(actual, expected)
}
#[test]
fn test_from_datetime() {
let origin = DateTime::parse_from_rfc3339("2019-01-01T00:00:00-00:00").unwrap();
let actual = from_datetime(origin, 3);
assert_eq!(actual, 1_546_300_800_000)
}
} |
use graphql_client::GraphQLQuery;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "src/infra/persistent/counter_adapter/schemas/schema.graphql",
query_path = "src/infra/persistent/counter_adapter/schemas/get_counter.graphql",
response_derives = "Debug,Serialize,Deserialize"
)]
pub struct GetCounter;
|
use specs::Join;
pub struct DepthBallSystem;
impl<'a> ::specs::System<'a> for DepthBallSystem {
type SystemData = (
::specs::ReadStorage<'a, ::component::Contactor>,
::specs::ReadStorage<'a, ::component::Player>,
::specs::ReadStorage<'a, ::component::DepthBall>,
::specs::WriteStorage<'a, ::component::Life>,
::specs::Fetch<'a, ::resource::Audio>,
::specs::FetchMut<'a, ::resource::DepthCoef>,
);
fn run(&mut self, (contactors, players, depth_balls, mut lifes, audio, mut depth_coef): Self::SystemData) {
for (_, life, contactor) in (&depth_balls, &mut lifes, &contactors).join() {
if contactor.contacts.is_empty() {
continue;
}
life.kill();
let mut attack = false;
if contactor.contacts.iter().any(|&(e, _)| players.get(e).is_some()) {
depth_coef.0 /= ::CONFIG.depth_coef_divider;
attack = true;
audio.play_unspatial(::audio::Sound::DepthBallAttack);
}
if !attack {
audio.play(::audio::Sound::DepthBallBirthDeath, contactor.contacts.first().unwrap().1.world1.coords.into());
}
}
}
}
|
use crate::{multi_window::NewWindowRequest, tracked_window::{DisplayCreationError, TrackedWindow, TrackedWindowContainer, TrackedWindowControl}, windows::popup_window::PopupWindow};
use egui_glow::EguiGlow;
use glutin::{PossiblyCurrent, event_loop::ControlFlow};
use crate::MultiWindow;
use crate::windows::MyWindows;
pub struct RootWindow {
pub button_press_count: u32,
pub num_popups_created: u32,
}
impl RootWindow {
pub fn new() -> NewWindowRequest {
NewWindowRequest {
window_state: RootWindow {
button_press_count: 0,
num_popups_created: 0,
}.into(),
builder: glutin::window::WindowBuilder::new()
.with_resizable(true)
.with_inner_size(glutin::dpi::LogicalSize {
width: 800.0,
height: 600.0,
})
.with_title("egui-multiwin root window")
}
}
}
impl TrackedWindow for RootWindow {
fn handle_event(&mut self, event: &glutin::event::Event<()>, other_windows: Vec<&mut MyWindows>, egui: &mut EguiGlow, gl_window: &mut glutin::WindowedContext<PossiblyCurrent>, gl: &mut glow::Context) -> TrackedWindowControl {
// Child window's requested control flow.
let mut control_flow = ControlFlow::Wait; // Unless this changes, we're fine waiting until the next event comes in.
let mut windows_to_create = vec![];
let mut redraw = || {
egui.begin_frame(gl_window.window());
let mut quit = false;
egui::SidePanel::left("my_side_panel").show(egui.ctx(), |ui| {
ui.heading("Hello World!");
if ui.button("New popup").clicked() {
windows_to_create.push(PopupWindow::new(format!("popup window #{}", self.num_popups_created)));
self.num_popups_created += 1;
}
if ui.button("Quit").clicked() {
quit = true;
}
});
egui::CentralPanel::default().show(egui.ctx(), |ui| {
ui.heading(format!("number {}", self.button_press_count));
for window in other_windows {
match window {
MyWindows::Popup(popup_window) => {
ui.add(egui::TextEdit::singleline(&mut popup_window.input));
},
_ => ()
}
}
});
let (needs_repaint, shapes) = egui.end_frame(gl_window.window());
if quit {
control_flow = glutin::event_loop::ControlFlow::Exit;
} else if needs_repaint {
gl_window.window().request_redraw();
control_flow = glutin::event_loop::ControlFlow::Poll;
} else {
control_flow = glutin::event_loop::ControlFlow::Wait;
};
{
let color = egui::Rgba::from_rgb(0.1, 0.3, 0.2);
unsafe {
use glow::HasContext as _;
gl.clear_color(color[0], color[1], color[2], color[3]);
gl.clear(glow::COLOR_BUFFER_BIT);
}
// draw things behind egui here
egui.paint(gl_window, gl, shapes);
// draw things on top of egui here
gl_window.swap_buffers().unwrap();
}
};
match event {
// Platform-dependent event handlers to workaround a winit bug
// See: https://github.com/rust-windowing/winit/issues/987
// See: https://github.com/rust-windowing/winit/issues/1619
glutin::event::Event::RedrawEventsCleared if cfg!(windows) => redraw(),
glutin::event::Event::RedrawRequested(_) if !cfg!(windows) => redraw(),
glutin::event::Event::WindowEvent { event, .. } => {
if egui.is_quit_event(event) {
control_flow = glutin::event_loop::ControlFlow::Exit;
}
if let glutin::event::WindowEvent::Resized(physical_size) = event {
gl_window.resize(*physical_size);
}
egui.on_event(event);
gl_window.window().request_redraw(); // TODO: ask egui if the events warrants a repaint instead
}
glutin::event::Event::LoopDestroyed => {
egui.destroy(gl);
}
_ => (),
}
TrackedWindowControl {
requested_control_flow: control_flow,
windows_to_create
}
}
}
|
// Copyright 2019 Parity Technologies
//
// 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.
//! [Compact encoding](https://docs.substrate.io/v3/advanced/scale-codec/#compactgeneral-integers)
use arrayvec::ArrayVec;
use crate::alloc::vec::Vec;
use crate::codec::{Encode, Decode, Input, Output, EncodeAsRef};
use crate::encode_like::EncodeLike;
use crate::Error;
#[cfg(feature = "fuzz")]
use arbitrary::Arbitrary;
struct ArrayVecWrapper<const N: usize>(ArrayVec<u8, N>);
impl<const N: usize> Output for ArrayVecWrapper<N> {
fn write(&mut self, bytes: &[u8]) {
let old_len = self.0.len();
let new_len = old_len + bytes.len();
assert!(new_len <= self.0.capacity());
unsafe {
self.0.set_len(new_len);
}
self.0[old_len..new_len].copy_from_slice(bytes);
}
fn push_byte(&mut self, byte: u8) {
self.0.push(byte);
}
}
/// Prefix another input with a byte.
struct PrefixInput<'a, T> {
prefix: Option<u8>,
input: &'a mut T,
}
impl<'a, T: 'a + Input> Input for PrefixInput<'a, T> {
fn remaining_len(&mut self) -> Result<Option<usize>, Error> {
let len = if let Some(len) = self.input.remaining_len()? {
Some(len.saturating_add(self.prefix.iter().count()))
} else {
None
};
Ok(len)
}
fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
match self.prefix.take() {
Some(v) if !buffer.is_empty() => {
buffer[0] = v;
self.input.read(&mut buffer[1..])
}
_ => self.input.read(buffer)
}
}
}
/// Something that can return the compact encoded length for a given value.
pub trait CompactLen<T> {
/// Returns the compact encoded length for the given value.
fn compact_len(val: &T) -> usize;
}
/// Compact-encoded variant of T. This is more space-efficient but less compute-efficient.
#[derive(Eq, PartialEq, Clone, Copy, Ord, PartialOrd)]
#[cfg_attr(feature = "fuzz", derive(Arbitrary))]
pub struct Compact<T>(pub T);
impl<T> From<T> for Compact<T> {
fn from(x: T) -> Compact<T> { Compact(x) }
}
impl<'a, T: Copy> From<&'a T> for Compact<T> {
fn from(x: &'a T) -> Compact<T> { Compact(*x) }
}
/// Allow foreign structs to be wrap in Compact
pub trait CompactAs: From<Compact<Self>> {
/// A compact-encodable type that should be used as the encoding.
type As;
/// Returns the compact-encodable type.
fn encode_as(&self) -> &Self::As;
/// Decode `Self` from the compact-decoded type.
fn decode_from(_: Self::As) -> Result<Self, Error>;
}
impl<T> EncodeLike for Compact<T>
where
for<'a> CompactRef<'a, T>: Encode,
{}
impl<T> Encode for Compact<T>
where
for<'a> CompactRef<'a, T>: Encode,
{
fn size_hint(&self) -> usize {
CompactRef(&self.0).size_hint()
}
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
CompactRef(&self.0).encode_to(dest)
}
fn encode(&self) -> Vec<u8> {
CompactRef(&self.0).encode()
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
CompactRef(&self.0).using_encoded(f)
}
}
impl<'a, T> EncodeLike for CompactRef<'a, T>
where
T: CompactAs,
for<'b> CompactRef<'b, T::As>: Encode,
{}
impl<'a, T> Encode for CompactRef<'a, T>
where
T: CompactAs,
for<'b> CompactRef<'b, T::As>: Encode,
{
fn size_hint(&self) -> usize {
CompactRef(self.0.encode_as()).size_hint()
}
fn encode_to<Out: Output + ?Sized>(&self, dest: &mut Out) {
CompactRef(self.0.encode_as()).encode_to(dest)
}
fn encode(&self) -> Vec<u8> {
CompactRef(self.0.encode_as()).encode()
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
CompactRef(self.0.encode_as()).using_encoded(f)
}
}
impl<T> Decode for Compact<T>
where
T: CompactAs,
Compact<T::As>: Decode,
{
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let as_ = Compact::<T::As>::decode(input)?;
Ok(Compact(<T as CompactAs>::decode_from(as_.0)?))
}
}
macro_rules! impl_from_compact {
( $( $ty:ty ),* ) => {
$(
impl From<Compact<$ty>> for $ty {
fn from(x: Compact<$ty>) -> $ty { x.0 }
}
)*
}
}
impl_from_compact! { (), u8, u16, u32, u64, u128 }
/// Compact-encoded variant of &'a T. This is more space-efficient but less compute-efficient.
#[derive(Eq, PartialEq, Clone, Copy)]
pub struct CompactRef<'a, T>(pub &'a T);
impl<'a, T> From<&'a T> for CompactRef<'a, T> {
fn from(x: &'a T) -> Self { CompactRef(x) }
}
impl<T> core::fmt::Debug for Compact<T> where T: core::fmt::Debug {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.0.fmt(f)
}
}
#[cfg(feature = "serde")]
impl<T> serde::Serialize for Compact<T> where T: serde::Serialize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
T::serialize(&self.0, serializer)
}
}
#[cfg(feature = "serde")]
impl<'de, T> serde::Deserialize<'de> for Compact<T> where T: serde::Deserialize<'de> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
T::deserialize(deserializer).map(Compact)
}
}
/// Trait that tells you if a given type can be encoded/decoded in a compact way.
pub trait HasCompact: Sized {
/// The compact type; this can be
type Type: for<'a> EncodeAsRef<'a, Self> + Decode + From<Self> + Into<Self>;
}
impl<'a, T: 'a> EncodeAsRef<'a, T> for Compact<T> where CompactRef<'a, T>: Encode + From<&'a T> {
type RefType = CompactRef<'a, T>;
}
impl<T: 'static> HasCompact for T where
Compact<T>: for<'a> EncodeAsRef<'a, T> + Decode + From<Self> + Into<Self>
{
type Type = Compact<T>;
}
impl<'a> Encode for CompactRef<'a, ()> {
fn encode_to<W: Output + ?Sized>(&self, _dest: &mut W) {
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&[])
}
fn encode(&self) -> Vec<u8> {
Vec::new()
}
}
impl<'a> Encode for CompactRef<'a, u8> {
fn size_hint(&self) -> usize {
Compact::compact_len(self.0)
}
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
match self.0 {
0..=0b0011_1111 => dest.push_byte(self.0 << 2),
_ => ((u16::from(*self.0) << 2) | 0b01).encode_to(dest),
}
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
let mut r = ArrayVecWrapper(ArrayVec::<u8, 2>::new());
self.encode_to(&mut r);
f(&r.0)
}
}
impl CompactLen<u8> for Compact<u8> {
fn compact_len(val: &u8) -> usize {
match val {
0..=0b0011_1111 => 1,
_ => 2,
}
}
}
impl<'a> Encode for CompactRef<'a, u16> {
fn size_hint(&self) -> usize {
Compact::compact_len(self.0)
}
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
match self.0 {
0..=0b0011_1111 => dest.push_byte((*self.0 as u8) << 2),
0..=0b0011_1111_1111_1111 => ((*self.0 << 2) | 0b01).encode_to(dest),
_ => ((u32::from(*self.0) << 2) | 0b10).encode_to(dest),
}
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
let mut r = ArrayVecWrapper(ArrayVec::<u8, 4>::new());
self.encode_to(&mut r);
f(&r.0)
}
}
impl CompactLen<u16> for Compact<u16> {
fn compact_len(val: &u16) -> usize {
match val {
0..=0b0011_1111 => 1,
0..=0b0011_1111_1111_1111 => 2,
_ => 4,
}
}
}
impl<'a> Encode for CompactRef<'a, u32> {
fn size_hint(&self) -> usize {
Compact::compact_len(self.0)
}
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
match self.0 {
0..=0b0011_1111 => dest.push_byte((*self.0 as u8) << 2),
0..=0b0011_1111_1111_1111 => (((*self.0 as u16) << 2) | 0b01).encode_to(dest),
0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => ((*self.0 << 2) | 0b10).encode_to(dest),
_ => {
dest.push_byte(0b11);
self.0.encode_to(dest);
}
}
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
let mut r = ArrayVecWrapper(ArrayVec::<u8, 5>::new());
self.encode_to(&mut r);
f(&r.0)
}
}
impl CompactLen<u32> for Compact<u32> {
fn compact_len(val: &u32) -> usize {
match val {
0..=0b0011_1111 => 1,
0..=0b0011_1111_1111_1111 => 2,
0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => 4,
_ => 5,
}
}
}
impl<'a> Encode for CompactRef<'a, u64> {
fn size_hint(&self) -> usize {
Compact::compact_len(self.0)
}
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
match self.0 {
0..=0b0011_1111 => dest.push_byte((*self.0 as u8) << 2),
0..=0b0011_1111_1111_1111 => (((*self.0 as u16) << 2) | 0b01).encode_to(dest),
0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => (((*self.0 as u32) << 2) | 0b10).encode_to(dest),
_ => {
let bytes_needed = 8 - self.0.leading_zeros() / 8;
assert!(bytes_needed >= 4, "Previous match arm matches anyting less than 2^30; qed");
dest.push_byte(0b11 + ((bytes_needed - 4) << 2) as u8);
let mut v = *self.0;
for _ in 0..bytes_needed {
dest.push_byte(v as u8);
v >>= 8;
}
assert_eq!(v, 0, "shifted sufficient bits right to lead only leading zeros; qed")
}
}
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
let mut r = ArrayVecWrapper(ArrayVec::<u8, 9>::new());
self.encode_to(&mut r);
f(&r.0)
}
}
impl CompactLen<u64> for Compact<u64> {
fn compact_len(val: &u64) -> usize {
match val {
0..=0b0011_1111 => 1,
0..=0b0011_1111_1111_1111 => 2,
0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => 4,
_ => {
(8 - val.leading_zeros() / 8) as usize + 1
},
}
}
}
impl<'a> Encode for CompactRef<'a, u128> {
fn size_hint(&self) -> usize {
Compact::compact_len(self.0)
}
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
match self.0 {
0..=0b0011_1111 => dest.push_byte((*self.0 as u8) << 2),
0..=0b0011_1111_1111_1111 => (((*self.0 as u16) << 2) | 0b01).encode_to(dest),
0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => (((*self.0 as u32) << 2) | 0b10).encode_to(dest),
_ => {
let bytes_needed = 16 - self.0.leading_zeros() / 8;
assert!(bytes_needed >= 4, "Previous match arm matches anyting less than 2^30; qed");
dest.push_byte(0b11 + ((bytes_needed - 4) << 2) as u8);
let mut v = *self.0;
for _ in 0..bytes_needed {
dest.push_byte(v as u8);
v >>= 8;
}
assert_eq!(v, 0, "shifted sufficient bits right to lead only leading zeros; qed")
}
}
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
let mut r = ArrayVecWrapper(ArrayVec::<u8, 17>::new());
self.encode_to(&mut r);
f(&r.0)
}
}
impl CompactLen<u128> for Compact<u128> {
fn compact_len(val: &u128) -> usize {
match val {
0..=0b0011_1111 => 1,
0..=0b0011_1111_1111_1111 => 2,
0..=0b0011_1111_1111_1111_1111_1111_1111_1111 => 4,
_ => {
(16 - val.leading_zeros() / 8) as usize + 1
},
}
}
}
impl Decode for Compact<()> {
fn decode<I: Input>(_input: &mut I) -> Result<Self, Error> {
Ok(Compact(()))
}
}
const U8_OUT_OF_RANGE: &str = "out of range decoding Compact<u8>";
const U16_OUT_OF_RANGE: &str = "out of range decoding Compact<u16>";
const U32_OUT_OF_RANGE: &str = "out of range decoding Compact<u32>";
const U64_OUT_OF_RANGE: &str = "out of range decoding Compact<u64>";
const U128_OUT_OF_RANGE: &str = "out of range decoding Compact<u128>";
impl Decode for Compact<u8> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let prefix = input.read_byte()?;
Ok(Compact(match prefix % 4 {
0 => prefix >> 2,
1 => {
let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111 && x <= 255 {
x as u8
} else {
return Err(U8_OUT_OF_RANGE.into());
}
},
_ => return Err("unexpected prefix decoding Compact<u8>".into()),
}))
}
}
impl Decode for Compact<u16> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let prefix = input.read_byte()?;
Ok(Compact(match prefix % 4 {
0 => u16::from(prefix) >> 2,
1 => {
let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111 && x <= 0b0011_1111_1111_1111 {
x
} else {
return Err(U16_OUT_OF_RANGE.into());
}
},
2 => {
let x = u32::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111_1111_1111 && x < 65536 {
x as u16
} else {
return Err(U16_OUT_OF_RANGE.into());
}
},
_ => return Err("unexpected prefix decoding Compact<u16>".into()),
}))
}
}
impl Decode for Compact<u32> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let prefix = input.read_byte()?;
Ok(Compact(match prefix % 4 {
0 => u32::from(prefix) >> 2,
1 => {
let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111 && x <= 0b0011_1111_1111_1111 {
u32::from(x)
} else {
return Err(U32_OUT_OF_RANGE.into());
}
},
2 => {
let x = u32::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111_1111_1111 && x <= u32::MAX >> 2 {
x
} else {
return Err(U32_OUT_OF_RANGE.into());
}
},
3 => {
if prefix >> 2 == 0 {
// just 4 bytes. ok.
let x = u32::decode(input)?;
if x > u32::MAX >> 2 {
x
} else {
return Err(U32_OUT_OF_RANGE.into());
}
} else {
// Out of range for a 32-bit quantity.
return Err(U32_OUT_OF_RANGE.into());
}
},
_ => unreachable!(),
}))
}
}
impl Decode for Compact<u64> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let prefix = input.read_byte()?;
Ok(Compact(match prefix % 4 {
0 => u64::from(prefix) >> 2,
1 => {
let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111 && x <= 0b0011_1111_1111_1111 {
u64::from(x)
} else {
return Err(U64_OUT_OF_RANGE.into());
}
},
2 => {
let x = u32::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111_1111_1111 && x <= u32::MAX >> 2 {
u64::from(x)
} else {
return Err(U64_OUT_OF_RANGE.into());
}
},
3 => match (prefix >> 2) + 4 {
4 => {
let x = u32::decode(input)?;
if x > u32::MAX >> 2 {
u64::from(x)
} else {
return Err(U64_OUT_OF_RANGE.into());
}
},
8 => {
let x = u64::decode(input)?;
if x > u64::MAX >> 8 {
x
} else {
return Err(U64_OUT_OF_RANGE.into());
}
},
x if x > 8 => return Err("unexpected prefix decoding Compact<u64>".into()),
bytes_needed => {
let mut res = 0;
for i in 0..bytes_needed {
res |= u64::from(input.read_byte()?) << (i * 8);
}
if res > u64::MAX >> ((8 - bytes_needed + 1) * 8) {
res
} else {
return Err(U64_OUT_OF_RANGE.into());
}
},
},
_ => unreachable!(),
}))
}
}
impl Decode for Compact<u128> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let prefix = input.read_byte()?;
Ok(Compact(match prefix % 4 {
0 => u128::from(prefix) >> 2,
1 => {
let x = u16::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111 && x <= 0b0011_1111_1111_1111 {
u128::from(x)
} else {
return Err(U128_OUT_OF_RANGE.into());
}
},
2 => {
let x = u32::decode(&mut PrefixInput{prefix: Some(prefix), input})? >> 2;
if x > 0b0011_1111_1111_1111 && x <= u32::MAX >> 2 {
u128::from(x)
} else {
return Err(U128_OUT_OF_RANGE.into());
}
},
3 => match (prefix >> 2) + 4 {
4 => {
let x = u32::decode(input)?;
if x > u32::MAX >> 2 {
u128::from(x)
} else {
return Err(U128_OUT_OF_RANGE.into());
}
},
8 => {
let x = u64::decode(input)?;
if x > u64::MAX >> 8 {
u128::from(x)
} else {
return Err(U128_OUT_OF_RANGE.into());
}
},
16 => {
let x = u128::decode(input)?;
if x > u128::MAX >> 8 {
x
} else {
return Err(U128_OUT_OF_RANGE.into());
}
},
x if x > 16 => return Err("unexpected prefix decoding Compact<u128>".into()),
bytes_needed => {
let mut res = 0;
for i in 0..bytes_needed {
res |= u128::from(input.read_byte()?) << (i * 8);
}
if res > u128::MAX >> ((16 - bytes_needed + 1) * 8) {
res
} else {
return Err(U128_OUT_OF_RANGE.into());
}
},
},
_ => unreachable!(),
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compact_128_encoding_works() {
let tests = [
(0u128, 1usize), (63, 1), (64, 2), (16383, 2),
(16384, 4), (1073741823, 4),
(1073741824, 5), ((1 << 32) - 1, 5),
(1 << 32, 6), (1 << 40, 7), (1 << 48, 8), ((1 << 56) - 1, 8), (1 << 56, 9), ((1 << 64) - 1, 9),
(1 << 64, 10), (1 << 72, 11), (1 << 80, 12), (1 << 88, 13), (1 << 96, 14), (1 << 104, 15),
(1 << 112, 16), ((1 << 120) - 1, 16), (1 << 120, 17), (u128::MAX, 17)
];
for &(n, l) in &tests {
let encoded = Compact(n as u128).encode();
assert_eq!(encoded.len(), l);
assert_eq!(Compact::compact_len(&n), l);
assert_eq!(<Compact<u128>>::decode(&mut &encoded[..]).unwrap().0, n);
}
}
#[test]
fn compact_64_encoding_works() {
let tests = [
(0u64, 1usize), (63, 1), (64, 2), (16383, 2),
(16384, 4), (1073741823, 4),
(1073741824, 5), ((1 << 32) - 1, 5),
(1 << 32, 6), (1 << 40, 7), (1 << 48, 8), ((1 << 56) - 1, 8), (1 << 56, 9), (u64::MAX, 9)
];
for &(n, l) in &tests {
let encoded = Compact(n as u64).encode();
assert_eq!(encoded.len(), l);
assert_eq!(Compact::compact_len(&n), l);
assert_eq!(<Compact<u64>>::decode(&mut &encoded[..]).unwrap().0, n);
}
}
#[test]
fn compact_32_encoding_works() {
let tests = [(0u32, 1usize), (63, 1), (64, 2), (16383, 2), (16384, 4), (1073741823, 4), (1073741824, 5), (u32::MAX, 5)];
for &(n, l) in &tests {
let encoded = Compact(n as u32).encode();
assert_eq!(encoded.len(), l);
assert_eq!(Compact::compact_len(&n), l);
assert_eq!(<Compact<u32>>::decode(&mut &encoded[..]).unwrap().0, n);
}
}
#[test]
fn compact_16_encoding_works() {
let tests = [(0u16, 1usize), (63, 1), (64, 2), (16383, 2), (16384, 4), (65535, 4)];
for &(n, l) in &tests {
let encoded = Compact(n as u16).encode();
assert_eq!(encoded.len(), l);
assert_eq!(Compact::compact_len(&n), l);
assert_eq!(<Compact<u16>>::decode(&mut &encoded[..]).unwrap().0, n);
}
assert!(<Compact<u16>>::decode(&mut &Compact(65536u32).encode()[..]).is_err());
}
#[test]
fn compact_8_encoding_works() {
let tests = [(0u8, 1usize), (63, 1), (64, 2), (255, 2)];
for &(n, l) in &tests {
let encoded = Compact(n as u8).encode();
assert_eq!(encoded.len(), l);
assert_eq!(Compact::compact_len(&n), l);
assert_eq!(<Compact<u8>>::decode(&mut &encoded[..]).unwrap().0, n);
}
assert!(<Compact<u8>>::decode(&mut &Compact(256u32).encode()[..]).is_err());
}
fn hexify(bytes: &[u8]) -> String {
bytes.iter().map(|ref b| format!("{:02x}", b)).collect::<Vec<String>>().join(" ")
}
#[test]
fn compact_integers_encoded_as_expected() {
let tests = [
(0u64, "00"),
(63, "fc"),
(64, "01 01"),
(16383, "fd ff"),
(16384, "02 00 01 00"),
(1073741823, "fe ff ff ff"),
(1073741824, "03 00 00 00 40"),
((1 << 32) - 1, "03 ff ff ff ff"),
(1 << 32, "07 00 00 00 00 01"),
(1 << 40, "0b 00 00 00 00 00 01"),
(1 << 48, "0f 00 00 00 00 00 00 01"),
((1 << 56) - 1, "0f ff ff ff ff ff ff ff"),
(1 << 56, "13 00 00 00 00 00 00 00 01"),
(u64::MAX, "13 ff ff ff ff ff ff ff ff")
];
for &(n, s) in &tests {
// Verify u64 encoding
let encoded = Compact(n as u64).encode();
assert_eq!(hexify(&encoded), s);
assert_eq!(<Compact<u64>>::decode(&mut &encoded[..]).unwrap().0, n);
// Verify encodings for lower-size uints are compatible with u64 encoding
if n <= u32::MAX as u64 {
assert_eq!(<Compact<u32>>::decode(&mut &encoded[..]).unwrap().0, n as u32);
let encoded = Compact(n as u32).encode();
assert_eq!(hexify(&encoded), s);
assert_eq!(<Compact<u64>>::decode(&mut &encoded[..]).unwrap().0, n as u64);
}
if n <= u16::MAX as u64 {
assert_eq!(<Compact<u16>>::decode(&mut &encoded[..]).unwrap().0, n as u16);
let encoded = Compact(n as u16).encode();
assert_eq!(hexify(&encoded), s);
assert_eq!(<Compact<u64>>::decode(&mut &encoded[..]).unwrap().0, n as u64);
}
if n <= u8::MAX as u64 {
assert_eq!(<Compact<u8>>::decode(&mut &encoded[..]).unwrap().0, n as u8);
let encoded = Compact(n as u8).encode();
assert_eq!(hexify(&encoded), s);
assert_eq!(<Compact<u64>>::decode(&mut &encoded[..]).unwrap().0, n as u64);
}
}
}
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[derive(PartialEq, Eq, Clone)]
struct Wrapper(u8);
impl CompactAs for Wrapper {
type As = u8;
fn encode_as(&self) -> &u8 {
&self.0
}
fn decode_from(x: u8) -> Result<Wrapper, Error> {
Ok(Wrapper(x))
}
}
impl From<Compact<Wrapper>> for Wrapper {
fn from(x: Compact<Wrapper>) -> Wrapper {
x.0
}
}
#[test]
fn compact_as_8_encoding_works() {
let tests = [(0u8, 1usize), (63, 1), (64, 2), (255, 2)];
for &(n, l) in &tests {
let compact: Compact<Wrapper> = Wrapper(n).into();
let encoded = compact.encode();
assert_eq!(encoded.len(), l);
assert_eq!(Compact::compact_len(&n), l);
let decoded = <Compact<Wrapper>>::decode(&mut & encoded[..]).unwrap();
let wrapper: Wrapper = decoded.into();
assert_eq!(wrapper, Wrapper(n));
}
}
struct WithCompact<T: HasCompact> {
_data: T,
}
#[test]
fn compact_as_has_compact() {
let _data = WithCompact { _data: Wrapper(1) };
}
#[test]
fn compact_using_encoded_arrayvec_size() {
Compact(u8::MAX).using_encoded(|_| {});
Compact(u16::MAX).using_encoded(|_| {});
Compact(u32::MAX).using_encoded(|_| {});
Compact(u64::MAX).using_encoded(|_| {});
Compact(u128::MAX).using_encoded(|_| {});
CompactRef(&u8::MAX).using_encoded(|_| {});
CompactRef(&u16::MAX).using_encoded(|_| {});
CompactRef(&u32::MAX).using_encoded(|_| {});
CompactRef(&u64::MAX).using_encoded(|_| {});
CompactRef(&u128::MAX).using_encoded(|_| {});
}
#[test]
#[should_panic]
fn array_vec_output_oob() {
let mut v = ArrayVecWrapper(ArrayVec::<u8, 4>::new());
v.write(&[1, 2, 3, 4, 5]);
}
#[test]
fn array_vec_output() {
let mut v = ArrayVecWrapper(ArrayVec::<u8, 4>::new());
v.write(&[1, 2, 3, 4]);
}
macro_rules! check_bound {
( $m:expr, $ty:ty, $typ1:ty, [ $(($ty2:ty, $ty2_err:expr)),* ]) => {
$(
check_bound!($m, $ty, $typ1, $ty2, $ty2_err);
)*
};
( $m:expr, $ty:ty, $typ1:ty, $ty2:ty, $ty2_err:expr) => {
let enc = ((<$ty>::MAX >> 2) as $typ1 << 2) | $m;
assert_eq!(Compact::<$ty2>::decode(&mut &enc.to_le_bytes()[..]),
Err($ty2_err.into()));
};
}
macro_rules! check_bound_u32 {
( [ $(($ty2:ty, $ty2_err:expr)),* ]) => {
$(
check_bound_u32!($ty2, $ty2_err);
)*
};
( $ty2:ty, $ty2_err:expr ) => {
assert_eq!(Compact::<$ty2>::decode(&mut &[0b11, 0xff, 0xff, 0xff, 0xff >> 2][..]),
Err($ty2_err.into()));
};
}
macro_rules! check_bound_high {
( $m:expr, [ $(($ty2:ty, $ty2_err:expr)),* ]) => {
$(
check_bound_high!($m, $ty2, $ty2_err);
)*
};
( $s:expr, $ty2:ty, $ty2_err:expr) => {
let mut dest = Vec::new();
dest.push(0b11 + (($s - 4) << 2) as u8);
for _ in 0..($s - 1) {
dest.push(u8::MAX);
}
dest.push(0);
assert_eq!(Compact::<$ty2>::decode(&mut &dest[..]),
Err($ty2_err.into()));
};
}
#[test]
fn compact_u64_test() {
for a in [
u64::MAX,
u64::MAX - 1,
u64::MAX << 8,
(u64::MAX << 8) - 1,
u64::MAX << 16,
(u64::MAX << 16) - 1,
].iter() {
let e = Compact::<u64>::encode(&Compact(*a));
let d = Compact::<u64>::decode(&mut &e[..]).unwrap().0;
assert_eq!(*a, d);
}
}
#[test]
fn compact_u128_test() {
for a in [
u64::MAX as u128,
(u64::MAX - 10) as u128,
u128::MAX,
u128::MAX - 10,
].iter() {
let e = Compact::<u128>::encode(&Compact(*a));
let d = Compact::<u128>::decode(&mut &e[..]).unwrap().0;
assert_eq!(*a, d);
}
}
#[test]
fn should_avoid_overlapping_definition() {
check_bound!(
0b01, u8, u16, [ (u8, U8_OUT_OF_RANGE), (u16, U16_OUT_OF_RANGE),
(u32, U32_OUT_OF_RANGE), (u64, U64_OUT_OF_RANGE), (u128, U128_OUT_OF_RANGE)]
);
check_bound!(
0b10, u16, u32, [ (u16, U16_OUT_OF_RANGE),
(u32, U32_OUT_OF_RANGE), (u64, U64_OUT_OF_RANGE), (u128, U128_OUT_OF_RANGE)]
);
check_bound_u32!(
[(u32, U32_OUT_OF_RANGE), (u64, U64_OUT_OF_RANGE), (u128, U128_OUT_OF_RANGE)]
);
for i in 5..=8 {
check_bound_high!(i, [(u64, U64_OUT_OF_RANGE), (u128, U128_OUT_OF_RANGE)]);
}
for i in 8..=16 {
check_bound_high!(i, [(u128, U128_OUT_OF_RANGE)]);
}
}
macro_rules! quick_check_roundtrip {
( $( $ty:ty : $test:ident ),* ) => {
$(
quickcheck::quickcheck! {
fn $test(v: $ty) -> bool {
let encoded = Compact(v).encode();
let deencoded = <Compact<$ty>>::decode(&mut &encoded[..]).unwrap().0;
v == deencoded
}
}
)*
}
}
quick_check_roundtrip! {
u8: u8_roundtrip,
u16: u16_roundtrip,
u32 : u32_roundtrip,
u64 : u64_roundtrip,
u128 : u128_roundtrip
}
}
|
pub(crate) mod response;
mod use_case;
use apllodb_immutable_schema_engine::ApllodbImmutableSchemaEngine;
use apllodb_shared_components::{ApllodbSessionResult, Session};
use apllodb_sql_processor::SqlProcessorContext;
use std::sync::Arc;
use use_case::UseCase;
use crate::ApllodbCommandSuccess;
#[derive(Clone, Debug)]
pub struct ApllodbServer {
context: Arc<SqlProcessorContext<ApllodbImmutableSchemaEngine>>,
}
impl Default for ApllodbServer {
fn default() -> Self {
let engine = ApllodbImmutableSchemaEngine::default();
let context = Arc::new(SqlProcessorContext::new(engine));
Self { context }
}
}
impl ApllodbServer {
pub async fn command(
&self,
session: Session,
sql: String,
) -> ApllodbSessionResult<ApllodbCommandSuccess> {
self.use_case().command(session, &sql).await
}
fn use_case(&self) -> UseCase<ApllodbImmutableSchemaEngine> {
UseCase::new(self.context.clone())
}
}
|
use tomorrow_core::{Error, Result};
use super::Requester;
use std::io::Read;
use serde_json;
use serde::de::DeserializeOwned;
use hyper::Client as HttpClient;
use hyper::status::StatusCode;
use hyper::header::Headers;
pub struct Client {
client: HttpClient,
headers: Headers,
api_url: String
}
impl Client {
pub fn new(client: HttpClient, headers: Headers, api_url: String) -> Self {
Client {
client: client,
headers: headers,
api_url: api_url
}
}
}
impl Requester for Client {
fn request<T>(&self, endpoint: &str) -> Result<T> where T: DeserializeOwned {
let url = format!("{}/{}", self.api_url, endpoint);
let mut response = self.client
.get(&url)
.headers(self.headers.clone())
.send()?;
let mut body = String::new();
response.read_to_string(&mut body)?;
match response.status {
StatusCode::Conflict |
StatusCode::BadRequest |
StatusCode::UnprocessableEntity |
StatusCode::Unauthorized |
StatusCode::NotFound |
StatusCode::Forbidden => Err(Error::from(body)),
_ => Ok(serde_json::from_str::<T>(&body)?)
}
}
} |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use consts::*;
use dividend::*;
use wasmlib::*;
mod consts;
mod dividend;
mod types;
#[no_mangle]
fn on_load() {
let exports = ScExports::new();
exports.add_func(FUNC_DIVIDE, func_divide);
exports.add_func(FUNC_MEMBER, func_member);
}
|
#[doc = "Register `APB1FZR2` reader"]
pub type R = crate::R<APB1FZR2_SPEC>;
#[doc = "Register `APB1FZR2` writer"]
pub type W = crate::W<APB1FZR2_SPEC>;
#[doc = "Field `DBG_LPTIM2_STOP` reader - LPTIM2 counter stopped when core is halted"]
pub type DBG_LPTIM2_STOP_R = crate::BitReader;
#[doc = "Field `DBG_LPTIM2_STOP` writer - LPTIM2 counter stopped when core is halted"]
pub type DBG_LPTIM2_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 5 - LPTIM2 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_lptim2_stop(&self) -> DBG_LPTIM2_STOP_R {
DBG_LPTIM2_STOP_R::new(((self.bits >> 5) & 1) != 0)
}
}
impl W {
#[doc = "Bit 5 - LPTIM2 counter stopped when core is halted"]
#[inline(always)]
#[must_use]
pub fn dbg_lptim2_stop(&mut self) -> DBG_LPTIM2_STOP_W<APB1FZR2_SPEC, 5> {
DBG_LPTIM2_STOP_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 = "Debug MCU APB1 freeze register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1fzr2::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 [`apb1fzr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct APB1FZR2_SPEC;
impl crate::RegisterSpec for APB1FZR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`apb1fzr2::R`](R) reader structure"]
impl crate::Readable for APB1FZR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`apb1fzr2::W`](W) writer structure"]
impl crate::Writable for APB1FZR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets APB1FZR2 to value 0"]
impl crate::Resettable for APB1FZR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::file::FileHash;
use crate::{Address, Range, Size};
/// A register number.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Register(pub u16);
impl Register {
/// The name of the register, if known.
pub fn name(self, hash: &FileHash) -> Option<&'static str> {
hash.file.get_register_name(self)
}
}
/// A location within the stack frame.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct FrameLocation {
/// The offset from the frame pointer.
pub offset: i64,
/// The size of the value in bits.
pub bit_size: Size,
}
/// A piece of a value.
// TODO: include the address ranges for which this piece is valid
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Piece {
/// The offset of the piece within the containing object.
pub bit_offset: u64,
/// The size of the piece. If none, then the piece is the complete value.
pub bit_size: Size,
/// The location of the piece.
pub location: Location,
/// The offset of the piece within the location.
pub location_offset: u64,
/// If `true`, then the piece does not have a location.
/// Instead, `location` is the value of the piece.
pub is_value: bool,
}
/// A value location.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Location {
/// The value has been optimized away.
Empty,
/// A literal address or value.
Literal {
/// The literal address or value.
value: u64,
},
/// The value is stored in a register.
Register {
/// The register number.
register: Register,
},
/// The value is stored in memory at an offset from an address stored in a register.
RegisterOffset {
/// The register number.
register: Register,
/// The offset.
offset: i64,
},
/// The value is stored in memory at an offset from the frame base.
FrameOffset {
/// The offset.
offset: i64,
},
/// The value is stored in memory at an offset from the CFA.
CfaOffset {
/// The offset.
offset: i64,
},
/// The value is stored in memory at an address. This address may need relocation.
Address {
/// The offset.
address: Address,
},
/// The value is stored in memory at an offset within TLS.
TlsOffset {
/// The offset.
offset: u64,
},
/// The value is more complex than any of the above variants.
Other,
}
pub(crate) fn registers(
locations: &[(Range, Piece)],
) -> impl Iterator<Item = (Range, Register)> + '_ {
locations.iter().filter_map(|(range, piece)| {
if piece.is_value {
return None;
}
match piece.location {
Location::Register { register } => Some((*range, register)),
_ => None,
}
})
}
pub(crate) fn frame_locations(
locations: &[(Range, Piece)],
) -> impl Iterator<Item = FrameLocation> + '_ {
locations.iter().filter_map(|(_, piece)| {
if piece.is_value {
return None;
}
match piece.location {
// TODO: do we need to distinguish between these?
Location::FrameOffset { offset } | Location::CfaOffset { offset } => {
Some(FrameLocation {
offset,
bit_size: piece.bit_size,
})
}
_ => None,
}
})
}
pub(crate) fn register_offsets(
locations: &[(Range, Piece)],
) -> impl Iterator<Item = (Range, Register, i64)> + '_ {
locations.iter().filter_map(|(range, piece)| {
if piece.is_value {
return None;
}
match piece.location {
Location::RegisterOffset { register, offset } => Some((*range, register, offset)),
_ => None,
}
})
}
|
// Copyright 2021 The MWC 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 crate::grin_util::Mutex;
use crate::swap::types::Currency;
use crate::swap::ErrorKind;
use secp256k1::SecretKey;
use std::sync::Arc;
use std::{collections::HashMap, u64};
use web3::types::{Address, TransactionReceipt, H256};
use super::to_eth_address;
/// Ethereum node client
pub trait EthNodeClient: Sync + Send + 'static {
/// Name of this client. Normally it is URL
fn name(&self) -> String;
/// Get node height
fn height(&self) -> Result<u64, ErrorKind>;
/// Get balance for the address
fn balance(&self, currency: Currency) -> Result<(String, u64), ErrorKind>;
/// Retrieve receipt
fn retrieve_receipt(&self, tx_hash: H256) -> Result<TransactionReceipt, ErrorKind>;
/// Send coins to destination account
fn transfer(&self, currency: Currency, to: Address, value: u64) -> Result<H256, ErrorKind>;
/// erc20 approve
fn erc20_approve(&self, currency: Currency, value: u64, gas: f32) -> Result<H256, ErrorKind>;
/// initiate swap
fn initiate(
&self,
currency: Currency,
refund_time: u64,
address_from_secret: Address,
participant: Address,
value: u64,
gas: f32,
) -> Result<H256, ErrorKind>;
/// redeem ether
fn redeem(
&self,
currency: Currency,
address_from_secret: Address,
secret_key: SecretKey,
gas: f32,
) -> Result<H256, ErrorKind>;
/// refund ether
fn refund(
&self,
currency: Currency,
address_from_secret: Address,
gas: f32,
) -> Result<H256, ErrorKind>;
/// get swap info
fn get_swap_details(
&self,
currency: Currency,
address_from_secret: Address,
) -> Result<(u64, Option<Address>, Address, Address, u64), ErrorKind>;
}
/// Mock Eth node for the testing
#[derive(Debug, Clone)]
pub struct TestEthNodeClientState {
/// current height
pub height: u64,
}
/// Mock ETH node client
#[derive(Debug, Clone)]
pub struct TestEthNodeClient {
/// mock node state
pub state: Arc<Mutex<TestEthNodeClientState>>,
/// swap HashMap
pub swap_store: Arc<Mutex<HashMap<Address, (u64, Option<Address>, Address, Address, u64)>>>,
/// txs HashMap
pub tx_store: Arc<Mutex<HashMap<H256, String>>>,
}
impl TestEthNodeClient {
/// Create an instance at height
pub fn new(height: u64) -> Self {
Self {
state: Arc::new(Mutex::new(TestEthNodeClientState { height })),
swap_store: Arc::new(Mutex::new(HashMap::with_capacity(10))),
tx_store: Arc::new(Mutex::new(HashMap::with_capacity(10))),
}
}
/// Get a current state for the test chain
pub fn get_state(&self) -> TestEthNodeClientState {
self.state.lock().clone()
}
/// Set a state for the test chain
pub fn set_state(&self, chain_state: &TestEthNodeClientState) {
let mut state = self.state.lock();
*state = chain_state.clone();
}
/// Clean the data, not height. Reorg attack
pub fn clean(&self) {
// let mut state = self.state.lock();
}
}
impl EthNodeClient for TestEthNodeClient {
/// Name of this client. Normally it is URL
fn name(&self) -> String {
String::from("ETH test client")
}
/// Fetch the current chain height
fn height(&self) -> Result<u64, ErrorKind> {
Ok(self.state.lock().height)
}
/// get wallet balance
fn balance(&self, _currency: Currency) -> Result<(String, u64), ErrorKind> {
Ok(("1.00".to_string(), 1_000_000_000_000_000_000u64))
}
/// Retrieve receipt
fn retrieve_receipt(&self, tx_hash: H256) -> Result<TransactionReceipt, ErrorKind> {
let receipt_str = r#"{
"blockHash": "0x83eaba432089a0bfe99e9fc9022d1cfcb78f95f407821be81737c84ae0b439c5",
"blockNumber": "0x38",
"contractAddress": "0x03d8c4566478a6e1bf75650248accce16a98509f",
"cumulativeGasUsed": "0x927c0",
"gasUsed": "0x927c0",
"logs": [],
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"root": null,
"transactionHash": "0x422fb0d5953c0c48cbb42fb58e1c30f5e150441c68374d70ca7d4f191fd56f26",
"transactionIndex": "0x0",
"status": "0x1"
}"#;
let mut receipt: TransactionReceipt = serde_json::from_str(receipt_str).unwrap();
receipt.transaction_hash = tx_hash;
Ok(receipt)
}
/// Send coins
fn transfer(&self, _currency: Currency, _to: Address, _value: u64) -> Result<H256, ErrorKind> {
unimplemented!()
}
fn erc20_approve(
&self,
_currency: Currency,
_value: u64,
_gas: f32,
) -> Result<H256, ErrorKind> {
unimplemented!()
}
/// initiate swap offer
fn initiate(
&self,
_currency: Currency,
refund_time: u64,
address_from_secret: Address,
participant: Address,
value: u64,
_gas: f32,
) -> Result<H256, ErrorKind> {
//todo need to check balance
let mut store = self.swap_store.lock();
if store.contains_key(&address_from_secret) {
return Err(ErrorKind::InvalidEthSwapTradeIndex);
}
store.insert(
address_from_secret,
(
refund_time,
None,
to_eth_address("0xAB90ddDF7bdff0e4FCAB3c9bF608393a6C7e2390".to_string()).unwrap(),
participant,
value,
),
);
if store.contains_key(&address_from_secret) {
let mut txs = self.tx_store.lock();
txs.insert(H256::from([1u8; 32]), "initiate".to_string());
Ok(H256::from([1u8; 32]))
} else {
Ok(H256::zero())
}
}
/// ether buyer redeem
fn redeem(
&self,
_currency: Currency,
address_from_secret: Address,
_secret_key: SecretKey,
_gas: f32,
) -> Result<H256, ErrorKind> {
let mut store = self.swap_store.lock();
if store.contains_key(&address_from_secret) {
let mut txs = self.tx_store.lock();
txs.insert(H256::from([2u8; 32]), "redeem".to_string());
store.remove(&address_from_secret);
Ok(H256::from([2u8; 32]))
} else {
Ok(H256::zero())
}
}
/// refund ether
fn refund(
&self,
_currency: Currency,
address_from_secret: Address,
_gas: f32,
) -> Result<H256, ErrorKind> {
let mut store = self.swap_store.lock();
if store.contains_key(&address_from_secret) {
let mut txs = self.tx_store.lock();
txs.insert(H256::from([3u8; 32]), "refund".to_string());
store.remove(&address_from_secret);
Ok(H256::from([3u8; 32]))
} else {
Ok(H256::zero())
}
}
/// get swap info
fn get_swap_details(
&self,
_currency: Currency,
address_from_secret: Address,
) -> Result<(u64, Option<Address>, Address, Address, u64), ErrorKind> {
let store = self.swap_store.lock();
if store.contains_key(&address_from_secret) {
Ok(store[&address_from_secret])
} else {
Err(ErrorKind::InvalidEthSwapTradeIndex)
}
}
}
|
pub trait Summary {
fn summarize(&self) -> String;
}
//
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
//
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
fn main() {
test_life();
test_struct_life();
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
};
println!("1 new tweet: {}", tweet.summarize());
}
fn test_life() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
struct ImportantExcerpt<'a> {
part: &'a str,
}
fn test_struct_life() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.')
.next()
.expect("Could not find a '.'");
let i = ImportantExcerpt { part: first_sentence };
}
|
typeof1
f
fn
fn1
trai2
trait
trait3
typeof
typeo1
type1
typ1
et c = b + 1;
let b = b + 2;
println!("My First Program in Rust {} {} {}", a, b, c);
} |
pub type Reg = usize;
#[derive(Debug, PartialEq)]
pub enum Val {
Reg(usize),
Imm(i32),
}
// Clone is needed to tokenize.
#[derive(Debug, PartialEq, Clone)]
pub enum Op2 {
Add,
Sub,
Mul,
Div,
Mod,
LT,
Eq
}
#[derive(Debug, PartialEq)]
pub enum Printable {
Id(String),
Val(Val),
Array(Val, Val),
}
#[derive(Debug, PartialEq)]
pub enum Instr {
Goto(Val),
Exit(Val),
Abort(),
Op2(Reg, Op2, Val, Val, Box<Instr>),
Copy(Reg, Val, Box<Instr>),
Load(Reg, Val, Box<Instr>),
Store(Reg, Val, Box<Instr>),
IfZ(Val, Box<Instr>, Box<Instr>),
Malloc(Reg, Val, Box<Instr>),
Print(Printable, Box<Instr>),
Free(Reg, Box<Instr>),
}
pub type Block = (i32, Instr);
|
//! Simplifies stevia expression trees via word-level transformations.
#![doc(html_root_url = "https://docs.rs/stevia_utils/0.1.0")]
#![feature(fn_traits)]
#![feature(unboxed_closures)]
// #![allow(missing_docs)]
#![allow(dead_code)]
extern crate stevia_ast as ast;
mod bitblaster;
mod gate_encoder;
mod repr;
|
use sdl2::render::{Texture, TextureCreator, Canvas};
use sdl2::video::{WindowContext, Window};
use sdl2::pixels::{PixelFormatEnum};
use crate::nes::nes::NES;
use crate::gfx::render;
use super::window::RenderableWindow;
const TEXTURE_WIDTH: u32 = 128;
const TEXTURE_HEIGHT: u32 = 128;
pub struct PatternTableWindow<'a> {
width: u32,
height: u32,
pattern_table_index: u8,
left_texture: Texture<'a>,
right_texture : Texture<'a>
}
impl<'a> PatternTableWindow<'a> {
pub fn new(texture_creator: &'a TextureCreator<WindowContext>,
width: u32,
height: u32,
pattern_table_index: u8) -> PatternTableWindow {
let left_texture = texture_creator
.create_texture_streaming(PixelFormatEnum::RGB24, TEXTURE_WIDTH, TEXTURE_HEIGHT).unwrap();
let right_texture = texture_creator
.create_texture_streaming(PixelFormatEnum::RGB24, TEXTURE_WIDTH, TEXTURE_HEIGHT).unwrap();
PatternTableWindow { left_texture,right_texture, width, height, pattern_table_index }
}
fn _update_texture(&mut self, nes: &NES, pattern_table_index: u8) -> Result<(), String>{
let pixel_data = nes.get_ppu().patterntable_to_texture_data(pattern_table_index);
let mut texture_rgb_data = [0 as u8; (128 * 128 * 3) as usize];
for (i, val) in pixel_data.iter().enumerate() {
match val {
0 => {},
1 => {
texture_rgb_data[i * 3] = 255;
}
2 => {
texture_rgb_data[i * 3 + 1] = 255;
},
3 => {
texture_rgb_data[i * 3 ] = 255;
texture_rgb_data[i * 3 + 1] = 255;
texture_rgb_data[i * 3 + 2] = 255;
}
_ => unreachable!()
}
}
if pattern_table_index == 0 {
self.left_texture.update(None, &texture_rgb_data, (TEXTURE_WIDTH * 3) as usize)
.map_err(|e| e.to_string())?;
} else {
self.right_texture.update(None, &texture_rgb_data, (TEXTURE_WIDTH * 3) as usize).map_err(|e| e.to_string())?;
}
Ok(())
}
}
impl<'a> RenderableWindow for PatternTableWindow<'a> {
fn render(&mut self,
canvas: &mut Canvas<Window>,
x: i32,
y: i32,
nes: &NES) -> Result<(), String> {
self._update_texture(nes, 0)?;
self._update_texture(nes, 1)?;
render::textured_window(canvas, x, y, self.width, self.height, &self.left_texture)?;
render::textured_window(canvas, x + self.width as i32 + 5, y, self.width, self.height, &self.right_texture)?;
Ok(())
}
}
|
#![allow(unconditional_recursion)]
use backend::models as m;
use pest::prelude::*;
use std::collections::LinkedList;
use super::ast;
use super::errors::*;
/// Check if character is an indentation character.
fn is_indent(c: char) -> bool {
match c {
' ' | '\t' => true,
_ => false,
}
}
/// Find the number of whitespace characters that the given string is indented.
fn find_indent(input: &str) -> Option<usize> {
input.chars().enumerate().find(|&(_, c)| !is_indent(c)).map(|(i, _)| i)
}
fn code_block_indent(input: &str) -> Option<(usize, usize, usize)> {
let mut indent: Option<usize> = None;
let mut start = 0;
let mut end = 0;
let mut first_line = false;
for (line_no, line) in input.lines().enumerate() {
if let Some(current) = find_indent(line) {
end = line_no + 1;
if indent.map(|i| i > current).unwrap_or(true) {
indent = Some(current);
}
first_line = true;
} else {
if !first_line {
start += 1;
}
}
}
indent.map(|indent| (indent, start, end - start))
}
/// Strip common indent from all input lines.
fn strip_code_block(input: &str) -> Vec<String> {
if let Some((indent, empty_start, len)) = code_block_indent(input) {
input.lines()
.skip(empty_start)
.take(len)
.map(|line| {
if line.len() < indent {
line.to_owned()
} else {
(&line[indent..]).to_owned()
}
})
.collect()
} else {
input.lines().map(ToOwned::to_owned).collect()
}
}
/// Decode an escaped string.
fn decode_escaped_string(input: &str) -> Result<String> {
let mut out = String::new();
let mut it = input.chars().skip(1).peekable();
loop {
let c = match it.next() {
None => break,
Some(c) => c,
};
// strip end quote
if it.peek().is_none() {
break;
}
if c == '\\' {
let escaped = match it.next().ok_or("expected character")? {
'n' => '\n',
'r' => '\r',
't' => '\t',
'u' => decode_unicode4(&mut it)?,
_ => return Err(ErrorKind::InvalidEscape.into()),
};
out.push(escaped);
continue;
}
out.push(c);
}
Ok(out)
}
/// Decode the next four characters as a unicode escape sequence.
fn decode_unicode4(it: &mut Iterator<Item = char>) -> Result<char> {
let mut res = 0u32;
for x in 0..4u32 {
let c = it.next().ok_or("expected hex character")?.to_string();
let c = u32::from_str_radix(&c, 16)?;
res += c << (4 * (3 - x));
}
Ok(::std::char::from_u32(res).ok_or("expected valid character")?)
}
impl_rdp! {
grammar! {
file = _{ package_decl ~ use_decl* ~ decl* ~ eoi }
decl = { type_decl | interface_decl | tuple_decl | enum_decl }
use_decl = { use_keyword ~ package_ident ~ use_as? ~ semi_colon }
use_as = { as_keyword ~ identifier }
package_decl = { package_keyword ~ package_ident ~ semi_colon }
type_decl = { type_keyword ~ type_identifier ~ left_curly ~ type_body ~ right_curly }
type_body = _{ member* }
tuple_decl = { tuple_keyword ~ type_identifier ~ left_curly ~ tuple_body ~ right_curly }
tuple_body = _{ member* }
interface_decl = { interface_keyword ~ type_identifier ~ left_curly ~ interface_body ~ right_curly }
interface_body = _{ member* ~ sub_type* }
enum_decl = { enum_keyword ~ type_identifier ~ left_curly ~ enum_body ~ right_curly }
enum_body = _{ enum_body_value* ~ member* }
enum_body_value = { enum_value }
sub_type = { type_identifier ~ left_curly ~ sub_type_body ~ right_curly }
sub_type_body = _{ member* }
member = { option_decl | match_decl | field | code_block }
field = { identifier ~ optional? ~ colon ~ type_spec ~ field_as? ~ semi_colon }
field_as = { as_keyword ~ value }
code_block = @{ identifier ~ whitespace* ~ code_start ~ code_body ~ code_end }
code_body = { (!(["}}"]) ~ any)* }
enum_value = { type_identifier ~ enum_arguments? ~ enum_ordinal? ~ semi_colon }
enum_arguments = { (left_paren ~ (value ~ (comma ~ value)*) ~ right_paren) }
enum_ordinal = { equals ~ value }
option_decl = { identifier ~ (value ~ (comma ~ value)*) ~ semi_colon }
match_decl = { match_keyword ~ left_curly ~ match_member_entry* ~ right_curly }
match_member_entry = { match_member }
match_member = { match_condition ~ hash_rocket ~ value ~ semi_colon }
match_condition = { match_variable | match_value }
match_variable = { identifier ~ colon ~ type_spec }
match_value = { value }
package_ident = @{ identifier ~ (dot ~ identifier)* }
type_spec = _{
float_type |
double_type |
signed_type |
unsigned_type |
boolean_type |
string_type |
bytes_type |
any_type |
map_type |
array_type |
custom_type
}
// Types
float_type = @{ ["float"] }
double_type = @{ ["double"] }
signed_type = @{ ["signed"] ~ type_bits? }
unsigned_type = @{ ["unsigned"] ~ type_bits? }
boolean_type = @{ ["boolean"] }
string_type = @{ ["string"] }
bytes_type = @{ ["bytes"] }
any_type = @{ ["any"] }
map_type = { left_curly ~ type_spec ~ colon ~ type_spec ~ right_curly }
array_type = { ["["] ~ type_spec ~ ["]"] }
custom_type = @{ used_prefix? ~ type_identifier ~ (dot ~ type_identifier)* }
used_prefix = @{ identifier ~ scope }
// Keywords and tokens
enum_keyword = @{ ["enum"] }
use_keyword = @{ ["use"] }
as_keyword = @{ ["as"] }
package_keyword = @{ ["package"] }
type_keyword = @{ ["type"] }
tuple_keyword = @{ ["tuple"] }
interface_keyword = @{ ["interface"] }
match_keyword = @{ ["match"] }
hash_rocket = @{ ["=>"] }
comma = @{ [","] }
colon = @{ [":"] }
scope = @{ ["::"] }
semi_colon = @{ [";"] }
left_curly = @{ ["{"] }
right_curly = @{ ["}"] }
code_start = @{ ["{{"] }
code_end = @{ ["}}"] }
left_paren = @{ ["("] }
right_paren = @{ [")"] }
forward_slash = @{ ["/"] }
optional = @{ ["?"] }
equals = @{ ["="] }
dot = @{ ["."] }
type_bits = _{ (forward_slash ~ unsigned) }
value = { instance | constant | boolean | identifier | string | number }
instance = { custom_type ~ (left_paren ~ (field_init ~ (comma ~ field_init)*)? ~ right_paren) }
constant = { custom_type }
field_init = { identifier ~ colon ~ value }
identifier = @{ ['a'..'z'] ~ (['0'..'9'] | ['a'..'z'] | ["_"])* }
type_identifier = @{ ['A'..'Z'] ~ (['A'..'Z'] | ['a'..'z'])* }
string = @{ ["\""] ~ (escape | !(["\""] | ["\\"]) ~ any)* ~ ["\""] }
escape = _{ ["\\"] ~ (["\""] | ["\\"] | ["/"] | ["n"] | ["r"] | ["t"] | unicode) }
unicode = _{ ["u"] ~ hex ~ hex ~ hex ~ hex }
hex = _{ ['0'..'9'] | ['a'..'f'] }
unsigned = @{ int }
number = @{ ["-"]? ~ int ~ (dot ~ ['0'..'9']+)? ~ (["e"] ~ int)? }
int = _{ ["0"] | ['1'..'9'] ~ ['0'..'9']* }
boolean = { ["true"] | ["false"] }
whitespace = _{ [" "] | ["\t"] | ["\r"] | ["\n"] }
comment = _{
// line comment
( ["//"] ~ (!(["\r"] | ["\n"]) ~ any)* ~ (["\n"] | ["\r\n"] | ["\r"] | eoi) ) |
// block comment
( ["/*"] ~ (!(["*/"]) ~ any)* ~ ["*/"] )
}
}
process! {
_file(&self) -> Result<ast::File> {
(
_: package_decl,
_: package_keyword,
package: _package(), _: semi_colon,
uses: _use_list(),
decls: _decl_list(),
) => {
let package = package;
let uses = uses?.into_iter().collect();
let decls = decls?.into_iter().collect();
Ok(ast::File {
package: package,
uses: uses,
decls: decls
})
},
}
_use_list(&self) -> Result<LinkedList<ast::Token<ast::UseDecl>>> {
(token: use_decl, use_decl: _use_decl(), tail: _use_list()) => {
let pos = (token.start, token.end);
let mut tail = tail?;
tail.push_front(ast::Token::new(use_decl, pos));
Ok(tail)
},
() => Ok(LinkedList::new()),
}
_use_decl(&self) -> ast::UseDecl {
(_: use_keyword, package: _package(), alias: _use_as(), _: semi_colon) => {
ast::UseDecl {
package: package,
alias: alias,
}
}
}
_use_as(&self) -> Option<String> {
(_: use_as, _: as_keyword, &alias: identifier) => Some(alias.to_owned()),
() => None,
}
_package(&self) -> ast::Token<m::Package> {
(token: package_ident, idents: _ident_list()) => {
let pos = (token.start, token.end);
let idents = idents;
let package = m::Package::new(idents.into_iter().collect());
ast::Token::new(package, pos)
},
}
_decl_list(&self) -> Result<LinkedList<ast::Token<ast::Decl>>> {
(token: decl, value: _decl(), tail: _decl_list()) => {
let mut tail = tail?;
let pos = (token.start, token.end);
tail.push_front(ast::Token::new(value?, pos));
Ok(tail)
},
() => Ok(LinkedList::new()),
}
_decl(&self) -> Result<ast::Decl> {
(
_: type_decl,
_: type_keyword,
&name: type_identifier,
_: left_curly,
members: _member_list(),
_: right_curly,
) => {
let members = members?.into_iter().collect();
let body = ast::TypeBody {
name: name.to_owned(),
members: members
};
Ok(ast::Decl::Type(body))
},
(
_: tuple_decl,
_: tuple_keyword,
&name: type_identifier,
_: left_curly,
members: _member_list(),
_: right_curly,
) => {
let members = members?.into_iter().collect();
let body = ast::TupleBody {
name: name.to_owned(),
members: members,
};
Ok(ast::Decl::Tuple(body))
},
(
_: interface_decl,
_: interface_keyword,
&name: type_identifier,
_: left_curly,
members: _member_list(),
sub_types: _sub_type_list(),
_: right_curly,
) => {
let members = members?.into_iter().collect();
let sub_types = sub_types?.into_iter().collect();
let body = ast::InterfaceBody {
name: name.to_owned(),
members: members,
sub_types: sub_types,
};
Ok(ast::Decl::Interface(body))
},
(
_: enum_decl,
_: enum_keyword,
&name: type_identifier,
_: left_curly,
values: _enum_value_list(),
members: _member_list(),
_: right_curly,
) => {
let values = values?.into_iter().collect();
let members = members?.into_iter().collect();
let body = ast::EnumBody {
name: name.to_owned(),
values: values,
members: members,
};
Ok(ast::Decl::Enum(body))
},
}
_enum_value_list(&self) -> Result<LinkedList<ast::Token<ast::EnumValue>>> {
(_: enum_body_value, value: _enum_value(), tail: _enum_value_list()) => {
let mut tail = tail?;
tail.push_front(value?);
Ok(tail)
},
() => Ok(LinkedList::new()),
}
_enum_value(&self) -> Result<ast::Token<ast::EnumValue>> {
(
token: enum_value,
&name: type_identifier,
values: _enum_arguments(),
ordinal: _enum_ordinal(),
_: semi_colon
) => {
let arguments = values?.into_iter().collect();
let ordinal = ordinal?;
let pos = (token.start, token.end);
let enum_value = ast::EnumValue { name: name.to_owned(), arguments: arguments, ordinal: ordinal };
Ok(ast::Token::new(enum_value, pos))
},
}
_enum_arguments(&self) -> Result<LinkedList<ast::Token<ast::Value>>> {
(_: enum_arguments, _: left_paren, values: _value_list(), _: right_paren) => values,
() => Ok(LinkedList::new()),
}
_enum_ordinal(&self) -> Result<Option<ast::Token<ast::Value>>> {
(_: enum_ordinal, _: equals, value: _value_token()) => value.map(Some),
() => Ok(None),
}
_value_list(&self) -> Result<LinkedList<ast::Token<ast::Value>>> {
(value: _value_token(), _: comma, tail: _value_list()) => {
let mut tail = tail?;
tail.push_front(value?);
Ok(tail)
},
(value: _value_token()) => {
let mut tail = LinkedList::new();
tail.push_front(value?);
Ok(tail)
},
}
_value_token(&self) -> Result<ast::Token<ast::Value>> {
(token: value, value: _value()) => {
let pos = (token.start, token.end);
value.map(move |v| ast::Token::new(v, pos))
},
}
_value(&self) -> Result<ast::Value> {
(
token: instance,
_: custom_type,
custom: _custom(),
_: left_paren,
arguments: _field_init_list(),
_: right_paren,
) => {
let pos = (token.start, token.end);
let arguments = arguments?.into_iter().collect();
let instance = ast::Instance {
ty: custom,
arguments: arguments,
};
Ok(ast::Value::Instance(ast::Token::new(instance, pos)))
},
(
token: constant,
_: custom_type,
custom: _custom(),
) => {
let pos = (token.start, token.end);
let instance = ast::Constant {
prefix: custom.prefix,
parts: custom.parts,
};
Ok(ast::Value::Constant(ast::Token::new(instance, pos)))
},
(&value: string) => {
let value = decode_escaped_string(value)?;
Ok(ast::Value::String(value))
},
(&value: identifier) => {
Ok(ast::Value::Identifier(value.to_owned()))
},
(&value: number) => {
let value = value.parse::<f64>()?;
Ok(ast::Value::Number(value))
},
(&value: boolean) => {
let value = match value {
"true" => true,
"false" => false,
_ => panic!("should not happen"),
};
Ok(ast::Value::Boolean(value))
},
}
_used_prefix(&self) -> Option<String> {
(_: used_prefix, &prefix: identifier, _: scope) => Some(prefix.to_owned()),
() => None,
}
_field_init_list(&self) -> Result<LinkedList<ast::Token<ast::FieldInit>>> {
(
token: field_init,
&name: identifier,
_: colon,
value: _value_token(),
_: comma,
tail: _field_init_list()
) => {
let mut tail = tail?;
let pos = (token.start, token.end);
let name = name.to_owned();
let value = value?;
let field_init = ast::FieldInit {
name: ast::Token::new(name, pos),
value: value,
};
tail.push_front(ast::Token::new(field_init, pos));
Ok(tail)
},
(
token: field_init,
&name: identifier,
_: colon,
value: _value_token(),
tail: _field_init_list()
) => {
let mut tail = tail?;
let pos = (token.start, token.end);
let name = name.to_owned();
let value = value?;
let field_init = ast::FieldInit {
name: ast::Token::new(name, pos),
value: value,
};
tail.push_front(ast::Token::new(field_init, pos));
Ok(tail)
},
() => Ok(LinkedList::new()),
}
_member_list(&self) -> Result<LinkedList<ast::Token<ast::Member>>> {
(token: member, value: _member(), tail: _member_list()) => {
let mut tail = tail?;
let pos = (token.start, token.end);
tail.push_front(ast::Token::new(value?, pos));
Ok(tail)
},
() => Ok(LinkedList::new()),
}
_member(&self) -> Result<ast::Member> {
(
_: field,
&name: identifier,
modifier: _modifier(),
_: colon,
type_spec: _type_spec(),
field_as: _field_as(),
_: semi_colon,
) => {
let field = ast::Field {
modifier: modifier,
name: name.to_owned(),
ty: type_spec?,
field_as: field_as?,
};
Ok(ast::Member::Field(field))
},
(
_: code_block,
&context: identifier,
_: code_start,
&content: code_body,
_: code_end,
) => {
let block = strip_code_block(content);
Ok(ast::Member::Code(context.to_owned(), block))
},
(
token: option_decl,
&name: identifier,
values: _value_list(),
_: semi_colon,
) => {
let pos = (token.start, token.end);
let values = values?.into_iter().collect();
let option_decl = ast::OptionDecl { name: name.to_owned(), values: values };
Ok(ast::Member::Option(ast::Token::new(option_decl, pos)))
},
(
_: match_decl,
_: match_keyword,
_: left_curly,
members: _match_member_list(),
_: right_curly,
) => {
let members = members?.into_iter().collect();
let decl = ast::MatchDecl {
members: members,
};
Ok(ast::Member::Match(decl))
},
}
_field_as(&self) -> Result<Option<ast::Token<ast::Value>>> {
(_: field_as, _: as_keyword, value: _value_token()) => Ok(Some(value?)),
() => Ok(None),
}
_sub_type_list(&self) -> Result<LinkedList<ast::Token<ast::SubType>>> {
(token: sub_type, value: _sub_type(), tail: _sub_type_list()) => {
let mut tail = tail?;
let pos = (token.start, token.end);
tail.push_front(ast::Token::new(value?, pos));
Ok(tail)
},
() => {
Ok(LinkedList::new())
},
}
_sub_type(&self) -> Result<ast::SubType> {
(
&name: type_identifier,
_: left_curly,
members: _member_list(),
_: right_curly,
) => {
let name = name.to_owned();
let members = members?.into_iter().collect();
Ok(ast::SubType { name: name, members: members })
},
}
_match_member_list(&self) -> Result<LinkedList<ast::Token<ast::MatchMember>>> {
(
_: match_member_entry,
member: _match_member(),
tail: _match_member_list(),
) => {
let mut tail = tail?;
tail.push_front(member?);
Ok(tail)
},
() => Ok(LinkedList::new()),
}
_match_member(&self) -> Result<ast::Token<ast::MatchMember>> {
(
token: match_member,
condition: _match_condition(),
_: hash_rocket,
value: _value_token(),
_: semi_colon,
) => {
let pos = (token.start, token.end);
let member = ast::MatchMember {
condition: condition?,
value: value?,
};
Ok(ast::Token::new(member, pos))
},
}
_match_condition(&self) -> Result<ast::Token<ast::MatchCondition>> {
(
token: match_condition,
_: match_value,
value: _value_token(),
) => {
let pos = (token.start, token.end);
let value = value?;
let condition = ast::MatchCondition::Value(value);
Ok(ast::Token::new(condition, pos))
},
(
token: match_condition,
_: match_variable,
&name: identifier,
_: colon,
ty: _type_spec(),
) => {
let pos = (token.start, token.end);
let name = name.to_owned();
let ty = ty?;
let variable = ast::MatchVariable {
name: name,
ty: ty,
};
let condition = ast::MatchCondition::Type(variable);
Ok(ast::Token::new(condition, pos))
},
}
_type_spec(&self) -> Result<m::Type> {
(_: double_type) => {
Ok(m::Type::Double)
},
(_: float_type) => {
Ok(m::Type::Float)
},
(_: signed_type, _: forward_slash, &size: unsigned) => {
let size = size.parse::<usize>()?;
Ok(m::Type::Signed(Some(size)))
},
(_: unsigned_type, _: forward_slash, &size: unsigned) => {
let size = size.parse::<usize>()?;
Ok(m::Type::Unsigned(Some(size)))
},
(_: signed_type) => {
Ok(m::Type::Signed(None))
},
(_: unsigned_type) => {
Ok(m::Type::Unsigned(None))
},
(_: boolean_type) => {
Ok(m::Type::Boolean)
},
(_: string_type) => {
Ok(m::Type::String)
},
(_: bytes_type) => {
Ok(m::Type::Bytes)
},
(_: any_type) => {
Ok(m::Type::Any)
},
(_: array_type, argument: _type_spec()) => {
let argument = argument?;
Ok(m::Type::Array(Box::new(argument)))
},
(
_: map_type,
_: left_curly,
key: _type_spec(),
_: colon,
value: _type_spec(),
_: right_curly
) => {
let key = key?;
let value = value?;
Ok(m::Type::Map(Box::new(key), Box::new(value)))
},
(_: custom_type, custom: _custom()) => {
Ok(m::Type::Custom(custom))
},
}
_custom(&self) -> m::Custom {
(prefix: _used_prefix(), parts: _type_identifier_list()) => {
let parts = parts.into_iter().collect();
m::Custom {
prefix: prefix,
parts: parts,
}
},
}
_modifier(&self) -> m::Modifier {
(_: optional) => m::Modifier::Optional,
() => m::Modifier::Required,
}
_ident_list(&self) -> LinkedList<String> {
(&value: identifier, _: dot, mut tail: _ident_list()) => {
tail.push_front(value.to_owned());
tail
},
(&value: identifier, mut tail: _ident_list()) => {
tail.push_front(value.to_owned());
tail
},
() => LinkedList::new(),
}
_type_identifier_list(&self) -> LinkedList<String> {
(&value: type_identifier, _: dot, mut tail: _type_identifier_list()) => {
tail.push_front(value.to_owned());
tail
},
(&value: type_identifier) => {
let mut tail = LinkedList::new();
tail.push_front(value.to_owned());
tail
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Check that a parsed value equals expected.
macro_rules! assert_value_eq {
($expected:expr, $input:expr) => {{
let mut parser = parse($input);
assert!(parser.value());
let v = parser._value_token().unwrap().inner;
assert_eq!($expected, v);
}}
}
macro_rules! assert_type_spec_eq {
($expected:expr, $input:expr) => {{
let mut parser = parse($input);
assert!(parser.type_spec());
assert!(parser.end());
let v = parser._type_spec().unwrap();
assert_eq!($expected, v);
}}
}
const FILE1: &[u8] = include_bytes!("tests/file1.reproto");
const INTERFACE1: &[u8] = include_bytes!("tests/interface1.reproto");
fn parse(input: &'static str) -> Rdp<StringInput> {
Rdp::new(StringInput::new(input))
}
#[test]
fn test_file1() {
let input = ::std::str::from_utf8(FILE1).unwrap();
let mut parser = parse(input);
assert!(parser.file());
assert!(parser.end());
let file = parser._file().unwrap();
let package = m::Package::new(vec!["foo".to_owned(), "bar".to_owned(), "baz".to_owned()]);
assert_eq!(package, *file.package);
assert_eq!(4, file.decls.len());
}
#[test]
fn test_array() {
let mut parser = parse("[string]");
assert!(parser.type_spec());
assert!(parser.end());
let ty = parser._type_spec().unwrap();
if let m::Type::Array(inner) = ty {
if let m::Type::String = *inner {
return;
}
}
panic!("Expected Type::Array(Type::String)");
}
#[test]
fn test_map() {
let mut parser = parse("{string: unsigned/123}");
assert!(parser.type_spec());
assert!(parser.end());
let ty = parser._type_spec().unwrap();
// TODO: use #![feature(box_patterns)]:
// if let m::Type::Map(box m::Type::String, box m::Type::Unsigned(size)) = ty {
// }
if let m::Type::Map(key, value) = ty {
if let m::Type::String = *key {
if let m::Type::Unsigned(size) = *value {
assert_eq!(Some(123usize), size);
return;
}
}
}
panic!("Expected Type::Array(Type::String)");
}
#[test]
fn test_block_comment() {
let mut parser = parse("/* hello \n world */");
assert!(parser.comment());
}
#[test]
fn test_line_comment() {
let mut parser = parse("// hello world\n");
assert!(parser.comment());
}
#[test]
fn test_code_block() {
let mut parser = parse("a { b { c } d } e");
assert!(parser.code_body());
assert!(parser.end());
}
#[test]
fn test_code() {
let mut parser = parse("java{{\na { b { c } d } e\n}}");
assert!(parser.code_block());
assert!(parser.end());
}
#[test]
fn test_find_indent() {
assert_eq!(Some(4), find_indent(" \thello"));
assert_eq!(Some(0), find_indent("nope"));
assert_eq!(None, find_indent(""));
assert_eq!(None, find_indent(" "));
}
#[test]
fn test_strip_code_block() {
let result = strip_code_block("\n hello\n world\n\n\n again\n\n\n");
assert_eq!(vec![" hello", " world", "", "", "again"], result);
}
#[test]
fn test_interface() {
let input = ::std::str::from_utf8(INTERFACE1).unwrap();
let mut parser = parse(input);
assert!(parser.file());
assert!(parser.end());
let file = parser._file().unwrap();
assert_eq!(1, file.decls.len());
}
#[test]
fn test_values() {
let field = ast::FieldInit {
name: ast::Token::new("hello".to_owned(), (8, 17)),
value: ast::Token::new(ast::Value::Number(12f64), (15, 17)),
};
let field = ast::Token::new(field, (8, 17));
let instance = ast::Instance {
ty: m::Type::Custom(None, vec!["Foo".to_owned(), "Bar".to_owned()]),
arguments: vec![field],
};
assert_value_eq!(ast::Value::Instance(ast::Token::new(instance, (0, 18))),
"Foo.Bar(hello: 12)");
assert_value_eq!(ast::Value::String("foo\nbar".to_owned()), "\"foo\\nbar\"");
assert_value_eq!(ast::Value::Number(1f64), "1");
}
#[test]
fn test_type_spec() {
assert_type_spec_eq!(m::Type::String, "string");
assert_type_spec_eq!(m::Type::Custom(None, vec!["Hello".to_owned(), "World".to_owned()]),
"Hello.World");
}
#[test]
fn test_option_decl() {
let mut parser = parse("foo_bar_baz true, foo, \"bar\", 12;");
assert!(parser.option_decl());
assert!(parser.end());
if let ast::Member::Option(option) = parser._member().unwrap() {
assert_eq!("foo_bar_baz", option.name);
assert_eq!(4, option.values.len());
assert_eq!(ast::Value::Boolean(true), option.values[0].inner);
assert_eq!(ast::Value::Identifier("foo".to_owned()),
option.values[1].inner);
assert_eq!(ast::Value::String("bar".to_owned()), option.values[2].inner);
assert_eq!(ast::Value::Number(12f64), option.values[3].inner);
return;
}
panic!("option did not match");
}
}
|
use std::collections::{HashSet, HashMap};
pub struct Map { }
impl Map {
/// Calculates the Mean Average Precision of all queries provided.
pub fn calc(results: &HashMap<usize, Vec<usize>>, relevance_info: &HashMap<usize, HashSet<usize>>) -> f64 {
let mut count = 0.0;
let mut sum = 0.0;
for (query, docs) in relevance_info.iter() {
sum += Map::calc_average_precision(results.get(query).unwrap(), docs);
count += 1.0;
}
sum / count
}
/// Given a list of retrieved documents and the set of relevant
/// ones, returns theAverage Precision across the query.
pub fn calc_average_precision(retrieved_docs: &Vec<usize>, relevant_docs: &HashSet<usize>) -> f64 {
let mut relevant = 0.0;
let mut retrieved = 0.0;
let mut sum = 0.0;
for doc in retrieved_docs.iter() {
if relevant_docs.contains(doc) {
relevant += 1.0;
}
retrieved += 1.0;
sum += relevant / retrieved;
}
sum / (retrieved_docs.len() as f64)
}
}
|
use evitable::*;
#[evitable]
pub enum Context {
#[evitable(description("IO error"), from = std::io::Error)]
Io,
#[evitable(description("Writer closed"))]
WriterClosed,
}
|
use super::*;
use async_trait::async_trait;
use std::io;
use std::net::{IpAddr, Ipv4Addr};
use std::str::FromStr;
use std::sync::atomic::AtomicU64;
use util::vnet::chunk::Chunk;
use util::{vnet::router::Nic, vnet::*, Conn};
use waitgroup::WaitGroup;
pub(crate) struct MockConn;
#[async_trait]
impl Conn for MockConn {
async fn connect(&self, _addr: SocketAddr) -> io::Result<()> {
Ok(())
}
async fn recv(&self, _buf: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
async fn recv_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
Ok((0, SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0)))
}
async fn send(&self, _buf: &[u8]) -> io::Result<usize> {
Ok(0)
}
async fn send_to(&self, _buf: &[u8], _target: SocketAddr) -> io::Result<usize> {
Ok(0)
}
async fn local_addr(&self) -> io::Result<SocketAddr> {
Ok(SocketAddr::new(Ipv4Addr::new(0, 0, 0, 0).into(), 0))
}
}
pub(crate) struct VNet {
pub(crate) wan: Arc<Mutex<router::Router>>,
pub(crate) net0: Arc<net::Net>,
pub(crate) net1: Arc<net::Net>,
pub(crate) server: turn::server::Server,
}
impl VNet {
pub(crate) async fn close(&self) -> Result<(), Error> {
self.server.close()?;
let mut w = self.wan.lock().await;
w.stop().await?;
Ok(())
}
}
pub(crate) const VNET_GLOBAL_IPA: &str = "27.1.1.1";
pub(crate) const VNET_LOCAL_IPA: &str = "192.168.0.1";
pub(crate) const VNET_LOCAL_SUBNET_MASK_A: &str = "24";
pub(crate) const VNET_GLOBAL_IPB: &str = "28.1.1.1";
pub(crate) const VNET_LOCAL_IPB: &str = "10.2.0.1";
pub(crate) const VNET_LOCAL_SUBNET_MASK_B: &str = "24";
pub(crate) const VNET_STUN_SERVER_IP: &str = "1.2.3.4";
pub(crate) const VNET_STUN_SERVER_PORT: u16 = 3478;
pub(crate) async fn build_simple_vnet(
_nat_type0: nat::NatType,
_nat_type1: nat::NatType,
) -> Result<VNet, Error> {
// WAN
let wan = Arc::new(Mutex::new(router::Router::new(router::RouterConfig {
cidr: "0.0.0.0/0".to_owned(),
..Default::default()
})?));
let wnet = Arc::new(net::Net::new(Some(net::NetConfig {
static_ip: VNET_STUN_SERVER_IP.to_owned(), // will be assigned to eth0
..Default::default()
})));
connect_net2router(&wnet, &wan).await?;
// LAN
let lan = Arc::new(Mutex::new(router::Router::new(router::RouterConfig {
cidr: format!("{}/{}", VNET_LOCAL_IPA, VNET_LOCAL_SUBNET_MASK_A),
..Default::default()
})?));
let net0 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec!["192.168.0.1".to_owned()],
..Default::default()
})));
let net1 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec!["192.168.0.2".to_owned()],
..Default::default()
})));
connect_net2router(&net0, &lan).await?;
connect_net2router(&net1, &lan).await?;
connect_router2router(&lan, &wan).await?;
// start routers...
start_router(&wan).await?;
let server = add_vnet_stun(wnet).await?;
Ok(VNet {
wan,
net0,
net1,
server,
})
}
pub(crate) async fn build_vnet(
nat_type0: nat::NatType,
nat_type1: nat::NatType,
) -> Result<VNet, Error> {
// WAN
let wan = Arc::new(Mutex::new(router::Router::new(router::RouterConfig {
cidr: "0.0.0.0/0".to_owned(),
..Default::default()
})?));
let wnet = Arc::new(net::Net::new(Some(net::NetConfig {
static_ip: VNET_STUN_SERVER_IP.to_owned(), // will be assigned to eth0
..Default::default()
})));
connect_net2router(&wnet, &wan).await?;
// LAN 0
let lan0 = Arc::new(Mutex::new(router::Router::new(router::RouterConfig {
static_ips: if nat_type0.mode == nat::NatMode::Nat1To1 {
vec![format!("{}/{}", VNET_GLOBAL_IPA, VNET_LOCAL_IPA)]
} else {
vec![VNET_GLOBAL_IPA.to_owned()]
},
cidr: format!("{}/{}", VNET_LOCAL_IPA, VNET_LOCAL_SUBNET_MASK_A),
nat_type: Some(nat_type0),
..Default::default()
})?));
let net0 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec![VNET_LOCAL_IPA.to_owned()],
..Default::default()
})));
connect_net2router(&net0, &lan0).await?;
connect_router2router(&lan0, &wan).await?;
// LAN 1
let lan1 = Arc::new(Mutex::new(router::Router::new(router::RouterConfig {
static_ips: if nat_type1.mode == nat::NatMode::Nat1To1 {
vec![format!("{}/{}", VNET_GLOBAL_IPB, VNET_LOCAL_IPB)]
} else {
vec![VNET_GLOBAL_IPB.to_owned()]
},
cidr: format!("{}/{}", VNET_LOCAL_IPB, VNET_LOCAL_SUBNET_MASK_B),
nat_type: Some(nat_type1),
..Default::default()
})?));
let net1 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec![VNET_LOCAL_IPB.to_owned()],
..Default::default()
})));
connect_net2router(&net1, &lan1).await?;
connect_router2router(&lan1, &wan).await?;
// start routers...
start_router(&wan).await?;
let server = add_vnet_stun(wnet).await?;
Ok(VNet {
wan,
net0,
net1,
server,
})
}
pub(crate) struct TestAuthHandler {
pub(crate) cred_map: HashMap<String, Vec<u8>>,
}
impl TestAuthHandler {
pub(crate) fn new() -> Self {
let mut cred_map = HashMap::new();
cred_map.insert(
"user".to_owned(),
turn::auth::generate_auth_key("user", "webrtc.rs", "pass"),
);
TestAuthHandler { cred_map }
}
}
impl turn::auth::AuthHandler for TestAuthHandler {
fn auth_handle(
&self,
username: &str,
_realm: &str,
_src_addr: SocketAddr,
) -> Result<Vec<u8>, Error> {
if let Some(pw) = self.cred_map.get(username) {
Ok(pw.to_vec())
} else {
Err(Error::new("fake error".to_owned()))
}
}
}
pub(crate) async fn add_vnet_stun(wan_net: Arc<net::Net>) -> Result<turn::server::Server, Error> {
// Run TURN(STUN) server
let conn = wan_net
.bind(SocketAddr::from_str(&format!(
"{}:{}",
VNET_STUN_SERVER_IP, VNET_STUN_SERVER_PORT
))?)
.await?;
let server = turn::server::Server::new(turn::server::config::ServerConfig {
conn_configs: vec![turn::server::config::ConnConfig {
conn,
relay_addr_generator: Box::new(
turn::relay::relay_static::RelayAddressGeneratorStatic {
relay_address: IpAddr::from_str(VNET_STUN_SERVER_IP)?,
address: "0.0.0.0".to_owned(),
net: wan_net,
},
),
}],
realm: "webrtc.rs".to_owned(),
auth_handler: Arc::new(Box::new(TestAuthHandler::new())),
channel_bind_timeout: Duration::from_secs(0),
})
.await?;
Ok(server)
}
pub(crate) async fn connect_with_vnet(
a_agent: &Arc<Agent>,
b_agent: &Arc<Agent>,
) -> Result<(Arc<impl Conn>, Arc<impl Conn>), Error> {
// Manual signaling
let (a_ufrag, a_pwd) = a_agent.get_local_user_credentials().await;
let (b_ufrag, b_pwd) = b_agent.get_local_user_credentials().await;
gather_and_exchange_candidates(a_agent, b_agent).await?;
let (accepted_tx, mut accepted_rx) = mpsc::channel(1);
let (_a_cancel_tx, a_cancel_rx) = mpsc::channel(1);
let agent_a = Arc::clone(a_agent);
tokio::spawn(async move {
let a_conn = agent_a.accept(a_cancel_rx, b_ufrag, b_pwd).await?;
let _ = accepted_tx.send(a_conn).await;
Ok::<(), Error>(())
});
let (_b_cancel_tx, b_cancel_rx) = mpsc::channel(1);
let b_conn = b_agent.dial(b_cancel_rx, a_ufrag, a_pwd).await?;
// Ensure accepted
if let Some(a_conn) = accepted_rx.recv().await {
Ok((a_conn, b_conn))
} else {
Err(Error::new("no a_conn".to_owned()))
}
}
#[derive(Default)]
pub(crate) struct AgentTestConfig {
pub(crate) urls: Vec<Url>,
pub(crate) nat_1to1_ip_candidate_type: CandidateType,
}
pub(crate) async fn pipe_with_vnet(
v: &VNet,
a0test_config: AgentTestConfig,
a1test_config: AgentTestConfig,
) -> Result<(Arc<impl Conn>, Arc<impl Conn>), Error> {
let (a_notifier, mut a_connected) = on_connected();
let (b_notifier, mut b_connected) = on_connected();
let nat_1to1_ips = if a0test_config.nat_1to1_ip_candidate_type != CandidateType::Unspecified {
vec![VNET_GLOBAL_IPA.to_owned()]
} else {
vec![]
};
let cfg0 = AgentConfig {
urls: a0test_config.urls,
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
nat_1to1_ips,
nat_1to1_ip_candidate_type: a0test_config.nat_1to1_ip_candidate_type,
net: Some(Arc::clone(&v.net0)),
..Default::default()
};
let a_agent = Arc::new(Agent::new(cfg0).await?);
a_agent.on_connection_state_change(a_notifier).await;
let nat_1to1_ips = if a1test_config.nat_1to1_ip_candidate_type != CandidateType::Unspecified {
vec![VNET_GLOBAL_IPB.to_owned()]
} else {
vec![]
};
let cfg1 = AgentConfig {
urls: a1test_config.urls,
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
nat_1to1_ips,
nat_1to1_ip_candidate_type: a1test_config.nat_1to1_ip_candidate_type,
net: Some(Arc::clone(&v.net1)),
..Default::default()
};
let b_agent = Arc::new(Agent::new(cfg1).await?);
b_agent.on_connection_state_change(b_notifier).await;
let (a_conn, b_conn) = connect_with_vnet(&a_agent, &b_agent).await?;
// Ensure pair selected
// Note: this assumes ConnectionStateConnected is thrown after selecting the final pair
let _ = a_connected.recv().await;
let _ = b_connected.recv().await;
Ok((a_conn, b_conn))
}
pub(crate) fn on_connected() -> (OnConnectionStateChangeHdlrFn, mpsc::Receiver<()>) {
let (done_tx, done_rx) = mpsc::channel::<()>(1);
let done_tx = Arc::new(Mutex::new(Some(done_tx)));
let hdlr_fn: OnConnectionStateChangeHdlrFn = Box::new(move |state: ConnectionState| {
let done_tx_clone = Arc::clone(&done_tx);
Box::pin(async move {
if state == ConnectionState::Connected {
let mut tx = done_tx_clone.lock().await;
tx.take();
}
})
});
(hdlr_fn, done_rx)
}
pub(crate) async fn gather_and_exchange_candidates(
a_agent: &Arc<Agent>,
b_agent: &Arc<Agent>,
) -> Result<(), Error> {
let wg = WaitGroup::new();
let w1 = Arc::new(Mutex::new(Some(wg.worker())));
a_agent
.on_candidate(Box::new(
move |candidate: Option<Arc<dyn Candidate + Send + Sync>>| {
let w3 = Arc::clone(&w1);
Box::pin(async move {
if candidate.is_none() {
let mut w = w3.lock().await;
w.take();
}
})
},
))
.await;
a_agent.gather_candidates().await?;
let w2 = Arc::new(Mutex::new(Some(wg.worker())));
b_agent
.on_candidate(Box::new(
move |candidate: Option<Arc<dyn Candidate + Send + Sync>>| {
let w3 = Arc::clone(&w2);
Box::pin(async move {
if candidate.is_none() {
let mut w = w3.lock().await;
w.take();
}
})
},
))
.await;
b_agent.gather_candidates().await?;
wg.wait().await;
let candidates = a_agent.get_local_candidates().await?;
for c in candidates {
let c2: Arc<dyn Candidate + Send + Sync> =
Arc::new(b_agent.unmarshal_remote_candidate(c.marshal()).await?);
b_agent.add_remote_candidate(&c2).await?;
}
let candidates = b_agent.get_local_candidates().await?;
for c in candidates {
let c2: Arc<dyn Candidate + Send + Sync> =
Arc::new(a_agent.unmarshal_remote_candidate(c.marshal()).await?);
a_agent.add_remote_candidate(&c2).await?;
}
Ok(())
}
pub(crate) async fn start_router(router: &Arc<Mutex<router::Router>>) -> Result<(), Error> {
let mut w = router.lock().await;
w.start().await
}
pub(crate) async fn connect_net2router(
net: &Arc<net::Net>,
router: &Arc<Mutex<router::Router>>,
) -> Result<(), Error> {
let nic = net.get_nic()?;
{
let mut w = router.lock().await;
w.add_net(Arc::clone(&nic)).await?;
}
{
let n = nic.lock().await;
n.set_router(Arc::clone(router)).await?;
}
Ok(())
}
pub(crate) async fn connect_router2router(
child: &Arc<Mutex<router::Router>>,
parent: &Arc<Mutex<router::Router>>,
) -> Result<(), Error> {
{
let mut w = parent.lock().await;
w.add_router(Arc::clone(child)).await?;
}
{
let l = child.lock().await;
l.set_router(Arc::clone(parent)).await?;
}
Ok(())
}
#[tokio::test]
async fn test_connectivity_simple_vnet_full_cone_nats_on_both_ends() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
let stun_server_url = Url {
scheme: SchemeType::Stun,
host: VNET_STUN_SERVER_IP.to_owned(),
port: VNET_STUN_SERVER_PORT,
proto: ProtoType::Udp,
..Default::default()
};
// buildVNet with a Full-cone NATs both LANs
let nat_type = nat::NatType {
mapping_behavior: nat::EndpointDependencyType::EndpointIndependent,
filtering_behavior: nat::EndpointDependencyType::EndpointIndependent,
..Default::default()
};
let v = build_simple_vnet(nat_type, nat_type).await?;
log::debug!("Connecting...");
let a0test_config = AgentTestConfig {
urls: vec![stun_server_url.clone()],
..Default::default()
};
let a1test_config = AgentTestConfig {
urls: vec![stun_server_url.clone()],
..Default::default()
};
let (_ca, _cb) = pipe_with_vnet(&v, a0test_config, a1test_config).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
log::debug!("Closing...");
v.close().await?;
Ok(())
}
#[tokio::test]
async fn test_connectivity_vnet_full_cone_nats_on_both_ends() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
let stun_server_url = Url {
scheme: SchemeType::Stun,
host: VNET_STUN_SERVER_IP.to_owned(),
port: VNET_STUN_SERVER_PORT,
proto: ProtoType::Udp,
..Default::default()
};
let _turn_server_url = Url {
scheme: SchemeType::Turn,
host: VNET_STUN_SERVER_IP.to_owned(),
port: VNET_STUN_SERVER_PORT,
username: "user".to_owned(),
password: "pass".to_owned(),
proto: ProtoType::Udp,
};
// buildVNet with a Full-cone NATs both LANs
let nat_type = nat::NatType {
mapping_behavior: nat::EndpointDependencyType::EndpointIndependent,
filtering_behavior: nat::EndpointDependencyType::EndpointIndependent,
..Default::default()
};
let v = build_vnet(nat_type, nat_type).await?;
log::debug!("Connecting...");
let a0test_config = AgentTestConfig {
urls: vec![stun_server_url.clone()],
..Default::default()
};
let a1test_config = AgentTestConfig {
urls: vec![stun_server_url.clone()],
..Default::default()
};
let (_ca, _cb) = pipe_with_vnet(&v, a0test_config, a1test_config).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
log::debug!("Closing...");
v.close().await?;
Ok(())
}
#[tokio::test]
async fn test_connectivity_vnet_symmetric_nats_on_both_ends() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
let stun_server_url = Url {
scheme: SchemeType::Stun,
host: VNET_STUN_SERVER_IP.to_owned(),
port: VNET_STUN_SERVER_PORT,
proto: ProtoType::Udp,
..Default::default()
};
let turn_server_url = Url {
scheme: SchemeType::Turn,
host: VNET_STUN_SERVER_IP.to_owned(),
port: VNET_STUN_SERVER_PORT,
username: "user".to_owned(),
password: "pass".to_owned(),
proto: ProtoType::Udp,
};
// buildVNet with a Symmetric NATs for both LANs
let nat_type = nat::NatType {
mapping_behavior: nat::EndpointDependencyType::EndpointAddrPortDependent,
filtering_behavior: nat::EndpointDependencyType::EndpointAddrPortDependent,
..Default::default()
};
let v = build_vnet(nat_type, nat_type).await?;
log::debug!("Connecting...");
let a0test_config = AgentTestConfig {
urls: vec![stun_server_url.clone(), turn_server_url.clone()],
..Default::default()
};
let a1test_config = AgentTestConfig {
urls: vec![stun_server_url.clone()],
..Default::default()
};
let (_ca, _cb) = pipe_with_vnet(&v, a0test_config, a1test_config).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
log::debug!("Closing...");
v.close().await?;
Ok(())
}
#[tokio::test]
async fn test_connectivity_vnet_1to1_nat_with_host_candidate_vs_symmetric_nats() -> Result<(), Error>
{
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
// Agent0 is behind 1:1 NAT
let nat_type0 = nat::NatType {
mode: nat::NatMode::Nat1To1,
..Default::default()
};
// Agent1 is behind a symmetric NAT
let nat_type1 = nat::NatType {
mapping_behavior: nat::EndpointDependencyType::EndpointAddrPortDependent,
filtering_behavior: nat::EndpointDependencyType::EndpointAddrPortDependent,
..Default::default()
};
log::debug!("natType0: {:?}", nat_type0);
log::debug!("natType1: {:?}", nat_type1);
let v = build_vnet(nat_type0, nat_type1).await?;
log::debug!("Connecting...");
let a0test_config = AgentTestConfig {
urls: vec![],
nat_1to1_ip_candidate_type: CandidateType::Host, // Use 1:1 NAT IP as a host candidate
};
let a1test_config = AgentTestConfig {
urls: vec![],
..Default::default()
};
let (_ca, _cb) = pipe_with_vnet(&v, a0test_config, a1test_config).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
log::debug!("Closing...");
v.close().await?;
Ok(())
}
#[tokio::test]
async fn test_connectivity_vnet_1to1_nat_with_srflx_candidate_vs_symmetric_nats(
) -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
// Agent0 is behind 1:1 NAT
let nat_type0 = nat::NatType {
mode: nat::NatMode::Nat1To1,
..Default::default()
};
// Agent1 is behind a symmetric NAT
let nat_type1 = nat::NatType {
mapping_behavior: nat::EndpointDependencyType::EndpointAddrPortDependent,
filtering_behavior: nat::EndpointDependencyType::EndpointAddrPortDependent,
..Default::default()
};
log::debug!("natType0: {:?}", nat_type0);
log::debug!("natType1: {:?}", nat_type1);
let v = build_vnet(nat_type0, nat_type1).await?;
log::debug!("Connecting...");
let a0test_config = AgentTestConfig {
urls: vec![],
nat_1to1_ip_candidate_type: CandidateType::ServerReflexive, // Use 1:1 NAT IP as a srflx candidate
};
let a1test_config = AgentTestConfig {
urls: vec![],
..Default::default()
};
let (_ca, _cb) = pipe_with_vnet(&v, a0test_config, a1test_config).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
log::debug!("Closing...");
v.close().await?;
Ok(())
}
async fn block_until_state_seen(
expected_state: ConnectionState,
state_queue: &mut mpsc::Receiver<ConnectionState>,
) {
while let Some(s) = state_queue.recv().await {
if s == expected_state {
return;
}
}
}
// test_disconnected_to_connected asserts that an agent can go to disconnected, and then return to connected successfully
#[tokio::test]
async fn test_disconnected_to_connected() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
// Create a network with two interfaces
let wan = router::Router::new(router::RouterConfig {
cidr: "0.0.0.0/0".to_owned(),
..Default::default()
})?;
let drop_all_data = Arc::new(AtomicU64::new(0));
let drop_all_data2 = Arc::clone(&drop_all_data);
wan.add_chunk_filter(Box::new(move |_c: &(dyn Chunk + Send + Sync)| -> bool {
drop_all_data2.load(Ordering::SeqCst) != 1
}))
.await;
let wan = Arc::new(Mutex::new(wan));
let net0 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec!["192.168.0.1".to_owned()],
..Default::default()
})));
let net1 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec!["192.168.0.2".to_owned()],
..Default::default()
})));
connect_net2router(&net0, &wan).await?;
connect_net2router(&net1, &wan).await?;
start_router(&wan).await?;
let disconnected_timeout = Duration::from_secs(1);
let keepalive_interval = Duration::from_millis(20);
// Create two agents and connect them
let controlling_agent = Arc::new(
Agent::new(AgentConfig {
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(Arc::clone(&net0)),
disconnected_timeout: Some(disconnected_timeout),
keepalive_interval: Some(keepalive_interval),
check_interval: keepalive_interval,
..Default::default()
})
.await?,
);
let controlled_agent = Arc::new(
Agent::new(AgentConfig {
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(Arc::clone(&net1)),
disconnected_timeout: Some(disconnected_timeout),
keepalive_interval: Some(keepalive_interval),
check_interval: keepalive_interval,
..Default::default()
})
.await?,
);
let (controlling_state_changes_tx, mut controlling_state_changes_rx) =
mpsc::channel::<ConnectionState>(100);
let controlling_state_changes_tx = Arc::new(controlling_state_changes_tx);
controlling_agent
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let controlling_state_changes_tx_clone = Arc::clone(&controlling_state_changes_tx);
Box::pin(async move {
let _ = controlling_state_changes_tx_clone.try_send(c);
})
}))
.await;
let (controlled_state_changes_tx, mut controlled_state_changes_rx) =
mpsc::channel::<ConnectionState>(100);
let controlled_state_changes_tx = Arc::new(controlled_state_changes_tx);
controlled_agent
.on_connection_state_change(Box::new(move |c: ConnectionState| {
let controlled_state_changes_tx_clone = Arc::clone(&controlled_state_changes_tx);
Box::pin(async move {
let _ = controlled_state_changes_tx_clone.try_send(c);
})
}))
.await;
connect_with_vnet(&controlling_agent, &controlled_agent).await?;
// Assert we have gone to connected
block_until_state_seen(
ConnectionState::Connected,
&mut controlling_state_changes_rx,
)
.await;
block_until_state_seen(ConnectionState::Connected, &mut controlled_state_changes_rx).await;
// Drop all packets, and block until we have gone to disconnected
drop_all_data.store(1, Ordering::SeqCst);
block_until_state_seen(
ConnectionState::Disconnected,
&mut controlling_state_changes_rx,
)
.await;
block_until_state_seen(
ConnectionState::Disconnected,
&mut controlled_state_changes_rx,
)
.await;
// Allow all packets through again, block until we have gone to connected
drop_all_data.store(0, Ordering::SeqCst);
block_until_state_seen(
ConnectionState::Connected,
&mut controlling_state_changes_rx,
)
.await;
block_until_state_seen(ConnectionState::Connected, &mut controlled_state_changes_rx).await;
{
let mut w = wan.lock().await;
w.stop().await?;
}
controlling_agent.close().await?;
controlled_agent.close().await?;
Ok(())
}
//use std::io::Write;
// Agent.Write should use the best valid pair if a selected pair is not yet available
#[tokio::test]
async fn test_write_use_valid_pair() -> Result<(), Error> {
/*env_logger::Builder::new()
.format(|buf, record| {
writeln!(
buf,
"{}:{} [{}] {} - {}",
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.level(),
chrono::Local::now().format("%H:%M:%S.%6f"),
record.args()
)
})
.filter(None, log::LevelFilter::Trace)
.init();*/
// Create a network with two interfaces
let wan = router::Router::new(router::RouterConfig {
cidr: "0.0.0.0/0".to_owned(),
..Default::default()
})?;
wan.add_chunk_filter(Box::new(move |c: &(dyn Chunk + Send + Sync)| -> bool {
let raw = c.user_data();
if stun::message::is_message(&raw) {
let mut m = stun::message::Message {
raw,
..Default::default()
};
let result = m.decode();
if result.is_err() | m.contains(stun::attributes::ATTR_USE_CANDIDATE) {
return false;
}
}
true
}))
.await;
let wan = Arc::new(Mutex::new(wan));
let net0 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec!["192.168.0.1".to_owned()],
..Default::default()
})));
let net1 = Arc::new(net::Net::new(Some(net::NetConfig {
static_ips: vec!["192.168.0.2".to_owned()],
..Default::default()
})));
connect_net2router(&net0, &wan).await?;
connect_net2router(&net1, &wan).await?;
start_router(&wan).await?;
// Create two agents and connect them
let controlling_agent = Arc::new(
Agent::new(AgentConfig {
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(Arc::clone(&net0)),
..Default::default()
})
.await?,
);
let controlled_agent = Arc::new(
Agent::new(AgentConfig {
network_types: supported_network_types(),
multicast_dns_mode: MulticastDnsMode::Disabled,
net: Some(Arc::clone(&net1)),
..Default::default()
})
.await?,
);
gather_and_exchange_candidates(&controlling_agent, &controlled_agent).await?;
let (controlling_ufrag, controlling_pwd) = controlling_agent.get_local_user_credentials().await;
let (controlled_ufrag, controlled_pwd) = controlled_agent.get_local_user_credentials().await;
let controlling_agent_tx = Arc::clone(&controlling_agent);
tokio::spawn(async move {
let test_message = "Test Message";
let controlling_agent_conn = {
let agent_internal = Arc::clone(&controlling_agent_tx.agent_internal);
let mut ai = controlling_agent_tx.agent_internal.lock().await;
ai.start_connectivity_checks(agent_internal, true, controlled_ufrag, controlled_pwd)
.await?;
Arc::clone(&ai.agent_conn) as Arc<dyn Conn + Send + Sync>
};
log::debug!("controlling_agent start_connectivity_checks done...");
loop {
let result = controlling_agent_conn.send(test_message.as_bytes()).await;
if result.is_err() {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
Ok::<(), Error>(())
});
let controlled_agent_conn = {
let agent_internal = Arc::clone(&controlled_agent.agent_internal);
let mut ai = controlled_agent.agent_internal.lock().await;
ai.start_connectivity_checks(agent_internal, false, controlling_ufrag, controlling_pwd)
.await?;
Arc::clone(&ai.agent_conn) as Arc<dyn Conn + Send + Sync>
};
log::debug!("controlled_agent start_connectivity_checks done...");
let test_message = "Test Message";
let mut read_buf = vec![0u8; test_message.as_bytes().len()];
controlled_agent_conn.recv(&mut read_buf).await?;
assert_eq!(read_buf, test_message.as_bytes(), "should match");
{
let mut w = wan.lock().await;
w.stop().await?;
}
controlling_agent.close().await?;
controlled_agent.close().await?;
Ok(())
}
|
use std::collections::HashMap;
use std::collections::HashSet;
use serde::{Serialize, Deserialize};
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum PieceKind {
King,
Queen,
Rook,
Bishop,
Knight,
Pawn,
}
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum Color {
Black,
White,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Piece {
pub kind: PieceKind,
pub color: Color,
pub has_moved: bool,
}
impl Piece {
pub fn new(kind: PieceKind, color: Color) -> Piece {
Piece { kind, color, has_moved: false }
}
pub fn get_pretty_str(&self) -> String {
match self.color {
Color::White => {
match self.kind {
PieceKind::King => String::from("♔"),
PieceKind::Queen => String::from("♕"),
PieceKind::Rook => String::from("♖"),
PieceKind::Bishop => String::from("♗"),
PieceKind::Knight => String::from("♘"),
PieceKind::Pawn => String::from("♙"),
}
}
Color::Black => {
match self.kind {
PieceKind::King => String::from("♚"),
PieceKind::Queen => String::from("♛"),
PieceKind::Rook => String::from("♜"),
PieceKind::Bishop => String::from("♝"),
PieceKind::Knight => String::from("♞"),
PieceKind::Pawn => String::from("♟︎"),
}
}
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub struct Position {
pub row: i32,
pub col: i32,
}
impl Position {
pub fn new(row: i32, col: i32) -> Position {
Position { row, col }
}
pub fn add(p1: &Position, p2: &Position) -> Position {
Position::new(p1.row.clone() + p2.row.clone(), p1.col.clone() + p2.col.clone())
}
pub fn yield_all_inverse_positions(&self) -> Vec<Position> {
let scalars = vec![-1, 1];
let mut set = HashSet::new();
for i in scalars.iter() {
for j in scalars.iter() {
let row = i * self.row.clone();
let col = j * self.col.clone();
set.insert(Position::new(row, col));
}
}
set.iter().map(|x| x.clone()).collect()
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Board {
size: i32,
board: HashMap<Position, Piece>,
}
impl Board {
pub fn new(size: i32) -> Result<Board, String> {
if size < 0 {
Err("cannot have a negative size".to_string())
} else {
Ok(Board {
size: size,
board: HashMap::new(),
})
}
}
pub fn get_piece_positions(&self) -> &HashMap<Position, Piece> {
&self.board
}
pub fn fill(&mut self, row: Option<i32>, column: Option<i32>,
piece: Piece) -> Result<(), String> {
let mut update_positions = vec![];
match row {
Some(r_index) => match column {
Some(c_index) => update_positions.push(Position::new(r_index, c_index)),
None => {
for i in 0..self.size {
update_positions.push(Position::new(r_index, i));
}
}
},
None => match column {
Some(c_index) => {
for i in 0..self.size {
update_positions.push(Position::new(i, c_index));
update_positions.push(Position::new(i, c_index));
}
}
None => (),
},
}
for pos in update_positions.iter() {
self.set_space(pos, Some(piece.clone()))?;
}
Ok(())
}
pub fn populate(&mut self, setup_map: HashMap<Position, Piece>) -> Result<(), String>{
for (pos, piece) in setup_map {
self.set_space(&pos, Some(piece))?;
}
Ok(())
}
pub fn move_piece(&mut self, from: &Position, to: &Position) -> Result<Option<Piece>, String> {
match self.board.remove(from) {
Option::None => Err("The from space does not contain a piece to move".to_string()),
Option::Some(mut from_piece) => {
from_piece.has_moved = true;
let res = match self.set_space(to, Some(from_piece))? {
Option::None => Ok(Option::None),
Option::Some(to_piece) => Ok(Option::Some(to_piece))
};
res
}
}
}
pub fn get_space(&self, p: &Position) -> Result<Option<&Piece>, String> {
self.validate_position(p)?;
Ok(self.board.get(p))
}
pub fn is_empty_space(&self, p: &Position) -> bool {
match self.get_space(p) {
Ok(Option::None) => true,
_ => false,
}
}
pub fn pretty(&self) -> String {
let mut res = String::new();
res.push_str(&format!("{}\n", &self.get_chess_row_boarder_string()));
for row in 0..self.size {
let mut row_string = String::from("|");
for col in 0..self.size {
let symbol = match self.board.get(&Position::new(row, col)) {
Option::None => String::from(" "),
Option::Some(piece) => piece.get_pretty_str()
};
row_string.push_str(" ");
row_string.push_str(&symbol);
if col < self.size {
row_string.push_str(" |");
}
}
res.push_str(&format!("{}\n", &row_string));
res.push_str(&format!("{}\n", &self.get_chess_row_boarder_string()));
}
res
}
pub fn pretty_print(&self) {
println!("{}", &self.pretty());
}
pub fn get_size(&self) -> i32 {
self.size
}
fn get_chess_row_boarder_string(&self) -> String {
format!("{}", "------".repeat(self.size as usize))
}
fn set_space(&mut self, p: &Position, piece: Option<Piece>) -> Result<Option<Piece>, String> {
self.validate_position(p)?;
match piece {
Option::None => Ok(self.board.remove(p)),
Option::Some(piece) => Ok(self.board.insert(p.clone(), piece))
}
}
pub fn validate_position(&self, p: &Position) -> Result<(), String> {
if Board::is_out_of_bounds(p.col, 0, self.size)
|| Board::is_out_of_bounds(p.row, 0, self.size) {
Err(String::from("Index out of bounds"))
} else {
Ok(())
}
}
fn is_out_of_bounds<T: Ord>(val: T, lower: T, upper: T) -> bool {
val < lower || val >= upper
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_board() -> Result<(), String> {
let mut b = Board::new(8)?;
let pos = Position::new(0, 1);
let mut op = b.get_space(&pos)?;
assert_eq!(None, op);
b.fill(None, Some(1), Piece::new(PieceKind::Pawn, Color::White))?;
op = b.get_space(&pos)?;
assert_eq!(
Some(&Piece { kind: PieceKind::Pawn, color: Color::White, has_moved: false }),
op
);
b.set_space(&pos, None)?;
op = b.get_space(&pos)?;
assert_eq!(None, op);
b.fill(Some(1), None, Piece::new(PieceKind::Pawn, Color::Black))?;
b.pretty_print();
Ok(())
}
}
|
use nix::unistd::*;
use super::process::Process;
impl Process {
pub(crate) fn pipe_first_connect(&self) -> Result<(), String> {
match self.get_pipe(self.len_pipes()) {
Some(pipes) => {
match dup2(pipes.1, 1) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe first dup2 error"));
}
}
match self.close_pipe(pipes) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe first close error"));
}
}
}
None => {
return Err(format!("pipe first missing"));
}
}
return Ok(());
}
pub(crate) fn pipe_end_connect(&self) -> Result<(), String> {
match self.get_pipe(self.len_pipes()) {
Some(pipes) => {
match dup2(pipes.0, 0) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe close dup2 error"));
}
}
match self.close_pipe(pipes) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe end close error"));
}
}
}
None => {
return Err(format!("pipe end missing"));
}
}
return Ok(());
}
pub(crate) fn pipe_route_connect(&self) -> Result<(), String> {
match self.get_pipe(self.len_pipes() - 1) {
Some(pipes) => {
match dup2(pipes.0, 0) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe route dup2 error"));
}
}
match self.close_pipe(pipes) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe route close error"));
}
}
}
None => {
return Err(format!("pipe route missinag"));
}
}
match self.get_pipe(self.len_pipes()) {
Some(pipes) => {
match dup2(pipes.1, 1) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe route dup2 error"));
}
}
match self.close_pipe(pipes) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe route close error"));
}
}
}
None => {
return Err(format!("pipe route missinag"));
}
}
return Ok(());
}
pub(crate) fn pearent_connect_end(&mut self) -> Result<(), String> {
match self.get_pipe(0) {
Some(pipes) => match self.close_pipe(pipes) {
Ok(_) => {}
Err(_) => {
return Err(format!("pearent end close error"));
}
},
None => {
return Err(format!("pipe missing"));
}
}
self.deque_pipe();
return Ok(());
}
pub(crate) fn close_pipe(&self, pipe: &(i32, i32)) -> Result<(), String> {
match close(pipe.0) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe close error"));
}
}
match close(pipe.1) {
Ok(_) => {}
Err(_) => {
return Err(format!("pipe clsoe error"));
}
}
return Ok(());
}
}
|
//! # Orderbook
//!
//! A module to trade shares using a naive on-chain orderbook.
//!
//! ## Overview
//!
//! TODO
//!
//! ## Interface
//!
//! ### Dispatches
//!
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use frame_support::traits::{Currency, ExistenceRequirement, ReservableCurrency, WithdrawReasons};
use frame_support::{decl_error, decl_event, decl_module, decl_storage, ensure};
// use frame_support::weights::Weight;
use frame_system::{self as system, ensure_signed};
use sp_runtime::traits::{CheckedMul, CheckedSub, Hash, Zero};
use sp_runtime::RuntimeDebug;
use sp_std::cmp;
use sp_std::vec::Vec;
use zrml_traits::shares::{ReservableShares, Shares};
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
fn remove_item<I: cmp::PartialEq + Copy>(items: &mut Vec<I>, item: I) {
let pos = items.iter().position(|&i| i == item).unwrap();
items.swap_remove(pos);
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)]
pub enum OrderSide {
Bid,
Ask,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)]
pub struct Order<AccountId, Balance, Hash> {
side: OrderSide,
maker: AccountId,
taker: Option<AccountId>,
share_id: Hash,
total: Balance,
price: Balance,
filled: Balance,
}
impl<AccountId, Balance: CheckedSub + CheckedMul, Hash> Order<AccountId, Balance, Hash> {
pub fn cost(&self) -> Balance {
self.total
.checked_sub(&self.filled)
.unwrap()
.checked_mul(&self.price)
.unwrap()
}
}
type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
pub trait Trait: frame_system::Trait {
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
type Currency: ReservableCurrency<Self::AccountId>;
type Shares: Shares<Self::AccountId, Self::Hash>
+ ReservableShares<Self::AccountId, Self::Hash, Balance = BalanceOf<Self>>;
}
decl_storage! {
trait Store for Module<T: Trait> as Orderbook {
Bids get(fn bids): map hasher(blake2_128_concat) T::Hash => Vec<T::Hash>;
Asks get(fn asks): map hasher(blake2_128_concat) T::Hash => Vec<T::Hash>;
OrderData get(fn order_data): map hasher(blake2_128_concat) T::Hash =>
Option<Order<T::AccountId, BalanceOf<T>, T::Hash>>;
Nonce get(fn nonce): u64;
}
}
decl_event! {
pub enum Event<T>
where
AccountId = <T as frame_system::Trait>::AccountId,
Hash = <T as frame_system::Trait>::Hash,
{
/// [maker, order_hash]
OrderMade(AccountId, Hash),
/// [taker, order_hash]
OrderFilled(AccountId, Hash),
}
}
decl_error! {
pub enum Error for Module<T: Trait> {
OrderDoesNotExist,
OrderAlreadyTaken,
InsufficientBalance,
NotOrderCreator,
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
type Error = Error<T>;
fn deposit_event() = default;
#[weight = 0]
fn make_order(
origin,
share_id: T::Hash,
side: OrderSide,
amount: BalanceOf<T>,
price: BalanceOf<T>,
) {
let sender = ensure_signed(origin)?;
// Only store nonce in memory for now.
let nonce = Nonce::get();
let hash = Self::order_hash(&sender, share_id.clone(), nonce);
// Love the smell of fresh orders in the morning.
let order = Order {
side: side.clone(),
maker: sender.clone(),
taker: None,
share_id,
total: amount,
price,
filled: Zero::zero(),
};
let cost = order.cost();
match side {
OrderSide::Bid => {
ensure!(
T::Currency::can_reserve(&sender, cost),
Error::<T>::InsufficientBalance,
);
<Bids<T>>::mutate(share_id, |b: &mut Vec<T::Hash>| {
b.push(hash.clone());
});
T::Currency::reserve(&sender, cost)?;
}
OrderSide::Ask => {
ensure!(
T::Shares::can_reserve(share_id, &sender, amount),
Error::<T>::InsufficientBalance,
);
<Asks<T>>::mutate(share_id, |a| {
a.push(hash.clone());
});
T::Shares::reserve(share_id, &sender, amount)?;
}
}
<OrderData<T>>::insert(hash, order);
<Nonce>::mutate(|n| *n += 1);
Self::deposit_event(RawEvent::OrderMade(sender, hash))
}
#[weight = 0]
fn fill_order(origin, order_hash: T::Hash) {
let sender = ensure_signed(origin)?;
if let Some(order_data) = Self::order_data(order_hash) {
ensure!(order_data.taker.is_none(), Error::<T>::OrderAlreadyTaken);
let cost = order_data.cost();
let share_id = order_data.share_id;
let maker = order_data.maker;
match order_data.side {
OrderSide::Bid => {
T::Shares::ensure_can_withdraw(share_id, &sender, order_data.total)?;
T::Currency::unreserve(&maker, cost);
T::Currency::transfer(&maker, &sender, cost, ExistenceRequirement::AllowDeath)?;
T::Shares::transfer(share_id, &sender, &maker, order_data.total)?;
}
OrderSide::Ask => {
T::Currency::ensure_can_withdraw(&sender, cost, WithdrawReasons::all(), Zero::zero())?;
T::Shares::unreserve(share_id, &maker, order_data.total)?;
T::Shares::transfer(share_id, &maker, &sender, order_data.total)?;
T::Currency::transfer(&sender, &maker, cost, ExistenceRequirement::AllowDeath)?;
}
}
Self::deposit_event(RawEvent::OrderFilled(sender, order_hash));
} else {
Err(Error::<T>::OrderDoesNotExist)?;
}
}
#[weight = 0]
fn cancel_order(origin, share_id: T::Hash, order_hash: T::Hash) {
let sender = ensure_signed(origin)?;
if let Some(order_data) = Self::order_data(order_hash) {
ensure!(
sender == order_data.maker,
Error::<T>::NotOrderCreator
);
match order_data.side {
OrderSide::Bid => {
let mut bids = Self::bids(share_id);
remove_item::<T::Hash>(&mut bids, order_hash);
<Bids<T>>::insert(share_id, bids);
}
OrderSide::Ask => {
let mut asks = Self::asks(share_id);
remove_item::<T::Hash>(&mut asks, order_hash);
<Asks<T>>::insert(share_id, asks);
}
}
<OrderData<T>>::remove(order_hash);
} else {
Err(Error::<T>::OrderDoesNotExist)?;
}
}
}
}
impl<T: Trait> Module<T> {
pub fn order_hash(creator: &T::AccountId, share_id: T::Hash, nonce: u64) -> T::Hash {
(&creator, share_id, nonce).using_encoded(<T as frame_system::Trait>::Hashing::hash)
}
}
|
use crate::*;
#[derive(PartialEq, Debug, Clone)]
pub enum Expr {
FuncApp {
func_name: String,
args: Vec<TypedExpr>,
},
Constant(Literal),
OpExp {
lhs: Box<TypedExpr>,
rhs: Box<TypedExpr>,
op: Operator,
},
// just a name that gets looked up in the namespace, with precedence to locally scoped vars
VarExp(String),
TupleExp(Vec<TypedExpr>),
}
impl Expr {
/*
fn arity(&self) -> TupleArity {
match self {
Expr::TupleExp(ref tup) => tup.len(),
Expr::FuncApp {
ref func_name,
args,
..
} => {
// args + return type is the arity
todo!("Maybe move this to typed expr? need return type for arity")
}
Expr::Constant(..) => 1,
Expr::VarExp { .. } => todo!("check arity of variable, or assign it here"),
Expr::OpExp { .. } => 1, // I think this is correct
}
}
*/
}
|
#[doc = "Reader of register SPINLOCK12"]
pub type R = crate::R<u32, super::SPINLOCK12>;
impl R {}
|
use pt_server::{
config::Config,
db,
logger::{create_logger, LoggerExt},
server,
};
#[actix_web::main]
async fn main() -> anyhow::Result<()> {
let config = Config::from_env()?;
let db_pool = db::connect(&config).await?;
let log = create_logger(&config).with_scope("http-server");
server::run(config, log, db_pool).await
}
|
mod lib;
#[derive(Debug)]
struct gen<T, U> {
name: T,
age: U,
}
impl<T, U> gen<T, U> {
fn test_knowlege(&self) -> &T {
&self.name
}
fn test_knowlege1(&self) -> &U {
&self.age
}
}
impl gen<&str, i32> {
fn find_age_times_10(&self) -> i32 {
self.age * 10
}
}
#[derive(Debug)]
struct point<T, U> {
name: T,
age: U,
}
impl<T, U> point<T, U> {
fn mixup<V, W>(self, other: point<V, W>) -> point<T, W> {
point {
name: self.name,
age: other.age,
}
}
}
fn main() {
let test = gen {
name: "Pratik",
age: 32,
};
println!("{:?}", test.test_knowlege());
println!("{:?}", test.test_knowlege1());
println!("{:?}", test.find_age_times_10());
let p = point {
name: "pt",
age: "pw",
};
let p1 = point {
name: 1,
age: 2,
};
let p3 = p.mixup(p1);
// println!("{:?}", p);
println!("{:?}", p3);
let n = NewsFeed {
location: String::from("india"),
date: String::from("1/2"),
content: String::from("fffff"),
author: String::from("prat"),
};
println!("{}",n.summarize());
notify(&n);
notify_trait_bound(&n);
}
struct NewsFeed {
location: String,
date: String,
content: String,
author: String,
}
impl Summary for NewsFeed {
fn summarize_author(&self) -> String {
format!("Summarising author:: {}, {}", self.location, self.date)
}
}
pub fn notify(item: &impl Summary){
println!(" Notifying:: {}", item.summarize());
}
pub fn notify_trait_bound<T: Summary>(item: &T){
println!(" Notifying trait bound:: {}", item.summarize());
}
pub trait Summary {
fn summarize(&self) -> String{
format!("{}", self.summarize_author())
}
fn summarize_author(&self) -> String;
} |
use std::env;
fn main(){
let target = env::var("TARGET").unwrap();
if target.contains("arm") {
println!("cargo:rustc-link-lib=dylib=mosquitto");
println!("cargo:rustc-link-lib=dylib=crypto");
println!("cargo:rustc-link-lib=dylib=ssl");
println!("cargo:rustc-link-lib=dylib=cares");
println!("cargo:rustc-link-search=all=mosquitto/usr/lib/arm-linux-gnueabihf");
}
}
|
use sqlx::arguments::Arguments;
use sqlx::sqlite::{SqliteArguments, SqliteQueryAs};
use sqlx::SqlitePool;
pub async fn get_last_inserted_id(pool: &SqlitePool) -> Result<i32, sqlx::Error> {
let rec: (i32, ) = sqlx::query_as("SELECT last_insert_rowid()")
.fetch_one(pool)
.await?;
Ok(rec.0)
}
pub struct DynUpdate {
sql: String,
pub bind_values: SqliteArguments,
}
impl DynUpdate {
pub fn new() -> Self {
return DynUpdate {
sql: String::new(),
bind_values: SqliteArguments::default(),
};
}
pub fn add<T>(&mut self, field_name: &str, value: T)
where
T: sqlx::encode::Encode<sqlx::Sqlite> + sqlx::Type<sqlx::Sqlite>,
{
self.sql.push_str(format!(" {} = ?,", field_name).as_str());
self.bind_values.add(value);
}
pub fn add_option<T>(&mut self, field_name: &str, value: Option<T>)
where
T: sqlx::encode::Encode<sqlx::Sqlite> + sqlx::Type<sqlx::Sqlite>,
{
if value.is_some() {
self.add(field_name, value.unwrap());
}
}
pub fn has_updates(&self) -> bool {
return self.sql.len() > 0;
}
pub fn to_query_str(&self, prefix: &str, suffix: &str) -> String {
let mut sql = String::from(prefix);
sql.push_str(self.sql.as_str());
if self.has_updates() {
// remove the last comma
sql.remove(sql.len() - 1);
}
sql.push_str(suffix);
return sql;
}
} |
//! Performance counters and statistics
use std::cmp::max;
use time::{get_time, Timespec};
/// Type that provides counters for the GC to gain some measure of performance.
pub trait StatsLogger: Send {
/// mark start of time
fn mark_start_time(&mut self);
/// mark end of time
fn mark_end_time(&mut self);
/// add a number of milliseconds that the GcThread was asleep
fn add_sleep(&mut self, ms: usize);
/// add a count of dropped objects
fn add_dropped(&mut self, count: usize);
/// give the current heap object count
fn current_heap_size(&mut self, size: usize);
/// print statistics
fn dump_to_stdout(&self);
/// log something to stdout
fn log(&self, string: &str) {
println!("{}", string);
}
}
pub struct DefaultLogger {
max_heap_size: usize,
total_dropped: usize,
drop_iterations: usize,
start_time: Timespec,
stop_time: Timespec,
sleep_time: u64,
}
unsafe impl Send for DefaultLogger {}
impl DefaultLogger {
pub fn new() -> DefaultLogger {
DefaultLogger {
max_heap_size: 0,
total_dropped: 0,
drop_iterations: 0,
start_time: Timespec::new(0, 0),
stop_time: Timespec::new(0, 0),
sleep_time: 0,
}
}
}
impl StatsLogger for DefaultLogger {
fn mark_start_time(&mut self) {
self.start_time = get_time();
}
fn mark_end_time(&mut self) {
self.stop_time = get_time();
}
fn add_sleep(&mut self, ms: usize) {
self.sleep_time += ms as u64;
}
fn add_dropped(&mut self, count: usize) {
self.total_dropped += count;
self.drop_iterations += 1;
}
fn current_heap_size(&mut self, size: usize) {
self.max_heap_size = max(self.max_heap_size, size);
}
fn dump_to_stdout(&self) {
// calculate timing
let total_time = max((self.stop_time - self.start_time).num_milliseconds(), 1);
let active_time = total_time - self.sleep_time as i64;
let percent_active_time = active_time * 100 / total_time;
// calculate drop rate
let dropped_per_second = self.total_dropped as i64 * 1000 / active_time;
println!("max-heap {}; dropped {} (per second {}); active {}/{}ms ({}%)",
self.max_heap_size,
self.total_dropped,
dropped_per_second,
active_time,
total_time,
percent_active_time);
}
}
|
pub mod handling;
pub enum TransformationResult {
Unchanged,
Modified,
Canceled
}
impl TransformationResult {
pub(crate) fn combine(&mut self, other: TransformationResult) -> bool {
match self {
TransformationResult::Unchanged => {
match other {
TransformationResult::Modified => {
*self = TransformationResult::Modified;
}
TransformationResult::Canceled => {
*self = TransformationResult::Canceled;
return true;
}
_ => {}
}
}
TransformationResult::Modified => {
match other {
TransformationResult::Canceled => {
*self = TransformationResult::Canceled;
return true;
}
_ => {}
}
}
TransformationResult::Canceled => {
return true;
}
}
false
}
} |
use amethyst::core::{Hidden, Transform};
use amethyst::ecs::{Entities, Join, ReadStorage, System};
use amethyst::renderer::{Camera, SpriteRender};
use crate::components::{Explored, Init, Intent, Mob, Player, Tile};
#[derive(Default)]
pub struct DebugSystem;
impl<'s> System<'s> for DebugSystem {
type SystemData = (
ReadStorage<'s, Camera>,
ReadStorage<'s, Explored>,
ReadStorage<'s, Hidden>,
ReadStorage<'s, Init>,
ReadStorage<'s, Intent>,
ReadStorage<'s, Mob>,
ReadStorage<'s, Player>,
ReadStorage<'s, SpriteRender>,
ReadStorage<'s, Tile>,
ReadStorage<'s, Transform>,
Entities<'s>
);
fn run(&mut self, (camera, explored, hidden, init, intent, mob, player,
sprite, tile, transform, entities): Self::SystemData) {
for entity in entities.join() {
log::debug!("{:?}: [", entity);
if let Some(c) = camera.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = explored.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = hidden.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = init.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = intent.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = mob.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = player.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = sprite.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = tile.get(entity) {
log::debug!(" {:?}, ", c);
}
if let Some(c) = transform.get(entity) {
log::debug!(" {:?}", c);
}
log::debug!("]");
}
}
}
|
use actix::prelude::*;
use actix::registry::SystemService;
use futures::future::*;
use chrono;
#[cfg(feature = "python")]
use cpython::{FromPyObject, PyDict, PyObject, PyResult, Python};
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum ScriptType {
StreamSpan,
// Python function that can act on a test
// def on_test(test):
// import requests
// import json
// requests.post("https://requestb.in/XXXXXXX", data=json.dumps(test))
StreamTest,
// Python function that can act on a test
// def reports_for_test(test):
// return [{'group': 'TestClass', ''name': test.tags['test.class'], 'category': None}]
ReportFilterTestResult,
// JS script that returns HTML that will be displayed on each test in test detail view
// (test) => '<a href="http://google.com">' + test.name + '</a>'
UITest,
// JS script that returns HTML that will be displayed on each test result in test detail view
// (result, spans) => '<a href="http://spans.com">' + spans.length + ' spans</a>'
UITestResult,
}
impl Default for ScriptType {
fn default() -> Self {
ScriptType::ReportFilterTestResult
}
}
impl From<i32> for ScriptType {
fn from(val: i32) -> ScriptType {
match val {
0 => ScriptType::StreamSpan,
1 => ScriptType::StreamTest,
2 => ScriptType::UITest,
3 => ScriptType::UITestResult,
4 => ScriptType::ReportFilterTestResult,
_ => ScriptType::StreamTest,
}
}
}
impl Into<i32> for ScriptType {
fn into(self) -> i32 {
match self {
ScriptType::StreamSpan => 0,
ScriptType::StreamTest => 1,
ScriptType::UITest => 2,
ScriptType::UITestResult => 3,
ScriptType::ReportFilterTestResult => 4,
}
}
}
impl Into<String> for ScriptType {
fn into(self) -> String {
match self {
ScriptType::StreamSpan => "StreamSpan".to_string(),
ScriptType::StreamTest => "StreamTest".to_string(),
ScriptType::UITest => "UITest".to_string(),
ScriptType::UITestResult => "UITestResult".to_string(),
ScriptType::ReportFilterTestResult => "ReportFilterTestResult".to_string(),
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum ScriptStatus {
Enabled,
Disabled,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct Script {
pub id: Option<String>,
pub name: String,
pub source: String,
pub script_type: ScriptType,
pub date_added: Option<chrono::NaiveDateTime>,
pub status: Option<ScriptStatus>,
}
pub struct Streamer {
scripts: Vec<Script>,
}
impl Actor for Streamer {
type Context = Context<Self>;
}
impl Default for Streamer {
fn default() -> Self {
Streamer { scripts: vec![] }
}
}
impl Supervised for Streamer {}
impl SystemService for Streamer {
fn service_started(&mut self, _ctx: &mut Context<Self>) {
info!("started Streamer")
}
}
#[derive(Message)]
pub struct LoadScripts;
impl Handler<LoadScripts> for Streamer {
type Result = ();
fn handle(&mut self, _msg: LoadScripts, _ctx: &mut Context<Self>) -> Self::Result {
Arbiter::spawn_fn(move || {
crate::DB_READ_EXECUTOR_POOL
.send(crate::db::read::scripts::GetAll(Some(vec![
ScriptType::StreamTest,
ScriptType::ReportFilterTestResult,
])))
.then(|scripts| {
if let Ok(scripts) = scripts {
actix::System::current()
.registry()
.get::<crate::engine::streams::Streamer>()
.do_send(UpdateScripts(scripts));
}
result(Ok(()))
})
})
}
}
#[derive(Message)]
pub struct UpdateScripts(Vec<Script>);
impl Handler<UpdateScripts> for Streamer {
type Result = ();
fn handle(&mut self, msg: UpdateScripts, _ctx: &mut Context<Self>) -> Self::Result {
self.scripts = msg.0;
}
}
#[derive(Message)]
pub struct AddScript(pub Script);
impl Handler<AddScript> for Streamer {
type Result = ();
fn handle(&mut self, msg: AddScript, _ctx: &mut Context<Self>) -> Self::Result {
self.scripts.push(msg.0);
}
}
#[derive(Message)]
pub struct RemoveScript(pub Script);
impl Handler<RemoveScript> for Streamer {
type Result = ();
fn handle(&mut self, msg: RemoveScript, _ctx: &mut Context<Self>) -> Self::Result {
let index = self
.scripts
.iter()
.position(|x| {
(*x.id.clone().expect("script should have an ID"))
== msg.0.id.clone().expect("script should have an ID")
})
.expect("script not found");
self.scripts.remove(index);
}
}
#[derive(Message)]
pub struct UpdateScript(pub Script);
impl Handler<UpdateScript> for Streamer {
type Result = ();
fn handle(&mut self, msg: UpdateScript, _ctx: &mut Context<Self>) -> Self::Result {
let index = self
.scripts
.iter()
.position(|x| {
(*x.id.clone().expect("script should have an ID"))
== msg.0.id.clone().expect("script should have an ID")
})
.expect("script not found");
self.scripts.remove(index);
self.scripts.push(msg.0);
}
}
#[cfg(feature = "python")]
#[derive(Debug)]
struct ReportTarget {
group: String,
name: String,
category: Option<String>,
}
#[cfg(feature = "python")]
impl<'a> FromPyObject<'a> for ReportTarget {
fn extract(py: Python, obj: &'a PyObject) -> PyResult<Self> {
let locals = PyDict::new(py);
locals.set_item(py, "obj", obj).unwrap();
Ok(ReportTarget {
group: py.eval("obj['group']", None, Some(&locals))?.extract(py)?,
name: py.eval("obj['name']", None, Some(&locals))?.extract(py)?,
category: py
.eval("obj['category']", None, Some(&locals))?
.extract(py)?,
})
}
}
#[derive(Message, Debug)]
pub struct Test(pub crate::engine::test_result::TestResult);
impl Handler<Test> for Streamer {
type Result = ();
#[cfg(feature = "python")]
fn handle(&mut self, msg: Test, _ctx: &mut Context<Self>) -> Self::Result {
if self.scripts.len() > 0 {
let gil = Python::acquire_gil();
let py = gil.python();
let locals = PyDict::new(py);
locals.set_item(py, "test", msg.0.clone()).unwrap();
let stream_test_script: Vec<&Script> = self
.scripts
.iter()
.filter(|script| match script.script_type {
ScriptType::StreamTest => true,
_ => false,
})
.collect();
for script in stream_test_script {
match py.run(script.source.as_ref(), None, Some(&locals)) {
Ok(_) => match py.eval("on_test(test)", None, Some(&locals)) {
Ok(_) => (),
Err(err) => warn!(
"error executing python script {}: {:?}",
script.id.clone().unwrap(),
err
), // TODO disable script after failure
},
_ => (),
}
}
let report_filter_test_script: Vec<&Script> = self
.scripts
.iter()
.filter(|script| match script.script_type {
ScriptType::ReportFilterTestResult => true,
_ => false,
})
.collect();
for script in report_filter_test_script {
match py.run(script.source.as_ref(), None, Some(&locals)) {
Ok(_) => match py.eval("reports_for_test(test)", None, Some(&locals)) {
Ok(py_reports) => {
let reports = py_reports.extract::<Vec<ReportTarget>>(py);
if let Ok(reports) = reports {
for report in reports {
actix::System::current()
.registry()
.get::<::engine::report::Reporter>()
.do_send(::engine::report::ResultForReport {
report_group: report.group,
report_name: report.name,
category: report.category,
result: msg.0.clone(),
})
}
}
}
Err(err) => warn!(
"error executing python script {}: {:?}",
script.id.clone().unwrap(),
err
), // TODO disable script after failure
},
_ => (),
}
}
}
}
#[cfg(not(feature = "python"))]
fn handle(&mut self, _msg: Test, _ctx: &mut Context<Self>) -> Self::Result {}
}
|
fn main() {
{
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{} {}", hello, world);
// string slices are a pointer and a length
let _slice = &s[..2];
let _slice = &s[7..];
}
// a string with outstanding slices *cannot* be modified
{
let mut s = String::from("hello world");
let word = first_word(&s);
// mutable borrow is not allowed!!!
s.clear(); // error!
println!("the first word is: {}", word);
}
{
let my_string = String::from("hello world");
// first_word works on slices of `String`s
let _word = first_word(&my_string[..]);
let my_string_literal = "hello world";
// first_word works on slices of string literals
let _word = first_word(&my_string_literal[..]);
// Because string literals *are* string slices already,
// this works too, without the slice syntax!
let _word = first_word(my_string_literal);
}
}
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
} |
use super::*;
use roaring::RoaringBitmap;
/// # Drop.
impl Graph {
/// Return a roaringbitmap with the node ids to keep.
///
/// If both node\_names and node\_types are specified the result will be the
/// union of both queries.
///
/// # Arguments
/// * `node_names` : Option<Vec<String>> - The nodes to keep as strings
/// * `node_types` : Option<Vec<String>> - The nodes types to keep as strings
///
pub(crate) fn get_filter_bitmap(
&self,
node_names: Option<Vec<String>>,
node_types: Option<Vec<String>>
) -> Result<Option<RoaringBitmap>, String> {
let mut node_ids = RoaringBitmap::new();
if let Some(ns) = node_names {
node_ids.extend(
ns.iter()
.map(|node_name| self.get_node_id(node_name))
.collect::<Result<Vec<NodeT>, String>>()?,
);
}
if let Some(ndt) = node_types {
if !self.has_node_types(){
return Err("The current graph has no node types.".to_owned());
}
let node_types_ids = self.translate_node_types(ndt)?;
node_ids.extend(self.get_nodes_iter().filter_map(|(node_id, node_type)| {
if node_types_ids.contains(&node_type.unwrap()) {
return Some(node_id);
}
None
}));
}
Ok(optionify!(node_ids))
}
} |
use cosmwasm_std::{Decimal, HumanAddr, Uint128};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use terraswap::asset::Asset;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InitMsg {
pub terraswap_factory: HumanAddr,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub enum HandleMsg {
bond {
contract: HumanAddr,
assets: [Asset; 2],
slippage_tolerance: Option<Decimal>,
compound_rate: Option<Decimal>,
},
bond_hook {
contract: HumanAddr,
asset_token: HumanAddr,
staking_token: HumanAddr,
staker_addr: HumanAddr,
prev_staking_token_amount: Uint128,
compound_rate: Option<Decimal>,
},
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct QueryMsg {}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct MigrateMsg {}
|
//! Flash memory
//!
//! This currently implements basic chip startup-related functions. You will probably not need to
//! use this interface directly, as the Flash peripheral is mostly configured by `Rcc::freeze`
use core::ptr;
use crate::common::Constrain;
use crate::power::{self, Power};
use crate::stm32l0x1::{flash, FLASH};
use crate::time::Hertz;
use fhal::flash::{Locking, WriteErase};
mod private {
/// The Sealed trait prevents other crates from implementing helper traits defined here
pub trait Sealed {}
impl Sealed for crate::power::VCoreRange1 {}
impl Sealed for crate::power::VCoreRange2 {}
impl Sealed for crate::power::VCoreRange3 {}
}
impl Constrain<Flash> for FLASH {
fn constrain(self) -> Flash {
Flash {
acr: ACR(()),
sr: SR(()),
pecr: PECR(()),
pekeyr: PEKEYR(()),
prgkeyr: PRGKEYR(()),
}
}
}
#[derive(Debug)]
/// Non-error flash read and write statuses
pub enum FlashStatus {
/// Memory interface busy
///
/// Write/erase operations are in progress.
Busy,
/// End of program
///
/// This bit is set by hardware at the end of a write or erase operation when the operation has
/// not been aborted.
Done,
/// Ready for read and write/erase operations
Ready,
/// High voltage is executing a write/erase operation in the NVM
HVOngoing,
}
#[derive(Debug)]
/// Error states
pub enum FlashError {
/// The data eeprom and FLASH_PECR register is locked
Locked,
/// Write protection error
///
/// This bit is set by hardware when an address to be programmed or erased is write-protected.
WriteProtect,
/// Programming alignment error
///
/// This bit is set by hardware when an alignment error has happened: the first word of a
/// half-page operation is not aligned to a half-page, or one of the following words in a
/// half-page operation does not belong to the same half-page as the first word.
Alignment,
/// Size error
///
/// This bit is set by hardware when the size of data to program is not correct.
Size,
/// Read protection error
///
/// This bit is set by hardware when the user tries to read an area protected by PcROP.
ReadProtection,
/// The write operation is attempting to write to a not-erased region
///
/// This bit is set by hardware when a program in the Flash program or System Memory tries to
/// overwrite a not-zero area.
NotZero,
/// A write/erase operation aborted to perform a fetch.
///
/// This bit is set by hardware when a write/erase operation is aborted to perform a fetch.
/// This is not a real error, but it is used to inform that the write/erase operation did not
/// execute.
FetchAbort,
/// Some otherwise unknown error has happened or an unexpected status has arisen
Unknown,
}
impl FlashError {
/// Helper method to clear error bits raised
pub fn clear(&self, sr: &mut SR) {
match self {
FlashError::WriteProtect => sr.inner().modify(|_, w| w.wrperr().set_bit()),
FlashError::Alignment => sr.inner().modify(|_, w| w.pgaerr().set_bit()),
FlashError::Size => sr.inner().modify(|_, w| w.sizerr().set_bit()),
FlashError::ReadProtection => sr.inner().modify(|_, w| w.rderr().set_bit()),
FlashError::NotZero => sr.inner().modify(|_, w| w.notzeroerr().set_bit()),
FlashError::FetchAbort => sr.inner().modify(|_, w| w.fwwerr().set_bit()),
_ => {}
};
}
}
/// A constrained FLASH peripheral
pub struct Flash {
/// FLASH_ACR
acr: ACR,
/// FLASH_SR
sr: SR,
/// FLASH_PECR
pecr: PECR,
/// FLASH_PEKEYR
pekeyr: PEKEYR,
/// FLASH_PRGKEYR
prgkeyr: PRGKEYR,
}
impl Flash {
/// Sets the clock cycle latency for the flash peripheral based on power level and clock speed
pub fn set_latency<VDD, VCORE, RTC>(&mut self, sysclk: Hertz, _pwr: &Power<VDD, VCORE, RTC>)
where
VCORE: Latency,
{
unsafe {
VCORE::latency(sysclk).set(&mut self.acr);
}
}
/// Retrieves the clock cycle latency based on current register settings
pub fn get_latency(&mut self) -> FlashLatency {
match self.acr.acr().read().latency().bit() {
true => FlashLatency::_1_Clk,
false => FlashLatency::_0_Clk,
}
}
/// Immediately write `value` to `address`
pub unsafe fn program_word_immediate(&mut self, address: usize, value: u32) {
ptr::write_volatile(address as *mut u32, value);
}
}
/// Couples the necessary flash latency to the VCore power range of the cpu
pub trait Latency: private::Sealed {
/// Taken from fig. 11 "Performance versus Vdd and Vcore range"
fn latency(f: Hertz) -> FlashLatency;
}
impl Latency for power::VCoreRange1 {
fn latency(f: Hertz) -> FlashLatency {
if f.0 > 16_000_000 {
FlashLatency::_1_Clk
} else {
FlashLatency::_0_Clk
}
}
}
impl Latency for power::VCoreRange2 {
fn latency(f: Hertz) -> FlashLatency {
if f.0 > 8_000_000 {
FlashLatency::_1_Clk
} else {
FlashLatency::_0_Clk
}
}
}
impl Latency for power::VCoreRange3 {
fn latency(_: Hertz) -> FlashLatency {
FlashLatency::_0_Clk
}
}
#[allow(non_camel_case_types)]
/// Flash latencies available for this chip
pub enum FlashLatency {
/// Flash reads have a latency of 1 clock cycle
_1_Clk,
/// Flash reads have a latency of 0 clock cycles
_0_Clk,
}
impl FlashLatency {
/// Use the ACR register to set the flash value according to the variant
///
/// This function is unsafe because it does not (cannot) check to see that the latency value
/// being set is appropriate for the current VCore range and clock speed of the chip
pub unsafe fn set(&self, acr: &mut ACR) {
match self {
FlashLatency::_1_Clk => acr.flash_latency_1(),
FlashLatency::_0_Clk => acr.flash_latency_0(),
};
}
}
/// Opaque access control register
pub struct ACR(());
impl ACR {
/// Direct access to FLASH_ACR
pub(crate) fn acr(&mut self) -> &flash::ACR {
// NOTE(unsafe) this proxy grants exclusive access to this register
unsafe { &(*FLASH::ptr()).acr }
}
/// Set the flash latency to 1 clock cycle
pub(crate) fn flash_latency_1(&mut self) -> FlashLatency {
self.acr().modify(|_, w| w.latency().set_bit());
while self.acr().read().latency().bit_is_clear() {}
FlashLatency::_1_Clk
}
/// Set the flash latency to 0 clock cycles
pub(crate) fn flash_latency_0(&mut self) -> FlashLatency {
self.acr().modify(|_, w| w.latency().clear_bit());
while self.acr().read().latency().bit_is_set() {}
FlashLatency::_0_Clk
}
}
/// Status register
pub struct SR(());
impl SR {
/// Retrieve a pointer to the SR register
pub(crate) fn inner(&self) -> &flash::SR {
unsafe { &(*FLASH::ptr()).sr }
}
/// Is the memory interface busy?
pub fn is_busy(&self) -> bool {
self.inner().read().bsy().bit_is_set()
}
}
/// Program and erase control register
pub struct PECR(());
impl PECR {
/// Retrieve a pointer to the PECR register
fn inner() -> &'static flash::PECR {
unsafe { &(*FLASH::ptr()).pecr }
}
/// Is is FLASH_PECR register locked?
pub fn is_pecr_locked(&self) -> bool {
Self::inner().read().pelock().bit_is_set()
}
/// Is program memory locked?
pub fn is_prgmem_locked(&self) -> bool {
Self::inner().read().prglock().bit_is_set()
}
/// Lock the PECR
pub fn lock(&mut self) {
Self::inner().modify(|_, w| w.pelock().set_bit());
}
/// Enable flash to be erased (requires that PECR is unlocked)
pub fn enable_erase(&mut self) -> Result<(), FlashError> {
if self.is_pecr_locked() {
Err(FlashError::Locked)
} else {
Self::inner().modify(|_, w| w.erase().set_bit().prog().set_bit());
Ok(())
}
}
/// Disable writes to flash (requires that PECR is unlocked)
pub fn disable_erase(&mut self) -> Result<(), FlashError> {
if self.is_pecr_locked() {
Err(FlashError::Locked)
} else {
Self::inner().modify(|_, w| w.erase().clear_bit().prog().clear_bit());
Ok(())
}
}
}
/// PECR unlock key register
pub struct PEKEYR(());
impl PEKEYR {
/// Retrieve a pointer to the PEKEYR register
pub(crate) fn inner(&mut self) -> &flash::PEKEYR {
unsafe { &(*FLASH::ptr()).pekeyr }
}
}
/// Program and erase key register
pub struct PRGKEYR(());
impl PRGKEYR {
/// Retrieve a pointer tot he PRGKEYR register
pub(crate) fn inner(&mut self) -> &flash::PRGKEYR {
unsafe { &(*FLASH::ptr()).prgkeyr }
}
}
/// First key value to unlock data EEPROM and the PECR register (see 3.3.4)
const PEKEY1: u32 = 0x89ABCDEF;
/// Second key value to unlock data EEPROM and the PECR register (see 3.3.4)
const PEKEY2: u32 = 0x02030405;
/// First key value to unlock flash write (see 3.3.4)
const PRGKEY1: u32 = 0x8C9DAEBF;
/// Second key value to unlock flash write (see 3.3.4)
const PRGKEY2: u32 = 0x13141516;
impl Locking for Flash {
type Error = FlashError;
fn is_locked(&self) -> bool {
self.pecr.is_prgmem_locked()
}
fn lock(&mut self) {
self.pecr.lock();
}
fn unlock(&mut self) {
if self.sr.is_busy() {
panic!("cannot lock! flash is busy");
}
if self.pecr.is_pecr_locked() {
self.pekeyr.inner().write(|w| w.bits(PEKEY1));
self.pekeyr.inner().write(|w| w.bits(PEKEY2));
if self.pecr.is_prgmem_locked() {
self.prgkeyr.inner().write(|w| w.bits(PRGKEY1));
self.prgkeyr.inner().write(|w| w.bits(PRGKEY2));
}
}
}
}
impl WriteErase for Flash
where
Flash: Locking,
{
type Error = FlashError;
type Status = FlashStatus;
/// Return the current Flash status
fn status(&self) -> Result<Self::Status, Self::Error> {
if self.sr.is_busy() {
Ok(FlashStatus::Busy)
} else if self.sr.inner().read().eop().bit_is_set() {
Ok(FlashStatus::Done)
} else if self.sr.inner().read().ready().bit_is_set() {
Ok(FlashStatus::Ready)
} else if self.sr.inner().read().endhv().bit_is_clear() {
Ok(FlashStatus::HVOngoing)
} else if self.sr.inner().read().wrperr().bit_is_set() {
Err(FlashError::WriteProtect)
} else if self.sr.inner().read().pgaerr().bit_is_set() {
Err(FlashError::Alignment)
} else if self.sr.inner().read().sizerr().bit_is_set() {
Err(FlashError::Size)
} else if self.sr.inner().read().rderr().bit_is_set() {
Err(FlashError::ReadProtection)
} else if self.sr.inner().read().notzeroerr().bit_is_set() {
Err(FlashError::NotZero)
} else if self.sr.inner().read().fwwerr().bit_is_set() {
Err(FlashError::FetchAbort)
} else {
Err(FlashError::Unknown)
}
}
fn erase_page(&mut self, address: usize) -> Result<(), FlashError> {
self.pecr.enable_erase()?;
unsafe {
ptr::write_volatile(address as *mut u32, 0);
}
while self.sr.is_busy() {}
let result = match self.status() {
Ok(_) => Ok(()),
Err(e) => Err(e),
};
self.pecr.disable_erase()?;
result
}
fn program_word(&mut self, address: usize, value: u32) -> Result<(), FlashError> {
self.erase_page(address)?;
unsafe { self.program_word_immediate(address, value) };
while self.sr.is_busy() {}
match self.status() {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
}
|
#[doc = "Register `SR` reader"]
pub type R = crate::R<SR_SPEC>;
#[doc = "Field `C1VAL` reader - COMP channel 1 output status bit"]
pub type C1VAL_R = crate::BitReader;
#[doc = "Field `C2VAL` reader - COMP channel 2 output status bit"]
pub type C2VAL_R = crate::BitReader;
#[doc = "Field `C1IF` reader - COMP channel 1 Interrupt Flag"]
pub type C1IF_R = crate::BitReader;
#[doc = "Field `C2IF` reader - COMP channel 2 Interrupt Flag"]
pub type C2IF_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - COMP channel 1 output status bit"]
#[inline(always)]
pub fn c1val(&self) -> C1VAL_R {
C1VAL_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - COMP channel 2 output status bit"]
#[inline(always)]
pub fn c2val(&self) -> C2VAL_R {
C2VAL_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 16 - COMP channel 1 Interrupt Flag"]
#[inline(always)]
pub fn c1if(&self) -> C1IF_R {
C1IF_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - COMP channel 2 Interrupt Flag"]
#[inline(always)]
pub fn c2if(&self) -> C2IF_R {
C2IF_R::new(((self.bits >> 17) & 1) != 0)
}
}
#[doc = "Comparator status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SR_SPEC;
impl crate::RegisterSpec for SR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`sr::R`](R) reader structure"]
impl crate::Readable for SR_SPEC {}
#[doc = "`reset()` method sets SR to value 0"]
impl crate::Resettable for SR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::geo::*;
use serde::Deserialize;
use std::{collections::HashMap, fs::File, io::BufReader, path::Path};
use thiserror::Error;
#[derive(Error, Debug)]
/// Error types for vulkan compute operations
pub enum ToolError {
#[error("Tool table not found in file")]
Table,
#[error("Tool number not found in table")]
ToolIndex,
#[error("Tool type not supported")]
InvalidTool,
#[error("Couldn't read tool table")]
Io(#[from] std::io::Error),
#[error("Error parsing tool table")]
Json(#[from] serde_json::Error),
}
#[cfg_attr(feature = "python", pyclass)]
/// Tool for CAM operations, represented as a point cloud
#[derive(Default, Clone)]
pub struct Tool {
pub bbox: Line3d,
pub diameter: f32,
pub points: Vec<Point3d>,
}
#[derive(Deserialize, Debug)]
pub struct ToolTable {
#[serde(rename = "TableName")]
table_name: String,
#[serde(rename = "Tools")]
tools: HashMap<String, ToolParams>,
}
#[derive(Deserialize, Debug)]
pub struct ToolParams {
#[serde(rename = "CornerRadius")]
corner_radius: Option<f32>,
#[serde(rename = "cuttingEdgeAngle")]
angle: Option<f32>,
diameter: f32,
#[serde(rename = "tooltype")]
tool_type: String,
}
impl Tool {
pub fn from_file<P: AsRef<Path>>(
path: P,
table: usize,
tool_index: usize,
scale: f32,
) -> Result<(Tool, f32), ToolError> {
let file = File::open(path)?;
let reader = BufReader::new(file);
let tool_index = tool_index.to_string();
// Read the JSON contents of the file as an instance of `User`.
let t: Vec<ToolTable> = serde_json::from_reader(reader)?;
if t.len() < table {
return Err(ToolError::Table);
}
if !t[table - 1].tools.contains_key(&tool_index) {
return Err(ToolError::ToolIndex);
}
let diameter = t[table - 1].tools[&tool_index].diameter;
let tool = match t[table - 1].tools[&tool_index].tool_type.as_str() {
"EndMill" => Tool::new_endmill(diameter, scale),
// TODO: support angle for ball endmill
"BallEndMill" => Tool::new_ball(diameter, scale),
"Engraver" => Tool::new_v_bit(diameter, t[table - 1].tools[&tool_index].angle.unwrap(), scale),
_ => return Err(ToolError::InvalidTool),
};
Ok((tool, diameter))
}
pub fn new_endmill(diameter: f32, scale: f32) -> Tool {
let radius = diameter / 2.;
let circle = Circle::new(Point3d::new(0., 0., 0.), radius);
let points = Tool::circle_to_points(&circle, scale);
Tool {
bbox: circle.bbox(),
diameter,
points,
}
}
pub fn new_v_bit(diameter: f32, angle: f32, scale: f32) -> Tool {
let radius = diameter / 2.;
let circle = Circle::new(Point3d::new(0., 0., 0.), radius);
let percent = (90. - (angle / 2.)).to_radians().tan();
let points = Tool::circle_to_points(&circle, scale);
let points = points
.iter()
.map(|point| {
let distance = (point.pos.x.powi(2) + point.pos.y.powi(2)).sqrt();
let z = distance * percent;
Point3d::new(point.pos.x, point.pos.y, z)
})
.collect();
Tool {
bbox: circle.bbox(),
diameter,
points,
}
}
// TODO: this approximates a ball end mill, probably want to generate the
// geometry better
pub fn new_ball(diameter: f32, scale: f32) -> Tool {
let radius = diameter / 2.;
let circle = Circle::new(Point3d::new(0., 0., 0.), radius);
let points = Tool::circle_to_points(&circle, scale);
let points = points
.iter()
.map(|point| {
let distance = (point.pos.x.powi(2) + point.pos.y.powi(2)).sqrt();
let z = if distance > 0. {
// 65. is the angle
radius + (-radius * (65. / (radius / distance)).to_radians().cos())
} else {
0.
};
Point3d::new(point.pos.x, point.pos.y, z)
})
.collect();
Tool {
bbox: circle.bbox(),
diameter,
points,
}
}
pub fn circle_to_points(circle: &Circle, scale: f32) -> Vec<Point3d> {
let mut points: Vec<Point3d> = (0..=(circle.radius * scale) as i32)
.flat_map(|x| {
(0..=(circle.radius * scale) as i32).flat_map(move |y| {
vec![
Point3d::new(-x as f32 / scale, y as f32 / scale, 0.0),
Point3d::new(-x as f32 / scale, -y as f32 / scale, 0.0),
Point3d::new(x as f32 / scale, -y as f32 / scale, 0.0),
Point3d::new(x as f32 / scale, y as f32 / scale, 0.0),
]
})
})
.filter(|x| circle.in_2d_bounds(&x))
.collect();
points.sort();
points.dedup();
points
}
}
|
//! Implementation Control Block
#[cfg(any(armv7m, armv8m, native))]
use volatile_register::RO;
use volatile_register::RW;
/// Register block
#[repr(C)]
pub struct RegisterBlock {
/// Interrupt Controller Type Register
///
/// The bottom four bits of this register give the number of implemented
/// interrupt lines, divided by 32. So a value of `0b0010` indicates 64
/// interrupts.
#[cfg(any(armv7m, armv8m, native))]
pub ictr: RO<u32>,
/// The ICTR is not defined in the ARMv6-M Architecture Reference manual, so
/// we replace it with this.
#[cfg(not(any(armv7m, armv8m, native)))]
_reserved: u32,
/// Auxiliary Control Register
///
/// This register is entirely implementation defined -- the standard gives
/// it an address, but does not define its role or contents.
pub actlr: RW<u32>,
/// Coprocessor Power Control Register
#[cfg(armv8m)]
pub cppwr: RW<u32>,
}
|
mod compare_at;
use self::compare_at::{execute_home_compare_at, home_compare_at_subcommand, SUB_HOME_COMPARE_AT};
use clap::{App, Arg, ArgMatches, SubCommand};
use comparators::HomeInvest;
pub const SUB_HOME: &str = "home";
const ARG_SUPPLY: &str = "supply";
const ARG_LOAN: &str = "loan";
const ARG_LOAN_RATE: &str = "loan-rate";
const ARG_PURCHASE_CHARGES: &str = "purchase-charges";
const ARG_ANNUAL_CHARGES: &str = "annual-charges";
const ARG_HOME_APPRECIATION: &str = "home-appreciation";
const ARG_HOME_RENT: &str = "rent";
const ARG_INVEST_RATE_RENT: &str = "invest-rate";
const ARG_YEARS: &str = "years";
/// Returns the home sub commands
pub fn home_sub_commands<'a, 'b>() -> Vec<App<'a, 'b>> {
let home_sub_commands = vec![home_compare_at_subcommand()];
let sub_commands = vec![SubCommand::with_name(SUB_HOME).subcommands(home_sub_commands)];
sub_commands
}
/// Execute the home sub command
///
/// # Arguments
/// * `matches` - The command matches to retrieve the parameters
pub fn execute_home_sub_command<'a>(matches: &ArgMatches<'a>) {
match matches.subcommand() {
(SUB_HOME_COMPARE_AT, Some(matches)) => execute_home_compare_at(matches),
_ => println!("*** No command found"),
}
}
/// Return the common arguments for home
pub fn common_home_args<'a, 'b>() -> Vec<Arg<'a, 'b>> {
vec![
Arg::with_name(ARG_SUPPLY)
.long(ARG_SUPPLY)
.short("s")
.takes_value(true)
.required(true)
.help("supply for the home purchase"),
Arg::with_name(ARG_LOAN)
.long(ARG_LOAN)
.short("l")
.takes_value(true)
.required(true)
.help("the loan value for home purchase"),
Arg::with_name(ARG_LOAN_RATE)
.long(ARG_LOAN_RATE)
.short("r")
.takes_value(true)
.required(true)
.help("the loan rate (everything included)"),
Arg::with_name(ARG_PURCHASE_CHARGES)
.long(ARG_PURCHASE_CHARGES)
.short("p")
.takes_value(true)
.required(true)
.help("the purchase charges"),
Arg::with_name(ARG_ANNUAL_CHARGES)
.long(ARG_ANNUAL_CHARGES)
.short("a")
.takes_value(true)
.required(true)
.help("the annual charges"),
Arg::with_name(ARG_HOME_APPRECIATION)
.long(ARG_HOME_APPRECIATION)
.short("e")
.takes_value(true)
.required(true)
.help("the home appreciation by year"),
Arg::with_name(ARG_HOME_RENT)
.long(ARG_HOME_RENT)
.short("m")
.takes_value(true)
.required(true)
.help("the home rent for a month"),
Arg::with_name(ARG_INVEST_RATE_RENT)
.long(ARG_INVEST_RATE_RENT)
.short("i")
.takes_value(true)
.required(true)
.help("the investment interest rate"),
Arg::with_name(ARG_YEARS)
.long(ARG_YEARS)
.short("y")
.takes_value(true)
.required(true)
.help("the years for the purchase"),
]
}
/// Parse the common home arguments from the cli
///
/// # Arguments
/// * `matches` - cli arguments matches
pub fn parse_common_home_args<'a>(matches: &ArgMatches<'a>) -> HomeInvest {
HomeInvest::new(
matches
.value_of(ARG_SUPPLY)
.unwrap()
.parse::<u32>()
.unwrap(),
matches.value_of(ARG_LOAN).unwrap().parse::<u32>().unwrap(),
matches
.value_of(ARG_LOAN_RATE)
.unwrap()
.parse::<f32>()
.unwrap()
/ 100_f32,
matches
.value_of(ARG_PURCHASE_CHARGES)
.unwrap()
.parse::<f32>()
.unwrap()
/ 100_f32,
matches
.value_of(ARG_ANNUAL_CHARGES)
.unwrap()
.parse::<f32>()
.unwrap()
/ 100_f32,
matches
.value_of(ARG_HOME_APPRECIATION)
.unwrap()
.parse::<f32>()
.unwrap()
/ 100_f32,
matches
.value_of(ARG_HOME_RENT)
.unwrap()
.parse::<u32>()
.unwrap(),
matches
.value_of(ARG_INVEST_RATE_RENT)
.unwrap()
.parse::<f32>()
.unwrap()
/ 100_f32,
matches.value_of(ARG_YEARS).unwrap().parse::<u8>().unwrap(),
)
}
|
use std::fs::File;
use std::io::Read;
#[derive(Debug, PartialEq)]
enum Operation {
SwapPos((usize, usize)),
SwapLetter((char, char)),
RotateLeft(usize),
RotateRight(usize),
RotatePos(char),
Reverse((usize, usize)),
Move((usize, usize)),
}
fn parse_operation(op: &str) -> Operation {
let words: Vec<&str> = op.split(' ').collect();
if words[0] == "swap" {
if words[1] == "position" {
let first = words[2].parse::<usize>().unwrap();
let second = words[5].parse::<usize>().unwrap();
return Operation::SwapPos((first, second));
} else if words[1] == "letter" {
let first = words[2].chars().nth(0).unwrap();
let second = words[5].chars().nth(0).unwrap();
return Operation::SwapLetter((first, second));
} else {
panic!("Swap instruction error: '{}'", op);
}
} else if words[0] == "rotate" {
if words[1] == "left" {
let val = words[2].parse::<usize>().unwrap();
return Operation::RotateLeft(val);
} else if words[1] == "right" {
let val = words[2].parse::<usize>().unwrap();
return Operation::RotateRight(val);
} else if words[1] == "based" {
let anchor = words[6].chars().nth(0).unwrap();
return Operation::RotatePos(anchor);
} else {
panic!("Rotate instruction error: '{}'", op);
}
} else if words[0] == "reverse" {
let first = words[2].parse::<usize>().unwrap();
let second = words[4].parse::<usize>().unwrap();
return Operation::Reverse((first, second));
} else if words[0] == "move" {
let first = words[2].parse::<usize>().unwrap();
let second = words[5].parse::<usize>().unwrap();
return Operation::Move((first, second));
} else {
panic!("Wrong operator '{}'", op);
}
}
fn apply_op(op: &str, password: &str) -> String {
let operation = parse_operation(op);
let mut chars: Vec<char> = password.chars().collect();
match operation {
Operation::SwapPos((first, second)) => {
let t = chars[first];
chars[first] = chars[second];
chars[second] = t;
},
Operation::SwapLetter((from, to)) => {
let pos1 = password.find(from).unwrap();
let pos2 = password.find(to).unwrap();
let t = chars[pos1];
chars[pos1] = chars[pos2];
chars[pos2] = t;
},
Operation::Reverse((from, to)) => {
let mut i = from;
let mut j = to;
while i < j {
let t = chars[i];
chars[i] = chars[j];
chars[j] = t;
i += 1;
j -= 1;
}
},
Operation::RotateLeft(amount) => {
let copy = chars.clone();
for i in 0 .. chars.len() {
chars[i] = copy[(i + amount) % copy.len()];
}
},
Operation::RotateRight(amount) => {
let copy = chars.clone();
for i in 0 .. chars.len() {
chars[i] = copy[((i + copy.len() - amount) % copy.len())];
}
},
Operation::RotatePos(which) => {
let copy = chars.clone();
let pos = password.find(which).unwrap();
let amount = (1 + pos + if pos >= 4 {1} else {0}) % copy.len();
for i in 0 .. chars.len() {
chars[i] = copy[((i + copy.len() - amount) % copy.len())];
}
},
Operation::Move((from, to)) => {
let t = chars[from];
if from < to {
for i in from .. to {
chars[i] = chars[i+1];
}
} else {
for i in (to+1 .. from+1).rev() {
chars[i] = chars[i-1];
}
}
chars[to] = t;
}
};
chars.into_iter().collect::<String>()
}
fn apply(instruction_text: &str, password: &str) -> String {
let mut output: String = password.to_string();
for ln in instruction_text.lines() {
if ln.len() < 1 {
continue;
}
output = apply_op(ln, &output);
}
output
}
fn main() {
let mut file = File::open("input21.txt").unwrap();
let mut text = String::new();
file.read_to_string(&mut text).unwrap();
println!("Part 1: {}", apply(&text, "abcdefgh"));
// println!("Part 2: {}", part2());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_example() {
let password = "abcde";
let ops = "swap position 4 with position 0\n\
swap letter d with letter b\n\
reverse positions 0 through 4\n\
rotate left 1 step\n\
move position 1 to position 4\n\
move position 3 to position 0\n\
rotate based on position of letter b\n\
rotate based on position of letter d";
assert_eq!(apply(&ops, &password), "decab");
}
#[test]
fn test_parse_operation() {
assert_eq!(parse_operation("swap position 4 with position 0"), Operation::SwapPos((4, 0)));
assert_eq!(parse_operation("swap letter d with letter b"), Operation::SwapLetter(('d', 'b')));
assert_eq!(parse_operation("reverse positions 0 through 4"), Operation::Reverse((0, 4)));
assert_eq!(parse_operation("rotate left 1 step"), Operation::RotateLeft(1));
assert_eq!(parse_operation("rotate right 2 steps"), Operation::RotateRight(2));
assert_eq!(parse_operation("move position 1 to position 4"), Operation::Move((1, 4)));
assert_eq!(parse_operation("rotate based on position of letter b"), Operation::RotatePos('b'));
}
#[test]
fn test_operations() {
assert_eq!(apply_op("swap position 4 with position 0", "abcde"), "ebcda");
assert_eq!(apply_op("swap letter d with letter b", "ebcda"), "edcba");
assert_eq!(apply_op("reverse positions 0 through 4", "edcba"), "abcde");
assert_eq!(apply_op("rotate left 1 step", "abcde"), "bcdea");
assert_eq!(apply_op("move position 1 to position 4", "bcdea"), "bdeac");
assert_eq!(apply_op("move position 3 to position 0", "bdeac"), "abdec");
assert_eq!(apply_op("rotate right 2 steps", "bcdea"), "eabcd");
assert_eq!(apply_op("rotate based on position of letter b", "abdec"), "ecabd");
assert_eq!(apply_op("rotate based on position of letter d", "ecabd"), "decab");
}
}
|
fn main() {
let mut contador = 1;
while contador <= 10 {
println!("Contador: {}", contador);
contador += 1;
}
//123 -> 3 = 12
//12345 -> 5
// 123456789 -> 9
let mut numero = 123456789;
let mut contador = 0;
while numero > 0 {
numero = numero / 10;
contador += 1;
}
println!("La cantidad de digitos son {}", contador);
}
|
use regex::Regex;
use std::error::Error;
use std::fs;
use std::path::Path;
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq)]
struct Entry {
min: usize,
max: usize,
look_up_char: char,
password: String,
}
impl FromStr for Entry {
type Err = Box<dyn Error>;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let re = Regex::new(r"^(\d+)-(\d+)\s+([a-zA-Z]):\s+(\w+)$").expect("Failed to parse line!");
let caps = re.captures(input).unwrap();
let min = caps.get(1).unwrap().as_str().parse::<usize>().expect("NaN");
let max = caps.get(2).unwrap().as_str().parse::<usize>().expect("NaN");
let look_up_char = caps.get(3).unwrap().as_str().chars().next().unwrap();
let password = caps.get(4).unwrap().as_str().into();
Ok(Entry {
min,
max,
look_up_char,
password,
})
}
}
fn main() {
let data = read_file("./input/input.txt");
println!("{:?}", part1(data.clone()));
println!("{:?}", part2(data.clone()));
}
fn part1(data: Vec<Entry>) -> std::result::Result<usize, String> {
Ok(data
.into_iter()
.filter(|entry| {
let split_cnt = entry.password.split(entry.look_up_char).count() - 1;
// println!("{:?}", split_cnt);
split_cnt >= entry.min && split_cnt <= entry.max
})
.count())
}
fn part2(data: Vec<Entry>) -> std::result::Result<usize, String> {
Ok(data
.into_iter()
.filter(|entry| {
let pass: Vec<char> = entry.password.chars().collect();
pass[entry.min - 1].eq(&entry.look_up_char)
^ pass[entry.max - 1].eq(&entry.look_up_char)
})
.count())
}
fn read_file<P>(filename: P) -> Vec<Entry>
where
P: AsRef<Path>,
{
fs::read_to_string(filename)
.expect("Failed to load file")
.lines()
.flat_map(|l| Entry::from_str(l))
.collect()
}
|
// This file is part of dpdk. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2017 The developers of dpdk. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/dpdk/master/COPYRIGHT.
pub trait ValidWorkCompletion: Sized
{
#[inline(always)]
fn flags(&self) -> c_int;
#[inline(always)]
fn hasFlag(&self, flag: c_int) -> bool
{
self.flags() & flag == flag
}
#[inline(always)]
fn workRequestOperationWas(&self) -> ibv_wc_opcode;
// Only relevant for UD => Unreliable datagram?
// AKA source queue pair number
#[inline(always)]
fn receiveWorkRequestRemoteQueuePairNumber(&self) -> QueuePairNumber;
#[inline(always)]
fn immediateDataInNetworkByteOrder(&self) -> Option<u32>
{
const IBV_WC_WITH_IMM: c_int = 2;
if unlikely(self.hasFlag(IBV_WC_WITH_IMM))
{
let workRequestOperation = self.workRequestOperationWas();
if likely(workRequestOperation == ibv_wc_opcode::IBV_WC_SEND || workRequestOperation == ibv_wc_opcode::IBV_WC_RDMA_WRITE)
{
return Some(self.rawImmediateDataInNetworkByteOrder());
}
}
None
}
#[doc(hidden)]
#[inline(always)]
fn rawImmediateDataInNetworkByteOrder(&self) -> u32;
// Only relevant for UD; all UD have a 40 byte reserved space at the beginning
#[inline(always)]
fn validGlobalRoutingHeaderPresentInFirst40Bytes(&self) -> bool
{
const IBV_WC_GRH: c_int = 1;
self.hasFlag(IBV_WC_GRH)
}
// Only relevant for UD
#[inline(always)]
fn receiveWorkRequestSourceLocalIdentifier(&self) -> LocalIdentifier;
// Only relevant for UD
#[inline(always)]
fn receiveWorkRequestServiceLevel(&self) -> ServiceLevel;
// Only relevant for UD and only then for unicast messages
#[inline(always)]
fn receiveWorkRequestDestinationLocalIdentifierPath(&self) -> LocalIdentifierPath;
/// The number of bytes transferred. Relevant if the Receive Queue for incoming Send or RDMA Write with immediate operations. This value doesn't include the length of the immediate data, if such exists. Relevant in the Send Queue for RDMA Read and Atomic operations.
/// For the Receive Queue of a UD QP that is not associated with an SRQ or for an SRQ that is associated with a UD QP this value equals to the payload of the message plus the 40 bytes reserved for the GRH.
/// The number of bytes transferred is the payload of the message plus the 40 bytes reserved for the GRH, whether or not the GRH is present
#[inline(always)]
fn numberOfBytesTransferred(&self) -> u32;
#[inline(always)]
fn partitionKeyIndex(&self) -> PartitionKeyIndex;
}
|
#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct Envelope {
pub period: u16, // constant volume/envelope period
divider: u16,
pub decay_counter: u16, // remainder of envelope divider
pub start: bool, // restarts envelope
pub length_counter_halt: bool, // also the envelope loop flag
}
impl Envelope {
pub fn new() -> Self {
Envelope {
period: 0,
divider: 0,
decay_counter: 0,
start: false,
length_counter_halt: false,
}
}
pub fn clock(&mut self) {
// When clocked by the frame counter, one of two actions occurs:
// if the start flag is clear, the divider is clocked,
if !self.start {
self.clock_divider();
} else {
self.start = false; // otherwise the start flag is cleared,
self.decay_counter = 15; // the decay level counter is loaded with 15,
self.divider = self.period; // and the divider's period is immediately reloaded
}
}
fn clock_divider(&mut self) {
// When the divider is clocked while at 0, it is loaded with V and clocks the decay level counter.
if self.divider == 0 {
self.divider = self.period;
// Then one of two actions occurs: If the counter is non-zero, it is decremented,
if self.decay_counter != 0 {
self.decay_counter -= 1;
} else if self.length_counter_halt {
// otherwise if the loop flag is set, the decay level counter is loaded with 15.
self.decay_counter = 15;
}
} else {
self.divider -= 1;
}
}
}
|
/*
$ ipcal 192.168.1.0/24
Network addr : 192.168.1.0
Hosts addr : 192.160.1.1 - 192.168.1.254
Broadcast addr : 192.168.1.255
Hosts addr num : 254
*/
use std::env;
#[derive(Debug, PartialEq)]
struct IPAddr {
addr: [u8; 4],
prefix: u8,
}
impl IPAddr {
fn compose(&self) -> u32{
let mut composed_addr :u32 = 0;
for i in 0..self.addr.len() {
let octet = (self.addr[i] as u32) << 8 * (self.addr.len() - i - 1);
composed_addr |= octet;
}
composed_addr
}
fn generate_network_addr(&self) -> u32 {
let u32_addr = self.compose();
u32_addr & ((2u32.pow(self.prefix as u32) - 1) << (32 - self.prefix))
}
fn get_humanreadable_addr(&self, ip: u32) -> String {
let octet_1st = (ip >> 24) & (2u32.pow(8) - 1);
let octet_2nd = (ip >> 16) & (2u32.pow(8) - 1);
let octet_3rd = (ip >> 8) & (2u32.pow(8) - 1);
let octet_4th = (ip >> 0) & (2u32.pow(8) - 1);
format!("{}.{}.{}.{}", octet_1st, octet_2nd, octet_3rd, octet_4th)
}
pub fn get_network_addr(&self) -> String {
let ip = self.generate_network_addr();
self.get_humanreadable_addr(ip)
}
pub fn get_hosts_first_addr(&self) -> String {
let mut ip = self.generate_network_addr();
ip += 1;
self.get_humanreadable_addr(ip)
}
pub fn get_hosts_last_addr(&self) -> String {
let mut ip = self.generate_network_addr();
ip += 2u32.pow(32 - self.prefix as u32) - 2;
self.get_humanreadable_addr(ip)
}
pub fn get_broadcast_addr(&self) -> String {
let mut ip = self.generate_network_addr();
ip += 2u32.pow(32 - self.prefix as u32) - 1;
self.get_humanreadable_addr(ip)
}
pub fn get_hosts_addr_num(&self) -> u32 {
2u32.pow(32 - self.prefix as u32) - 2
}
}
fn parse_arg_to_ip(s: &String) -> IPAddr {
// divide into "addr" and "prefix"
let ss = &s;
let separated: Vec<&str> = ss.split('/').collect();
if separated.len() != 2 {
eprintln!(
"error: illegal <ipaddr>"
);
std::process::exit(1);
}
// get and check prefix
let prefix: u8 = separated[1].parse().unwrap();
if prefix > 32 {
eprintln!(
"error: prefix length must be less than 32"
);
std::process::exit(1);
}
// get and check address
let mut addr: [u8; 4] = Default::default();
let itr: Vec<&str> = separated[0].split('.').collect();
if itr.len() != 4 {
eprintln!(
"error: address part must be 'x.x.x.x' syntax"
);
std::process::exit(1);
}
for i in 0..itr.len() {
// for catching error
let a: u32 = itr[i].parse().unwrap_or(256);
if a > 255 {
eprintln!(
"error: each octets must be less than 255"
);
std::process::exit(1);
}
addr[i] = a as u8;
}
IPAddr {
addr: addr,
prefix: prefix,
}
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!(
"Usage: ipcal <ipaddr>"
);
std::process::exit(1);
}
let ip = parse_arg_to_ip(&args[1]);
println!("Network addr : {}", ip.get_network_addr());
println!("Hosts addr : {} - {}", ip.get_hosts_first_addr(), ip.get_hosts_last_addr());
println!("Broadcast addr : {}", ip.get_broadcast_addr());
println!("Hosts addr num : {}", ip.get_hosts_addr_num());
}
#[cfg(test)]
mod tests {
use super::IPAddr;
#[test]
fn parse_string_to_ip() {
let s1 = "192.168.1.0/24";
let ip1 = IPAddr { addr: [192, 168, 1, 0], prefix: 24 };
assert_eq!(super::parse_arg_to_ip(&s1.to_string()), ip1);
let s2 = "10.0.1.0/20";
let ip2 = IPAddr { addr: [10, 0, 1, 0], prefix: 20 };
assert_eq!(super::parse_arg_to_ip(&s2.to_string()), ip2);
}
#[test]
fn generate_ip_string() {
let ip1 = IPAddr {
addr: [192, 168, 1, 0],
prefix: 24,
};
assert_eq!(ip1.get_network_addr(), "192.168.1.0");
assert_eq!(ip1.get_hosts_first_addr(), "192.168.1.1");
assert_eq!(ip1.get_hosts_last_addr(), "192.168.1.254");
assert_eq!(ip1.get_hosts_addr_num(), 254);
let ip2 = IPAddr {
addr: [10, 0, 40, 1],
prefix: 19,
};
assert_eq!(ip2.get_network_addr(), "10.0.32.0");
assert_eq!(ip2.get_hosts_first_addr(), "10.0.32.1");
assert_eq!(ip2.get_hosts_last_addr(), "10.0.63.254");
assert_eq!(ip2.get_hosts_addr_num(), 8190);
}
} |
use holochain_json_api::error::JsonError;
use holochain_persistence_api::{
cas::{
content::{Address, AddressableContent, Content},
storage::ContentAddressableStorage,
},
error::PersistenceResult,
reporting::{ReportStorage, StorageReport},
};
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod};
use std::{
fmt::{Debug, Error, Formatter},
path::Path,
sync::{Arc, RwLock},
time::Duration,
};
use uuid::Uuid;
const PERSISTENCE_INTERVAL: Duration = Duration::from_millis(5000);
#[derive(Clone)]
pub struct PickleStorage {
id: Uuid,
db: Arc<RwLock<PickleDb>>,
}
impl Debug for PickleStorage {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
f.debug_struct("PickleStorage")
.field("id", &self.id)
.finish()
}
}
impl PickleStorage {
pub fn new<P: AsRef<Path> + Clone>(db_path: P) -> PickleStorage {
let cas_db = db_path.as_ref().join("cas").with_extension("db");
PickleStorage {
id: Uuid::new_v4(),
db: Arc::new(RwLock::new(
PickleDb::load(
cas_db.clone(),
PickleDbDumpPolicy::PeriodicDump(PERSISTENCE_INTERVAL),
SerializationMethod::Cbor,
)
.unwrap_or_else(|_| {
PickleDb::new(
cas_db,
PickleDbDumpPolicy::PeriodicDump(PERSISTENCE_INTERVAL),
SerializationMethod::Cbor,
)
}),
)),
}
}
}
impl ContentAddressableStorage for PickleStorage {
fn add(&mut self, content: &dyn AddressableContent) -> PersistenceResult<()> {
let mut inner = self.db.write().unwrap();
inner
.set(&content.address().to_string(), &content.content())
.map_err(|e| JsonError::ErrorGeneric(e.to_string()))?;
Ok(())
}
fn contains(&self, address: &Address) -> PersistenceResult<bool> {
let inner = self.db.read().unwrap();
Ok(inner.exists(&address.to_string()))
}
fn fetch(&self, address: &Address) -> PersistenceResult<Option<Content>> {
let inner = self.db.read().unwrap();
Ok(inner.get(&address.to_string()))
}
fn get_id(&self) -> Uuid {
self.id
}
}
impl ReportStorage for PickleStorage {
fn get_storage_report(&self) -> PersistenceResult<StorageReport> {
let db = self.db.read()?;
let bytes_total = db.iter().fold(0, |total_bytes, kv| {
let value = kv.get_value::<Content>().unwrap();
total_bytes + value.to_string().bytes().len()
});
Ok(StorageReport::new(bytes_total))
}
}
#[cfg(test)]
mod tests {
use crate::cas::pickle::PickleStorage;
use holochain_json_api::json::RawString;
use holochain_persistence_api::{
cas::{
content::{Content, ExampleAddressableContent, OtherExampleAddressableContent},
storage::{CasBencher, ContentAddressableStorage, StorageTestSuite},
},
reporting::{ReportStorage, StorageReport},
};
use tempfile::{tempdir, TempDir};
pub fn test_pickle_cas() -> (PickleStorage, TempDir) {
let dir = tempdir().expect("Could not create a tempdir for CAS testing");
(PickleStorage::new(dir.path()), dir)
}
#[bench]
fn bench_pickle_cas_add(b: &mut test::Bencher) {
let (store, _) = test_pickle_cas();
CasBencher::bench_add(b, store);
}
#[bench]
fn bench_pickle_cas_fetch(b: &mut test::Bencher) {
let (store, _) = test_pickle_cas();
CasBencher::bench_fetch(b, store);
}
#[test]
/// show that content of different types can round trip through the same storage
/// this is copied straight from the example with a file CAS
fn pickle_content_round_trip_test() {
let (cas, _dir) = test_pickle_cas();
let test_suite = StorageTestSuite::new(cas);
test_suite.round_trip_test::<ExampleAddressableContent, OtherExampleAddressableContent>(
RawString::from("foo").into(),
RawString::from("bar").into(),
);
}
#[test]
fn pickle_report_storage_test() {
let (mut cas, _) = test_pickle_cas();
// add some content
cas.add(&Content::from_json("some bytes"))
.expect("could not add to CAS");
assert_eq!(cas.get_storage_report().unwrap(), StorageReport::new(10),);
// add some more
cas.add(&Content::from_json("more bytes"))
.expect("could not add to CAS");
assert_eq!(
cas.get_storage_report().unwrap(),
StorageReport::new(10 + 10),
);
}
}
|
// This file is part of Substrate.
// Copyright (C) 2019-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.
//! Combines [sc_rpc_api::state::StateClient] with [frame_support::storage::generator] traits
//! to provide strongly typed chain state queries over rpc.
#![warn(missing_docs)]
use codec::{DecodeAll, FullCodec, FullEncode};
use core::marker::PhantomData;
use frame_support::storage::generator::{StorageDoubleMap, StorageMap, StorageValue};
use futures::compat::Future01CompatExt;
use jsonrpc_client_transports::RpcError;
use sc_rpc_api::state::StateClient;
use serde::{de::DeserializeOwned, Serialize};
use sp_storage::{StorageData, StorageKey};
/// A typed query on chain state usable from an RPC client.
///
/// ```no_run
/// # use futures::compat::Future01CompatExt;
/// # use jsonrpc_client_transports::RpcError;
/// # use jsonrpc_client_transports::transports::http;
/// # use codec::Encode;
/// # use frame_support::{decl_storage, decl_module};
/// # use substrate_frame_rpc_support::StorageQuery;
/// # use frame_system::Trait;
/// # use sc_rpc_api::state::StateClient;
/// #
/// # // Hash would normally be <TestRuntime as frame_system::Trait>::Hash, but we don't have
/// # // frame_system::Trait implemented for TestRuntime. Here we just pretend.
/// # type Hash = ();
/// #
/// # fn main() -> Result<(), RpcError> {
/// # tokio::runtime::Runtime::new().unwrap().block_on(test())
/// # }
/// #
/// # struct TestRuntime;
/// #
/// # decl_module! {
/// # pub struct Module<T: Trait> for enum Call where origin: T::Origin {}
/// # }
/// #
/// pub type Loc = (i64, i64, i64);
/// pub type Block = u8;
///
/// // Note that all fields are marked pub.
/// decl_storage! {
/// trait Store for Module<T: Trait> as TestRuntime {
/// pub LastActionId: u64;
/// pub Voxels: map hasher(blake2_128_concat) Loc => Block;
/// pub Actions: map hasher(blake2_128_concat) u64 => Loc;
/// pub Prefab: double_map hasher(blake2_128_concat) u128, hasher(blake2_128_concat) (i8, i8, i8) => Block;
/// }
/// }
///
/// # async fn test() -> Result<(), RpcError> {
/// let conn = http::connect("http://[::1]:9933").compat().await?;
/// let cl = StateClient::<Hash>::new(conn);
///
/// let q = StorageQuery::value::<LastActionId>();
/// let _: Option<u64> = q.get(&cl, None).await?;
///
/// let q = StorageQuery::map::<Voxels, _>((0, 0, 0));
/// let _: Option<Block> = q.get(&cl, None).await?;
///
/// let q = StorageQuery::map::<Actions, _>(12);
/// let _: Option<Loc> = q.get(&cl, None).await?;
///
/// let q = StorageQuery::double_map::<Prefab, _, _>(3, (0, 0, 0));
/// let _: Option<Block> = q.get(&cl, None).await?;
/// #
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct StorageQuery<V> {
key: StorageKey,
_spook: PhantomData<V>,
}
impl<V: FullCodec> StorageQuery<V> {
/// Create a storage query for a StorageValue.
pub fn value<St: StorageValue<V>>() -> Self {
Self { key: StorageKey(St::storage_value_final_key().to_vec()), _spook: PhantomData }
}
/// Create a storage query for a value in a StorageMap.
pub fn map<St: StorageMap<K, V>, K: FullEncode>(key: K) -> Self {
Self { key: StorageKey(St::storage_map_final_key(key)), _spook: PhantomData }
}
/// Create a storage query for a value in a StorageDoubleMap.
pub fn double_map<St: StorageDoubleMap<K1, K2, V>, K1: FullEncode, K2: FullEncode>(
key1: K1,
key2: K2,
) -> Self {
Self { key: StorageKey(St::storage_double_map_final_key(key1, key2)), _spook: PhantomData }
}
/// Send this query over RPC, await the typed result.
///
/// Hash should be <YourRuntime as frame::Trait>::Hash.
///
/// # Arguments
///
/// state_client represents a connection to the RPC server.
///
/// block_index indicates the block for which state will be queried. A value of None indicates
/// the latest block.
pub async fn get<Hash: Send + Sync + 'static + DeserializeOwned + Serialize>(
self,
state_client: &StateClient<Hash>,
block_index: Option<Hash>,
) -> Result<Option<V>, RpcError> {
let opt: Option<StorageData> = state_client.storage(self.key, block_index).compat().await?;
opt.map(|encoded| V::decode_all(&encoded.0))
.transpose()
.map_err(|decode_err| RpcError::Other(decode_err.into()))
}
}
|
// mod print;ß
// mod vars;
// mod strings;
// mod tuples;
// mod vectors;
// mod functions;
mod linkedList_test;
fn main() {
linkedList_test::run();
}
|
use std::fs::File;
fn create(filename: &str) -> std::io::Result<()> {
File::create("xxx")?; // is equivalent of
match File::create(filename) {
Ok(f) => f,
Err(e) => return Err(e),
};
Ok(())
}
fn main() {
let t = create("/tmp/xxx");
println!("{:?}", t);
}
|
include!(concat!(env!("OUT_DIR"), "/load_assets.rs"));
pub fn dfinity_logo() -> String {
if atty::is(atty::Stream::Stdout) {
include_str!("../../assets/dfinity-color.aart").to_string()
} else {
include_str!("../../assets/dfinity-nocolor.aart").to_string()
}
}
|
use core::f64::consts::PI;
use core::f64::consts::FRAC_PI_2;
use std::num::FpCategory;
use crate::coord_plane::CartPoint;
use crate::coord_plane::map_one_point;
use crate::coord_plane::LatLonPoint;
#[derive(Debug)]
pub struct MapBounds {
pub upper_x: f64,
pub lower_x: f64,
pub upper_y: f64,
pub lower_y: f64,
}
pub enum BoundLocation {
LowerLeftUpperRight,
UpperLeftLowerRight,
MaxXandY,
Zeros,
}
impl MapBounds {
#[allow(dead_code)]
pub fn new(mapping_function: &Box<dyn Fn(Vec<LatLonPoint>) -> Vec<CartPoint>>,
bound_loc: BoundLocation) -> Self
{
match bound_loc {
BoundLocation::LowerLeftUpperRight => {
let lower_left =
map_one_point(mapping_function, LatLonPoint {
lambda: -FRAC_PI_2, phi: -FRAC_PI_2
});
let upper_right =
map_one_point(mapping_function, LatLonPoint {
lambda: FRAC_PI_2, phi: FRAC_PI_2
});
MapBounds {
upper_x: upper_right.x,
upper_y: upper_right.y,
lower_x: lower_left.x,
lower_y: lower_left.y,
}
},
BoundLocation::UpperLeftLowerRight => {
let upper_left =
map_one_point(mapping_function, LatLonPoint {
lambda: -FRAC_PI_2, phi: FRAC_PI_2
});
let lower_right =
map_one_point(mapping_function, LatLonPoint {
lambda: FRAC_PI_2, phi: -FRAC_PI_2
});
MapBounds {
upper_x: lower_right.x,
upper_y: upper_left.y,
lower_x: upper_left.x,
lower_y: lower_right.y,
}
},
BoundLocation::MaxXandY => MapBounds {
upper_y: map_one_point(&mapping_function,
LatLonPoint { lambda: 0.0, phi: FRAC_PI_2 }).y,
lower_y: map_one_point(&mapping_function,
LatLonPoint { lambda: 0.0, phi: -FRAC_PI_2 }).y,
upper_x: map_one_point(&mapping_function,
LatLonPoint { lambda: FRAC_PI_2, phi: 0.0 }).x,
lower_x: map_one_point(&mapping_function,
LatLonPoint { lambda: -FRAC_PI_2, phi: 0.0 }).x,
},
BoundLocation::Zeros => MapBounds {
upper_x: 0.0,
upper_y: 0.0,
lower_x: 0.0,
lower_y: 0.0,
}
}
}
#[allow(dead_code)]
pub fn add_size(self, inc: f64) -> Self {
MapBounds {
upper_x: self.upper_x + inc,
upper_y: self.upper_y + inc,
lower_x: self.lower_x - inc,
lower_y: self.lower_y - inc,
}
}
#[allow(dead_code)]
pub fn to_vec(&self) -> Vec<f64> {
vec![
self.upper_x, self.upper_y,
self.lower_x, self.lower_y
]
}
#[allow(dead_code)]
pub fn bounds_from_vec(arr: Vec<f64>) -> MapBounds {
MapBounds {
upper_x: arr[0],
upper_y: arr[1],
lower_x: arr[2],
lower_y: arr[3],
}
}
#[allow(dead_code)]
pub fn to_normal_vals(&self, inf_approx: f64) -> MapBounds {
MapBounds::bounds_from_vec(
self.to_vec().iter().map(
|float| match float.classify() {
FpCategory::Normal => {
//If value is greater than "infinity",
match float.abs() > inf_approx.abs() {
true => inf_approx.copysign(*float),
false => *float
}
}
//If you use 0, it can cause the plotting library to hang
FpCategory::Zero => 0.00001,
FpCategory::Infinite => {
match *float > 0.0 {
true => inf_approx,
false => -inf_approx,
}
},
FpCategory::Nan => panic!("0/0 or inf/inf division attempted"),
FpCategory::Subnormal => *float,
}
).collect::<Vec<f64>>()
)
}
}
|
extern crate piston;
extern crate graphics;
extern crate glutin_window;
extern crate opengl_graphics;
extern crate rand;
extern crate find_folder;
use piston::event_loop::*;
use piston::input::*;
use opengl_graphics::glyph_cache::GlyphCache;
use opengl_graphics::GlGraphics;
use glutin_window::GlutinWindow as Window;
use self::rand::Rng;
use models::player::Player;
use models::bullet::Bullet;
use models::enemy::Enemy;
use music;
use std::thread;
const FIRE_COOLDOWN: f64 = 1.5;
/// houses the direction that a game object may point in
#[derive(Copy, Clone)]
pub enum Direction {
WEST,
NORTH,
EAST,
SOUTH
}
/// Contains states and objects used in berzerk
pub struct Game {
player: Player,
player_bullets: Vec<Bullet>,
enemy_bullets: Vec<Bullet>,
enemies: Vec<Enemy>,
dimensions: [f64;2],
game_over: bool,
score: u32,
level:u32,
fire_cooldown: f64,
pub walls: Vec<[f64;4]>, //make [f64;4] a Wall object with [x0 y0 x1 y1]
new_level: bool,
won: bool,
}
pub const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
pub const YELLOW: [f32; 4] = [1.0, 1.0, 0.5, 1.0];
pub const BLUE: [f32; 4] = [0.5, 0.6, 0.7, 1.0];
pub const FPS: u64 = 60;
impl Game {
pub fn new(width:f64, height: f64) -> Self {
Game {
player: Player::new(75.0, height / 2.0),
player_bullets:Vec::<Bullet>::new(),
enemy_bullets:Vec::<Bullet>::new(),
dimensions: [width,height],
game_over: false,
enemies: Vec::new(),
score: 0,
level:1,
fire_cooldown: 0.0,
walls: Vec::new(),
new_level: false,
won: false,
}
}
//pos[x0, y0, x1, y1] for opposite points of rect
pub fn make_border(&self, gl: &mut GlGraphics, c: graphics::Context, pos: [f64;4]) {
use self::graphics::*;
let square = rectangle::rectangle_by_corners(pos[0], pos[1],pos[2],pos[3]);
let (x,y) = (0.0, 0.0);
let transform = c.transform.trans(x,y);
rectangle(BLUE, square, transform, gl);
}
pub fn make_level_borders(&mut self,gl: &mut GlGraphics, c: graphics::Context,) {
let half_width =self.dimensions[0]/2.0;
let half_height =self.dimensions[1]/2.0;
let quarter_width = self.dimensions[0]/4.0;
let quarter_height = self.dimensions[1]/4.0;
let left_vertical = [5.0,5.0,30.0,self.dimensions[1]-75.0];
let left_top =[30.0,5.0,half_width-125.0,30.0];
let right_top = [half_width+125.0,5.0,self.dimensions[0]-5.0,30.0];
let right_vertical = [self.dimensions[0]-30.0,25.0,self.dimensions[0]-5.0,self.dimensions[1]-75.0];
let left_bottom = [25.0,self.dimensions[1]-100.0,(half_width)-125.0,self.dimensions[1]-75.0];
let right_bottom = [half_width+125.0,self.dimensions[1]-100.0,self.dimensions[0]-5.0,self.dimensions[1]-75.0];
let middle_top_vert = [quarter_width,quarter_height,quarter_width+25.0,quarter_height*3.0-75.0];
let middle_right_vert = [quarter_width*3.0,quarter_height,quarter_width*3.0+25.0,quarter_height*3.0-75.0];
let middle_middle = [quarter_width+25.0,half_height-50.0,quarter_width*3.0,half_height-25.0];
// in update we use this to check for collision with enemy and eventually player
self.add_walls(left_vertical,left_top,right_top,right_vertical,left_bottom,right_bottom,
middle_top_vert, middle_right_vert, middle_middle);
//border pieces of level 1
self.make_border(gl,c, left_vertical);
self.make_border(gl,c, left_top);
self.make_border(gl,c, right_top);
self.make_border(gl,c, right_vertical);
self.make_border(gl,c, left_bottom);
self.make_border(gl,c, right_bottom);
//middle part of level 1
self.make_border(gl,c, middle_top_vert); //left vertical
self.make_border(gl,c, middle_right_vert); //right vertical
self.make_border(gl,c, middle_middle); //middle bar
}
//middle_top_vert, middle_right_vert, middle_middle
pub fn add_walls(&mut self, lf:[f64;4],lt:[f64;4],rt:[f64;4],rv:[f64;4],lb:[f64;4],rb:[f64;4],mtv:[f64;4],mrv:[f64;4],mm:[f64;4],) {
self.walls.push(lf);
self.walls.push(lt);
self.walls.push(rt);
self.walls.push(rv);
self.walls.push(lb);
self.walls.push(rb);
self.walls.push(mtv);
self.walls.push(mrv);
self.walls.push(mm);
}
fn on_draw(&mut self, args: &RenderArgs, gl: &mut GlGraphics, glyph_cache: &mut GlyphCache) {
use self::graphics::*;
gl.draw(args.viewport(), |c, gl| {
clear(BLACK, gl);
for bullet in &self.player_bullets {
bullet.draw(c, gl);
}
for bullet in &self.enemy_bullets {
bullet.draw(c, gl);
}
for enemy in &mut self.enemies {
enemy.draw(c,gl);
}
self.make_level_borders(gl,c);
self.player.draw(c, gl);
if self.player.health > 0 {
let mut pos_heart = (self.dimensions[1]/4.0)*3.5;
for _ in 0..self.player.health {
pos_heart +=35.0;
self.player.draw_lives(pos_heart, self.dimensions[1]-35.0, c,gl);
}
}
text(YELLOW, 38, format!("{}", self.score).as_str(),
glyph_cache,
c.transform.trans(self.dimensions[0]/2.0,self.dimensions[1]-25.0),
gl);
text(YELLOW, 38, format!("{}", self.level).as_str(),
glyph_cache,
c.transform.trans(50.0,self.dimensions[1]-25.0),
gl);
if self.game_over {
text(YELLOW, 38, format!("GAME OVER PRESS R TO RESTART").as_str(),
glyph_cache,
c.transform.trans(self.dimensions[0]/2.0-95.0,self.dimensions[1]/2.0),
gl);
}
if self.won {
text(YELLOW, 38, format!("CONGRATS YOU WON").as_str(),
glyph_cache,
c.transform.trans(self.dimensions[0]/2.0-95.0,self.dimensions[1]/2.0),
gl);
}
});
}
fn player_bullet_check(&mut self) {
for bullet in &mut self.player_bullets {
bullet.update();
for enemy in &mut self.enemies {
if bullet.collides_enemy(enemy) {
bullet.alive = false;
enemy.alive = false;
if self.fire_cooldown <= 0.0 {
music::play(2);
self.fire_cooldown = FIRE_COOLDOWN;
}
self.score += 50;
}
}
for wall in &self.walls {
if bullet.collides_wall(wall){
bullet.alive = false;
}
}
}
}
fn enemy_bullet_check(&mut self) {
for bullet in &mut self.enemy_bullets {
bullet.update();
if bullet.collides_p(&self.player) {
bullet.alive = false;
self.player.health -=1;
if self.fire_cooldown <= 0.0 {
music::play(1);
self.fire_cooldown = FIRE_COOLDOWN;
}
}
for wall in &self.walls {
if bullet.collides_wall(wall){
bullet.alive = false;
}
}
}
}
fn enemy_chance_shoot(&mut self) {
if self.enemies.len() != 0 {
let chance_shot: u32 = rand::thread_rng().gen_range(1, 100-(3*self.level));
if chance_shot == 5 {
let index_enemy_shooting = rand::thread_rng().gen_range(0, self.enemies.len());
let enemy_shooting = &self.enemies[index_enemy_shooting];
if self.fire_cooldown <= 0.0 {
thread::spawn(|| {
music::play(3);
});
self.fire_cooldown = FIRE_COOLDOWN; //so two shooting threads dont start SDL
self.enemy_bullets.push(
Bullet::new(enemy_shooting.pos.x, enemy_shooting.pos.y, enemy_shooting.dir)
);
}
}
}
}
fn enemy_update(&mut self) {
for enemy in &mut self.enemies {
enemy.update(self.player.pos.x, self.player.pos.y);
for wall in &self.walls {
if enemy.collides(wall) {
enemy.alive = false;
if self.fire_cooldown <= 0.0 {
music::play(2);
self.fire_cooldown = FIRE_COOLDOWN;
}
self.score += 50;
return
}
if self.player.collides_enemy(enemy) {
enemy.alive = false;
self.player.health -=1;
self.player.place_random(self.dimensions);
if self.fire_cooldown <= 0.0 {
music::play(1);
self.fire_cooldown = FIRE_COOLDOWN;
}
return
}
}
}
}
fn wall_update(&mut self) {
for wall in &self.walls {
if self.player.collides(wall){
self.player.health -= 1;
self.player.place_random(self.dimensions);
if self.fire_cooldown <= 0.0 {
music::play(1);
self.fire_cooldown = FIRE_COOLDOWN;
}
match self.player.dir {
Direction::NORTH => self.player.pos.y += 50.0,
Direction::SOUTH => self.player.pos.y -= 50.0,
Direction::EAST => self.player.pos.x -= 50.0,
Direction::WEST => self.player.pos.x += 50.0 }
}
}
}
fn on_update(&mut self, args: &UpdateArgs) {
self.player_bullet_check();
self.enemy_bullet_check();
if self.fire_cooldown > 0.0 {
self.fire_cooldown -= args.dt;
}
self.player_bullets.retain(|b| b.alive);
self.enemy_bullets.retain(|b| b.alive);
self.enemies.retain(|enemy| enemy.alive);
self.enemy_chance_shoot();
self.enemy_update();
self.wall_update();
if self.player.health == 0 {
if self.fire_cooldown <= 0.0 {
music::play(4);
self.fire_cooldown = FIRE_COOLDOWN;
}
self.game_over = true;
}
self.check_win();
if self.new_level {
if self.level == 5 {
self.won = true;
} else {
self.player.reset(75.0, self.dimensions[1] / 2.0);
self.player_bullets.clear();
let num_of_enemies = 4+(2*self.level);
for _ in 0..num_of_enemies {
self.gameobject_random_placement();
}
}
self.new_level = false;
}
}
fn input(&mut self, button: &Button, is_press: bool) {
if is_press && !self.game_over && !self.won {
if let Button::Keyboard(key) = *button {
match key {
Key::Up => {
self.player.is_moving = true;
self.player.dir = Direction::NORTH;
},
Key::Down => {
self.player.is_moving= true;
self.player.dir = Direction::SOUTH;
},
Key::Left => {
self.player.is_moving= true;
self.player.dir = Direction::WEST;
},
Key::Right => {
self.player.is_moving= true;
self.player.dir = Direction::EAST;
},
Key::Space => {
self.player.is_moving= false;
if self.fire_cooldown <= 0.0 {
thread::spawn(|| {
music::play(0);
});
self.fire_cooldown = FIRE_COOLDOWN;
self.player_bullets.push(
Bullet::new(self.player.pos.x, self.player.pos.y, self.player.dir)
);
} else {
self.player_bullets.push(
Bullet::new(self.player.pos.x, self.player.pos.y, self.player.dir)
);
}
},
Key::R => {
self.hard_reset();
}
_ => (),
}
}
} else {
self.player.is_moving= false;
if let Button::Keyboard(key) = *button {
match key {
Key::Up | Key::Down | Key::Left | Key::Right => self.player.is_moving =false,
Key::R => {
self.hard_reset();
},
_ => (),
}
}
}
}
pub fn run(&mut self, window: &mut Window,
mut gl: &mut GlGraphics,
mut glyph_cache: &mut GlyphCache) {
let mut events = Events::new(EventSettings::new());
events.set_ups(FPS);
let num_of_enemies = 4+(2*self.level);
for _ in 0..num_of_enemies {
self.gameobject_random_placement();
}
while let Some(e) = events.next(window) {
if !self.game_over && !self.won {
if let Some(r) = e.update_args() {
self.on_update(&r);
}
}
if let Some(k) = e.press_args() {
self.input(&k,true);
} else if let Some(k) = e.release_args() {
self.input(&k, false);
}
if let Some(u) = e.render_args() {
self.on_draw(&u, &mut gl, &mut glyph_cache);
}
}
}
fn gameobject_random_placement(&mut self) {
let rand_block: u32 = rand::thread_rng().gen_range(1, 4);
let mut randx: f64;
let mut randy: f64;
match rand_block {
1 => { //left
randx= rand::thread_rng().gen_range(45.0, self.dimensions[0]/4.0-20.0);
randy= rand::thread_rng().gen_range(40.0, self.dimensions[1]-135.0);
},
2 => { //top
randx= rand::thread_rng().gen_range(self.dimensions[0]/4.0+50.0, (self.dimensions[0]/4.0)*3.0);
randy= rand::thread_rng().gen_range(40.0, self.dimensions[1]/4.0);
},
3 => { //right
randx= rand::thread_rng().gen_range((self.dimensions[0]/4.0)*3.0+50.0, self.dimensions[0]-50.0);
randy= rand::thread_rng().gen_range(40.0, self.dimensions[1]-135.0);
},
4 => { //bottom
randx= rand::thread_rng().gen_range(self.dimensions[0]/4.0+50.0, (self.dimensions[0]/4.0)*3.0);
randy= rand::thread_rng().gen_range((self.dimensions[1]/4.0)*3.0, self.dimensions[1]-135.0);
},
_ => {
randx= rand::thread_rng().gen_range(45.0, self.dimensions[0]/4.0-20.0);
randy = rand::thread_rng().gen_range(40.0, self.dimensions[1]-135.0);
}
}
//if enemy too close to the player starting try again
while randx > 40.0 && randx < 90.0 && randy > self.dimensions[1] / 2.0 - 50.0 && randy < self.dimensions[1] / 2.0 + 50.0 {
randx = rand::thread_rng().gen_range(45.0, self.dimensions[0]/4.0-10.0);
randy = rand::thread_rng().gen_range(40.0, self.dimensions[1]-135.0);
}
self.enemies.push(Enemy::new(randx, randy));
}
fn hard_reset(&mut self) {
self.level = 1;
self.score = 0;
self.won = false;
self.player.reset(75.0, self.dimensions[1] / 2.0);
self.player_bullets.clear();
self.enemies.clear();
self.game_over = false;
let num_of_enemies = 4+(2*self.level);
for _ in 0..num_of_enemies {
self.gameobject_random_placement();
}
}
fn check_win(&mut self) {
if self.player.pos.x > self.dimensions[0]/2.0-125.0 &&
self.player.pos.x < self.dimensions[0]/2.0+125.0 &&
self.player.pos.y > 5.0 && self.player.pos.y < 30.0 &&
self.enemies.len() == 0 {
self.level +=1;
self.new_level = true;
}
}
}
#[cfg(test)]
mod berzerk_test {
use piston::window::WindowSettings;
use glutin_window::GlutinWindow as Window;
use opengl_graphics::OpenGL;
use super::*;
#[test]
fn test_new_game() {
let opengl = OpenGL::V3_2;
//OpenGL function pointers must be loaded before creating the `Gl` backend
//That is why this window is created
let _window: Window = WindowSettings::new("create test",
[500, 500])
.exit_on_esc(true)
.build()
.expect("Error creating window");
let _gl = GlGraphics::new(opengl);
let _g = Game::new(500.0,500.0);
}
#[test]
fn test_game_walls() {
let opengl = OpenGL::V3_2;
//OpenGL function pointers must be loaded before creating the `Gl` backend
//That is why this window is created
let _window: Window = WindowSettings::new("create test",
[500, 500])
.exit_on_esc(true)
.build()
.expect("Error creating window");
let _gl = GlGraphics::new(opengl);
let mut g = Game::new(500.0,500.0);
let t_walls = [1.0,1.0,2.0,2.0];
g.add_walls(t_walls,t_walls,t_walls,t_walls,t_walls,t_walls,t_walls,t_walls,t_walls);
assert!(g.walls.len() == 9);
}
}
|
use super::Icon;
use crate::JsObject;
pub struct ChatItem {
display_name: String,
peer_id: String,
character_id: Option<u128>,
icon: Icon,
payload: String,
}
impl ChatItem {
pub fn new(
display_name: impl Into<String>,
peer_id: impl Into<String>,
character_id: Option<u128>,
icon: Icon,
payload: impl Into<String>,
) -> Self {
Self {
display_name: display_name.into(),
peer_id: peer_id.into(),
character_id,
icon: icon,
payload: payload.into(),
}
}
pub fn display_name(&self) -> &String {
&self.display_name
}
pub fn peer_id(&self) -> &String {
&self.peer_id
}
pub fn character_id(&self) -> Option<u128> {
self.character_id.clone()
}
pub fn icon(&self) -> &Icon {
&self.icon
}
pub fn payload(&self) -> &String {
&self.payload
}
pub fn as_object(&self) -> JsObject {
object! {
display_name: &self.display_name,
peer_id: &self.peer_id,
character_id: self.character_id.map(|x| x.to_string()),
icon: self.icon.as_object(),
payload: &self.payload
}
}
}
impl From<JsObject> for ChatItem {
fn from(object: JsObject) -> Self {
let display_name = object
.get("display_name")
.and_then(|x| x.as_string())
.unwrap_or(String::from(""));
let peer_id = object
.get("peer_id")
.and_then(|x| x.as_string())
.unwrap_or(String::from(""));
let character_id = object
.get("character_id")
.and_then(|x| x.as_string())
.and_then(|x| x.parse().ok());
let icon = object
.get("icon")
.map(|x| Icon::from(x))
.unwrap_or(Icon::None);
let payload = object
.get("payload")
.and_then(|x| x.as_string())
.unwrap_or(String::from(""));
Self {
display_name,
peer_id,
character_id,
icon,
payload,
}
}
}
|
//! See [`Matrix`].
use crate::types::{ConPat, Lang, Pat, RawPat};
use std::fmt;
/// A 2-D matrix of [`Pat`]s.
pub(crate) struct Matrix<L: Lang> {
/// invariant: all rows are the same length.
rows: Vec<Row<L>>,
}
impl<L: Lang> Default for Matrix<L> {
fn default() -> Self {
Self { rows: Vec::new() }
}
}
impl<L: Lang> Clone for Matrix<L> {
fn clone(&self) -> Self {
Self { rows: self.rows.clone() }
}
}
impl<L: Lang> fmt::Debug for Matrix<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Matrix").field("rows", &self.rows).finish()
}
}
impl<L: Lang> Matrix<L> {
/// Returns the number of rows.
pub(crate) fn num_rows(&self) -> usize {
self.rows.len()
}
/// Returns the number of columns, or `None` if there are no rows.
pub(crate) fn num_cols(&self) -> Option<usize> {
self.rows.first().map(Row::len)
}
/// Returns an iterator over the non-empty rows. Panics if the rows are empty.
pub(crate) fn non_empty_rows(&self) -> impl Iterator<Item = &NonEmptyRow<L>> {
self.rows.iter().map(|r| match r {
Row::Empty => panic!("empty row"),
Row::NonEmpty(r) => r,
})
}
/// Adds a row to the bottom of the matrix.
///
/// If the row ends with a [`Pat::Or`], the row will be expanded into many
/// rows.
///
/// Panics if `row.len()` is not equal to the number of columns in this
/// matrix.
pub(crate) fn push(&mut self, mut row: Vec<Pat<L>>) {
if let Some(nc) = self.num_cols() {
assert_eq!(nc, row.len());
}
match row.pop() {
None => self.rows.push(Row::Empty),
Some(pat) => {
let mut con_pats = Vec::new();
expand_or(&mut con_pats, pat);
for con_pat in con_pats {
self.rows.push(Row::NonEmpty(NonEmptyRow { pats: row.clone(), con_pat }));
}
}
}
}
}
/// Recursively expands or patterns.
fn expand_or<L: Lang>(ac: &mut Vec<ConPat<L>>, pat: Pat<L>) {
match pat.raw {
RawPat::Con(p) => ac.push(p),
RawPat::Or(pats) => {
for pat in pats {
expand_or(ac, pat);
}
}
}
}
/// A matrix row.
enum Row<L: Lang> {
Empty,
NonEmpty(NonEmptyRow<L>),
}
impl<L: Lang> Clone for Row<L> {
fn clone(&self) -> Self {
match self {
Self::Empty => Self::Empty,
Self::NonEmpty(r) => Self::NonEmpty(r.clone()),
}
}
}
impl<L: Lang> fmt::Debug for Row<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Row::Empty => f.write_str("Empty"),
Row::NonEmpty(row) => f.debug_tuple("NonEmpty").field(&row).finish(),
}
}
}
impl<L: Lang> Row<L> {
fn len(&self) -> usize {
match self {
Row::Empty => 0,
Row::NonEmpty(r) => r.pats.len() + 1,
}
}
}
/// An non-empty row, whose last element is a non-or pattern with the given
/// constructor and arguments.
pub(crate) struct NonEmptyRow<L: Lang> {
/// The other patterns in this row.
pub pats: Vec<Pat<L>>,
/// The last pattern.
pub con_pat: ConPat<L>,
}
impl<L: Lang> Clone for NonEmptyRow<L> {
fn clone(&self) -> Self {
Self { pats: self.pats.clone(), con_pat: self.con_pat.clone() }
}
}
impl<L: Lang> fmt::Debug for NonEmptyRow<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NonEmptyRow").field("pats", &self.pats).field("con_pat", &self.con_pat).finish()
}
}
|
fn palindrome_permutation(s1: &str) -> bool {
s1.to_owned()
.replace(" ", "")
.chars()
.rev()
.collect::<String>()
== s1.to_owned().replace(" ", "")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
assert!(palindrome_permutation("taco cat"));
}
#[test]
fn test_2() {
assert!(!palindrome_permutation("banana smooth"));
}
}
|
#[cfg(test)]
#[path = "../../../tests/unit/format/problem/fleet_reader_test.rs"]
mod fleet_reader_test;
use crate::extensions::create_typed_actor_groups;
use crate::format::coord_index::CoordIndex;
use crate::format::problem::reader::{ApiProblem, ProblemProperties};
use crate::format::problem::Matrix;
use crate::parse_time;
use hashbrown::{HashMap, HashSet};
use std::sync::Arc;
use vrp_core::construction::constraints::{Area, TravelLimitFunc};
use vrp_core::models::common::*;
use vrp_core::models::problem::*;
pub(crate) fn create_transport_costs(
api_problem: &ApiProblem,
matrices: &[Matrix],
) -> Result<Arc<dyn TransportCost + Sync + Send>, String> {
if !matrices.iter().all(|m| m.profile.is_some()) && !matrices.iter().all(|m| m.profile.is_none()) {
return Err("all matrices should have profile set or none of them".to_string());
}
if matrices.iter().any(|m| m.profile.is_none()) && matrices.iter().any(|m| m.timestamp.is_some()) {
return Err("when timestamp is set, all matrices should have profile set".to_string());
}
let matrix_profiles = get_profile_index_map(api_problem);
if matrix_profiles.len() > matrices.len() {
return Err(format!(
"not enough routing matrices specified for fleet profiles defined: \
{} must be less or equal to {}",
matrix_profiles.len(),
matrices.len()
));
}
let matrix_data = matrices
.iter()
.enumerate()
.map(|(idx, matrix)| {
let profile = matrix.profile.as_ref().and_then(|p| matrix_profiles.get(p)).cloned().unwrap_or(idx);
(profile, matrix.timestamp.clone(), matrix)
})
.map(|(profile, timestamp, matrix)| {
let (durations, distances) = if let Some(error_codes) = &matrix.error_codes {
let mut durations: Vec<Duration> = Default::default();
let mut distances: Vec<Distance> = Default::default();
for (i, error) in error_codes.iter().enumerate() {
if *error > 0 {
durations.push(-1.);
distances.push(-1.);
} else {
durations.push(*matrix.travel_times.get(i).unwrap() as f64);
distances.push(*matrix.distances.get(i).unwrap() as f64);
}
}
(durations, distances)
} else {
(
matrix.travel_times.iter().map(|d| *d as f64).collect(),
matrix.distances.iter().map(|d| *d as f64).collect(),
)
};
MatrixData::new(profile, timestamp.map(|t| parse_time(&t)), durations, distances)
})
.collect::<Vec<_>>();
let matrix_indices = matrix_data.iter().map(|data| data.index).collect::<HashSet<_>>().len();
if matrix_profiles.len() != matrix_indices {
return Err("amount of fleet profiles does not match matrix profiles".to_string());
}
create_matrix_transport_cost(matrix_data)
}
pub(crate) fn read_fleet(api_problem: &ApiProblem, props: &ProblemProperties, coord_index: &CoordIndex) -> Fleet {
let profile_indices = get_profile_index_map(api_problem);
let mut vehicles: Vec<Arc<Vehicle>> = Default::default();
api_problem.fleet.vehicles.iter().for_each(|vehicle| {
let costs = Costs {
fixed: vehicle.costs.fixed.unwrap_or(0.),
per_distance: vehicle.costs.distance,
per_driving_time: vehicle.costs.time,
per_waiting_time: vehicle.costs.time,
per_service_time: vehicle.costs.time,
};
let index = *profile_indices.get(&vehicle.profile.matrix).unwrap();
let profile = Profile::new(index, vehicle.profile.scale);
let tour_size = vehicle.limits.as_ref().and_then(|l| l.tour_size);
let mut areas = vehicle.limits.as_ref().and_then(|l| l.allowed_areas.as_ref()).map(|areas| {
areas
.iter()
.map(|area| Area {
priority: area.priority,
outer_shape: area.outer_shape.iter().map(|l| l.to_lat_lng()).collect::<Vec<_>>(),
})
.collect::<Vec<_>>()
});
for (shift_index, shift) in vehicle.shifts.iter().enumerate() {
let start = {
let location = coord_index.get_by_loc(&shift.start.location).unwrap();
let earliest = parse_time(&shift.start.earliest);
let latest = shift.start.latest.as_ref().map(|time| parse_time(&time));
(location, earliest, latest)
};
let end = shift.end.as_ref().map(|end| {
let location = coord_index.get_by_loc(&end.location).unwrap();
let time = parse_time(&end.latest);
(location, time)
});
let details = vec![VehicleDetail {
start: Some(VehiclePlace {
location: start.0,
time: TimeInterval { earliest: Some(start.1), latest: start.2 },
}),
end: end.map(|(location, time)| VehiclePlace {
location,
time: TimeInterval { earliest: None, latest: Some(time) },
}),
}];
vehicle.vehicle_ids.iter().for_each(|vehicle_id| {
let mut dimens: Dimensions = Default::default();
dimens.set_value("type_id", vehicle.type_id.clone());
dimens.set_value("shift_index", shift_index);
dimens.set_id(vehicle_id);
if let Some(areas) = areas.take() {
dimens.set_value("areas", areas);
}
if let Some(tour_size) = tour_size {
dimens.set_value("tour_size", tour_size);
}
if props.has_multi_dimen_capacity {
dimens.set_capacity(MultiDimLoad::new(vehicle.capacity.clone()));
} else {
dimens.set_capacity(SingleDimLoad::new(*vehicle.capacity.first().unwrap()));
}
add_vehicle_skills(&mut dimens, &vehicle.skills);
vehicles.push(Arc::new(Vehicle {
profile: profile.clone(),
costs: costs.clone(),
dimens,
details: details.clone(),
}));
});
}
});
let drivers = vec![Arc::new(Driver {
costs: Costs {
fixed: 0.0,
per_distance: 0.0,
per_driving_time: 0.0,
per_waiting_time: 0.0,
per_service_time: 0.0,
},
dimens: Default::default(),
details: vec![],
})];
Fleet::new(drivers, vehicles, Box::new(|actors| create_typed_actor_groups(actors)))
}
pub fn read_travel_limits(api_problem: &ApiProblem) -> Option<TravelLimitFunc> {
let limits = api_problem.fleet.vehicles.iter().filter(|vehicle| vehicle.limits.is_some()).fold(
HashMap::new(),
|mut acc, vehicle| {
let limits = vehicle.limits.as_ref().unwrap().clone();
acc.insert(vehicle.type_id.clone(), (limits.max_distance, limits.shift_time));
acc
},
);
if limits.is_empty() {
None
} else {
Some(Arc::new(move |actor: &Actor| {
if let Some(limits) = limits.get(actor.vehicle.dimens.get_value::<String>("type_id").unwrap()) {
(limits.0, limits.1)
} else {
(None, None)
}
}))
}
}
fn get_profile_index_map(api_problem: &ApiProblem) -> HashMap<String, usize> {
api_problem.fleet.profiles.iter().fold(Default::default(), |mut acc, profile| {
if acc.get(&profile.name).is_none() {
acc.insert(profile.name.clone(), acc.len());
}
acc
})
}
fn add_vehicle_skills(dimens: &mut Dimensions, skills: &Option<Vec<String>>) {
if let Some(skills) = skills {
dimens.set_value("skills", skills.iter().cloned().collect::<HashSet<_>>());
}
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use ::libra_types::proto::*;
pub mod sgtypes {
include!(concat!(env!("OUT_DIR"), "/sgtypes.rs"));
}
|
use crate::server::{ServerConnection, RealServerConnection};
use serenity::framework::standard::{Args, CommandError};
use serenity::model::channel::Message;
use serenity::prelude::Context;
use super::alias_from_arg_or_channel_name;
use crate::db::*;
use crate::model::*;
use crate::commands::servers::{get_details_for_alias, StartedStateDetails, PotentialPlayer};
use crate::commands::servers::NationDetails;
use crate::commands::servers::turn_check::{notify_player_for_new_turn, NewTurnNation};
fn start_helper<C: ServerConnection>(
db_conn: &DbConnection,
address: &str,
alias: &str,
) -> Result<(), CommandError> {
let server = db_conn.game_for_alias(&alias)?;
match server.state {
GameServerState::StartedState(_, _) => {
return Err(CommandError::from("game already started"))
}
GameServerState::Lobby(lobby_state) => {
let game_data = C::get_game_data(&address)?;
if game_data.nations.len() as i32 > lobby_state.player_count {
return Err(CommandError::from("game has more players than the lobby"));
}
let started_state = StartedState {
address: address.to_string(),
last_seen_turn: game_data.turn,
};
db_conn.insert_started_state(&alias, &started_state)?;
// This is a bit of a hack, the turncheck should take care of it
let started_details = get_details_for_alias::<RealServerConnection>(db_conn, alias)?;
let option_snek_state = crate::snek::snek_details(address).ok().and_then(|i| i);
let mut new_turn_messages = vec![];
if let NationDetails::Started(started_details) = started_details.nations {
if let StartedStateDetails::Uploading(uploading_details) = started_details.state {
for player in uploading_details.uploading_players {
if let PotentialPlayer::RegisteredOnly(user_id, nation_id) = player.potential_player {
new_turn_messages.push(NewTurnNation {
user_id,
message: format!(
"Uploading has started in {}! You registered as {}. Server address is '{}'.",
alias, nation_id.name(option_snek_state.as_ref()), started_details.address
),
});
}
}
}
}
for new_turn_message in &new_turn_messages {
let _ = notify_player_for_new_turn(new_turn_message);
}
}
}
Ok(())
}
pub fn start<C: ServerConnection>(
context: &mut Context,
message: &Message,
mut args: Args,
) -> Result<(), CommandError> {
let data = context.data.lock();
let db_conn = data
.get::<DbConnectionKey>()
.ok_or("No DbConnection was created on startup. This is a bug.")?;
let address = args.single_quoted::<String>()?;
let alias = alias_from_arg_or_channel_name(&mut args, &message)?;
if !args.is_empty() {
return Err(CommandError::from(
"Too many arguments. TIP: spaces in arguments need to be quoted \"like this\"",
));
}
start_helper::<C>(db_conn, &address, &alias)?;
message.reply(&"started!")?;
Ok(())
}
|
use totsu::prelude::*;
use totsu::*;
use totsu_f32cuda::F32CUDA;
use totsu_core::LinAlgEx;
use rand::prelude::*;
use rand_xoshiro::rand_core::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
use std::str::FromStr;
fn bench<L: LinAlgEx<F=f32>>(sz: usize) {
let n = sz;
let m = n + sz;
let p = 0;
let mut rng = Xoshiro256StarStar::seed_from_u64(0);
//----- construct LP
let vec_c = MatBuild::new(MatType::General(n, 1))
.by_fn(|_, _| {
-rng.gen::<f32>()
});
//println!("vec_c:\n{}", vec_c);
let mat_g = MatBuild::new(MatType::General(m, n))
.by_fn(|r, c| {
if r < n {
if r == c {
-1.
}
else {
0.
}
}
else {
rng.gen()
}
});
//println!("mat_g:\n{}", mat_g);
let vec_h = MatBuild::new(MatType::General(m, 1))
.by_fn(|r, _| {
if r < n {
0.
}
else {
rng.gen()
}
});
//println!("vec_h:\n{}", vec_h);
let mat_a = MatBuild::new(MatType::General(p, n));
let vec_b = MatBuild::new(MatType::General(p, 1));
//println!("mat_a:\n{}", mat_a);
//println!("vec_b:\n{}", vec_b);
//----- solve LP
let s = Solver::<L>::new()
.par(|p| {
p.eps_acc = 1e-3;
});
let mut lp = ProbLP::new(vec_c, mat_g, vec_h, mat_a, vec_b);
let prob = lp.problem();
let rslt = s.solve(prob).unwrap();
let vec_r = MatBuild::<L>::new(MatType::General(n, 1))
.iter_colmaj(rslt.0);
println!("result:\n{}", vec_r);
}
fn main() -> anyhow::Result<()> {
env_logger::init();
let mut sz = 100;
let args: Vec<String> = std::env::args().collect();
if args.len() >= 2 {
if let Ok(a) = usize::from_str(&args[1]) {
sz = a; // sz can be specified by 1st argument
}
}
bench::<FloatGeneric<f32>>(sz);
bench::<F32CUDA>(sz);
Ok(())
}
|
mod net;
pub use net::{PipeConnection, PipeListener, ClientConnection};
|
use glob::{glob, GlobError};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::{create_dir_all, read_to_string};
use std::path::PathBuf;
use tauri::api::path::{document_dir, resource_dir};
use tauri::Window;
#[derive(Serialize, Deserialize)]
struct Metadata {
api: i16,
name: String,
description: String,
author: String,
icon: String,
tags: String,
}
pub struct Script {
metadata: Metadata,
pub string: String,
}
impl Script {
fn new(string: &str) -> Result<Script, serde_json::error::Error> {
let start_bytes = string.find("/**").unwrap_or(0) + 3;
let end_bytes = string.find("**/").unwrap_or(string.len());
match parse_meta(&string[start_bytes..end_bytes]) {
Err(msg) => Err(msg),
Ok(meta) => Ok(Script {
metadata: meta,
string: string.to_string().replace("require(", "await requireMod("),
}),
}
}
}
fn parse_meta(string: &str) -> serde_json::Result<Metadata> {
serde_json::from_str(&string)
}
fn append_script(
window: &Window,
script_list: &mut HashMap<String, Script>,
script: Result<&PathBuf, &GlobError>,
) -> tauri::Result<()> {
let file = script.unwrap();
let script_string = read_to_string(&file).unwrap();
match Script::new(&script_string) {
Err(_) => Ok(()),
Ok(val) => {
let meta = &val.metadata;
window.eval(&format!(
"spotlight.addAction({:?}, {:?}, {:?}, {:?})",
meta.name, meta.description, meta.icon, meta.tags
))?;
script_list.insert(meta.name.to_string(), val);
Ok(())
}
}
}
fn append_lib(
script_list: &mut HashMap<String, Script>,
script: Result<&PathBuf, &GlobError>,
builtin: bool,
) -> tauri::Result<()> {
let file = script.unwrap();
let script_string = read_to_string(&file).unwrap();
let file_name = file.file_name().unwrap().to_str().unwrap();
let lib = Script {
metadata: Metadata {
api: 1,
name: if builtin {
String::from("@boop/") + file_name
} else {
String::from("lib/") + file_name
},
description: "Is lib".into(),
author: "Is lib".into(),
icon: "Is lib".into(),
tags: "lib".into(),
},
string: script_string.to_string(),
};
script_list.insert(lib.metadata.name.to_string(), lib);
Ok(())
}
pub fn build_scripts(
window: Window,
script_list: &mut HashMap<String, Script>,
) -> tauri::Result<()> {
script_list.clear(); // flush scripts on reload
if let Some(resource_dir) = resource_dir(&crate::PACKAGE_INFO.get().unwrap()) {
let script_path = &resource_dir.join("scripts");
install_scripts(&window, script_list, script_path, true)?;
}
if let Some(user_dir) = document_dir() {
let bloop_dir = user_dir.join("bloop");
if bloop_dir.exists() {
install_scripts(&window, script_list, &bloop_dir, false)?;
} else {
create_dir_all(bloop_dir).unwrap();
}
}
window.eval("spotlight.spotlightActions.finalize()")?;
Ok(())
}
pub fn install_scripts(
window: &Window,
script_list: &mut HashMap<String, Script>,
pattern: &PathBuf,
builtin: bool,
) -> tauri::Result<()> {
for script in glob(pattern.join("*.js").to_str().unwrap()).unwrap() {
append_script(window, script_list, script.as_ref())?;
}
for script in glob(pattern.join("lib").join("*.js").to_str().unwrap()).unwrap() {
append_lib(script_list, script.as_ref(), builtin)?;
}
Ok(())
}
pub fn script_eval(script_obj: &Script, window: &Window) -> tauri::Result<()> {
let js = format!(
"(async () => {{ {}; main(editorObj) }})()",
&script_obj.string
);
window.eval(&js)?;
window.eval("spotlight.spotlightActions.Ok()")?;
Ok(())
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.