text stringlengths 8 4.13M |
|---|
use amethyst::{
assets::Handle,
core::{nalgebra::Vector3, Transform},
input::{is_close_requested, is_key_down},
prelude::*,
renderer::{Camera, DisplayConfig, Projection, VirtualKeyCode},
ui::{Anchor, FontAsset, UiText, UiTransform},
};
use crate::component::{Ball, Block, Cube, Direction, Paddle};
use crate::config::{BallConfig, BlockConfig, PaddleConfig};
use crate::intro;
use crate::pause::Pause;
use crate::resources::{Lifes, MaterialVector, WindowSize};
use crate::util::*;
use ncollide2d::{math, shape};
pub struct Level;
#[derive(PartialEq)]
pub enum GameState {
Running,
Menu,
}
impl Default for GameState {
fn default() -> Self {
GameState::Menu
}
}
impl<'a, 'b> State<GameData<'a, 'b>, StateEvent> for Level {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let world = data.world;
*world.write_resource() = GameState::Running;
initialize_camera(world);
initialize_world_boundaries(world);
initialize_pad(world);
initialize_ball(world);
initialize_block(world);
initialize_lifes(world);
}
fn update(&mut self, data: StateData<GameData>) -> Trans<GameData<'a, 'b>, StateEvent> {
data.data.update(&data.world);
if data.world.read_storage::<Block>().is_empty() {
return Trans::Switch(Box::new(intro::Intro { ui: None }));
}
if !data.world.read_storage::<Ball>().is_empty() {
return Trans::None;
}
let lifes = data.world.write_resource::<Lifes>().lifes - 1;
if let Some(e) = data.world.read_resource::<Lifes>().e {
if let Some(text) = data.world.write_storage::<UiText>().get_mut(e) {
text.text = format!("{}", lifes).to_string();
}
}
if lifes == 0 {
Trans::Switch(Box::new(intro::Intro { ui: None }))
} else {
initialize_ball(data.world);
data.world.write_resource::<Lifes>().lifes = lifes;
Trans::None
}
}
fn on_stop(&mut self, data: StateData<GameData>) {
data.world.delete_all();
*data.world.write_resource() = GameState::Menu;
}
fn on_resume(&mut self, data: StateData<GameData>) {
*data.world.write_resource() = GameState::Running;
}
fn handle_event(
&mut self,
data: StateData<GameData>,
event: StateEvent,
) -> Trans<GameData<'a, 'b>, StateEvent> {
if let StateEvent::Window(event) = &event {
if is_close_requested(&event) || is_key_down(&event, VirtualKeyCode::Escape) {
Trans::Quit
} else if is_key_down(&event, VirtualKeyCode::P) {
*data.world.write_resource() = GameState::Menu;
Trans::Push(Box::new(Pause { ui: None }))
} else {
Trans::None
}
} else {
Trans::None
}
}
}
fn initialize_camera(world: &mut World) {
let (width, height) = {
let conf = world.read_resource::<DisplayConfig>();
let (w, h) = conf.dimensions.unwrap();
(w as f32, h as f32)
};
let mut transform = Transform::default();
transform.set_z(1.0);
world
.create_entity()
.with(Camera::from(Projection::orthographic(
0.0, width, 0.0, height,
)))
.with(transform)
.build();
*world.write_resource() = WindowSize { width, height };
}
fn initialize_world_boundaries(world: &mut World) {
let (width, height) = {
let conf = world.read_resource::<DisplayConfig>();
let (w, h) = conf.dimensions.unwrap();
(w as f32, h as f32)
};
{
// top border
let cube = Cube {
obj: shape::Cuboid::new(math::Vector::new(2. * width, 10.)),
};
let mut tran = Transform::default();
tran.set_xyz(-width * 0.5, height + 5., 0.);
world.create_entity().with(cube).with(tran).build();
}
{
// left border
let cube = Cube {
obj: shape::Cuboid::new(math::Vector::new(10., 2. * height)),
};
let mut tran = Transform::default();
tran.set_xyz(-5., 0., 0.);
world.create_entity().with(cube).with(tran).build();
}
{
// right border
let cube = Cube {
obj: shape::Cuboid::new(math::Vector::new(10., 2. * height)),
};
let mut tran = Transform::default();
tran.set_xyz(width + 5., 0., 0.);
world.create_entity().with(cube).with(tran).build();
}
}
fn initialize_pad(world: &mut World) {
let (half_width, half_height, offset, speed) = {
let config = world.read_resource::<PaddleConfig>();
(
config.width / 2.0,
config.height / 2.0,
config.offset,
config.speed,
)
};
let pad_mesh = create_mesh(
world,
generate_rectangle_vertices(-half_width, -half_height, half_width, half_height),
);
let pad_material = {
let m = world.read_resource::<MaterialVector>();
m.pad.clone()
};
let mut trans = Transform::default();
{
let conf = world.read_resource::<DisplayConfig>();
let (w, _) = conf.dimensions.unwrap();
trans.set_xyz((w as f32) * 0.5 - half_width, half_height + offset, 0.);
}
let pad = Paddle { speed };
let cube = Cube {
obj: shape::Cuboid::new(math::Vector::new(half_width, half_height)),
};
world
.create_entity()
.with(pad_mesh)
.with(cube)
.with(pad_material)
.with(trans)
.with(pad)
.with(Direction(Vector3::new(0f32, 0f32, 0f32)))
.build();
}
fn initialize_ball(world: &mut World) {
let (speed, radius) = {
let config = world.read_resource::<BallConfig>();
(config.speed, config.radius)
};
let pad_mesh = create_mesh(world, generate_circle_vertices(radius, 16));
let pad_material = {
let m = world.read_resource::<MaterialVector>();
m.ball.clone()
};
let mut trans = Transform::default();
{
let conf = world.read_resource::<DisplayConfig>();
let (w, h) = conf.dimensions.unwrap();
trans.set_xyz((w as f32) / 2. - radius, (h as f32) / 2. - radius, 0.);
};
let ball = Ball {
obj: shape::Ball::new(radius),
};
world
.create_entity()
.with(pad_mesh)
.with(pad_material)
.with(trans)
.with(ball)
.with(Direction(Vector3::new(speed, speed, 0f32)))
.build();
}
fn initialize_block(world: &mut World) {
let (half_width, half_height) = {
let config = world.read_resource::<BlockConfig>();
(config.width / 2.0, config.height / 2.0)
};
let width_off = {
let conf = world.read_resource::<DisplayConfig>();
let (w, _) = conf.dimensions.unwrap();
((w as f32) - 10f32 * 2.0 * half_width) / 11f32
};
for rows in 0..10 {
for cols in 0..3 {
let pad_mesh = create_mesh(
world,
generate_rectangle_vertices(-half_width, -half_height, half_width, half_height),
);
let life = cols + 1;
let material = {
let m = world.read_resource::<MaterialVector>();
m.lifes[life + 1].clone()
};
let mut trans = Transform::default();
let x = width_off + half_width + (2.0 * half_width + width_off) * (rows as f32);
let y = 400f32 + (cols as f32) * (2.0 * half_height + 10f32);
trans.set_xyz(x, y, 0.);
let block = Block { life: life as i32 };
let cube = Cube {
obj: shape::Cuboid::new(math::Vector::new(half_width, half_height)),
};
world
.create_entity()
.with(pad_mesh)
.with(cube)
.with(material)
.with(trans)
.with(block)
.build();
}
}
}
fn initialize_lifes(world: &mut World) {
let lifes = match world.read_resource::<Lifes>().lifes {
0 => 3,
x => x,
};
let font = world.read_resource::<Handle<FontAsset>>().clone();
let transform = UiTransform::new(
"P1".to_string(),
Anchor::BottomRight,
-50.,
50.,
1.,
50.,
50.,
0,
);
let text = UiText::new(
font,
format!("{}", lifes).to_string(),
[1., 1., 1., 1.],
50.,
);
let e = world.create_entity().with(transform).with(text).build();
world.write_resource::<Lifes>().lifes = lifes;
world.write_resource::<Lifes>().e.replace(e);
}
|
//! Responses for Network service Commands
use super::types::*;
use atat::atat_derive::AtatResp;
use heapless::{consts, String};
/// 7.3 Signal quality +CSQ
#[derive(Clone, AtatResp, defmt::Format)]
pub struct SignalQuality {
#[at_arg(position = 0)]
pub signal_power: u8,
#[at_arg(position = 1)]
pub qual: u8,
}
/// 7.5 Operator selection +COPS
#[derive(Clone, AtatResp)]
pub struct OperatorSelection {
#[at_arg(position = 0)]
pub mode: OperatorSelectionMode,
#[at_arg(position = 1)]
pub oper: Option<OperatorNameFormat>,
#[at_arg(position = 2)]
pub act: Option<RatAct>,
}
/// 7.8 Radio Access Technology (RAT) selection +URAT
#[derive(Clone, AtatResp)]
pub struct RadioAccessTechnology {
#[at_arg(position = 0)]
pub act: RadioAccessTechnologySelected,
}
/// 7.14 Network registration status +CREG
#[derive(Clone, AtatResp)]
pub struct NetworkRegistrationStatus {
#[at_arg(position = 0)]
pub n: NetworkRegistrationUrcConfig,
#[at_arg(position = 1)]
pub stat: NetworkRegistrationStat,
#[at_arg(position = 2)]
pub lac: Option<String<consts::U4>>,
#[at_arg(position = 3)]
pub ci: Option<String<consts::U8>>,
#[at_arg(position = 4)]
pub act_status: Option<u8>,
}
|
use siro::html::{
attr::{placeholder, value},
button, div,
event::{on_click, on_input},
input,
};
use siro::prelude::*;
use futures::prelude::*;
use futures::{select, stream::FuturesUnordered};
use serde::Deserialize;
use wasm_bindgen::prelude::*;
use wee_alloc::WeeAlloc;
#[global_allocator]
static ALLOC: WeeAlloc = WeeAlloc::INIT;
// ==== model ====
struct Model {
repo_slug: String,
branch: String,
response: Option<Branch>,
}
#[derive(Debug, Deserialize)]
struct Branch {
name: String,
commit: Commit,
}
#[derive(Debug, Deserialize)]
struct Commit {
sha: String,
commit: CommitDetails,
}
#[derive(Debug, Deserialize)]
struct CommitDetails {
author: Signature,
committer: Signature,
}
#[derive(Debug, Deserialize)]
struct Signature {
name: String,
email: String,
}
// ==== update ====
enum Msg {
UpdateRepoSlug(String),
UpdateBranch(String),
RequestFetch,
UpdateResponse(Branch),
}
// Cmd is a user-defined type that indicates the operations performed
// by the runtime.
//
// Unlike Elm, this type is defined on the application side that is not
// tied to the concrete logic.
enum Cmd {
Fetch(String),
}
fn update(model: &mut Model, msg: Msg) -> Option<Cmd> {
match msg {
Msg::UpdateRepoSlug(slug) => {
model.repo_slug = slug;
None
}
Msg::UpdateBranch(branch) => {
model.branch = branch;
None
}
Msg::RequestFetch => {
let repo_slug = model.repo_slug.trim();
let mut branch = model.branch.trim();
if branch.is_empty() {
branch = "master";
}
let url = format!(
"https://api.github.com/repos/{}/branches/{}",
repo_slug, branch
);
Some(Cmd::Fetch(url))
}
Msg::UpdateResponse(response) => {
model.response.replace(response);
None
}
}
}
// ==== view ====
fn view(model: &Model) -> impl Nodes<Msg> {
div(
(),
(
div(
(),
(
input::text((
placeholder("Repository"),
value(model.repo_slug.clone()),
on_input(Msg::UpdateRepoSlug),
)),
input::text((
placeholder("Branch (default: master)"),
value(model.branch.clone()),
on_input(Msg::UpdateBranch),
)),
button(on_click(|| Msg::RequestFetch), "Fetch"),
),
), //
div(
(),
match model.response {
Some(ref branch) => format!("branch: {:?}", branch).into(),
None => None,
},
),
),
)
}
// ==== runtime ====
#[wasm_bindgen(start)]
pub async fn main() -> siro_web::Result<()> {
console_error_panic_hook::set_once();
let env = siro_web::Env::new()?;
// Start the Web application and mount on the specified DOM node.
let mut app = env.mount("#app")?;
// Miscellaneous values used in event loop.
let client = reqwest::Client::new();
let mut cmd_tasks = FuturesUnordered::new();
// Initialize the model and render as DOM tree.
let mut model = Model {
repo_slug: "ubnt-intrepid/siro".into(),
branch: "main".into(),
response: None,
};
app.render(view(&model))?;
// Run the event loop.
loop {
// Receive a message from the environment.
let msg = select! {
msg = app.select_next_some() => msg,
msg = cmd_tasks.select_next_some() => msg,
complete => break,
};
// Apply the message to model and update the view.
let cmd = update(&mut model, msg);
app.render(view(&model))?;
// Dispatch the command returned from application.
//
// Here, `cmd` is just a value that is not abstracted like `Cmd<Msg>`,
// and it is manually dispatched inside the event loop.
//
// The dispatch result will be returned to the application side
// as the value of `Msg`.
match cmd {
Some(Cmd::Fetch(url)) => {
let send = client
.get(&url)
.header("Accept", "application/vnd.github.v3+json")
.send();
cmd_tasks.push(async move {
let resp = send.await.unwrap();
let text = resp.text().await.unwrap();
let branch_info: Branch = serde_json::from_str(&text).unwrap();
Msg::UpdateResponse(branch_info)
});
}
None => (),
}
}
Ok(())
}
|
use std::fs::{self, File};
use std::time::{Instant, Duration};
use serde_json::value::Value as JValue;
use serde_json;
use csv::Writer as CSVWriter;
use csv::Result as CSVResult;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
#[derive(Serialize, Deserialize)]
struct Field {
path : String,
typename : Option<String>
}
#[derive(Serialize, Deserialize)]
struct Mapping {
if_has_key : Option<String>,
fields : BTreeMap<String, Field>
}
#[derive(Serialize, Deserialize)]
struct Schema {
record_type_key : String,
mappings : BTreeMap<String, Mapping>
}
struct Writer {
csvwriter : CSVWriter<File>,
count : u64,
path : PathBuf,
next_write : Instant
}
pub struct Translator<F>
where F : FnMut(&Path, &str, u64) -> bool
{
outfiles : BTreeMap<String, Writer>,
schema : Schema,
write_interval : Duration,
retry_interval : Duration,
write_cb : F
}
fn fetch_schema(path : &Path) -> Result<Schema, String> {
let schemafile = File::open(path).map_err(|e| e.to_string())?;
serde_json::from_reader(schemafile).map_err(|e| e.to_string())
}
impl<F> Translator<F>
where F : FnMut(&Path, &str, u64) -> bool
{
pub fn new(
write_dir: &Path,
write_interval : Duration,
retry_interval : Duration,
schema_file : &Path,
write_cb : F) -> Translator<F> {
let schema = fetch_schema(schema_file).unwrap();
let res : BTreeMap<String, Writer> =
schema.mappings.iter().fold( BTreeMap::new(), |mut m, (k,mapping)| {
let path = write_dir.join(k);
let columns : Vec<&String> = mapping.fields.keys().collect();
let w = Self::new_writer(&path, true, &columns).unwrap();
m.insert(k.clone(), Writer {
path : PathBuf::from(path),
csvwriter : w,
count : 0,
next_write : Instant::now() + write_interval
});
m
});
return Translator {
outfiles : res,
schema : schema,
write_interval : write_interval,
retry_interval : retry_interval,
write_cb : write_cb
}
}
fn new_writer(path : &Path, _truncate : bool, columns : &Vec<&String>) -> Result<CSVWriter<File>, String> {
let f = fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path).map_err(|e| e.to_string())?;
let mut w = CSVWriter::from_writer(f); //.flexible(true);
// add the header
w.encode(columns).unwrap();
Ok(w)
}
pub fn process(&mut self, jval : &JValue) -> Option<u64>
{
let ref appname = jval.get(&self.schema.record_type_key);
if appname.is_none() { return None; }
let app = appname.unwrap().as_str().unwrap();
let mapping = self.schema.mappings.get(app);
if mapping.is_none() { return None; }
let mapping = mapping.unwrap();
match mapping.if_has_key {
Some(ref ifhk) => {
if jval.get(ifhk).is_none() {
return None
}
},
None => {}
}
let mut result = Vec::<String>::with_capacity(mapping.fields.len());
for (_, field) in mapping.fields.iter() {
match jval.pointer(&field.path) {
Some(val) => {
if val.is_number() {
match val.as_f64() {
Some(v) => result.push(v.to_string()),
None => result.push("0".to_owned())
}
} else {
match val.as_str() {
Some(v) => result.push(v.to_owned()),
None => result.push(String::new())
}
}
},
None => {result.push(String::new())}
}
}
if result.is_empty() {
return None
}
let ref mut writer = self.outfiles.get_mut(app).unwrap();
match writer.csvwriter.write(result.iter()) {
Ok(_) => { writer.count += 1;},
Err(e) => { error!("{}", e.to_string()); }
}
if (writer.next_write <= Instant::now()) && writer.count > 0 {
writer.csvwriter.flush().unwrap();
let ref mut cb = self.write_cb;
if cb(&writer.path, app, writer.count) {
writer.next_write = Instant::now() + self.write_interval;
writer.count = 0;
let columns : Vec<&String> = mapping.fields.keys().collect();
writer.csvwriter = Self::new_writer(&writer.path, true, &columns).unwrap();
} else {
writer.next_write = Instant::now() + self.retry_interval;
}
}
Some(writer.count)
}
}
|
pub trait HasArea {
fn name(&self) -> String;
fn area(&self) -> f64;
}
pub struct Circle {
pub x: f64,
pub y: f64,
pub radius: f64,
pub name: String
}
impl HasArea for Circle {
fn name(&self) -> String {
self.name.clone()
}
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
impl Default for Circle {
fn default() -> Self {
Self {
x: 0.0f64,
y: 0.0f64,
radius: 0.0f64,
name: String::from("circle"),
}
}
}
pub struct Square {
pub x: f64,
pub y: f64,
pub side: f64,
pub name: String
}
impl HasArea for Square {
fn name(&self) -> String {
self.name.clone()
}
fn area(&self) -> f64 {
self.side * self.side
}
}
impl Default for Square {
fn default() -> Self {
Self {
x: 0.0f64,
y: 0.0f64,
side: 0.0f64,
name: String::from("square"),
}
}
}
pub fn print_area<T: HasArea>(shape: T) {
println!("This {} has an area of {}", shape.name(), shape.area());
} |
use super::pool::*;
use super::config::*;
pub struct Client{
pub pool: Pool,
}
impl Client {
pub fn new<C: ToPqConfig>(conf: C, pool_size: usize) -> Result<Client, ConfParseError> {
Ok(Client{
pool: Pool::new(conf, pool_size)?,
})
}
pub async fn get_conn(&self) -> Result<PooledConnection, ConnectionPoolError> {
self.pool.get_conn().await
}
}
#[derive(Debug)]
pub enum ClientError {
}
|
//https://ptrace.fefe.de/wp/wpopt.rs
// gcc -o lines lines.c
// tar xzf llvm-8.0.0.src.tar.xz
// find llvm-8.0.0.src -type f | xargs cat | tr -sc 'a-zA-Z0-9_' '\n' | perl -ne 'print unless length($_) > 1000;' | ./lines > words.txt
//#![feature(impl_trait_in_bindings)]
use std::fmt::Write;
use std::io;
use std::iter::FromIterator;
use bytes::{BufMut, Bytes, BytesMut};
use futures::future;
use futures::stream;
use futures::Stream;
use tokio::codec::{BytesCodec, FramedRead, FramedWrite};
use tokio::prelude::*;
use tokio::runtime::Runtime;
use word_count::util::*;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use std::cmp::max;
use parallel_stream::stream_fork::ForkRR;
//use word_count::StreamExt;
//use word_count::TimedStream;
const BUFFER_SIZE: usize = 4;
//use futures::sync::mpsc::channel;
const CHUNKS_CAPACITY: usize = 256;
fn reduce_task<InItem, OutItem, FBuildPipeline, OutFuture, E>(
src: Receiver<InItem>,
sink: Sender<OutItem>,
builder: FBuildPipeline,
) -> impl Future<Item = (), Error = ()>
where
E: std::error::Error,
OutFuture: Future<Item = OutItem, Error = E>,
FBuildPipeline: FnOnce(Receiver<InItem>) -> OutFuture,
{
future::lazy(move || {
let task = builder(src)
.and_then(|result| {
sink.sink_map_err(|e| panic!("join send error: {}", e))
.send(result)
})
.map(|_sink| ())
.map_err(|e| panic!("pipe_err:{:?}", e));
task
})
}
#[inline(never)]
fn task_fn(stream: Receiver<Bytes>) -> impl Future<Item = FreqTable, Error = io::Error> {
let table_future = stream
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("recv error: {:#?}", e)))
.fold(FreqTable::new(), |mut frequency, text| {
count_bytes(&mut frequency, &text);
future::ok::<FreqTable, io::Error>(frequency)
});
table_future
}
fn main() -> io::Result<()> {
let conf = parse_args("word count parallel buf");
let mut runtime = Runtime::new()?;
let (input, output) = open_io_async(&conf);
let input_stream = FramedRead::new(input, WholeWordsCodec::new());
let output_stream = FramedWrite::new(output, BytesCodec::new());
let (fork, join) = {
let mut senders = Vec::new();
//let mut join = Join::new(|(_word, count)| { *count});
let pipe_theards = max(1, conf.threads); // discount I/O Thread
let (out_tx, out_rx) = channel::<FreqTable>(pipe_theards);
for _i in 0..pipe_theards {
let (in_tx, in_rx) = channel::<Bytes>(BUFFER_SIZE);
senders.push(in_tx);
let pipe = reduce_task(in_rx, out_tx.clone(), task_fn);
runtime.spawn(pipe);
//join.add(out_rx);
}
let fork = ForkRR::new(senders);
(fork, out_rx)
};
let file_reader = input_stream
//.meter("file_src".to_string())
.forward(fork.sink_map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("fork send error: {}", e))
}))
.map(|(_in, _out)| ())
.map_err(|e| {
eprintln!("error: {}", e);
panic!()
});
runtime.spawn(file_reader);
let sub_table_stream /*: impl Stream<Item=HashMap<Vec<u8>, u64>, Error=io::Error> + Send*/ = join
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("recv error: {:#?}", e)));
let file_writer = sub_table_stream
.fold(FreqTable::new(), |mut frequency, mut sub_table| {
for (word, count) in sub_table.drain() {
*frequency.entry(word).or_insert(0) += count;
}
future::ok::<FreqTable, io::Error>(frequency)
})
.map(|mut frequency| {
let mut frequency_vec = Vec::from_iter(frequency.drain());
frequency_vec.sort_by(|&(_, a), &(_, b)| b.cmp(&a));
stream::iter_ok(frequency_vec).chunks(CHUNKS_CAPACITY) // <- TODO performance?
})
.flatten_stream()
//TODO//.tag()
.map(|chunk| {
let mut buffer = BytesMut::with_capacity(CHUNKS_CAPACITY * 15);
for (word_raw, count) in chunk {
let word = utf8(&word_raw).expect("UTF8 encoding error");
let max_len = word_raw.len() + 15;
if buffer.remaining_mut() < max_len {
buffer.reserve(10 * max_len);
}
buffer
.write_fmt(format_args!("{} {}\n", word, count))
.expect("Formating error");
//for testing w/o output: // buffer.truncate(0);
}
buffer.freeze()
})
.forward(output_stream);
let (_word_stream, _out_file) = runtime.block_on(file_writer)?;
runtime.shutdown_on_idle();
Ok(())
}
|
pub trait GraphTraversal {
fn bwd_edges(&self, v: usize) -> &Vec<usize>;
fn fwd_edges(&self, v: usize) -> &Vec<usize>;
fn all_bwd_edges(&self) -> &Vec<Vec<usize>>;
fn all_fwd_edges(&self) -> &Vec<Vec<usize>>;
fn sources(&self) -> Vec<usize>;
}
pub struct Graph {
e_fwd: Vec<Vec<usize>>,
e_bwd: Vec<Vec<usize>>,
}
impl GraphTraversal for Graph {
fn bwd_edges(&self, v: usize) -> &Vec<usize> {
self.e_bwd.get(v).unwrap()
}
fn fwd_edges(&self, v: usize) -> &Vec<usize> {
self.e_fwd.get(v).unwrap()
}
fn all_bwd_edges(&self) -> &Vec<Vec<usize>> {
&self.e_bwd
}
fn all_fwd_edges(&self) -> &Vec<Vec<usize>> {
&self.e_fwd
}
fn sources(&self) -> Vec<usize> {
self.e_bwd.iter().enumerate().filter_map(|(i, edges)| { if edges.len() == 0 { Some(i) } else { None } } ).collect::<Vec<usize>>()
}
}
impl Graph {
pub fn new() -> Graph {
Graph { e_fwd: Vec::new(), e_bwd: Vec::new() }
}
pub fn new_with_edges(e_fwd: Vec<Vec<usize>>, e_bwd: Vec<Vec<usize>>) -> Graph {
Graph { e_fwd: e_fwd, e_bwd: e_bwd }
}
pub fn sort_fwd(&mut self) -> &Graph {
for mut s in &mut self.e_fwd {
s.sort();
}
self
}
pub fn sort_bwd(&mut self) -> &Graph {
for mut s in &mut self.e_bwd {
s.sort();
}
self
}
pub fn len(&self) -> usize {
self.e_fwd.len()
}
}
#[test]
fn simple_graph() {
}
|
pub mod binding;
mod environment;
pub mod global_user;
pub mod metadata;
pub mod target;
pub use environment::{Environment, QueryEnvironment};
|
use crate::headers::from_headers::*;
use crate::prelude::*;
use crate::resources::collection::{IndexingPolicy, PartitionKey};
use azure_core::headers::{etag_from_headers, session_token_from_headers};
use azure_core::{collect_pinned_stream, Request as HttpRequest, Response as HttpResponse};
use chrono::{DateTime, Utc};
#[derive(Debug, Clone)]
pub struct CreateCollectionOptions {
partition_key: PartitionKey,
consistency_level: Option<ConsistencyLevel>,
indexing_policy: Option<IndexingPolicy>,
offer: Option<Offer>,
}
impl CreateCollectionOptions {
pub fn new<P: Into<PartitionKey>>(partition_key: P) -> Self {
Self {
partition_key: partition_key.into(),
consistency_level: None,
indexing_policy: None,
offer: None,
}
}
setters! {
consistency_level: ConsistencyLevel => Some(consistency_level),
indexing_policy: IndexingPolicy => Some(indexing_policy),
offer: Offer => Some(offer),
}
pub(crate) fn decorate_request(
&self,
request: &mut HttpRequest,
collection_name: &str,
) -> crate::Result<()> {
azure_core::headers::add_optional_header2(&self.offer, request)?;
azure_core::headers::add_optional_header2(&self.consistency_level, request)?;
let collection = CreateCollectionBody {
id: collection_name,
indexing_policy: &self.indexing_policy,
partition_key: &self.partition_key,
};
request.set_body(bytes::Bytes::from(serde_json::to_string(&collection)?).into());
Ok(())
}
}
/// Body for the create collection request
#[derive(Serialize, Debug)]
struct CreateCollectionBody<'a> {
pub id: &'a str,
#[serde(rename = "indexingPolicy", skip_serializing_if = "Option::is_none")]
pub indexing_policy: &'a Option<IndexingPolicy>,
#[serde(rename = "partitionKey")]
pub partition_key: &'a PartitionKey,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CreateCollectionResponse {
pub collection: Collection,
pub charge: f64,
pub activity_id: uuid::Uuid,
pub etag: String,
pub session_token: String,
pub last_state_change: DateTime<Utc>,
pub schema_version: String,
pub service_version: String,
pub gateway_version: String,
pub alt_content_path: String,
pub quorum_acked_lsn: u64,
pub current_write_quorum: u64,
pub current_replica_set_size: u64,
}
impl CreateCollectionResponse {
pub async fn try_from(response: HttpResponse) -> crate::Result<Self> {
let (_status_code, headers, pinned_stream) = response.deconstruct();
let body = collect_pinned_stream(pinned_stream).await?;
Ok(Self {
collection: serde_json::from_slice(&body)?,
charge: request_charge_from_headers(&headers)?,
activity_id: activity_id_from_headers(&headers)?,
etag: etag_from_headers(&headers)?,
session_token: session_token_from_headers(&headers)?,
last_state_change: last_state_change_from_headers(&headers)?,
schema_version: schema_version_from_headers(&headers)?.to_owned(),
service_version: service_version_from_headers(&headers)?.to_owned(),
gateway_version: gateway_version_from_headers(&headers)?.to_owned(),
alt_content_path: alt_content_path_from_headers(&headers)?.to_owned(),
quorum_acked_lsn: quorum_acked_lsn_from_headers(&headers)?,
current_write_quorum: current_write_quorum_from_headers(&headers)?,
current_replica_set_size: current_replica_set_size_from_headers(&headers)?,
})
}
}
|
use std::future::Future;
use std::io::Error as IOError;
use std::marker::Unpin;
use std::pin::Pin;
use std::result::Result as StdResult;
use std::sync::Arc;
use async_trait::async_trait;
use futures::channel::{mpsc, oneshot};
use futures::{Sink, Stream};
use tokio::sync::Notify;
use crate::payload::SetupPayload;
use crate::spi::{ClientResponder, RSocket, ServerResponder};
use crate::{error::RSocketError, frame::Frame};
use crate::{Error, Result};
pub type FrameSink = dyn Sink<Frame, Error = RSocketError> + Send + Unpin;
pub type FrameStream = dyn Stream<Item = StdResult<Frame, RSocketError>> + Send + Unpin;
pub trait Connection {
fn split(self) -> (Box<FrameSink>, Box<FrameStream>);
}
#[async_trait]
pub trait Transport {
type Conn: Connection + Send;
async fn connect(self) -> Result<Self::Conn>;
}
#[async_trait]
pub trait ServerTransport {
type Item: Transport;
async fn start(&mut self) -> Result<()>;
async fn next(&mut self) -> Option<Result<Self::Item>>;
}
|
/// Namespace for operations that cannot be added to any other modules.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Miscellaneous {}
impl Miscellaneous {
#[inline]
pub fn admin_unadopted_list() -> MiscellaneousGetBuilder {
MiscellaneousGetBuilder {
param_page: None,
param_limit: None,
param_pattern: None,
}
}
#[inline]
pub fn render_markdown_raw() -> MiscellaneousPostBuilder1 {
MiscellaneousPostBuilder1
}
#[inline]
pub fn repo_download_pull_diff() -> MiscellaneousGetBuilder2<crate::generics::MissingOwner, crate::generics::MissingRepo, crate::generics::MissingIndex> {
MiscellaneousGetBuilder2 {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
_param_index: core::marker::PhantomData,
}
}
#[inline]
pub fn repo_download_pull_patch() -> MiscellaneousGetBuilder3<crate::generics::MissingOwner, crate::generics::MissingRepo, crate::generics::MissingIndex> {
MiscellaneousGetBuilder3 {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
_param_index: core::marker::PhantomData,
}
}
#[inline]
pub fn repo_signing_key() -> MiscellaneousGetBuilder4<crate::generics::MissingOwner, crate::generics::MissingRepo> {
MiscellaneousGetBuilder4 {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
}
}
#[inline]
pub fn get_signing_key() -> MiscellaneousGetBuilder5 {
MiscellaneousGetBuilder5
}
}
/// Builder created by [`Miscellaneous::admin_unadopted_list`](./struct.Miscellaneous.html#method.admin_unadopted_list) method for a `GET` operation associated with `Miscellaneous`.
#[derive(Debug, Clone)]
pub struct MiscellaneousGetBuilder {
param_page: Option<i64>,
param_limit: Option<i64>,
param_pattern: Option<String>,
}
impl MiscellaneousGetBuilder {
/// page number of results to return (1-based)
#[inline]
pub fn page(mut self, value: impl Into<i64>) -> Self {
self.param_page = Some(value.into());
self
}
/// page size of results
#[inline]
pub fn limit(mut self, value: impl Into<i64>) -> Self {
self.param_limit = Some(value.into());
self
}
/// pattern of repositories to search for
#[inline]
pub fn pattern(mut self, value: impl Into<String>) -> Self {
self.param_pattern = Some(value.into());
self
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for MiscellaneousGetBuilder {
type Output = Vec<String>;
const METHOD: http::Method = http::Method::GET;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
"/admin/unadopted".into()
}
fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> {
use crate::client::Request;
Ok(req
.query(&[
("page", self.param_page.as_ref().map(std::string::ToString::to_string)),
("limit", self.param_limit.as_ref().map(std::string::ToString::to_string)),
("pattern", self.param_pattern.as_ref().map(std::string::ToString::to_string))
]))
}
}
impl crate::client::ResponseWrapper<Vec<String>, MiscellaneousGetBuilder> {
#[inline]
pub fn message(&self) -> Option<String> {
self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
#[inline]
pub fn url(&self) -> Option<String> {
self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
}
/// Builder created by [`Miscellaneous::render_markdown_raw`](./struct.Miscellaneous.html#method.render_markdown_raw) method for a `POST` operation associated with `Miscellaneous`.
#[derive(Debug, Clone)]
pub struct MiscellaneousPostBuilder1;
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for MiscellaneousPostBuilder1 {
type Output = String;
const METHOD: http::Method = http::Method::POST;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
"/markdown/raw".into()
}
}
impl crate::client::ResponseWrapper<String, MiscellaneousPostBuilder1> {
#[inline]
pub fn message(&self) -> Option<String> {
self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
#[inline]
pub fn url(&self) -> Option<String> {
self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
}
/// Builder created by [`Miscellaneous::repo_download_pull_diff`](./struct.Miscellaneous.html#method.repo_download_pull_diff) method for a `GET` operation associated with `Miscellaneous`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct MiscellaneousGetBuilder2<Owner, Repo, Index> {
inner: MiscellaneousGetBuilder2Container,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
_param_index: core::marker::PhantomData<Index>,
}
#[derive(Debug, Default, Clone)]
struct MiscellaneousGetBuilder2Container {
param_owner: Option<String>,
param_repo: Option<String>,
param_index: Option<i64>,
}
impl<Owner, Repo, Index> MiscellaneousGetBuilder2<Owner, Repo, Index> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> MiscellaneousGetBuilder2<crate::generics::OwnerExists, Repo, Index> {
self.inner.param_owner = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// name of the repo
#[inline]
pub fn repo(mut self, value: impl Into<String>) -> MiscellaneousGetBuilder2<Owner, crate::generics::RepoExists, Index> {
self.inner.param_repo = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// index of the pull request to get
#[inline]
pub fn index(mut self, value: impl Into<i64>) -> MiscellaneousGetBuilder2<Owner, Repo, crate::generics::IndexExists> {
self.inner.param_index = Some(value.into());
unsafe { std::mem::transmute(self) }
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for MiscellaneousGetBuilder2<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::IndexExists> {
type Output = String;
const METHOD: http::Method = http::Method::GET;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/pulls/{index}.diff", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?"), index=self.inner.param_index.as_ref().expect("missing parameter index?")).into()
}
}
/// Builder created by [`Miscellaneous::repo_download_pull_patch`](./struct.Miscellaneous.html#method.repo_download_pull_patch) method for a `GET` operation associated with `Miscellaneous`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct MiscellaneousGetBuilder3<Owner, Repo, Index> {
inner: MiscellaneousGetBuilder3Container,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
_param_index: core::marker::PhantomData<Index>,
}
#[derive(Debug, Default, Clone)]
struct MiscellaneousGetBuilder3Container {
param_owner: Option<String>,
param_repo: Option<String>,
param_index: Option<i64>,
}
impl<Owner, Repo, Index> MiscellaneousGetBuilder3<Owner, Repo, Index> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> MiscellaneousGetBuilder3<crate::generics::OwnerExists, Repo, Index> {
self.inner.param_owner = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// name of the repo
#[inline]
pub fn repo(mut self, value: impl Into<String>) -> MiscellaneousGetBuilder3<Owner, crate::generics::RepoExists, Index> {
self.inner.param_repo = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// index of the pull request to get
#[inline]
pub fn index(mut self, value: impl Into<i64>) -> MiscellaneousGetBuilder3<Owner, Repo, crate::generics::IndexExists> {
self.inner.param_index = Some(value.into());
unsafe { std::mem::transmute(self) }
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for MiscellaneousGetBuilder3<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::IndexExists> {
type Output = String;
const METHOD: http::Method = http::Method::GET;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/pulls/{index}.patch", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?"), index=self.inner.param_index.as_ref().expect("missing parameter index?")).into()
}
}
/// Builder created by [`Miscellaneous::repo_signing_key`](./struct.Miscellaneous.html#method.repo_signing_key) method for a `GET` operation associated with `Miscellaneous`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct MiscellaneousGetBuilder4<Owner, Repo> {
inner: MiscellaneousGetBuilder4Container,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
}
#[derive(Debug, Default, Clone)]
struct MiscellaneousGetBuilder4Container {
param_owner: Option<String>,
param_repo: Option<String>,
}
impl<Owner, Repo> MiscellaneousGetBuilder4<Owner, Repo> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> MiscellaneousGetBuilder4<crate::generics::OwnerExists, Repo> {
self.inner.param_owner = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// name of the repo
#[inline]
pub fn repo(mut self, value: impl Into<String>) -> MiscellaneousGetBuilder4<Owner, crate::generics::RepoExists> {
self.inner.param_repo = Some(value.into());
unsafe { std::mem::transmute(self) }
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for MiscellaneousGetBuilder4<crate::generics::OwnerExists, crate::generics::RepoExists> {
type Output = String;
const METHOD: http::Method = http::Method::GET;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/signing-key.gpg", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?")).into()
}
}
/// Builder created by [`Miscellaneous::get_signing_key`](./struct.Miscellaneous.html#method.get_signing_key) method for a `GET` operation associated with `Miscellaneous`.
#[derive(Debug, Clone)]
pub struct MiscellaneousGetBuilder5;
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for MiscellaneousGetBuilder5 {
type Output = String;
const METHOD: http::Method = http::Method::GET;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
"/signing-key.gpg".into()
}
}
|
use crate::prelude::*;
use azure_core::prelude::*;
use http::StatusCode;
use std::convert::TryInto;
#[derive(Debug, Clone)]
pub struct GetAttachmentBuilder<'a, 'b> {
attachment_client: &'a AttachmentClient,
if_match_condition: Option<IfMatchCondition<'b>>,
user_agent: Option<azure_core::UserAgent<'b>>,
activity_id: Option<azure_core::ActivityId<'b>>,
consistency_level: Option<ConsistencyLevel>,
}
impl<'a, 'b> GetAttachmentBuilder<'a, 'b> {
pub(crate) fn new(attachment_client: &'a AttachmentClient) -> Self {
Self {
attachment_client,
if_match_condition: None,
user_agent: None,
activity_id: None,
consistency_level: None,
}
}
pub fn attachment_client(&self) -> &'a AttachmentClient {
self.attachment_client
}
fn if_match_condition(&self) -> Option<IfMatchCondition<'b>> {
self.if_match_condition
}
fn user_agent(&self) -> Option<azure_core::UserAgent<'b>> {
self.user_agent
}
fn activity_id(&self) -> Option<azure_core::ActivityId<'b>> {
self.activity_id
}
fn consistency_level(&self) -> Option<ConsistencyLevel> {
self.consistency_level.clone()
}
pub fn with_if_match_condition(self, if_match_condition: IfMatchCondition<'b>) -> Self {
Self {
if_match_condition: Some(if_match_condition),
..self
}
}
pub fn with_user_agent(self, user_agent: &'b str) -> Self {
Self {
user_agent: Some(azure_core::UserAgent::new(user_agent)),
..self
}
}
pub fn with_activity_id(self, activity_id: &'b str) -> Self {
Self {
activity_id: Some(azure_core::ActivityId::new(activity_id)),
..self
}
}
pub fn with_consistency_level(self, consistency_level: ConsistencyLevel) -> Self {
Self {
consistency_level: Some(consistency_level),
..self
}
}
pub async fn execute(&self) -> Result<crate::responses::GetAttachmentResponse, CosmosError> {
let mut req = self
.attachment_client
.prepare_request_with_attachment_name(http::Method::GET);
// add trait headers
req = crate::headers::add_header(self.if_match_condition(), req);
req = crate::headers::add_header(self.user_agent(), req);
req = crate::headers::add_header(self.activity_id(), req);
req = crate::headers::add_header(self.consistency_level(), req);
req = crate::headers::add_partition_keys_header(
self.attachment_client.document_client().partition_keys(),
req,
);
let req = req.body(EMPTY_BODY.as_ref())?;
debug!("req == {:#?}", req);
Ok(self
.attachment_client
.http_client()
.execute_request_check_status(req, StatusCode::OK)
.await?
.try_into()?)
}
}
|
#[doc = "Register `EMR2` reader"]
pub type R = crate::R<EMR2_SPEC>;
#[doc = "Register `EMR2` writer"]
pub type W = crate::W<EMR2_SPEC>;
#[doc = "Field `EM32` reader - CPU wakeup with interrupt mask on event input"]
pub type EM32_R = crate::BitReader;
#[doc = "Field `EM32` writer - CPU wakeup with interrupt mask on event input"]
pub type EM32_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM33` reader - CPU wakeup with interrupt mask on event input"]
pub type EM33_R = crate::BitReader;
#[doc = "Field `EM33` writer - CPU wakeup with interrupt mask on event input"]
pub type EM33_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM34` reader - CPU wakeup with interrupt mask on event input"]
pub type EM34_R = crate::BitReader;
#[doc = "Field `EM34` writer - CPU wakeup with interrupt mask on event input"]
pub type EM34_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM35` reader - CPU wakeup with interrupt mask on event input"]
pub type EM35_R = crate::BitReader;
#[doc = "Field `EM35` writer - CPU wakeup with interrupt mask on event input"]
pub type EM35_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM36` reader - CPU wakeup with interrupt mask on event input"]
pub type EM36_R = crate::BitReader;
#[doc = "Field `EM36` writer - CPU wakeup with interrupt mask on event input"]
pub type EM36_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM37` reader - CPU wakeup with interrupt mask on event input"]
pub type EM37_R = crate::BitReader;
#[doc = "Field `EM37` writer - CPU wakeup with interrupt mask on event input"]
pub type EM37_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM38` reader - CPU wakeup with interrupt mask on event input"]
pub type EM38_R = crate::BitReader;
#[doc = "Field `EM38` writer - CPU wakeup with interrupt mask on event input"]
pub type EM38_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM40` reader - CPU wakeup with interrupt mask on event input"]
pub type EM40_R = crate::BitReader;
#[doc = "Field `EM40` writer - CPU wakeup with interrupt mask on event input"]
pub type EM40_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM41` reader - CPU wakeup with interrupt mask on event input"]
pub type EM41_R = crate::BitReader;
#[doc = "Field `EM41` writer - CPU wakeup with interrupt mask on event input"]
pub type EM41_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EM42` reader - CPU wakeup with interrupt mask on event input"]
pub type EM42_R = crate::BitReader;
#[doc = "Field `EM42` writer - CPU wakeup with interrupt mask on event input"]
pub type EM42_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em32(&self) -> EM32_R {
EM32_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em33(&self) -> EM33_R {
EM33_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em34(&self) -> EM34_R {
EM34_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em35(&self) -> EM35_R {
EM35_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em36(&self) -> EM36_R {
EM36_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em37(&self) -> EM37_R {
EM37_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em38(&self) -> EM38_R {
EM38_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 8 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em40(&self) -> EM40_R {
EM40_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em41(&self) -> EM41_R {
EM41_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
pub fn em42(&self) -> EM42_R {
EM42_R::new(((self.bits >> 10) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em32(&mut self) -> EM32_W<EMR2_SPEC, 0> {
EM32_W::new(self)
}
#[doc = "Bit 1 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em33(&mut self) -> EM33_W<EMR2_SPEC, 1> {
EM33_W::new(self)
}
#[doc = "Bit 2 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em34(&mut self) -> EM34_W<EMR2_SPEC, 2> {
EM34_W::new(self)
}
#[doc = "Bit 3 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em35(&mut self) -> EM35_W<EMR2_SPEC, 3> {
EM35_W::new(self)
}
#[doc = "Bit 4 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em36(&mut self) -> EM36_W<EMR2_SPEC, 4> {
EM36_W::new(self)
}
#[doc = "Bit 5 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em37(&mut self) -> EM37_W<EMR2_SPEC, 5> {
EM37_W::new(self)
}
#[doc = "Bit 6 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em38(&mut self) -> EM38_W<EMR2_SPEC, 6> {
EM38_W::new(self)
}
#[doc = "Bit 8 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em40(&mut self) -> EM40_W<EMR2_SPEC, 8> {
EM40_W::new(self)
}
#[doc = "Bit 9 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em41(&mut self) -> EM41_W<EMR2_SPEC, 9> {
EM41_W::new(self)
}
#[doc = "Bit 10 - CPU wakeup with interrupt mask on event input"]
#[inline(always)]
#[must_use]
pub fn em42(&mut self) -> EM42_W<EMR2_SPEC, 10> {
EM42_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 = "EXTI CPU wakeup with event mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`emr2::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 [`emr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct EMR2_SPEC;
impl crate::RegisterSpec for EMR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`emr2::R`](R) reader structure"]
impl crate::Readable for EMR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`emr2::W`](W) writer structure"]
impl crate::Writable for EMR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets EMR2 to value 0"]
impl crate::Resettable for EMR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::{
ec_cycle_pcd::data_structures::{ECCyclePCDPK, ECCyclePCDVK, HelpCircuit, MainCircuit},
variable_length_crh::{constraints::VariableLengthCRHGadget, VariableLengthCRH},
CircuitSpecificSetupPCD, Error, PCDPredicate, UniversalSetupPCD, PCD,
};
use ark_crypto_primitives::snark::{
constraints::{SNARKGadget, UniversalSetupSNARKGadget},
CircuitSpecificSetupSNARK, FromFieldElementsGadget,
UniversalSetupIndexError::{NeedLargerBound, Other},
UniversalSetupSNARK, SNARK,
};
use ark_ff::{prelude::*, to_bytes};
use ark_r1cs_std::{
alloc::AllocVar, bits::boolean::Boolean, fields::fp::FpVar, prelude::*, R1CSVar,
};
use ark_relations::r1cs::{
ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, OptimizationGoal, SynthesisError,
};
use ark_std::rand::{CryptoRng, Rng, RngCore};
use ark_std::{boxed::Box, marker::PhantomData, vec::Vec};
pub mod data_structures;
pub trait ECCyclePCDConfig<MainField: PrimeField, HelpField: PrimeField> {
type CRH: VariableLengthCRH<MainField>;
type CRHGadget: VariableLengthCRHGadget<Self::CRH, MainField>;
type MainSNARK: SNARK<MainField>;
type HelpSNARK: SNARK<HelpField>;
type MainSNARKGadget: SNARKGadget<MainField, HelpField, Self::MainSNARK>;
type HelpSNARKGadget: SNARKGadget<HelpField, MainField, Self::HelpSNARK>;
}
pub struct ECCyclePCD<
MainField: PrimeField,
HelpField: PrimeField,
IC: ECCyclePCDConfig<MainField, HelpField>,
> {
pub main_field_phantom: PhantomData<MainField>,
pub help_field_phantom: PhantomData<HelpField>,
pub ivc_config: PhantomData<IC>,
}
impl<MainField: PrimeField, HelpField: PrimeField, IC: ECCyclePCDConfig<MainField, HelpField>>
PCD<MainField> for ECCyclePCD<MainField, HelpField, IC>
{
type ProvingKey = ECCyclePCDPK<MainField, HelpField, IC>;
type VerifyingKey = ECCyclePCDVK<MainField, HelpField, IC>;
type Proof = <IC::HelpSNARK as SNARK<HelpField>>::Proof;
fn circuit_specific_setup<P: PCDPredicate<MainField>, R: Rng + CryptoRng>(
predicate: &P,
rng: &mut R,
) -> Result<(Self::ProvingKey, Self::VerifyingKey), Error> {
let crh_pp = IC::CRH::setup(rng)?;
let main_circuit = MainCircuit::<MainField, HelpField, IC, P> {
crh_pp: crh_pp.clone(),
predicate: predicate.clone(),
input_hash: None,
help_vk: None,
msg: None,
witness: None,
prior_msgs: Vec::new(),
prior_proofs: Vec::new(),
base_case_bit: None,
};
let (main_pk, main_vk) = IC::MainSNARK::circuit_specific_setup(main_circuit, rng)?;
let main_pvk = IC::MainSNARK::process_vk(&main_vk)?;
let help_circuit = HelpCircuit::<MainField, HelpField, IC> {
main_pvk: main_pvk.clone(),
input_hash: None,
main_proof: None,
};
let (help_pk, help_vk) = IC::HelpSNARK::circuit_specific_setup(help_circuit, rng)?;
let pk = ECCyclePCDPK::<MainField, HelpField, IC> {
crh_pp: crh_pp.clone(),
main_pk,
help_pk,
help_vk: help_vk.clone(),
main_pvk,
};
let vk = ECCyclePCDVK::<MainField, HelpField, IC> { crh_pp, help_vk };
Ok((pk, vk))
}
fn prove<P: PCDPredicate<MainField>, R: Rng + CryptoRng>(
pk: &ECCyclePCDPK<MainField, HelpField, IC>,
predicate: &P,
msg: &P::Message,
witness: &P::LocalWitness,
prior_msgs: &[P::Message],
prior_proofs: &[Self::Proof],
rng: &mut R,
) -> Result<Self::Proof, Error> {
/*
** Compute the input hash.
** To avoid issues when the verifying key's native has different ToBytes compared with the gadgets',
** here we simulate the computation inside the gadget
*/
let input_hash = {
let tcs_sys = ConstraintSystem::<MainField>::new();
let tcs = ConstraintSystemRef::new(tcs_sys);
tcs.set_optimization_goal(OptimizationGoal::Weight);
let help_vk_gadget = <IC::HelpSNARKGadget as SNARKGadget<
HelpField,
MainField,
IC::HelpSNARK,
>>::VerifyingKeyVar::new_witness(
ark_relations::ns!(tcs, "vk"),
|| Ok(pk.help_vk.clone()),
)?;
let msg_gadget =
P::MessageVar::new_witness(ark_relations::ns!(tcs, "msg"), || Ok(msg.clone()))?;
let help_vk_bytes_gadget = help_vk_gadget.to_bytes()?;
let mut committed_vk = Vec::<u8>::new();
for byte in &help_vk_bytes_gadget {
committed_vk.push(byte.value().unwrap_or_default());
}
let vk_hash = IC::CRH::evaluate(&pk.crh_pp, &committed_vk)?;
let vk_hash_bytes = to_bytes!(vk_hash)?;
let msg_bytes_gadget = msg_gadget.to_bytes()?;
let mut committed_input = Vec::<u8>::new();
for byte in vk_hash_bytes.iter() {
committed_input.push(*byte);
}
for byte in &msg_bytes_gadget {
committed_input.push(byte.value().unwrap_or_default());
}
IC::CRH::evaluate(&pk.crh_pp, &committed_input)?
};
let main_circuit: MainCircuit<MainField, HelpField, IC, P>;
if prior_msgs.is_empty() {
main_circuit = MainCircuit::<MainField, HelpField, IC, P> {
crh_pp: pk.crh_pp.clone(),
predicate: (*predicate).clone(),
input_hash: Some(input_hash.clone()),
help_vk: Some(pk.help_vk.clone()),
msg: Some(msg.clone()),
witness: Some(witness.clone()),
prior_msgs: Vec::new(),
prior_proofs: Vec::new(),
base_case_bit: Some(true),
};
} else {
main_circuit = MainCircuit::<MainField, HelpField, IC, P> {
crh_pp: pk.crh_pp.clone(),
predicate: (*predicate).clone(),
input_hash: Some(input_hash.clone()),
help_vk: Some(pk.help_vk.clone()),
msg: Some(msg.clone()),
witness: Some(witness.clone()),
prior_msgs: prior_msgs.to_vec(),
prior_proofs: prior_proofs.to_vec(),
base_case_bit: Some(false),
};
}
let main_proof = IC::MainSNARK::prove(&pk.main_pk, main_circuit, rng)?;
let help_circuit = HelpCircuit::<MainField, HelpField, IC> {
main_pvk: pk.main_pvk.clone(),
input_hash: Some(input_hash),
main_proof: Some(main_proof),
};
let help_proof = IC::HelpSNARK::prove(&pk.help_pk, help_circuit, rng)?;
Ok(help_proof)
}
fn verify<P: PCDPredicate<MainField>>(
vk: &Self::VerifyingKey,
msg: &P::Message,
proof: &Self::Proof,
) -> Result<bool, Error> {
/*
** Compute the input hash.
** To avoid issues when the verifying key's native has different ToBytes compared with the gadgets',
** here we simulate the computation inside the gadget
*/
let input_hash = {
let tcs_sys = ConstraintSystem::<MainField>::new();
let tcs = ConstraintSystemRef::new(tcs_sys);
tcs.set_optimization_goal(OptimizationGoal::Weight);
let help_vk_gadget = <IC::HelpSNARKGadget as SNARKGadget<
HelpField,
MainField,
IC::HelpSNARK,
>>::VerifyingKeyVar::new_witness(
ark_relations::ns!(tcs, "vk"),
|| Ok(vk.help_vk.clone()),
)?;
let msg_gadget =
P::MessageVar::new_witness(ark_relations::ns!(tcs, "msg"), || Ok(msg.clone()))?;
let help_vk_bytes_gadget = help_vk_gadget.to_bytes()?;
let mut committed_vk = Vec::<u8>::new();
for byte in &help_vk_bytes_gadget {
committed_vk.push(byte.value().unwrap_or_default());
}
let vk_hash = IC::CRH::evaluate(&vk.crh_pp, &committed_vk)?;
let vk_hash_bytes = to_bytes!(vk_hash)?;
let msg_bytes_gadget = msg_gadget.to_bytes()?;
let mut committed_input = Vec::<u8>::new();
for byte in vk_hash_bytes.iter() {
committed_input.push(*byte);
}
for byte in &msg_bytes_gadget {
committed_input.push(byte.value().unwrap_or_default());
}
IC::CRH::evaluate(&vk.crh_pp, &committed_input)?
};
let main_public_input = IC::CRH::convert_output_to_field_elements(input_hash).unwrap();
let help_public_input = <IC::MainSNARKGadget as SNARKGadget<
MainField,
HelpField,
IC::MainSNARK,
>>::InputVar::repack_input(&main_public_input);
let verify_result = IC::HelpSNARK::verify(&vk.help_vk, &help_public_input, &proof);
match verify_result {
Ok(res) => Ok(res),
Err(err) => Err(Box::new(err)),
}
}
}
impl<MainField: PrimeField, HelpField: PrimeField, IC: ECCyclePCDConfig<MainField, HelpField>>
CircuitSpecificSetupPCD<MainField> for ECCyclePCD<MainField, HelpField, IC>
where
IC::MainSNARK: CircuitSpecificSetupSNARK<MainField>,
IC::HelpSNARK: CircuitSpecificSetupSNARK<HelpField>,
{
}
pub struct BoundTestingPredicate<F: PrimeField, BoundCircuit: ConstraintSynthesizer<F> + Clone> {
pub bound_circuit: BoundCircuit,
pub field_phantom: PhantomData<F>,
}
impl<F: PrimeField, BoundCircuit: ConstraintSynthesizer<F> + Clone> Clone
for BoundTestingPredicate<F, BoundCircuit>
{
fn clone(&self) -> Self {
Self {
bound_circuit: self.bound_circuit.clone(),
field_phantom: PhantomData,
}
}
}
impl<F: PrimeField, BoundCircuit: ConstraintSynthesizer<F> + Clone> PCDPredicate<F>
for BoundTestingPredicate<F, BoundCircuit>
{
type Message = F;
type MessageVar = FpVar<F>;
type LocalWitness = F;
type LocalWitnessVar = FpVar<F>;
const PRIOR_MSG_LEN: usize = 1;
fn generate_constraints(
&self,
cs: ConstraintSystemRef<F>,
msg: &Self::MessageVar,
witness: &Self::LocalWitnessVar,
prior_msgs: &[Self::MessageVar],
_base_case: &Boolean<F>,
) -> Result<(), SynthesisError> {
assert!(prior_msgs.len() == Self::PRIOR_MSG_LEN);
// if base_core = 0, the prior_msgs[0] would be the default message, which is zero.
let msg_supposed = witness + &prior_msgs[0];
msg.enforce_equal(&msg_supposed)?;
self.bound_circuit
.clone()
.generate_constraints(ark_relations::ns!(cs, "bound").cs())?;
Ok(())
}
}
impl<MainField: PrimeField, HelpField: PrimeField, IC: ECCyclePCDConfig<MainField, HelpField>>
UniversalSetupPCD<MainField> for ECCyclePCD<MainField, HelpField, IC>
where
IC::MainSNARK: UniversalSetupSNARK<MainField>,
IC::HelpSNARK: UniversalSetupSNARK<HelpField>,
IC::MainSNARKGadget: UniversalSetupSNARKGadget<MainField, HelpField, IC::MainSNARK>,
{
type PredicateBound = <IC::MainSNARK as UniversalSetupSNARK<MainField>>::ComputationBound;
type PublicParameters = (
Self::PredicateBound,
<IC::CRH as VariableLengthCRH<MainField>>::Parameters,
<IC::MainSNARK as UniversalSetupSNARK<MainField>>::PublicParameters,
<IC::HelpSNARK as UniversalSetupSNARK<HelpField>>::PublicParameters,
);
fn universal_setup<R: RngCore + CryptoRng>(
predicate_bound: &Self::PredicateBound,
rng: &mut R,
) -> Result<Self::PublicParameters, Error> {
let crh_pp = IC::CRH::setup(rng)?;
let bound_testing_predicate = BoundTestingPredicate::<
MainField,
<IC::MainSNARKGadget as UniversalSetupSNARKGadget<
MainField,
HelpField,
IC::MainSNARK,
>>::BoundCircuit,
> {
bound_circuit: <IC::MainSNARKGadget as UniversalSetupSNARKGadget<
MainField,
HelpField,
IC::MainSNARK,
>>::BoundCircuit::from(predicate_bound.clone()),
field_phantom: PhantomData,
};
let mut main_bound = predicate_bound.clone();
let mut help_bound =
<IC::HelpSNARK as UniversalSetupSNARK<HelpField>>::ComputationBound::default();
loop {
let main_pp = <IC::MainSNARK as UniversalSetupSNARK<MainField>>::universal_setup(
&main_bound,
rng,
)?;
let help_pp = <IC::HelpSNARK as UniversalSetupSNARK<HelpField>>::universal_setup(
&help_bound,
rng,
)?;
let main_circuit_bound_index_result =
<IC::MainSNARK as UniversalSetupSNARK<MainField>>::index(
&main_pp,
<IC::MainSNARKGadget as UniversalSetupSNARKGadget<
MainField,
HelpField,
IC::MainSNARK,
>>::BoundCircuit::from(main_bound.clone()),
rng,
);
let help_vk_placeholder: Option<<IC::HelpSNARK as SNARK<HelpField>>::VerifyingKey>;
match main_circuit_bound_index_result {
Ok(main_keypair) => {
let main_pvk = IC::MainSNARK::process_vk(&main_keypair.1)?;
let help_circuit = HelpCircuit::<MainField, HelpField, IC> {
main_pvk: main_pvk.clone(),
input_hash: None,
main_proof: None,
};
let help_circuit_index_result = <IC::HelpSNARK as UniversalSetupSNARK<
HelpField,
>>::index(
&help_pp, help_circuit, rng
);
match help_circuit_index_result {
Ok(keypair) => help_vk_placeholder = Some(keypair.1),
Err(NeedLargerBound(bound)) => {
help_bound = bound;
continue;
}
Err(Other(err)) => return Err(Box::new(err)),
}
}
Err(NeedLargerBound(bound)) => {
main_bound = bound;
continue;
}
Err(Other(err)) => return Err(Box::new(err)),
}
let main_circuit = MainCircuit::<
MainField,
HelpField,
IC,
BoundTestingPredicate<
MainField,
<IC::MainSNARKGadget as UniversalSetupSNARKGadget<
MainField,
HelpField,
IC::MainSNARK,
>>::BoundCircuit,
>,
> {
crh_pp: crh_pp.clone(),
predicate: bound_testing_predicate.clone(),
input_hash: None,
help_vk: Some(help_vk_placeholder.unwrap()),
msg: None,
witness: None,
prior_msgs: Vec::new(),
prior_proofs: Vec::new(),
base_case_bit: None,
};
let main_circuit_index_result =
<IC::MainSNARK as UniversalSetupSNARK<MainField>>::index(
&main_pp,
main_circuit,
rng,
);
let main_vk: Option<<IC::MainSNARK as SNARK<MainField>>::VerifyingKey>;
match main_circuit_index_result {
Ok(keypair) => {
main_vk = Some(keypair.1);
}
Err(NeedLargerBound(bound)) => {
main_bound = bound;
continue;
}
Err(Other(err)) => return Err(Box::new(err)),
}
let main_pvk = IC::MainSNARK::process_vk(&main_vk.unwrap())?;
let help_circuit = HelpCircuit::<MainField, HelpField, IC> {
main_pvk: main_pvk.clone(),
input_hash: None,
main_proof: None,
};
let help_circuit_index_result =
<IC::HelpSNARK as UniversalSetupSNARK<HelpField>>::index(
&help_pp,
help_circuit,
rng,
);
match help_circuit_index_result {
Ok(_) => {
return Ok((main_bound, crh_pp, main_pp, help_pp));
}
Err(NeedLargerBound(bound)) => {
help_bound = bound;
continue;
}
Err(Other(err)) => return Err(Box::new(err)),
}
}
}
fn index<P: PCDPredicate<MainField>, R: Rng + CryptoRng>(
pp: &Self::PublicParameters,
predicate: &P,
rng: &mut R,
) -> Result<(Self::ProvingKey, Self::VerifyingKey), Error> {
let (main_bound, crh_pp, main_pp, help_pp) = pp;
let main_circuit_bound_index_result =
<IC::MainSNARK as UniversalSetupSNARK<MainField>>::index(
&main_pp,
<IC::MainSNARKGadget as UniversalSetupSNARKGadget<
MainField,
HelpField,
IC::MainSNARK,
>>::BoundCircuit::from(main_bound.clone()),
rng,
);
let help_vk_placeholder: Option<<IC::HelpSNARK as SNARK<HelpField>>::VerifyingKey>;
match main_circuit_bound_index_result {
Ok(main_keypair) => {
let main_pvk = IC::MainSNARK::process_vk(&main_keypair.1)?;
let help_circuit = HelpCircuit::<MainField, HelpField, IC> {
main_pvk,
input_hash: None,
main_proof: None,
};
let help_circuit_index_result =
<IC::HelpSNARK as UniversalSetupSNARK<HelpField>>::index(
&help_pp,
help_circuit,
rng,
);
match help_circuit_index_result {
Ok(keypair) => help_vk_placeholder = Some(keypair.1),
Err(NeedLargerBound(_)) => {
panic!("The bound is not correctly chosen.");
}
Err(Other(err)) => return Err(Box::new(err)),
}
}
Err(NeedLargerBound(_)) => {
panic!("The bound is not correctly chosen.");
}
Err(Other(err)) => return Err(Box::new(err)),
}
let main_circuit = MainCircuit::<MainField, HelpField, IC, P> {
crh_pp: crh_pp.clone(),
predicate: predicate.clone(),
input_hash: None,
help_vk: Some(help_vk_placeholder.unwrap()),
msg: None,
witness: None,
prior_msgs: Vec::new(),
prior_proofs: Vec::new(),
base_case_bit: None,
};
let main_circuit_index_result =
<IC::MainSNARK as UniversalSetupSNARK<MainField>>::index(&main_pp, main_circuit, rng);
let main_pk: Option<<IC::MainSNARK as SNARK<MainField>>::ProvingKey>;
let main_vk: Option<<IC::MainSNARK as SNARK<MainField>>::VerifyingKey>;
match main_circuit_index_result {
Ok(keypair) => {
main_pk = Some(keypair.0);
main_vk = Some(keypair.1);
}
Err(NeedLargerBound(_)) => {
panic!("The bound is not correctly chosen.");
}
Err(Other(err)) => return Err(Box::new(err)),
}
let main_pvk = IC::MainSNARK::process_vk(&main_vk.unwrap())?;
let help_circuit = HelpCircuit::<MainField, HelpField, IC> {
main_pvk: main_pvk.clone(),
input_hash: None,
main_proof: None,
};
let help_circuit_index_result =
<IC::HelpSNARK as UniversalSetupSNARK<HelpField>>::index(&help_pp, help_circuit, rng);
match help_circuit_index_result {
Ok(help_keypair) => {
let ivc_pk = ECCyclePCDPK::<MainField, HelpField, IC> {
crh_pp: crh_pp.clone(),
main_pk: main_pk.unwrap(),
main_pvk,
help_pk: help_keypair.0.clone(),
help_vk: help_keypair.1.clone(),
};
let ivc_vk = ECCyclePCDVK::<MainField, HelpField, IC> {
crh_pp: crh_pp.clone(),
help_vk: help_keypair.1,
};
Ok((ivc_pk, ivc_vk))
}
Err(NeedLargerBound(_)) => panic!("The bound is not correctly chosen."),
Err(Other(err)) => Err(Box::new(err)),
}
}
}
|
use serde::Deserialize;
#[derive(Deserialize, Clone)]
#[serde(default)]
pub struct BlockProperties {
pub name: String,
pub solid: bool,
pub opaque: bool,
pub flora: bool,
pub texture: BlockTextureProperties,
}
impl Default for BlockProperties {
fn default() -> Self {
Self {
name: String::from("minecraft:undefined"),
solid: true,
opaque: true,
flora: false,
texture: BlockTextureProperties::default(),
}
}
}
#[derive(Deserialize, Default, Copy, Clone)]
#[serde(default)]
pub struct BlockTextureProperties {
pub front: u8,
pub back: u8,
pub left: u8,
pub right: u8,
pub top: u8,
pub bottom: u8,
}
|
pub mod agenda;
pub mod partition;
pub mod push_down;
pub mod integerisable;
pub mod parsing;
pub mod reverse;
pub mod search;
pub mod tree;
pub mod factorizable;
use fnv::{FnvHashMap, FnvHashSet};
/// A `HashMap` with `usize` `Key`s.
/// It uses the `Fnv` hasher to provide fast access and insert
/// functionality with these keys.
pub type IntMap<T> = FnvHashMap<usize, T>;
// A `HashSet` with `usize` `Key`s.
/// It uses the `Fnv` hasher to provide fast access and insert
/// functionality with these keys.
pub type IntSet = FnvHashSet<usize>;
/// Fills a `Vec` with default entries until it can access it at
/// the specified index to return the mutuable reference.
pub fn vec_entry<T>(v: &mut Vec<T>, i: usize) -> &mut T
where
T: Default + Clone,
{
if i >= v.len() {
let diff = i - v.len() + 1;
v.extend(vec![Default::default(); diff]);
}
v.get_mut(i).unwrap()
}
/// Measures the time needed to execute a given command.
use time::{PreciseTime, Duration};
pub fn with_time<B, F>(f: F) -> (B, Duration)
where
F: FnOnce() -> B,
{
let t0 = PreciseTime::now();
let result = f();
let t1 = PreciseTime::now();
(result, t0.to(t1))
}
/// Like `Take`, but uses a `Capacity` instead of a `usize`.
pub enum TakeCapacity<I: Iterator> {
Inf(I),
Lim(I, usize)
}
use std::ops::SubAssign;
impl<I: Iterator> Iterator for TakeCapacity<I> {
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
match self {
&mut TakeCapacity::Inf(ref mut it) => it.next(),
&mut TakeCapacity::Lim(_, 0) => None,
&mut TakeCapacity::Lim(ref mut it, ref mut i) => { i.sub_assign(1); it.next() }
}
}
}
/// Construct a `CapacityIterator`.
pub fn take_capacity<I: Iterator>(it: I, c: agenda::Capacity) -> TakeCapacity<I> {
use self::agenda::Capacity::*;
match c {
Infinite => TakeCapacity::Inf(it),
Limit(i) => TakeCapacity::Lim(it, i)
}
} |
use std::convert::Infallible;
#[cfg(unix)]
use std::path::Path;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, SystemTime};
use tokio::sync::Mutex;
use tokio::time::delay_for;
use clap::{App, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand};
use eyre::Result;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use serde_json;
mod samples;
use samples::SampleBuf;
#[cfg(unix)]
use i2cdev::core::*;
#[cfg(unix)]
use i2cdev::linux::{LinuxI2CDevice, LinuxI2CError};
async fn temp_service(
req: Request<Body>,
rx: Arc<Mutex<SampleBuf<i16>>>,
) -> Result<Response<Body>> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") => {
let sample_buf = rx.lock().await;
Ok(Response::new(Body::from(
serde_json::to_string(&*sample_buf)?,
)))
}
_ => {
let mut not_found = Response::default();
*not_found.status_mut() = StatusCode::NOT_FOUND;
Ok(not_found)
}
}
}
#[cfg(unix)]
async fn measure<P>(path: P, addr: u16, tx: Arc<Mutex<SampleBuf<i16>>>) -> Result<()>
where
P: AsRef<Path>,
{
let mut dev = LinuxI2CDevice::new(path, addr)?;
dev.smbus_write_byte_data(0x01, 0x60)?;
loop {
let now = SystemTime::now();
// Measured: takes approx 1 millisecond.
let raw = i16::from_be(dev.smbus_read_word_data(0x00)? as i16) >> 4;
let mut lock = tx.lock().await;
lock.post(now, raw)?;
delay_for(Duration::from_millis(1000)).await;
}
}
async fn replay_synthesize(tx: Arc<Mutex<SampleBuf<i16>>>) -> Result<()> {
let mut fake_temp: i16 = -2048;
loop {
let now = SystemTime::now();
thread::sleep(Duration::from_millis(1));
let mut lock = tx.lock().await;
lock.post(now, fake_temp)?;
if lock.len() == lock.capacity() {
break;
}
delay_for(Duration::from_millis(1000)).await;
fake_temp += 1;
if fake_temp == 2048 {
fake_temp = -2048
}
}
Ok(())
}
fn parse_args<'a>() -> ArgMatches<'a> {
App::new("I2C Sensor Server")
.version("0.1")
.author("William D. Jones <thor0505@comcast.net>")
.about("Low speed I2C HTTP daemon")
.setting(AppSettings::SubcommandRequired)
.arg(
Arg::with_name("sample_rate")
.help("Sample rate (Hz)")
.short("s")
.value_name("RATE")
.takes_value(true),
)
.arg(
Arg::with_name("IP_ADDRESS")
.help("IP Address and Port")
.default_value("0.0.0.0:8000")
.index(1),
)
.subcommand(
SubCommand::with_name("measure")
.about("Run the server and obtain data from I2C sensors (Unix only).")
.arg(
Arg::with_name("replay")
.help("Write data to file for replay on exit (not implemented).")
.short("r")
.value_name("FILE")
.takes_value(true),
)
.arg(
Arg::with_name("device")
.help("Device type to talk to (not implemented).")
.short("d")
.value_name("DEVICE")
.takes_value(true),
)
.arg(
Arg::with_name("NODE")
.help("I2C device node")
.required(true)
.index(1),
)
.arg(
Arg::with_name("I2C_ADDRESS")
.help("I2C device address")
.required(true)
.index(2),
),
)
.subcommand(
SubCommand::with_name("replay")
.about("Run the server with synthesized data from a file.")
.arg(
Arg::with_name("synthesis")
.help("Synthesize fake data without a file.")
.short("s"),
)
.arg(
Arg::with_name("file")
.help("Replay data file to read (not implemented).")
.index(1),
)
.group(
ArgGroup::with_name("source")
.args(&["file", "synthesis"])
.required(true),
),
)
.get_matches()
}
#[tokio::main]
async fn main() -> Result<()> {
let matches = parse_args();
let i2c_tx = Arc::new(Mutex::new(SampleBuf::<i16>::new(86400, 1)));
let i2c_rx = Arc::clone(&i2c_tx);
let make_svc = make_service_fn(|_conn| {
let foo = Arc::clone(&i2c_rx);
async {
Ok::<_, Infallible>(service_fn(move |body: Request<Body>| {
temp_service(body, Arc::clone(&foo))
}))
}
});
let addr = matches.value_of("IP_ADDRESS").unwrap().parse()?;
let server = Server::bind(&addr).serve(make_svc);
if let Some(matches) = matches.subcommand_matches("measure") {
#[cfg(unix)]
{
let i2c_node = matches.value_of("NODE").unwrap();
let i2c_addr =
u16::from_str_radix(matches.value_of("I2C_ADDRESS").unwrap(), 16)?;
let (_, _) = tokio::join!(measure(i2c_node, i2c_addr, i2c_tx), server);
}
#[cfg(windows)]
println!("Measure subcommand only available on Unix systems.");
} else if let Some(matches) = matches.subcommand_matches("replay") {
if matches.is_present("synthesis") {
let replay_fn = replay_synthesize(i2c_tx);
let (_, _) = tokio::join!(replay_fn, server);
} else {
println!("Replay from file not yet implemented.");
}
}
Ok(())
}
|
// Stringy Strings
fn main() {
println!("{}", stringy(6) == "101010");
println!("{}", stringy(9) == "101010101");
println!("{}", stringy(4) == "1010");
println!("{}", stringy(7) == "1010101");
}
fn stringy(l: i32) -> String {
let mut result = "".to_string();
for n in 0..l {
if n % 2 == 0 {
result = result + "1";
} else {
result = result + "0";
}
}
result
}
|
extern crate libc;
use std::ffi::CString;
use std::fs::File;
use std::io::{Error, ErrorKind, Result};
use std::mem;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::path::Path;
use FsStats;
pub fn duplicate(file: &File) -> Result<File> {
unsafe {
let fd = libc::dup(file.as_raw_fd());
if fd < 0 {
Err(Error::last_os_error())
} else {
Ok(File::from_raw_fd(fd))
}
}
}
pub fn lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH)
}
pub fn lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX)
}
pub fn try_lock_shared(file: &File) -> Result<()> {
flock(file, libc::LOCK_SH | libc::LOCK_NB)
}
pub fn try_lock_exclusive(file: &File) -> Result<()> {
flock(file, libc::LOCK_EX | libc::LOCK_NB)
}
pub fn unlock(file: &File) -> Result<()> {
flock(file, libc::LOCK_UN)
}
pub fn lock_error() -> Error {
Error::from_raw_os_error(libc::EWOULDBLOCK)
}
#[cfg(not(target_os = "solaris"))]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
let ret = unsafe { libc::flock(file.as_raw_fd(), flag) };
if ret < 0 { Err(Error::last_os_error()) } else { Ok(()) }
}
/// Simulate flock() using fcntl(); primarily for Oracle Solaris.
#[cfg(target_os = "solaris")]
fn flock(file: &File, flag: libc::c_int) -> Result<()> {
let mut fl = libc::flock {
l_whence: 0,
l_start: 0,
l_len: 0,
l_type: 0,
l_pad: [0; 4],
l_pid: 0,
l_sysid: 0,
};
// In non-blocking mode, use F_SETLK for cmd, F_SETLKW otherwise, and don't forget to clear
// LOCK_NB.
let (cmd, operation) = match flag & libc::LOCK_NB {
0 => (libc::F_SETLKW, flag),
_ => (libc::F_SETLK, flag & !libc::LOCK_NB),
};
match operation {
libc::LOCK_SH => fl.l_type |= libc::F_RDLCK,
libc::LOCK_EX => fl.l_type |= libc::F_WRLCK,
libc::LOCK_UN => fl.l_type |= libc::F_UNLCK,
_ => return Err(Error::from_raw_os_error(libc::EINVAL)),
}
let ret = unsafe { libc::fcntl(file.as_raw_fd(), cmd, &fl) };
match ret {
// Translate EACCES to EWOULDBLOCK
-1 => match Error::last_os_error().raw_os_error() {
Some(libc::EACCES) => return Err(lock_error()),
_ => return Err(Error::last_os_error())
},
_ => Ok(())
}
}
pub fn allocated_size(file: &File) -> Result<u64> {
file.metadata().map(|m| m.blocks() as u64 * 512)
}
#[cfg(any(target_os = "linux",
target_os = "freebsd",
target_os = "android",
target_os = "nacl"))]
pub fn allocate(file: &File, len: u64) -> Result<()> {
let ret = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, len as libc::off_t) };
if ret == 0 { Ok(()) } else { Err(Error::last_os_error()) }
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn allocate(file: &File, len: u64) -> Result<()> {
let stat = try!(file.metadata());
if len > stat.blocks() as u64 * 512 {
let mut fstore = libc::fstore_t {
fst_flags: libc::F_ALLOCATECONTIG,
fst_posmode: libc::F_PEOFPOSMODE,
fst_offset: 0,
fst_length: len as libc::off_t,
fst_bytesalloc: 0,
};
let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &fstore) };
if ret == -1 {
// Unable to allocate contiguous disk space; attempt to allocate non-contiguously.
fstore.fst_flags = libc::F_ALLOCATEALL;
let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &fstore) };
if ret == -1 {
return Err(Error::last_os_error());
}
}
}
if len > stat.size() as u64 {
file.set_len(len)
} else {
Ok(())
}
}
#[cfg(any(target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly",
target_os = "solaris",
target_os = "haiku"))]
pub fn allocate(file: &File, len: u64) -> Result<()> {
// No file allocation API available, just set the length if necessary.
if len > try!(file.metadata()).len() as u64 {
file.set_len(len)
} else {
Ok(())
}
}
pub fn statvfs(path: &Path) -> Result<FsStats> {
let cstr = match CString::new(path.as_os_str().as_bytes()) {
Ok(cstr) => cstr,
Err(..) => return Err(Error::new(ErrorKind::InvalidInput, "path contained a null")),
};
unsafe {
let mut stat: libc::statvfs = mem::zeroed();
// danburkert/fs2-rs#1: cast is necessary for platforms where c_char != u8.
if libc::statvfs(cstr.as_ptr() as *const _, &mut stat) != 0 {
Err(Error::last_os_error())
} else {
Ok(FsStats {
free_space: stat.f_frsize as u64 * stat.f_bfree as u64,
available_space: stat.f_frsize as u64 * stat.f_bavail as u64,
total_space: stat.f_frsize as u64 * stat.f_blocks as u64,
allocation_granularity: stat.f_frsize as u64,
})
}
}
}
#[cfg(test)]
mod test {
extern crate tempdir;
extern crate libc;
use std::fs::{self, File};
use std::os::unix::io::AsRawFd;
use {FileExt, lock_contended_error};
/// The duplicate method returns a file with a new file descriptor.
#[test]
fn duplicate_new_fd() {
let tempdir = tempdir::TempDir::new("fs2").unwrap();
let path = tempdir.path().join("fs2");
let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap();
let file2 = file1.duplicate().unwrap();
assert!(file1.as_raw_fd() != file2.as_raw_fd());
}
/// The duplicate method should preservesthe close on exec flag.
#[test]
fn duplicate_cloexec() {
fn flags(file: &File) -> libc::c_int {
unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFL, 0) }
}
let tempdir = tempdir::TempDir::new("fs2").unwrap();
let path = tempdir.path().join("fs2");
let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap();
let file2 = file1.duplicate().unwrap();
assert_eq!(flags(&file1), flags(&file2));
}
/// Tests that locking a file descriptor will replace any existing locks
/// held on the file descriptor.
#[test]
fn lock_replace() {
let tempdir = tempdir::TempDir::new("fs2").unwrap();
let path = tempdir.path().join("fs2");
let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap();
let file2 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap();
// Creating a shared lock will drop an exclusive lock.
file1.lock_exclusive().unwrap();
file1.lock_shared().unwrap();
file2.lock_shared().unwrap();
// Attempting to replace a shared lock with an exclusive lock will fail
// with multiple lock holders, and remove the original shared lock.
assert_eq!(file2.try_lock_exclusive().unwrap_err().raw_os_error(),
lock_contended_error().raw_os_error());
file1.lock_shared().unwrap();
}
/// Tests that locks are shared among duplicated file descriptors.
#[test]
fn lock_duplicate() {
let tempdir = tempdir::TempDir::new("fs2").unwrap();
let path = tempdir.path().join("fs2");
let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap();
let file2 = file1.duplicate().unwrap();
let file3 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap();
// Create a lock through fd1, then replace it through fd2.
file1.lock_shared().unwrap();
file2.lock_exclusive().unwrap();
assert_eq!(file3.try_lock_shared().unwrap_err().raw_os_error(),
lock_contended_error().raw_os_error());
// Either of the file descriptors should be able to unlock.
file1.unlock().unwrap();
file3.lock_shared().unwrap();
}
}
|
use std::convert::TryFrom;
use nia_protocol_rust::GetDefinedModifiersRequest;
use crate::error::NiaServerError;
use crate::error::NiaServerResult;
use crate::protocol::Serializable;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NiaGetDefinedModifiersRequest {}
impl NiaGetDefinedModifiersRequest {
pub fn new() -> NiaGetDefinedModifiersRequest {
NiaGetDefinedModifiersRequest {}
}
}
impl TryFrom<nia_protocol_rust::GetDefinedModifiersRequest>
for NiaGetDefinedModifiersRequest
{
type Error = NiaServerError;
fn try_from(
_get_devices_request: nia_protocol_rust::GetDefinedModifiersRequest,
) -> Result<Self, Self::Error> {
Ok(NiaGetDefinedModifiersRequest::new())
}
}
impl
Serializable<
NiaGetDefinedModifiersRequest,
nia_protocol_rust::GetDefinedModifiersRequest,
> for NiaGetDefinedModifiersRequest
{
fn to_pb(&self) -> nia_protocol_rust::GetDefinedModifiersRequest {
let mut get_defined_modifiers_request_pb =
nia_protocol_rust::GetDefinedModifiersRequest::new();
get_defined_modifiers_request_pb
}
fn from_pb(
object_pb: nia_protocol_rust::GetDefinedModifiersRequest,
) -> NiaServerResult<NiaGetDefinedModifiersRequest> {
Ok(NiaGetDefinedModifiersRequest::new())
}
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[test]
fn serializes_and_deserializes() {
let expected = NiaGetDefinedModifiersRequest::new();
let bytes = expected.to_bytes().unwrap();
let result = NiaGetDefinedModifiersRequest::from_bytes(bytes).unwrap();
assert_eq!(expected, result);
}
}
|
/// Generate artifact information from unit dependencies for configuring the compiler environment.
use crate::core::compiler::unit_graph::UnitDep;
use crate::core::compiler::{Context, CrateType, FileFlavor, Unit};
use crate::core::TargetKind;
use crate::CargoResult;
use std::collections::HashMap;
use std::ffi::OsString;
/// Return all environment variables for the given unit-dependencies
/// if artifacts are present.
pub fn get_env(
cx: &Context<'_, '_>,
dependencies: &[UnitDep],
) -> CargoResult<HashMap<String, OsString>> {
let mut env = HashMap::new();
for unit_dep in dependencies.iter().filter(|d| d.unit.artifact.is_true()) {
for artifact_path in cx
.outputs(&unit_dep.unit)?
.iter()
.filter_map(|f| (f.flavor == FileFlavor::Normal).then(|| &f.path))
{
let artifact_type_upper = unit_artifact_type_name_upper(&unit_dep.unit);
let dep_name = unit_dep.dep_name.unwrap_or(unit_dep.unit.pkg.name());
let dep_name_upper = dep_name.to_uppercase().replace("-", "_");
let var = format!("CARGO_{}_DIR_{}", artifact_type_upper, dep_name_upper);
let path = artifact_path.parent().expect("parent dir for artifacts");
env.insert(var, path.to_owned().into());
let var = format!(
"CARGO_{}_FILE_{}_{}",
artifact_type_upper,
dep_name_upper,
unit_dep.unit.target.name()
);
env.insert(var, artifact_path.to_owned().into());
if unit_dep.unit.target.name() == dep_name.as_str() {
let var = format!("CARGO_{}_FILE_{}", artifact_type_upper, dep_name_upper,);
env.insert(var, artifact_path.to_owned().into());
}
}
}
Ok(env)
}
fn unit_artifact_type_name_upper(unit: &Unit) -> &'static str {
match unit.target.kind() {
TargetKind::Lib(kinds) => match kinds.as_slice() {
&[CrateType::Cdylib] => "CDYLIB",
&[CrateType::Staticlib] => "STATICLIB",
invalid => unreachable!("BUG: artifacts cannot be of type {:?}", invalid),
},
TargetKind::Bin => "BIN",
invalid => unreachable!("BUG: artifacts cannot be of type {:?}", invalid),
}
}
|
extern crate hyper;
extern crate futures;
use hyper::header::ContentLength;
pub fn not_allowed_error(text: &str) -> hyper::Response{
hyper::Response::new()
.with_status(hyper::StatusCode::MethodNotAllowed)
.with_header(ContentLength(text.len() as u64))
.with_body(String::from(text))
}
pub fn bad_request_error(text: &str) -> hyper::Response {
hyper::Response::new()
.with_status(hyper::StatusCode::BadRequest)
.with_header(ContentLength(text.len() as u64))
.with_body(String::from(text))
}
|
use super::SnapshotBuilder;
use super::{FileMetadata, Snapshot};
use crate::hash::Hash;
use blake2::{self, Digest};
use std::path;
use std::string::String;
// TODO: SnapshotBuilder should return self
impl SnapshotBuilder {
pub fn new() -> SnapshotBuilder {
SnapshotBuilder {
message: None,
id: None,
files: Vec::new(),
children: Vec::new(),
parent: None,
}
}
pub fn set_message(mut self, message: String) -> Self {
self.message = Some(message);
self
}
#[allow(dead_code)]
pub fn add_file(mut self, file_to_snapshot: FileMetadata) -> Self {
self.files.push(file_to_snapshot);
self
}
pub fn add_files(mut self, mut files_to_add: Vec<FileMetadata>) -> Self {
self.files.append(&mut files_to_add);
self
}
#[allow(dead_code)]
pub fn remove_file(mut self, file_to_remove: &path::Path) -> Self {
if let Some(index) = self
.files
.iter()
.position(|metadata| metadata.path() == file_to_remove)
{
self.files.swap_remove(index);
} else {
// TODO: This needs to be handled better
panic!("Attempted to remove a file from a snapshot that is not part of the snapshot");
}
self
}
pub fn change_parent(mut self, new_parent: Option<Hash>) -> Self {
self.parent = new_parent;
self
}
#[allow(dead_code)]
pub fn add_child(mut self, new_child: Hash) -> Self {
self.children.push(new_child);
self
}
#[allow(dead_code)]
pub fn remove_child(mut self, child_to_remove: &Hash) -> Self {
if let Some(index) = self
.children
.iter()
.position(|hash| hash == child_to_remove)
{
self.children.swap_remove(index);
} else {
// TODO: This needs to be handled better
panic!("Attempted to remove root hash that does not exist");
}
self
}
pub fn build(self) -> Snapshot {
if self.validate_snapshot() == false {
panic!("The snapshot being built was not valid: {:?}", self);
}
// TODO: Only build a new ID if it doesn't already have one
// TODO: Does a snapshot have to include a message for the hash
// Deconstruct self
let SnapshotBuilder {
mut files,
children,
parent,
message,
id,
} = self;
let message = message.unwrap();
// TODO: If a snapshot is actually changed then a history of the changes needs to be kept, in addition how does the hash that identifies the snapshot change?
if id.is_none() {
// Building a new snapshot
let new_id = SnapshotBuilder::generate_snapshot_id(message.as_bytes(), &mut files);
return Snapshot::new(new_id, message, files, children, parent);
} else {
// Editing a snapshot
// TODO: This wont work since it could lead to duplicate ID's
return Snapshot::new(id.unwrap(), message, files, children, parent);
}
}
/// Generates a snapshot hash to uniquely identify the snapshot
fn generate_snapshot_id(message_bytes: &[u8], files: &mut Vec<FileMetadata>) -> Hash {
// Sort by hash first
// let files = self.files.clone();
files.sort_by(|first, second| first.hash().cmp(&second.hash()));
let mut hash = blake2::Blake2b::new();
hash.input(message_bytes);
for stored_file in files.iter() {
hash.input(stored_file.hash().as_bytes());
}
let hash_result = hash.result();
Hash::from(hash_result.to_vec())
}
/// Checks to see if the builder can create a snapshot based on the data it has
fn validate_snapshot(&self) -> bool {
if self.message.is_none() {
// Can this be an empty string
return false;
}
if self.files.len() == 0 {
return false;
}
true
}
}
impl From<Snapshot> for SnapshotBuilder {
fn from(snapshot: Snapshot) -> Self {
let (id, children, files, parent, message) = snapshot.breakup();
SnapshotBuilder {
message: Some(message),
id: Some(id),
parent,
files,
children,
}
}
}
impl std::fmt::Debug for SnapshotBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn string_from_optional_hash(hash_to_display: Option<&Hash>) -> String {
return hash_to_display
.map(|hash| String::from(hash))
.unwrap_or(String::from("None"));
}
fn string_from_hash_vector(hash_vector: &[Hash]) -> String {
let mut temp = String::new();
for child in hash_vector {
temp.push_str(String::from(format!("{},", child)).as_str());
}
temp
}
// let bug = self.files.into_iter().map(|x| String::from(x));
writeln!(f, "Builder State").unwrap();
writeln!(
f,
"Message is {}",
self.message.as_ref().unwrap_or(&String::from("No Message"))
)
.unwrap();
writeln!(
f,
"Children are {}",
string_from_hash_vector(self.children.as_slice())
)
.unwrap();
for child in self.children.iter().map(|hash| String::from(hash)) {
write!(f, "{},", child).unwrap();
}
writeln!(
f,
"Parent is {}",
string_from_optional_hash(self.parent.as_ref())
)
.unwrap();
for data in self.files.iter().map(|data| String::from(data)) {
writeln!(f, "{}", data).unwrap();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{FileMetadata, SnapshotBuilder};
use crate::hash::Hash;
use testspace::TestSpace;
#[test]
fn build_a_snapshot_test() {
let builder = SnapshotBuilder::new();
let mut ts = TestSpace::new();
let mut file_list = ts.create_random_files(1, 2048);
let file = file_list.remove(0);
let test_hash = Hash::generate_random_hash();
let test_parent = Hash::generate_random_hash();
let result = builder
.set_message(String::from("A Message"))
.add_file(FileMetadata::new(test_hash, 2048, file.clone(), 0))
.change_parent(Some(test_parent.clone()))
.build();
assert_eq!(result.get_message(), "A Message");
assert_eq!(result.get_parent(), Some(test_parent).as_ref());
}
#[test]
fn change_snapshot_test() {}
}
|
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//!
//! An opt-in utility module for reporting equivocations.
//!
//! This module defines an offence type for GRANDPA equivocations
//! and some utility traits to wire together:
//! - a key ownership proof system (e.g. to prove that a given authority was
//! part of a session);
//! - a system for reporting offences;
//! - a system for signing and submitting transactions;
//! - a way to get the current block author;
//!
//! These can be used in an offchain context in order to submit equivocation
//! reporting extrinsics (from the client that's running the GRANDPA protocol).
//! And in a runtime context, so that the GRANDPA module can validate the
//! equivocation proofs in the extrinsic and report the offences.
//!
//! IMPORTANT:
//! When using this module for enabling equivocation reporting it is required
//! that the `ValidateUnsigned` for the GRANDPA pallet is used in the runtime
//! definition.
use sp_std::prelude::*;
use codec::{self as codec, Decode, Encode};
use frame_support::{debug, traits::KeyOwnerProofSystem};
use sp_finality_grandpa::{EquivocationProof, RoundNumber, SetId};
use sp_runtime::{
transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
},
DispatchResult, Perbill,
};
use sp_staking::{
offence::{Kind, Offence, OffenceError, ReportOffence},
SessionIndex,
};
use super::{Call, Module, Trait};
/// A trait with utility methods for handling equivocation reports in GRANDPA.
/// The offence type is generic, and the trait provides , reporting an offence
/// triggered by a valid equivocation report, and also for creating and
/// submitting equivocation report extrinsics (useful only in offchain context).
pub trait HandleEquivocation<T: Trait> {
/// The offence type used for reporting offences on valid equivocation reports.
type Offence: GrandpaOffence<T::KeyOwnerIdentification>;
/// Report an offence proved by the given reporters.
fn report_offence(
reporters: Vec<T::AccountId>,
offence: Self::Offence,
) -> Result<(), OffenceError>;
/// Returns true if all of the offenders at the given time slot have already been reported.
fn is_known_offence(
offenders: &[T::KeyOwnerIdentification],
time_slot: &<Self::Offence as Offence<T::KeyOwnerIdentification>>::TimeSlot,
) -> bool;
/// Create and dispatch an equivocation report extrinsic.
fn submit_unsigned_equivocation_report(
equivocation_proof: EquivocationProof<T::Hash, T::BlockNumber>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult;
/// Fetch the current block author id, if defined.
fn block_author() -> Option<T::AccountId>;
}
impl<T: Trait> HandleEquivocation<T> for () {
type Offence = GrandpaEquivocationOffence<T::KeyOwnerIdentification>;
fn report_offence(
_reporters: Vec<T::AccountId>,
_offence: GrandpaEquivocationOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError> {
Ok(())
}
fn is_known_offence(
_offenders: &[T::KeyOwnerIdentification],
_time_slot: &GrandpaTimeSlot,
) -> bool {
true
}
fn submit_unsigned_equivocation_report(
_equivocation_proof: EquivocationProof<T::Hash, T::BlockNumber>,
_key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult {
Ok(())
}
fn block_author() -> Option<T::AccountId> {
None
}
}
/// Generic equivocation handler. This type implements `HandleEquivocation`
/// using existing subsystems that are part of frame (type bounds described
/// below) and will dispatch to them directly, it's only purpose is to wire all
/// subsystems together.
pub struct EquivocationHandler<I, R, O = GrandpaEquivocationOffence<I>> {
_phantom: sp_std::marker::PhantomData<(I, R, O)>,
}
impl<I, R, O> Default for EquivocationHandler<I, R, O> {
fn default() -> Self {
Self { _phantom: Default::default() }
}
}
impl<T, R, O> HandleEquivocation<T> for EquivocationHandler<T::KeyOwnerIdentification, R, O>
where
// We use the authorship pallet to fetch the current block author and use
// `offchain::SendTransactionTypes` for unsigned extrinsic creation and
// submission.
T: Trait + pallet_authorship::Trait + frame_system::offchain::SendTransactionTypes<Call<T>>,
// A system for reporting offences after valid equivocation reports are
// processed.
R: ReportOffence<T::AccountId, T::KeyOwnerIdentification, O>,
// The offence type that should be used when reporting.
O: GrandpaOffence<T::KeyOwnerIdentification>,
{
type Offence = O;
fn report_offence(reporters: Vec<T::AccountId>, offence: O) -> Result<(), OffenceError> {
R::report_offence(reporters, offence)
}
fn is_known_offence(offenders: &[T::KeyOwnerIdentification], time_slot: &O::TimeSlot) -> bool {
R::is_known_offence(offenders, time_slot)
}
fn submit_unsigned_equivocation_report(
equivocation_proof: EquivocationProof<T::Hash, T::BlockNumber>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult {
use frame_system::offchain::SubmitTransaction;
let call = Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof);
match SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
Ok(()) => debug::info!("Submitted GRANDPA equivocation report."),
Err(e) => debug::error!("Error submitting equivocation report: {:?}", e),
}
Ok(())
}
fn block_author() -> Option<T::AccountId> {
Some(<pallet_authorship::Module<T>>::author())
}
}
/// A round number and set id which point on the time of an offence.
#[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Encode, Decode)]
pub struct GrandpaTimeSlot {
// The order of these matters for `derive(Ord)`.
/// Grandpa Set ID.
pub set_id: SetId,
/// Round number.
pub round: RoundNumber,
}
/// A `ValidateUnsigned` implementation that restricts calls to `report_equivocation_unsigned`
/// to local calls (i.e. extrinsics generated on this node) or that already in a block. This
/// guarantees that only block authors can include unsigned equivocation reports.
impl<T: Trait> frame_support::unsigned::ValidateUnsigned for Module<T> {
type Call = Call<T>;
fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
if let Call::report_equivocation_unsigned(equivocation_proof, _) = call {
// discard equivocation report not coming from the local node
match source {
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
_ => {
debug::warn!(
target: "afg",
"rejecting unsigned report equivocation transaction because it is not local/in-block."
);
return InvalidTransaction::Call.into()
},
}
ValidTransaction::with_tag_prefix("GrandpaEquivocation")
// We assign the maximum priority for any equivocation report.
.priority(TransactionPriority::max_value())
// Only one equivocation report for the same offender at the same slot.
.and_provides((
equivocation_proof.offender().clone(),
equivocation_proof.set_id(),
equivocation_proof.round(),
))
// We don't propagate this. This can never be included on a remote node.
.propagate(false)
.build()
} else {
InvalidTransaction::Call.into()
}
}
fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
if let Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof) = call {
// check the membership proof to extract the offender's id
let key = (sp_finality_grandpa::KEY_TYPE, equivocation_proof.offender().clone());
let offender = T::KeyOwnerProofSystem::check_proof(key, key_owner_proof.clone())
.ok_or(InvalidTransaction::BadProof)?;
// check if the offence has already been reported,
// and if so then we can discard the report.
let time_slot =
<T::HandleEquivocation as HandleEquivocation<T>>::Offence::new_time_slot(
equivocation_proof.set_id(),
equivocation_proof.round(),
);
let is_known_offence = T::HandleEquivocation::is_known_offence(&[offender], &time_slot);
if is_known_offence {
Err(InvalidTransaction::Stale.into())
} else {
Ok(())
}
} else {
Err(InvalidTransaction::Call.into())
}
}
}
/// A grandpa equivocation offence report.
#[allow(dead_code)]
pub struct GrandpaEquivocationOffence<FullIdentification> {
/// Time slot at which this incident happened.
pub time_slot: GrandpaTimeSlot,
/// The session index in which the incident happened.
pub session_index: SessionIndex,
/// The size of the validator set at the time of the offence.
pub validator_set_count: u32,
/// The authority which produced this equivocation.
pub offender: FullIdentification,
}
/// An interface for types that will be used as GRANDPA offences and must also
/// implement the `Offence` trait. This trait provides a constructor that is
/// provided all available data during processing of GRANDPA equivocations.
pub trait GrandpaOffence<FullIdentification>: Offence<FullIdentification> {
/// Create a new GRANDPA offence using the given equivocation details.
fn new(
session_index: SessionIndex,
validator_set_count: u32,
offender: FullIdentification,
set_id: SetId,
round: RoundNumber,
) -> Self;
/// Create a new GRANDPA offence time slot.
fn new_time_slot(set_id: SetId, round: RoundNumber) -> Self::TimeSlot;
}
impl<FullIdentification: Clone> GrandpaOffence<FullIdentification>
for GrandpaEquivocationOffence<FullIdentification>
{
fn new(
session_index: SessionIndex,
validator_set_count: u32,
offender: FullIdentification,
set_id: SetId,
round: RoundNumber,
) -> Self {
GrandpaEquivocationOffence {
session_index,
validator_set_count,
offender,
time_slot: GrandpaTimeSlot { set_id, round },
}
}
fn new_time_slot(set_id: SetId, round: RoundNumber) -> Self::TimeSlot {
GrandpaTimeSlot { set_id, round }
}
}
impl<FullIdentification: Clone> Offence<FullIdentification>
for GrandpaEquivocationOffence<FullIdentification>
{
const ID: Kind = *b"grandpa:equivoca";
type TimeSlot = GrandpaTimeSlot;
fn offenders(&self) -> Vec<FullIdentification> {
vec![self.offender.clone()]
}
fn session_index(&self) -> SessionIndex {
self.session_index
}
fn validator_set_count(&self) -> u32 {
self.validator_set_count
}
fn time_slot(&self) -> Self::TimeSlot {
self.time_slot
}
fn slash_fraction(offenders_count: u32, validator_set_count: u32) -> Perbill {
// the formula is min((3k / n)^2, 1)
let x = Perbill::from_rational_approximation(3 * offenders_count, validator_set_count);
// _ ^ 2
x.square()
}
}
|
fn main() {
// This is a vector similiar to a C++ vector.
// The vector information is on the stack,
// but the elements are stored on the heap.
let v = vec![1, 2, 3];
// Copy the stack-part of the vector to a mutable
// variable, but clone *NOT* the values (heap).
// This is also called "moving".
let mut v2 = v;
// Add a new element to the second vector.
v2.push(4);
// Print length of first vector. The length is
// is stored in the stack.
println!("{}", v.len()); // <-- Causes an error!
}
|
use super::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub struct Hash {
pub pairs: Vec<Pair>,
}
impl Display for Hash {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let out = self
.pairs
.iter()
.map(|pair| format!("{}:{}", pair.key, pair.value))
.collect::<Vec<String>>()
.join(", ");
write!(f, "{}", out)
}
}
impl TryFrom<Expr> for Hash {
type Error = Error;
fn try_from(value: Expr) -> Result<Self> {
match value {
Expr::Hash(hs) => Ok(hs),
expr => Err(ParserError::Convert(format!("{:?}", expr), "Hash".into()).into()),
}
}
}
|
mod set1;
mod set2;
mod utils;
fn main() {}
|
fn main() {
// 行コメント
let x = 5; // this is also a line comment.
println!("add_one(5) is {}",add_one(x));
}
/// 与えられた数値に1を加える
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(5));
/// # fn add_one(x: i32) -> i32 {
/// # x + 1
/// # }
/// ```
fn add_one(x: i32) -> i32 {
x + 1
}
|
use std::str;
use std::fs::File;
use std::io::prelude::*;
fn encrypt_repeating(buf: &[u8], keys: &[u8]) -> Vec<u8> {
let mut out = vec![0; buf.len()];
let keys_len = keys.len();
for x in 0..buf.len() {
let keys_pos = x % keys_len;
let key = keys[keys_pos];
out[x] = buf[x] ^ key;
}
return out;
}
fn main() -> std::io::Result<()> {
let mut file = File::open("src/secret.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let buf = contents.into_bytes();
let keys = "ICE".as_bytes();
let cipher = encrypt_repeating(&buf, &keys);
println!("{}", hex::encode(cipher));
Ok(())
}
|
use rdisk::vhd::VhdImage;
use std::path::PathBuf;
pub fn get_testdata_path() -> Option<PathBuf> {
std::env::var("CARGO_MANIFEST_DIR").ok().and_then(|dir| {
let dir = PathBuf::from(dir).join("testdata");
if dir.exists() {
Some(dir)
} else {
None
}
})
}
pub fn open_test_vhd(name: &str) -> Option<(VhdImage, String)> {
get_testdata_path().and_then(|dir| {
let path = dir.join(name);
let path = path.to_string_lossy().to_string();
if let Ok(vhd) = VhdImage::open(path.clone()) {
Some((vhd, path))
} else {
println!("No '{}'. Skipped.", path);
None
}
})
}
pub fn open_test_vhd_copy(name: &str) -> Option<(VhdImage, String)> {
get_testdata_path().and_then(|dir| {
let from = dir.join(name);
let copy_name = "copy_".to_string() + name;
let _ = std::fs::remove_file(©_name);
let to = dir.join(©_name);
std::fs::copy(from, to).ok().and_then(|_| open_test_vhd(©_name))
})
}
|
//! Sx127x FSK mode definitions
//!
//! Copyright 2019 Ryan Kurte
pub use super::common::*;
/// FSK and OOK mode configuration
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct FskConfig {
/// Preamble length in symbols (defaults to 0x8)
pub preamble_len: u16,
/// Payload length configuration (defaults to Variable / Explicit header mode)
pub payload_len: PayloadLength,
/// DC-Free encoding/decoding
pub dc_free: DcFree,
/// Payload RX CRC configuration (defaults to enabled)
pub crc: Crc,
/// Disable auto-clear FIFO and restart RX on CRC failure
pub crc_autoclear: CrcAutoClear,
/// Address filtering in RX mode
pub address_filter: AddressFilter,
/// Select CRC whitening algorithm
pub crc_whitening: CrcWhitening,
/// Set data processing mode
pub data_mode: DataMode,
/// Enable io-homecontrol compatibility mode
pub io_home: IoHome,
/// Enable beacon mode in fixed packet format
pub beacon: Beacon,
/// Receive mode Auto Frequency Compensation (AFC)
pub rx_afc: RxAfc,
/// Receive mode Auto Gain Compensation (AGC)
pub rx_agc: RxAgc,
/// Receive mode trigger
pub rx_trigger: RxTrigger,
/// Node address for filtering
pub node_address: u8,
/// Broadcast address for filtering
pub broadcast_address: u8,
/// IQ inversion configuration (defaults to disabled)
pub invert_iq: bool,
/// RX continuous mode
pub rx_continuous: bool,
/// Preamble
pub preamble: u16,
}
impl Default for FskConfig {
fn default() -> Self {
Self {
preamble_len: 0x8,
payload_len: PayloadLength::Variable,
dc_free: DcFree::Whitening,
crc: Crc::On,
crc_autoclear: CrcAutoClear::Off,
address_filter: AddressFilter::Off,
crc_whitening: CrcWhitening::Ccitt,
data_mode: DataMode::Packet,
io_home: IoHome::Off,
beacon: Beacon::Off,
rx_afc: RxAfc::On,
rx_agc: RxAgc::On,
rx_trigger: RxTrigger::PreambleDetect,
node_address: 0,
broadcast_address: 0,
invert_iq: false,
rx_continuous: false,
preamble: 0x0003,
}
}
}
/// Fsk radio channel configuration
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct FskChannel {
/// (G)FSK frequency in Hz (defaults to 434 MHz)
pub freq: u32,
/// (G)FSK channel baud-rate (defaults to 5kbps)
pub br: u32,
/// (G)FSK channel bandwidth
pub bw: Bandwidth,
/// (G)FSK AFC channel bandwidth
pub bw_afc: Bandwidth,
/// Frequency deviation in Hz (defaults to 5kHz)
pub fdev: u32,
}
impl Default for FskChannel {
fn default() -> Self {
Self {
freq: 434_000_000,
br: 4_800,
bw: Bandwidth::Bw12500,
bw_afc: Bandwidth::Bw12500,
fdev: 5_000,
}
}
}
// FSK bandwidth register values
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Bandwidth {
Bw2600 = 0x17,
Bw3100 = 0x0F,
Bw3900 = 0x07,
Bw5200 = 0x16,
Bw6300 = 0x0E,
Bw7800 = 0x06,
Bw10400 = 0x15,
Bw12500 = 0x0D,
Bw15600 = 0x05,
Bw20800 = 0x14,
Bw25000 = 0x0C,
Bw31300 = 0x04,
Bw41700 = 0x13,
Bw50000 = 0x0B,
Bw62500 = 0x03,
Bw83333 = 0x12,
Bw100000 = 0x0A,
Bw125000 = 0x02,
Bw166700 = 0x11,
Bw200000 = 0x09,
Bw250000 = 0x01,
}
pub const OPMODE_LRMODE_MASK: u8 = 0x80;
pub const OPMODE_SHAPING_MASK: u8 = 0b0001_1000;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Shaping {
Sh00 = 0x00,
Sh01 = 0x08,
Sh10 = 0x10,
Sh11 = 0x18,
}
pub const OPMODE_MODULATION_MASK: u8 = 0b0010_0000;
/// Modulation modes for the standard modem
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Modulation {
/// Frequency Shift Keying
Fsk = 0x00,
/// On Off Keying
Ook = 0x20,
}
pub const PACKETFORMAT_MASK: u8 = 0x80;
pub const PACKETFORMAT_VARIABLE: u8 = 0x80;
pub const PACKETFORMAT_FIXED: u8 = 0x80;
pub const DCFREE_MASK: u8 = 0x60;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum DcFree {
Off = 0x00,
Manchester = 0x20,
Whitening = 0x40,
}
pub const CRC_MASK: u8 = 0x10;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Crc {
Off = 0x00,
On = 0x10,
}
pub const CRC_AUTOCLEAR_MASK: u8 = 0x08;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum CrcAutoClear {
Off = 0x08,
On = 0x00,
}
pub const ADDRESS_FILTER_MASK: u8 = 0x08;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum AddressFilter {
Off = 0x00,
Node = 0x02,
NodeBroadcast = 0x04,
}
pub const CRC_WHITENING_MASK: u8 = 0x01;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum CrcWhitening {
Ccitt = 0x00,
Ibm = 0x01,
}
pub const WMBUS_CRC_MASK: u8 = 0x80;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum WmbusCrc {
Off = 0x00,
On = 0x80,
}
pub const DATAMODE_MASK: u8 = 0x40;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum DataMode {
Continuous = 0x00,
Packet = 0x40,
}
pub const IOHOME_MASK: u8 = 0x20;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum IoHome {
Off = 0x00,
On = 0x20,
}
pub const BEACON_MASK: u8 = 0x08;
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Beacon {
Off = 0x00,
On = 0x08,
}
pub const PAYLOADLEN_MSB_MASK: u8 = 0x07;
pub const TX_START_FIFOLEVEL: u8 = 0x00;
pub const TX_START_FIFOEMPTY: u8 = 0x80;
pub const TX_FIFOTHRESH_MASK: u8 = 0x1f;
pub const RXCONFIG_RESTARTRXONCOLLISION_MASK: u8 = 0x7F;
pub const RXCONFIG_RESTARTRXONCOLLISION_ON: u8 = 0x80;
pub const RXCONFIG_RESTARTRXONCOLLISION_OFF: u8 = 0x00; // Default
pub const RXCONFIG_RESTARTRX_PLL_MASK: u8 = 0b0110_0000;
pub const RXCONFIG_RESTARTRXWITHOUTPLLLOCK: u8 = 0x40; // Write only
pub const RXCONFIG_RESTARTRXWITHPLLLOCK: u8 = 0x20; // Write only
pub const RXCONFIG_AFCAUTO_MASK: u8 = 0xEF;
pub const RXCONFIG_AGCAUTO_MASK: u8 = 0xF7;
pub const RXCONFIG_RXTRIGER_MASK: u8 = 0xF8;
/// Receive mode Auto Frequency Calibration (AFC)
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum RxAfc {
On = 0x10,
Off = 0x00,
}
/// Receive mode Auto Gain Compensation (AGC)
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum RxAgc {
On = 0x08,
Off = 0x00,
}
/// Receive mode trigger configuration
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum RxTrigger {
Off = 0x00,
Rssi = 0x01,
PreambleDetect = 0x06,
RssiPreambleDetect = 0x07,
}
/// Control preamble detector state
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum PreambleDetect {
On = 0x80,
Off = 0x00,
}
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum PreambleDetectSize {
/// Interrupt on one byte
Ps1 = 0b0000_0000,
/// Interrupt on two bytes
Ps2 = 0b0010_0000,
/// Interrupt on three bytes
Ps3 = 0b0100_0000,
}
pub const PREAMBLE_DETECTOR_TOL: u8 = 0x0A;
bitflags! {
/// Interrupt flags register 1
pub struct Irq1: u8 {
/// Set when a given mode request is complete
const MODE_READY = 0b1000_0000;
/// Set in RSSI mode after RSSI, AGC and AFC
const RX_READY = 0b0100_0000;
/// Set in TX mode after PA ramp-up
const TX_READY = 0b0010_0000;
/// Set in (FS, Rx, Tx) when PLL is locked
const PLL_LOCKED = 0b0001_0000;
/// Set in Rx when RSSI exceeds the programmed RSSI threshold
const RSSI = 0b0000_1000;
/// Set when a timeout occurs
const TIMEOUT = 0b0000_0100;
/// Set when a preamble is detected (must be manually cleared)
const PREAMBLED_DETECT = 0b0000_0010;
/// Set when Sync and Address (if enabled) are detected
const SYNC_ADDR_MATCH = 0b0000_0001;
}
}
bitflags! {
/// Interrupt flags register two
pub struct Irq2: u8 {
/// Set when the FIFO is full
const FIFO_FULL = 0b1000_0000;
/// Set when the FIFO is empty
const FIFO_EMPTY = 0b0100_0000;
/// Set when the number of bytes in the FIFO exceeds the fifo threshold
const FIFO_LEVEL = 0b0010_0000;
/// Set when a FIFO overrun occurs
const FIFO_OVERRUN = 0b0001_0000;
/// Set in Tx when a packet has been sent
const PACKET_SENT = 0b0000_1000;
/// Set in Rx when a packet has been received and CRC has passed
const PAYLOAD_READY = 0b0000_0100;
/// Set in Rx when a packet CRC is okay
const CRC_OK = 0b0000_0010;
/// Set when the battery voltage drops below the low battery threshold
const LOW_BAT = 0b0000_0001;
}
}
|
extern crate llvm_sys;
use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::str::Chars;
use std::io::{self, Read, Write};
use std::iter::Peekable;
use llvm_sys::prelude::*;
fn cstr(s: &str) -> Box<CStr> {
CString::new(s).unwrap().into_boxed_c_str()
}
type ParseResult<T> = Result<T, Cow<'static, str>>;
type CompileResult<T> = Result<T, Cow<'static, str>>;
#[derive(Debug, PartialEq)]
enum Token {
Eof,
Def,
Extern,
Ident(String),
Number(f64),
Op(char),
}
impl Token {
fn get_op_name_or_panic(&self) -> char {
match *self {
Token::Op(op) => op,
_ => panic!("op is required"),
}
}
}
struct Lexer<'a> {
src: Peekable<Chars<'a>>,
next: Option<Token>,
}
impl<'a> Lexer<'a> {
fn new(src_text: &'a str) -> Lexer<'a> {
Lexer { src: src_text.chars().peekable(), next: None }
}
fn gettok(&mut self) -> ParseResult<Token> {
if let Some(tok) = self.next.take() {
return Ok(tok);
}
// skip any whitespace
loop {
match self.peekc() {
Some(&'#') => { // comment
while let Some(c) = self.getc() {
if c == '\r' || c == '\n' {
break;
}
}
},
Some(&c) if c.is_whitespace() => { self.getc(); },
Some(_) => break,
None => return Ok(Token::Eof),
}
}
let c = *self.peekc().unwrap();
// identifier: [a-zA-Z][a-zA-Z0-9]*
if c.is_ascii_alphabetic() {
let ident = self.read_while(|c| c.is_ascii_alphanumeric());
return match &ident[..] {
"def" => Ok(Token::Def),
"extern" => Ok(Token::Extern),
_ => Ok(Token::Ident(ident)),
}
}
// number: [0-9.]+
let is_numeric = |c: char| c.is_ascii_digit() || c == '.';
if is_numeric(c) {
let num_str = self.read_while(is_numeric);
let num = num_str.parse().map_err(|_| Cow::from("cannot parse number"))?;
return Ok(Token::Number(num));
}
// operator
match self.getc() {
Some(c) => Ok(Token::Op(c)),
None => Ok(Token::Eof),
}
}
fn peektok(&mut self) -> ParseResult<&Token> {
match self.next {
Some(ref tok) => Ok(tok),
None => {
self.next = Some(self.gettok()?);
Ok(self.next.as_ref().unwrap())
}
}
}
// Reads from src while pred returns true.
// It assumes that pred holds for the first character (thus skipping test with pred).
fn read_while(&mut self, pred: impl Fn(char) -> bool) -> String {
let mut s = self.getc().unwrap().to_string();
while let Some(&c) = self.peekc() {
if !pred(c) {
break;
}
s.push(self.getc().unwrap());
}
s
}
fn peekc(&mut self) -> Option<&char> {
self.src.peek()
}
fn getc(&mut self) -> Option<char> {
self.src.next()
}
}
struct LLVM {
ctx: LLVMContextRef,
builder: LLVMBuilderRef,
module: LLVMModuleRef,
named_values: HashMap<String, LLVMValueRef>,
}
impl LLVM {
fn new() -> LLVM {
let name = cstr("my cool jit");
unsafe {
let ctx = llvm_sys::core::LLVMContextCreate();
let builder = llvm_sys::core::LLVMCreateBuilder();
let module = llvm_sys::core::LLVMModuleCreateWithNameInContext(name.as_ptr(), ctx);
LLVM { ctx, builder, module, named_values: HashMap::new() }
}
}
}
#[derive(Debug)]
enum ExprAst {
Number(f64),
Variable(String),
Binary { op: char, lhs: Box<ExprAst>, rhs: Box<ExprAst> },
Call { callee: String, args: Vec<ExprAst> },
}
impl ExprAst {
fn codegen(&self, llvm: &mut LLVM) -> CompileResult<LLVMValueRef> {
match self {
ExprAst::Number(value) => unsafe {
let ty = llvm_sys::core::LLVMDoubleTypeInContext(llvm.ctx);
Ok(llvm_sys::core::LLVMConstReal(ty, *value))
},
ExprAst::Variable(name) => {
match llvm.named_values.get(name) {
Some(value) => Ok(*value),
None => Err(Cow::from("unknown variable name")),
}
},
ExprAst::Binary { op, lhs, rhs } => {
let lhs = lhs.codegen(llvm)?;
let rhs = rhs.codegen(llvm)?;
match op {
'+' => unsafe {
let name = cstr("addtmp");
Ok(llvm_sys::core::LLVMBuildFAdd(llvm.builder, lhs, rhs, name.as_ptr()))
},
'-' => unsafe {
let name = cstr("subtmp");
Ok(llvm_sys::core::LLVMBuildFSub(llvm.builder, lhs, rhs, name.as_ptr()))
},
'*' => unsafe {
let name = cstr("multmp");
Ok(llvm_sys::core::LLVMBuildFMul(llvm.builder, lhs, rhs, name.as_ptr()))
},
'<' => unsafe {
let name_cmp = cstr("cmptmp");
let name_bool = cstr("booltmp");
let b = llvm_sys::core::LLVMBuildFCmp(
llvm.builder, llvm_sys::LLVMRealPredicate::LLVMRealULT, lhs, rhs, name_cmp.as_ptr());
let ty = llvm_sys::core::LLVMDoubleTypeInContext(llvm.ctx);
Ok(llvm_sys::core::LLVMBuildUIToFP(llvm.builder, b, ty, name_bool.as_ptr()))
},
_ => Err(Cow::from("invalid binary operator")),
}
},
ExprAst::Call { callee, args } => {
let name = cstr(&callee);
let callee_f = unsafe { llvm_sys::core::LLVMGetNamedFunction(llvm.module, name.as_ptr()) };
let mut args_v = vec![];
for arg in args {
let arg_v = arg.codegen(llvm)?;
if arg_v.is_null() {
return Err(Cow::from("invalid function argument"));
}
args_v.push(arg_v);
}
let n_args = unsafe { llvm_sys::core::LLVMCountParams(callee_f) };
if n_args as usize != args_v.len() {
return Err(Cow::from(format!("invalid number of arguments: {} vs {}", n_args, args_v.len())));
}
let name = cstr("calltmp");
unsafe {
Ok(llvm_sys::core::LLVMBuildCall(llvm.builder, callee_f, args_v.as_mut_ptr(), n_args, name.as_ptr()))
}
},
}
}
}
#[derive(Debug)]
struct PrototypeAst {
name: String,
args: Vec<String>,
}
impl PrototypeAst {
fn new(name: String, args: Vec<String>) -> PrototypeAst {
PrototypeAst { name, args }
}
fn codegen(&self, llvm: &mut LLVM) -> LLVMValueRef {
let n_args = self.args.len();
let double = unsafe { llvm_sys::core::LLVMDoubleTypeInContext(llvm.ctx) };
let mut doubles = vec![double; n_args];
let ft = unsafe { llvm_sys::core::LLVMFunctionType(double, doubles.as_mut_ptr(), n_args as u32, 0) };
let name = cstr(&self.name);
// TODO(beam2d): linkage?
let f = unsafe { llvm_sys::core::LLVMAddFunction(llvm.module, name.as_ptr(), ft) };
for i in 0..n_args {
let param = unsafe { llvm_sys::core::LLVMGetParam(f, i as u32) };
let name = cstr(&self.args[i]);
unsafe { llvm_sys::core::LLVMSetValueName(param, name.as_ptr()) };
}
f
}
}
#[derive(Debug)]
struct FunctionAst {
proto: PrototypeAst,
body: ExprAst,
}
impl FunctionAst {
fn new(proto: PrototypeAst, body: ExprAst) -> FunctionAst {
FunctionAst { proto, body }
}
fn codegen(&self, llvm: &mut LLVM) -> CompileResult<LLVMValueRef> {
let name = cstr(&self.proto.name);
let mut f = unsafe { llvm_sys::core::LLVMGetNamedFunction(llvm.module, name.as_ptr()) };
if f.is_null() {
f = self.proto.codegen(llvm);
if f.is_null() {
return Err(Cow::from("function cannot be created"));
}
}
let empty = unsafe { llvm_sys::core::LLVMCountBasicBlocks(f) } == 0;
if !empty {
return Err(Cow::from("function cannot be redefined"));
}
let name = cstr("entry");
unsafe {
let bb = llvm_sys::core::LLVMAppendBasicBlock(f, name.as_ptr());
llvm_sys::core::LLVMPositionBuilderAtEnd(llvm.builder, bb);
}
llvm.named_values.clear();
let n_args = self.proto.args.len();
for i in 0..n_args {
let param = unsafe { llvm_sys::core::LLVMGetParam(f, i as u32) };
llvm.named_values.insert(self.proto.args[i].clone(), param);
}
match self.body.codegen(llvm) {
Ok(ret_val) => unsafe {
llvm_sys::core::LLVMBuildRet(llvm.builder, ret_val);
match llvm_sys::analysis::LLVMVerifyFunction(f, llvm_sys::analysis::LLVMVerifierFailureAction::LLVMPrintMessageAction) {
0 => Ok(f),
_ => {
llvm_sys::core::LLVMDeleteFunction(f);
Err(Cow::from("invalid function"))
},
}
},
Err(e) => unsafe {
llvm_sys::core::LLVMDeleteFunction(f);
Err(e)
},
}
}
}
struct Parser<'a> {
lexer: Lexer<'a>,
binop_precedence: HashMap<char, i32>,
}
impl<'a> Parser<'a> {
fn new(src_text: &'a str) -> Parser<'a> {
let mut binop_precedence = HashMap::new();
binop_precedence.insert('<', 10);
binop_precedence.insert('+', 20);
binop_precedence.insert('-', 20);
binop_precedence.insert('*', 40);
Parser { lexer: Lexer::new(src_text), binop_precedence }
}
// ident_expr
// ::= ident
// ::= ident '(' expr* ')'
fn parse_ident_expr(&mut self, name: String) -> ParseResult<ExprAst> {
match self.lexer.peektok()? {
Token::Op('(') => { self.lexer.gettok().unwrap(); },
_ => return Ok(ExprAst::Variable(name)),
}
let mut args = vec![];
while *self.lexer.peektok()? != Token::Op(')') {
let arg = self.parse_expr()?;
args.push(arg);
if let Token::Op(')') = self.lexer.peektok()? {
break;
}
self.consume_tok(&Token::Op(','))?;
}
self.lexer.gettok().unwrap(); // Op(')')
Ok(ExprAst::Call { callee: name, args })
}
// primary_expr
// ::= ident_expr
// ::= num_expr
// ::= parsen_expr
fn parse_primary_expr(&mut self) -> ParseResult<ExprAst> {
match self.lexer.gettok()? {
Token::Ident(name) => self.parse_ident_expr(name),
Token::Number(value) => Ok(ExprAst::Number(value)),
Token::Op('(') => {
let expr = self.parse_expr()?;
self.consume_tok(&Token::Op(')'))?;
Ok(expr)
},
_ => Err(Cow::from("unknown token when expecting an expression")),
}
}
// binop_rhs ::= ('+' primary)+
fn parse_binop_rhs(&mut self, prec: i32, mut lhs: ExprAst) -> ParseResult<ExprAst> {
loop {
let tok_prec = self.get_prec()?;
if tok_prec < prec {
return Ok(lhs);
}
let op = self.lexer.gettok()?.get_op_name_or_panic();
let mut rhs = self.parse_primary_expr()?;
let next_prec = self.get_prec()?;
if prec < next_prec {
rhs = self.parse_binop_rhs(tok_prec + 1, rhs)?;
}
lhs = ExprAst::Binary { op, lhs: Box::from(lhs), rhs: Box::from(rhs) };
}
}
// expr ::= primary binop_rhs
fn parse_expr(&mut self) -> ParseResult<ExprAst> {
let lhs = self.parse_primary_expr()?;
self.parse_binop_rhs(0, lhs)
}
// prototype ::= ident '(' ident* ')'
fn parse_prototype(&mut self) -> ParseResult<PrototypeAst> {
let name = self.consume_ident_tok()?;
self.consume_tok(&Token::Op('('))?;
let mut args = vec![];
while let Token::Ident(_) = self.lexer.peektok()? {
args.push(self.consume_ident_tok()?);
}
self.consume_tok(&Token::Op(')'))?;
Ok(PrototypeAst::new(name, args))
}
// definition ::= 'def' prototype expr
fn parse_definition(&mut self) -> ParseResult<FunctionAst> {
self.consume_tok(&Token::Def)?;
let proto = self.parse_prototype()?;
let body = self.parse_expr()?;
Ok(FunctionAst::new(proto, body))
}
// external ::= 'extern' prototype
fn parse_extern(&mut self) -> ParseResult<PrototypeAst> {
self.consume_tok(&Token::Extern)?;
Ok(self.parse_prototype()?)
}
// toplevelexpr ::= expr
fn parse_toplevel_expr(&mut self) -> ParseResult<FunctionAst> {
let expr = self.parse_expr()?;
let proto = PrototypeAst::new("".to_string(), vec![]);
Ok(FunctionAst::new(proto, expr))
}
// ---- helper functions ----
// Consumes the specified token
fn consume_tok(&mut self, tok: &Token) -> ParseResult<()> {
if self.lexer.gettok()? != *tok {
Err(Cow::from(format!("{:?} is expected", tok)))?;
}
Ok(())
}
// Consumes an identifier
fn consume_ident_tok(&mut self) -> ParseResult<String> {
match self.lexer.gettok()? {
Token::Ident(n) => Ok(n),
_ => Err(Cow::from("identifier is expected")),
}
}
// Gets the precedence of the next binop token or -1 if the next is not a binop
fn get_prec(&mut self) -> ParseResult<i32> {
if let Token::Op(op) = self.lexer.peektok()? {
return Ok(*self.binop_precedence.get(op).unwrap_or(&-1));
}
Ok(-1)
}
}
fn write_err(s: &str) {
write!(io::stderr(), "{}", s).unwrap();
}
fn handle_def(parser: &mut Parser, llvm: &mut LLVM) -> ParseResult<()> {
let fn_ast = parser.parse_definition()?;
let fn_ir = fn_ast.codegen(llvm)?;
if !fn_ir.is_null() {
write_err("Read function definition:");
unsafe {
llvm_sys::core::LLVMDumpValue(fn_ir);
}
write_err("\n");
}
Ok(())
}
fn handle_extern(parser: &mut Parser, llvm: &mut LLVM) -> ParseResult<()> {
let proto_ast = parser.parse_extern()?;
let fn_ir = proto_ast.codegen(llvm);
if !fn_ir.is_null() {
write_err("Read extern:");
unsafe {
llvm_sys::core::LLVMDumpValue(fn_ir);
}
write_err("\n");
}
Ok(())
}
fn handle_toplevel_expr(parser: &mut Parser, llvm: &mut LLVM) -> ParseResult<()> {
let fn_ast = parser.parse_toplevel_expr()?;
let fn_ir = fn_ast.codegen(llvm)?;
if !fn_ir.is_null() {
write_err("Read top-level expression:");
unsafe {
llvm_sys::core::LLVMDumpValue(fn_ir);
}
write_err("\n");
}
println!("{:?}", parser.parse_toplevel_expr()?);
Ok(())
}
fn main() -> Result<(), Cow<'static, str>> {
let stdin = io::stdin();
let mut src = String::new();
stdin.lock().read_to_string(&mut src).map_err(|_| Cow::from("cannot read stdin"))?;
let mut parser = Parser::new(&src);
let mut llvm = LLVM::new();
loop {
match parser.lexer.peektok()? {
Token::Eof => break,
Token::Op(';') => { parser.lexer.gettok()?; },
Token::Def => handle_def(&mut parser, &mut llvm)?,
Token::Extern => handle_extern(&mut parser, &mut llvm)?,
_ => handle_toplevel_expr(&mut parser, &mut llvm)?,
}
}
Ok(())
}
|
pub mod healthcare_parameters;
pub use healthcare_parameters::HealthcareParameters;
|
// traits.rs ---
//
// Filename: traits.rs
// Author: Jules <archjules>
// Created: Thu Mar 30 22:53:26 2017 (+0200)
// Last-Updated: Fri Mar 31 15:43:13 2017 (+0200)
// By: Jules <archjules>
//
pub trait ReadMemory {
fn read_byte(&self, address: usize) -> u8;
fn read_word(&self, address: usize) -> u16;
}
impl ReadMemory for Vec<u8> {
fn read_byte(&self, address: usize) -> u8 {
self[address]
}
fn read_word(&self, address: usize) -> u16 {
((self[address] as u16) << 8) |
(self[address + 1] as u16)
}
}
pub trait WriteMemory {
fn write_byte(&mut self, address: usize, value: u8);
fn write_word(&mut self, address: usize, value: u16);
}
impl WriteMemory for Vec<u8> {
fn write_byte(&mut self, address: usize, value: u8) {
self[address] = value;
}
fn write_word(&mut self, address: usize, value: u16) {
self[address] = (value >> 8) as u8;
self[address + 1] = value as u8;
}
}
|
use crate::headers::*;
use crate::AddAsHeader;
use http::request::Builder;
use std::str::FromStr;
use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LeaseId(Uuid);
impl std::fmt::Display for LeaseId {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
self.0.fmt(fmt)
}
}
impl std::str::FromStr for LeaseId {
type Err = <Uuid as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(uuid::Uuid::from_str(s)?))
}
}
impl AddAsHeader for LeaseId {
fn add_as_header(&self, builder: Builder) -> Builder {
builder.header(LEASE_ID, &format!("{}", self.0))
}
fn add_as_header2(
&self,
request: &mut crate::Request,
) -> Result<(), crate::errors::HTTPHeaderError> {
request
.headers_mut()
.append(LEASE_ID, http::HeaderValue::from_str(&self.0.to_string())?);
Ok(())
}
}
|
/*
chapter 4
primitive types
arrays
*/
fn main() {
let a = [1, 2, 3]; // a: [i32; 3]
println!("{:?}", a);
let mut b = [1, 3, 2]; // b: [i32; 3]
println!("{:?}", b);
b = [3, 2, 1];
println!("{:?}", b);
}
// output should be:
/*
[1, 2, 3]
[1, 3, 2]
[3, 2, 1]
*/
|
pub use self::r_layout::RLayout;
pub use self::constraints_layout::RConstraintsLayout;
mod r_layout;
mod constraints_layout;
pub fn hbox() {
}
pub fn align() {
} |
//! Commonly used Base58 alphabets.
/// Bitcoin's alphabet as defined in their Base58Check encoding.
///
/// See https://en.bitcoin.it/wiki/Base58Check_encoding#Base58_symbol_chart.
pub const BITCOIN: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
/// Monero's alphabet as defined in this forum post.
///
/// See https://forum.getmonero.org/4/academic-and-technical/221/creating-a-standard-for-physical-coins
pub const MONERO: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
/// Ripple's alphabet as defined in their wiki.
///
/// See https://wiki.ripple.com/Encodings
pub const RIPPLE: &[u8; 58] = b"rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz";
/// Flickr's alphabet for creating short urls from photo ids.
///
/// See https://www.flickr.com/groups/api/discuss/72157616713786392/
pub const FLICKR: &[u8; 58] = b"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
/// The default alphabet used if none is given. Currently is the
/// [`BITCOIN`](constant.BITCOIN.html) alphabet.
pub const DEFAULT: &[u8; 58] = BITCOIN;
/// Prepared Alpabet for [`EncodeBuilder`](crate::encode::EncodeBuilder) and [`DecodeBuilder`](crate::decode::DecodeBuilder).
#[derive(Clone, Copy)]
#[allow(missing_debug_implementations)]
pub struct Alphabet {
pub(crate) encode: [u8; 58],
pub(crate) decode: [u8; 128],
}
impl Alphabet {
/// Bitcoin's prepared alphabet.
pub const BITCOIN: &'static Self = &Self::new(BITCOIN);
/// Monero's prepared alphabet.
pub const MONERO: &'static Self = &Self::new(MONERO);
/// Ripple's prepared alphabet.
pub const RIPPLE: &'static Self = &Self::new(RIPPLE);
/// Flickr's prepared alphabet.
pub const FLICKR: &'static Self = &Self::new(FLICKR);
/// The default prepared alphabet used if none is given. Currently is the
/// [`Alphabet::Bitcoin`](Alphabet::BITCOIN) alphabet.
pub const DEFAULT: &'static Self = Self::BITCOIN;
/// Create prepared alphabet.
pub const fn new(base: &[u8; 58]) -> Alphabet {
let encode = [
base[0], base[1], base[2], base[3], base[4], base[5], base[6], base[7], base[8],
base[9], base[10], base[11], base[12], base[13], base[14], base[15], base[16],
base[17], base[18], base[19], base[20], base[21], base[22], base[23], base[24],
base[25], base[26], base[27], base[28], base[29], base[30], base[31], base[32],
base[33], base[34], base[35], base[36], base[37], base[38], base[39], base[40],
base[41], base[42], base[43], base[44], base[45], base[46], base[47], base[48],
base[49], base[50], base[51], base[52], base[53], base[54], base[55], base[56],
base[57],
];
let mut decode = [0xFF; 128];
decode[base[0] as usize] = 0;
decode[base[1] as usize] = 1;
decode[base[2] as usize] = 2;
decode[base[3] as usize] = 3;
decode[base[4] as usize] = 4;
decode[base[5] as usize] = 5;
decode[base[6] as usize] = 6;
decode[base[7] as usize] = 7;
decode[base[8] as usize] = 8;
decode[base[9] as usize] = 9;
decode[base[10] as usize] = 10;
decode[base[11] as usize] = 11;
decode[base[12] as usize] = 12;
decode[base[13] as usize] = 13;
decode[base[14] as usize] = 14;
decode[base[15] as usize] = 15;
decode[base[16] as usize] = 16;
decode[base[17] as usize] = 17;
decode[base[18] as usize] = 18;
decode[base[19] as usize] = 19;
decode[base[20] as usize] = 20;
decode[base[21] as usize] = 21;
decode[base[22] as usize] = 22;
decode[base[23] as usize] = 23;
decode[base[24] as usize] = 24;
decode[base[25] as usize] = 25;
decode[base[26] as usize] = 26;
decode[base[27] as usize] = 27;
decode[base[28] as usize] = 28;
decode[base[29] as usize] = 29;
decode[base[30] as usize] = 30;
decode[base[31] as usize] = 31;
decode[base[32] as usize] = 32;
decode[base[33] as usize] = 33;
decode[base[34] as usize] = 34;
decode[base[35] as usize] = 35;
decode[base[36] as usize] = 36;
decode[base[37] as usize] = 37;
decode[base[38] as usize] = 38;
decode[base[39] as usize] = 39;
decode[base[40] as usize] = 40;
decode[base[41] as usize] = 41;
decode[base[42] as usize] = 42;
decode[base[43] as usize] = 43;
decode[base[44] as usize] = 44;
decode[base[45] as usize] = 45;
decode[base[46] as usize] = 46;
decode[base[47] as usize] = 47;
decode[base[48] as usize] = 48;
decode[base[49] as usize] = 49;
decode[base[50] as usize] = 50;
decode[base[51] as usize] = 51;
decode[base[52] as usize] = 52;
decode[base[53] as usize] = 53;
decode[base[54] as usize] = 54;
decode[base[55] as usize] = 55;
decode[base[56] as usize] = 56;
decode[base[57] as usize] = 57;
Alphabet { encode, decode }
}
}
/// `std::borrow::Cow` alternative.
#[allow(variant_size_differences)]
pub(crate) enum AlphabetCow<'a> {
Borrowed(&'a Alphabet),
Owned(Alphabet),
}
|
pub struct FindIndices<'a> {
haystack: &'a str,
needle: String,
offset: usize,
}
impl<'a> FindIndices<'a> {
pub fn new(haystack: &'a str, needle: &str) -> Self {
FindIndices {
haystack,
needle: String::from(needle),
offset: 0,
}
}
}
impl<'a> Iterator for FindIndices<'a> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
self.haystack.find(&self.needle).and_then(|index| {
self.haystack = &self.haystack[index + 1..];
self.offset += index + 1;
Some(self.offset - 1)
})
}
}
pub trait IndicesOf {
fn indices_of<'a>(&'a self, needle: &str) -> FindIndices<'a>;
}
impl IndicesOf for str {
/// An iterator over the indices for matches of a pattern within a string
/// slice.
fn indices_of<'a>(&'a self, needle: &str) -> FindIndices<'a> {
FindIndices::new(self, needle)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_indices_of() {
let idx = "abaabaaaababbbaaaababbaab"
.indices_of("b")
.collect::<Vec<_>>();
assert_eq!(idx, vec![1, 4, 9, 11, 12, 13, 18, 20, 21, 24]);
}
}
|
pub fn f1(a: u8, b: u8) -> u8 {
(a + b) / 2 * 4
}
|
use stq_router::RouteParser;
use stq_types::*;
/// List of all routes with params for the app
#[derive(Clone, Debug, PartialEq)]
pub enum Route {
Roles,
RoleById {
id: RoleId,
},
RolesByUserId {
user_id: UserId,
},
Countries,
CountriesFlatten,
CountryByAlpha2 {
alpha2: Alpha2,
},
CountryByAlpha3 {
alpha3: Alpha3,
},
CountryByNumeric {
numeric: i32,
},
Products,
ProductsById {
base_product_id: BaseProductId,
},
ProductsByIdAndCompanyPackageId {
base_product_id: BaseProductId,
company_package_id: CompanyPackageId,
},
Companies,
CompanyById {
company_id: CompanyId,
},
Packages,
PackagesById {
package_id: PackageId,
},
CompaniesPackages,
CompaniesPackagesById {
company_package_id: CompanyPackageId,
},
CompaniesPackagesByIds {
company_id: CompanyId,
package_id: PackageId,
},
PackagesByCompanyId {
company_id: CompanyId,
},
CompaniesByPackageId {
package_id: PackageId,
},
CompanyPackageDeliveryPrice {
company_package_id: CompanyPackageId,
},
CompanyPackageRates {
company_package_id: CompanyPackageId,
},
AvailablePackages,
AvailablePackagesForUser {
base_product_id: BaseProductId,
},
AvailablePackagesForUserV2 {
base_product_id: BaseProductId,
},
AvailablePackageForUser {
base_product_id: BaseProductId,
company_package_id: CompanyPackageId,
},
AvailablePackageForUserByShippingId {
shipping_id: ShippingId,
},
AvailablePackageForUserByShippingIdV2 {
shipping_id: ShippingId,
},
UsersAddresses,
UserAddress {
user_id: UserId,
},
UserAddressById {
user_address_id: i32,
},
}
pub fn create_route_parser() -> RouteParser<Route> {
let mut route_parser = RouteParser::default();
route_parser.add_route(r"^/roles$", || Route::Roles);
route_parser.add_route_with_params(r"^/roles/by-user-id/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|user_id| Route::RolesByUserId { user_id })
});
route_parser.add_route_with_params(r"^/roles/by-id/([a-zA-Z0-9-]+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|id| Route::RoleById { id })
});
route_parser.add_route(r"^/countries$", || Route::Countries);
route_parser.add_route(r"^/countries/flatten$", || Route::CountriesFlatten);
// Countries search
route_parser.add_route_with_params(r"^/countries/alpha2/(\S+)$", |params| {
params
.get(0)
.map(|param| param.to_string().to_uppercase())
.map(Alpha2)
.map(|alpha2| Route::CountryByAlpha2 { alpha2 })
});
route_parser.add_route_with_params(r"^/countries/alpha3/(\S+)$", |params| {
params
.get(0)
.map(|param| param.to_string().to_uppercase())
.map(Alpha3)
.map(|alpha3| Route::CountryByAlpha3 { alpha3 })
});
route_parser.add_route_with_params(r"^/countries/numeric/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|numeric| Route::CountryByNumeric { numeric })
});
route_parser.add_route(r"^/products$", || Route::Products);
route_parser.add_route_with_params(r"^/products/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|base_product_id| Route::ProductsById { base_product_id })
});
route_parser.add_route_with_params(r"^/products/(\d+)/company_package/(\d+)$", |params| {
if let Some(base_product_id_s) = params.get(0) {
if let Some(company_package_id_s) = params.get(1) {
if let Ok(base_product_id) = base_product_id_s.parse().map(BaseProductId) {
if let Ok(company_package_id) = company_package_id_s.parse().map(CompanyPackageId) {
return Some(Route::ProductsByIdAndCompanyPackageId {
base_product_id,
company_package_id,
});
}
}
}
}
None
});
route_parser.add_route(r"^/companies$", || Route::Companies);
route_parser.add_route_with_params(r"^/companies/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|company_id| Route::CompanyById { company_id })
});
route_parser.add_route(r"^/packages$", || Route::Packages);
route_parser.add_route_with_params(r"^/packages/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|package_id| Route::PackagesById { package_id })
});
route_parser.add_route(r"^/companies_packages$", || Route::CompaniesPackages);
route_parser.add_route_with_params(r"^/companies_packages/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|company_package_id| Route::CompaniesPackagesById { company_package_id })
});
route_parser.add_route_with_params(r"^/companies_packages/(\d+)/price$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|company_package_id| Route::CompanyPackageDeliveryPrice { company_package_id })
});
route_parser.add_route_with_params(r"^/companies_packages/(\d+)/rates$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|company_package_id| Route::CompanyPackageRates { company_package_id })
});
route_parser.add_route_with_params(r"^/companies/(\d+)/packages$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|company_id| Route::PackagesByCompanyId { company_id })
});
route_parser.add_route_with_params(r"^/companies/(\d+)/packages/(\d+)$", |params| {
let company_id = params.get(0)?.parse().ok().map(CompanyId)?;
let package_id = params.get(1)?.parse().ok().map(PackageId)?;
Some(Route::CompaniesPackagesByIds { company_id, package_id })
});
route_parser.add_route_with_params(r"^/packages/(\d+)/companies$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|package_id| Route::CompaniesByPackageId { package_id })
});
route_parser.add_route(r"^/available_packages$", || Route::AvailablePackages);
route_parser.add_route_with_params(r"^/available_packages_for_user/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|base_product_id| Route::AvailablePackagesForUser { base_product_id })
});
route_parser.add_route_with_params(r"^/v2/available_packages_for_user/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|base_product_id| Route::AvailablePackagesForUserV2 { base_product_id })
});
route_parser.add_route_with_params(
r"^/available_packages_for_user/products/(\d+)/companies_packages/(\d+)$",
|params| {
let base_product_id = params.get(0)?.parse().ok().map(BaseProductId)?;
let company_package_id = params.get(1)?.parse().ok().map(CompanyPackageId)?;
Some(Route::AvailablePackageForUser {
base_product_id,
company_package_id,
})
},
);
route_parser.add_route_with_params(r"^/available_packages_for_user/by_shipping_id/(\d+)$", |params| {
let shipping_id = ShippingId(params.get(0)?.parse().ok()?);
Some(Route::AvailablePackageForUserByShippingId { shipping_id })
});
route_parser.add_route_with_params(r"^/v2/available_packages_for_user/by_shipping_id/(\d+)$", |params| {
let shipping_id = ShippingId(params.get(0)?.parse().ok()?);
Some(Route::AvailablePackageForUserByShippingIdV2 { shipping_id })
});
// /users/addresses route
route_parser.add_route(r"^/users/addresses$", || Route::UsersAddresses);
// /users/:id/addresses route
route_parser.add_route_with_params(r"^/users/(\d+)/addresses$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|user_id| Route::UserAddress { user_id })
});
// /users/addresses/:id route
route_parser.add_route_with_params(r"^/users/addresses/(\d+)$", |params| {
params
.get(0)
.and_then(|string_id| string_id.parse().ok())
.map(|user_address_id| Route::UserAddressById { user_address_id })
});
route_parser
}
|
use twang::{gen::White, mono::Mono64, Audio};
mod wav;
fn main() {
let mut out = Audio::<Mono64>::with_silence(48_000, 48_000 * 5);
let mut pink = White::new();
out.generate(&mut pink);
wav::write(out, "white.wav").expect("Failed to write WAV file");
}
|
use crate::*;
pub fn init_math(globals: &mut Globals) -> Value {
let id = globals.get_ident_id("Math");
let class = ClassRef::from(id, globals.builtins.object);
let obj = Value::class(globals, class);
globals.add_builtin_class_method(obj, "sqrt", sqrt);
globals.add_builtin_class_method(obj, "cos", cos);
globals.add_builtin_class_method(obj, "sin", sin);
obj
}
// Class methods
// Instance methods
fn sqrt(vm: &mut VM, _: Value, args: &Args) -> VMResult {
let arg = args[0];
let num = if arg.is_packed_num() {
if arg.is_packed_fixnum() {
arg.as_packed_fixnum() as f64
} else {
arg.as_packed_flonum()
}
} else {
return Err(vm.error_type("Must be a number."));
};
let res = Value::flonum(num.sqrt());
Ok(res)
}
fn cos(vm: &mut VM, _: Value, args: &Args) -> VMResult {
let arg = args[0];
let num = if arg.is_packed_num() {
if arg.is_packed_fixnum() {
arg.as_packed_fixnum() as f64
} else {
arg.as_packed_flonum()
}
} else {
return Err(vm.error_type("Must be a number."));
};
let res = Value::flonum(num.cos());
Ok(res)
}
fn sin(vm: &mut VM, _: Value, args: &Args) -> VMResult {
let arg = args[0];
let num = if arg.is_packed_num() {
if arg.is_packed_fixnum() {
arg.as_packed_fixnum() as f64
} else {
arg.as_packed_flonum()
}
} else {
return Err(vm.error_type("Must be a number."));
};
let res = Value::flonum(num.sin());
Ok(res)
}
|
#![cfg_attr(not(test), no_std)]
extern crate embedded_graphics;
use embedded_graphics::{
geometry::Size,
image::ImageRaw,
mono_font::{DecorationDimensions, MonoFont},
};
mod char_offset;
use char_offset::{char_offset_impl, CHARS_PER_ROW};
/// The 8x8 regular
///
/// [](https://raw.githubusercontent.com/sbechet/ibm437/master/doc/ibm437_font_8_8_regular.png)
///
#[cfg(feature = "regular8x8")]
pub const IBM437_8X8_REGULAR: MonoFont = MonoFont {
image: ImageRaw::new_binary(
include_bytes!(concat!(core::env!("OUT_DIR"),"/ibm437_font_8_8_regular.raw")),
CHARS_PER_ROW as u32 * 8,
),
glyph_mapping: &char_offset_impl,
character_size: Size::new(8, 8),
character_spacing: 0,
baseline: 6,
underline: DecorationDimensions::new(8, 1),
strikethrough: DecorationDimensions::default_strikethrough(8),
};
/// The 8x8 bold
///
/// [](https://raw.githubusercontent.com/sbechet/ibm437/master/doc/ibm437_font_8_8_bold.png)
///
#[cfg(feature = "bold8x8")]
pub const IBM437_8X8_BOLD: MonoFont = MonoFont {
image: ImageRaw::new_binary(
include_bytes!(concat!(core::env!("OUT_DIR"),"/ibm437_font_8_8_bold.raw")),
CHARS_PER_ROW as u32 * 8,
),
glyph_mapping: &char_offset_impl,
character_size: Size::new(8, 8),
character_spacing: 0,
baseline: 6,
underline: DecorationDimensions::new(8, 1),
strikethrough: DecorationDimensions::default_strikethrough(8),
};
/// The 9x14 regular
///
/// [](https://raw.githubusercontent.com/sbechet/ibm437/master/doc/ibm437_font_9_14_regular.png)
///
#[cfg(feature = "regular9x14")]
pub const IBM437_9X14_REGULAR: MonoFont = MonoFont {
image: ImageRaw::new_binary(
include_bytes!(concat!(core::env!("OUT_DIR"),"/ibm437_font_9_14_regular.raw")),
CHARS_PER_ROW as u32 * 9,
),
glyph_mapping: &char_offset_impl,
character_size: Size::new(9, 14),
character_spacing: 0,
baseline: 10,
underline: DecorationDimensions::new(14, 1),
strikethrough: DecorationDimensions::default_strikethrough(14),
};
#[cfg(test)]
mod test {
use super::*;
use embedded_graphics::{
mock_display::MockDisplay,
mono_font::{MonoTextStyle, MonoTextStyleBuilder},
pixelcolor::BinaryColor,
prelude::*,
text::Text,
};
#[test]
fn test_a() {
let mut display = MockDisplay::new();
assert_eq!(char_offset_impl('a'), 'a' as usize);
let style = MonoTextStyle::new(&IBM437_8X8_REGULAR, BinaryColor::On);
Text::new("a", Point::new(0, 6), style)
.draw(&mut display)
.unwrap();
assert_eq!(
display,
MockDisplay::from_pattern(&[
" ",
" ",
" #### ",
" # ",
" ##### ",
" # # ",
" ###### ",
" ",
])
);
}
#[test]
fn test_nbsp() {
let mut display = MockDisplay::new();
assert_eq!(char_offset_impl('\u{A0}'), '\u{A0}' as usize);
let style = MonoTextStyleBuilder::new()
.font(&IBM437_8X8_REGULAR)
.text_color(BinaryColor::On)
.background_color(BinaryColor::Off)
.build();
Text::new("\u{A0}", Point::new(0, 6), style)
.draw(&mut display)
.unwrap();
assert_eq!(
display,
MockDisplay::from_pattern(&[
"........ ",
"........ ",
"........ ",
"........ ",
"........ ",
"........ ",
"........ ",
"........ ",
])
);
}
#[test]
fn test_space() {
let mut display = MockDisplay::new();
assert_eq!(char_offset_impl(' '), ' ' as usize);
let style = MonoTextStyleBuilder::new()
.font(&IBM437_8X8_REGULAR)
.text_color(BinaryColor::On)
.background_color(BinaryColor::Off)
.build();
Text::new(" ", Point::new(0, 6), style)
.draw(&mut display)
.unwrap();
assert_eq!(
display,
MockDisplay::from_pattern(&[
"........ ",
"........ ",
"........ ",
"........ ",
"........ ",
"........ ",
"........ ",
"........ ",
])
);
}
}
|
use std::collections::HashSet;
use std::borrow::BorrowMut;
use std::rc::Rc;
use std::cell::RefCell;
use core::iter::FromIterator;
use rand::prelude::{Rng, RngCore};
use rand::IsaacRng;
use xcg::utils::Trim;
use xcg::model::Point;
use xcg::model::*;
use xcg::bot::TestBot;
#[test]
fn test_border() {
// test on the different cells sizes
let field_sizes = vec![(2, 2), (9, 3), (3, 4), (4, 7)];
// n
// * * * * * * *
// m * *
// * *
// * * * * * * *
for (m, n) in field_sizes {
let mut perimeter: Vec<Point> = vec![];
perimeter.append(&mut points_2(0, 0..n));
perimeter.append(&mut points_1(1..m - 1, n - 1));
perimeter.append(&mut points_2(m - 1, (0..n).rev()));
perimeter.append(&mut points_1((1..m - 1).rev(), 0));
let size = 2 * (m + n - 2) as usize;
assert_eq!(size, perimeter.len());
for l in 0..=(2*size) {
assert_eq!(perimeter[l % size], border_to_point(m as usize, n as usize, l as usize));
}
}
fn points_1(ii: impl Iterator<Item=i16>, j: i16) -> Vec<Point> {
ii.map(|i| Point(i, j)).collect()
}
fn points_2(i: i16, jj: impl Iterator<Item=i16>) -> Vec<Point> {
jj.map(|j| Point(i, j)).collect()
}
}
#[test]
fn test_create_origins() {
let m = 7;
let n = 9;
// 2 players - opposite corners
let o2 = create_origins_n(m, n, 2);
assert_eq!(vec![Point(0, 0), Point(6, 8)], o2);
// 4 players - all corners
let o4 = create_origins_n(m, n, 4);
assert_eq!(vec![Point(0, 0), Point(6, 8), Point(0, 8), Point(6, 0)], o4);
// otherwise - spread in the perimeter
let o8 = create_origins_n(m, n, 8);
assert_eq!(vec![
Point(0, 0), Point(0, 3), Point(0, 6), Point(1, 8),
Point(4, 8), Point(6, 7), Point(6, 4), Point(6, 1)
], o8);
}
#[test]
fn test_permutations() {
let perm0 = create_default_permutation(4);
assert_eq!(vec![0, 1, 2, 3], perm0);
let mut random = IsaacRng::new_from_u64(123);
assert_eq!(vec![2, 0, 1, 3], copy_shuffled_permutation(&perm0, &mut random));
assert_eq!(vec![3, 2, 1, 0], copy_shuffled_permutation(&perm0, &mut random));
assert_eq!(vec![2, 1, 3, 0], copy_shuffled_permutation(&perm0, &mut random));
}
#[test]
fn test_parse_string() {
let str0 = r#"
*.*.*.*.*A*a*a
*.3d2.2.2.0.*a
*.2D2.2C2.1.*.
*.2.2. . .1B*.
*.*.*.*.*.*b*b
reordering=[2,1,3,0]
stats=Stats(19,33,2,1,0,[1,2,9,1])
origins=[(0,6),(4,6),(4,0),(0,0)]
"#.trim_indent();
let gs = GameState::parse_string(&str0[..]).unwrap();
let str1 = gs.to_string();
assert_eq!(str0, str1);
}
#[test]
fn test_score() {
let gs = game_state(r#"
*.*.*.*.*.*.*.
*.0. A1.1.1.*.
*. a a B b2D*.
*.3C3.3. .2.*.
*.*.* *.*.*.*.
"#);
let stats = gs.stats;
assert_eq!( vec![1, 3, 2, 3], stats.scores);
assert_eq!( 29, stats.filled_count);
}
#[test]
fn test_flood() {
let gs: GameState = game_state(r#"
*.*.*.*.*.*.*.
*. .1. . . .*.
*. a a a a A*.
*. . .1. . .*.
*.*.*.*.*.*.*B
"#);
let all: Vec<Point> = gs.players.iter()
.flat_map(|p| p.0.clone())
.collect();
let bodies = HashSet::from_iter(all);
let points1: HashSet<Point> = [].iter().cloned().collect();
let points2: HashSet<Point> = [Point(1, 1)].iter().cloned().collect();
let points3: HashSet<Point> = [Point(3, 5), Point(3, 4)].iter().cloned().collect();
assert_eq!(points1, flood(&gs.field, &bodies, Point(2, 2)));
assert_eq!(points2, flood(&gs.field, &bodies, Point(1, 1)));
assert_eq!(points3, flood(&gs.field, &bodies, Point(3, 4)));
let flooded_area = calculate_flood_area(&gs.field, &gs.players[0].0);
assert_eq!(vec![Point(1, 1), Point(2, 1), Point(2, 2), Point(2, 3), Point(2, 4), Point(2, 5)], flooded_area)
}
#[test]
fn test_flood_step() {
let gs0 = game_state(r#"
*.*.*.*.*.*.*.
*. b B . A .*.
*. a a a a .*.
*. c c C . .*.
*.*.*.*.*.*.*.
"#);
let a = test_bot("u");
let gs1 = play(&gs0, &mut [a]);
let mut gs2 = game_state(r#"
*.*.*.*.*A*.*.
*.0.0B0.0. .*.
*.0.0.0.0. .*.
*. c c C . .*.
*.*.*.*.*.*.*.
"#);
gs2.stats.iteration = 1;
assert_eq!(gs2, gs1);
}
#[test]
fn test_select_respawn() {
// A's respawn is the upper left corner
let gs0 = game_state(r#"
*B*D*E*.*.*.*.
*C . . . . .*.
*. . . . A .*.
*. . . . . .*.
*.*.*.*.*.*.*.
"#);
let respawn = calculate_respawn(&gs0, 0);
assert_eq!(respawn, Some(Point(2, 0)))
}
#[test]
fn test_bite_other() {
let gs0 = game_state(r#"
*.*.*.*B*.*.*.
*. . . . . .*.
*A . . . . .*.
*. . . . . .*.
*.*.*.*.*.*.*C
"#);
let a = test_bot("rrrr");
let b = test_bot("dddd");
let c = test_bot("");
let gs1 = play(&gs0, &mut [a, b, c]);
let mut gs_exp = game_state(r#"
*.*.*.*.*.*.*.
*. . . . . .*.
*. a a A . .*.
*. . . . . .*B
*.*.*.*.*.*.*C
"#);
gs_exp.stats.bite_count = 1;
gs_exp.stats.iteration = 4;
gs_exp.stats.head_to_head_count = 2;
assert_eq!(gs_exp, gs1);
}
#[test]
fn test_bite_self() {
let gs0 = game_state(r#"
*A*.*.*.*.*.*.
*. . . . . .*.
*. . . . . .*.
*. . . . . .*.
*.*.*.*.*.*.*B
"#);
let a = test_bot("drrrrddlluu");
let b = test_bot("");
let gs1 = play(&gs0, &mut [a, b]);
let mut gs_exp = game_state(r#"
*A*.*.*.*.*.*.
*. . . . . .*.
*. . . . . .*.
*. . . . . .*.
*.*.*.*.*.*.*B
"#);
gs_exp.stats.ouroboros_count = 1;
gs_exp.stats.iteration = 11;
assert_eq!(gs_exp.stats, gs1.stats);
assert_eq!(gs_exp.to_string(), gs1.to_string());
}
#[test]
fn test_game_state_view() {
let gs = game_state(r#"
*.*.*.*.*.*.*.
*.0. A1.1.1.*.
*. a a B b2D*.
*.3C3.3. .2.*.
*.*.* *.*.*.*.
"#);
let mut gsv = GameStateView {
idx: 0,
field: gs.field.clone(),
players: gs.players.iter().map(|p| p.clone()).collect(),
};
make_game_state_view(&mut gsv, &gs, 0);
let exp = r#"
*.*.*.*.*.*.*.
*.0. A1.1.1.*.
*. a a B b2.*.
*.3.3.3. .2.*.
*.*.*.*.*.*.*.
"#.trim_indent();
assert_eq!(exp, gsv.to_string());
make_game_state_view(&mut gsv, &gs, 1);
let exp = r#"
*.*.*.*.*.*.*.
*.0. A1.1.1.*.
*. a a B b2.*.
*.3.3.3. .2.*.
*.*.*.*.*.*.*.
"#.trim_indent();
assert_eq!(exp, gsv.to_string());
make_game_state_view(&mut gsv, &gs, 2);
let exp = r#"
*.*.*.*.*.*.*.
*.0. A1.1.1.*.
*. a a B b2.*.
*.3C3.3. .2.*.
*.*.*.*.*.*.*.
"#.trim_indent();
assert_eq!(exp, gsv.to_string());
make_game_state_view(&mut gsv, &gs, 3);
let exp = r#"
*.*.*.*.*.*.*.
*.0. A1.1.1.*.
*. a a B b2D*.
*.3.3.3. .2.*.
*.*.*.*.*.*.*.
"#.trim_indent();
assert_eq!(exp, gsv.to_string());
}
#[test]
fn test_run_match_with_reordering() {
let match_seed = Some(69);
let random = Rc::new(RefCell::new(IsaacRng::new_from_u64(123)));
let a = test_bot_r(0, random.clone(), "dlu");
let b = test_bot_r(1, random.clone(), "llurr");
let c = test_bot_r(2, random.clone(), "urd");
let d = test_bot_r(3, random.clone(), "rrrdlll");
let mut bots: [Box<dyn Bot>; 4] = [Box::new(a), Box::new(b), Box::new(c), Box::new(d)];
let names = make_bot_names(&bots);
let mut the_match = create_match(5, 7, &names, 20, 0.9, match_seed);
let gs = game_state(r#"
*C*.*.*.*.*.*B
*. . . . . .*.
*. . . . . .*.
*. . . . . .*.
*D*.*.*.*.*.*A
reordering=[3,0,2,1]
origins=[(4,6),(0,6),(0,0),(4,0)]
"#);
assert_eq!(the_match.game_state, gs);
let logger = |_gs: &GameState| {
// println!("{}", gs)
};
run_match(&mut the_match, &mut bots, &logger);
let final_gs = game_state(r#"
*.*.*.*.*.*.*.
*.2C2D3. .1.*B
*.3.3.3. . .*.
*.3.3. . .0A*.
*.*.*.*.*.*.*.
reordering=[3,0,2,1]
stats=Stats(20,30,2,0,0,[1,1,2,6])
origins=[(4,6),(0,6),(0,0),(4,0)]
"#);
//assert_eq!(the_match.game_state.to_string(), final_gs.to_string());
assert_eq!(the_match.game_state, final_gs);
}
#[test]
fn test_run_replay() {
let random = Rc::new(RefCell::new(IsaacRng::new_from_u64(123)));
let a = test_bot_r(0, random.clone(), "dllll");
let b = test_bot_r(1, random.clone(), "luuuu");
let c = test_bot_r(2, random.clone(), "urrrr");
let d = test_bot_r(3, random.clone(), "rdddd");
let mut bots: [Box<dyn Bot>; 4] = [Box::new(a), Box::new(b), Box::new(c), Box::new(d)];
let names = make_bot_names(&bots);
let logger = |_gs: &GameState| {};
for _ in 0..100 {
// run match
let match_k_seed = (*random).borrow_mut().next_u64();
let mut match_k = create_match(11, 11, &names, 32, 0.9, Some(match_k_seed));
let replay_k = run_match(&mut match_k, &mut bots, &logger);
let gs1 = run_replay(&replay_k, &logger);
let gs2 = run_replay(&replay_k, &logger);
assert_eq!(match_k.game_state, gs1);
assert_eq!(match_k.game_state, gs2);
}
}
#[test]
fn test_run_tournament() {
let random = Rc::new(RefCell::new(IsaacRng::new_from_u64(123)));
let a = test_bot_r(0, random.clone(), "dlu");
let b = test_bot_r(1, random.clone(), "lur");
let c = test_bot_r(2, random.clone(), "urd");
let d = test_bot_r(3, random.clone(), "rdl");
let mut bots: [Box<dyn Bot>; 4] = [Box::new(a), Box::new(b), Box::new(c), Box::new(d)];
let names = make_bot_names(&mut bots);
let logger = |_gs: &GameState| {};
let match_count = 100;
let mut game_states = Vec::<GameState>::with_capacity(match_count);
let mut replays = Vec::<Replay>::with_capacity(match_count);
for _ in 0..match_count {
let seed = (*random).borrow_mut().next_u64();
let mut cur_match = create_match(7, 7, &names, 32, 0.9, Some(seed));
let cur_replay = run_match(&mut cur_match, &mut bots, &logger);
replays.push(cur_replay);
game_states.push(cur_match.game_state);
}
// tournament is done, check some matches
let exp66 = game_state(r#"
*C*.*.*.*.*.*.
*.2.2. .1.1.*.
*.2. . . .1.*.
*.2. . . B1.*.
*.3.3D . . .*.
*.3. . . . .*.
*.*.*.*.*.*A*.
reordering=[2,3,1,0]
stats=Stats(32,35,1,4,0,[0,4,4,3])
origins=[(6,6),(0,6),(0,0),(6,0)]
"#);
let rgs66 = run_replay(&replays[66], &logger);
assert_eq!(exp66.to_string(), game_states[66].to_string());
assert_eq!(exp66, game_states[66]);
assert_eq!(exp66, rgs66);
}
fn make_bot_names<T>(bots: &[T]) -> Vec<String> {
let mut names = vec![];
for k in 0..bots.len() {
// self.idx.map(|id| {
// let ch = (('A' as u8) + id) as char;
// format!("{}: {}", ch, from_utf8(&self.path).unwrap())
// }).unwrap_or_else(|| format!("_: {}", from_utf8(&self.path).unwrap()))
let idx = Some(k as u8);
let name = idx.map(|id| format!("{}", ((('A' as u8) + id) as char).to_string()))
.unwrap_or_else(|| "?".to_string());
names.push(name);
}
names
}
// === helpers ===
fn game_state(gs: &str) -> GameState {
GameState::parse_string(&gs.trim_indent()).unwrap()
}
fn test_bot(path: &str) -> TestBot<IsaacRng> {
TestBot::new(path)
}
fn test_bot_r<R: Rng>(idx: usize, rng: Rc<RefCell<R>>, path: &str) -> TestBot<R> {
TestBot::with_index_random(path, idx, rng)
}
fn play<B: Bot>(gs: &GameState, bots: &mut [B]) -> GameState {
let nb = bots.len();
let mut gs = gs.clone();
let mut progressing = true;
let mut iteration = 0;
// build client views of the game state
let mut pgss = vec![];
for k in 0..nb {
let pgs = GameStateView {
idx: k,
field: gs.field.clone(),
players: gs.players.iter().map(|p| p.clone()).collect(),
};
pgss.push(pgs);
}
// reset bot's state
for k in 0..bots.len() {
let idx = gs.reordering[k] as usize;
let cgs = &mut pgss[idx];
make_game_state_view(cgs, &gs, idx);
bots[idx].reset(cgs, idx, 0u64);
}
// iterating
while progressing {
gs.stats.iteration = iteration;
iteration += 1;
let mut moves = vec![];
for k in 0..bots.len() {
let idx = gs.reordering[k] as usize;
let cgs = &mut pgss[idx];
make_game_state_view(cgs, &gs, idx);
let mv = bots[idx].do_move(cgs);
moves.push(mv);
step(gs.borrow_mut(), idx, mv);
}
if moves.iter().all(|m| *m == Move::Stop) {
progressing = false;
}
}
gs
}
|
// SPDX-FileCopyrightText: 2020-2021 HH Partners
//
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Serialize};
/// https://spdx.github.io/spdx-spec/3-package-information/#39-package-verification-code
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct PackageVerificationCode {
/// Value of the verification code.
#[serde(rename = "packageVerificationCodeValue")]
pub value: String,
/// Files that were excluded when calculating the verification code.
#[serde(
rename = "packageVerificationCodeExcludedFiles",
skip_serializing_if = "Vec::is_empty",
default
)]
pub excludes: Vec<String>,
}
|
extern crate adder;
fn main() {
let a = 10;
let b = 15;
let sum = adder::add(a, b);
println!("{} + {} = {}", a, b, sum);
}
|
//!
//! [`RawDevice`](RawDevice) and [`RawSurface`](RawSurface)
//! implementations using the legacy mode-setting infrastructure.
//!
//! Usually this implementation will be wrapped into a [`GbmDevice`](::backend::drm::gbm::GbmDevice).
//! Take a look at `anvil`s source code for an example of this.
//!
//! For an example how to use this standalone, take a look at the `raw_drm` example.
//!
use super::{DevPath, Device, DeviceHandler, RawDevice};
use drm::control::{connector, crtc, encoder, Device as ControlDevice, ResourceHandles, ResourceInfo};
use drm::Device as BasicDevice;
use nix::libc::dev_t;
use nix::sys::stat::fstat;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::os::unix::io::{AsRawFd, RawFd};
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
mod surface;
pub use self::surface::LegacyDrmSurface;
use self::surface::{LegacyDrmSurfaceInternal, State};
pub mod error;
use self::error::*;
#[cfg(feature = "backend_session")]
pub mod session;
/// Open raw drm device utilizing legacy mode-setting
pub struct LegacyDrmDevice<A: AsRawFd + 'static> {
dev: Rc<Dev<A>>,
dev_id: dev_t,
active: Arc<AtomicBool>,
backends: Rc<RefCell<HashMap<crtc::Handle, Weak<LegacyDrmSurfaceInternal<A>>>>>,
handler: Option<RefCell<Box<dyn DeviceHandler<Device = LegacyDrmDevice<A>>>>>,
logger: ::slog::Logger,
}
pub(in crate::backend::drm) struct Dev<A: AsRawFd + 'static> {
fd: A,
priviledged: bool,
active: Arc<AtomicBool>,
old_state: HashMap<crtc::Handle, (crtc::Info, Vec<connector::Handle>)>,
logger: ::slog::Logger,
}
impl<A: AsRawFd + 'static> AsRawFd for Dev<A> {
fn as_raw_fd(&self) -> RawFd {
self.fd.as_raw_fd()
}
}
impl<A: AsRawFd + 'static> BasicDevice for Dev<A> {}
impl<A: AsRawFd + 'static> ControlDevice for Dev<A> {}
impl<A: AsRawFd + 'static> Drop for Dev<A> {
fn drop(&mut self) {
info!(self.logger, "Dropping device: {:?}", self.dev_path());
if self.active.load(Ordering::SeqCst) {
// Here we restore the tty to it's previous state.
// In case e.g. getty was running on the tty sets the correct framebuffer again,
// so that getty will be visible.
let old_state = self.old_state.clone();
for (handle, (info, connectors)) in old_state {
if let Err(err) = crtc::set(
&*self,
handle,
info.fb(),
&connectors,
info.position(),
info.mode(),
) {
error!(self.logger, "Failed to reset crtc ({:?}). Error: {}", handle, err);
}
}
}
if self.priviledged {
if let Err(err) = self.drop_master() {
error!(self.logger, "Failed to drop drm master state. Error: {}", err);
}
}
}
}
impl<A: AsRawFd + 'static> LegacyDrmDevice<A> {
/// Create a new [`LegacyDrmDevice`] from an open drm node
///
/// Returns an error if the file is no valid drm node or context creation was not
/// successful.
pub fn new<L>(dev: A, logger: L) -> Result<Self>
where
L: Into<Option<::slog::Logger>>,
{
let log = crate::slog_or_stdlog(logger).new(o!("smithay_module" => "backend_drm"));
info!(log, "DrmDevice initializing");
let dev_id = fstat(dev.as_raw_fd())
.chain_err(|| ErrorKind::UnableToGetDeviceId)?
.st_rdev;
let active = Arc::new(AtomicBool::new(true));
let mut dev = Dev {
fd: dev,
priviledged: true,
old_state: HashMap::new(),
active: active.clone(),
logger: log.clone(),
};
// we want to modeset, so we better be the master, if we run via a tty session
if dev.set_master().is_err() {
warn!(log, "Unable to become drm master, assuming unpriviledged mode");
dev.priviledged = false;
};
// enumerate (and save) the current device state
let res_handles = ControlDevice::resource_handles(&dev).chain_err(|| {
ErrorKind::DrmDev(format!("Error loading drm resources on {:?}", dev.dev_path()))
})?;
for &con in res_handles.connectors() {
let con_info = connector::Info::load_from_device(&dev, con).chain_err(|| {
ErrorKind::DrmDev(format!("Error loading connector info on {:?}", dev.dev_path()))
})?;
if let Some(enc) = con_info.current_encoder() {
let enc_info = encoder::Info::load_from_device(&dev, enc).chain_err(|| {
ErrorKind::DrmDev(format!("Error loading encoder info on {:?}", dev.dev_path()))
})?;
if let Some(crtc) = enc_info.current_crtc() {
let info = crtc::Info::load_from_device(&dev, crtc).chain_err(|| {
ErrorKind::DrmDev(format!("Error loading crtc info on {:?}", dev.dev_path()))
})?;
dev.old_state
.entry(crtc)
.or_insert((info, Vec::new()))
.1
.push(con);
}
}
}
Ok(LegacyDrmDevice {
dev: Rc::new(dev),
dev_id,
active,
backends: Rc::new(RefCell::new(HashMap::new())),
handler: None,
logger: log.clone(),
})
}
}
impl<A: AsRawFd + 'static> AsRawFd for LegacyDrmDevice<A> {
fn as_raw_fd(&self) -> RawFd {
self.dev.as_raw_fd()
}
}
impl<A: AsRawFd + 'static> BasicDevice for LegacyDrmDevice<A> {}
impl<A: AsRawFd + 'static> ControlDevice for LegacyDrmDevice<A> {}
impl<A: AsRawFd + 'static> Device for LegacyDrmDevice<A> {
type Surface = LegacyDrmSurface<A>;
fn device_id(&self) -> dev_t {
self.dev_id
}
fn set_handler(&mut self, handler: impl DeviceHandler<Device = Self> + 'static) {
self.handler = Some(RefCell::new(Box::new(handler)));
}
fn clear_handler(&mut self) {
let _ = self.handler.take();
}
fn create_surface(&mut self, crtc: crtc::Handle) -> Result<LegacyDrmSurface<A>> {
if self.backends.borrow().contains_key(&crtc) {
bail!(ErrorKind::CrtcAlreadyInUse(crtc));
}
if !self.active.load(Ordering::SeqCst) {
bail!(ErrorKind::DeviceInactive);
}
// Try to enumarate the current state to set the initial state variable correctly
let crtc_info = crtc::Info::load_from_device(self, crtc)
.chain_err(|| ErrorKind::DrmDev(format!("Error loading crtc info on {:?}", self.dev_path())))?;
let mode = crtc_info.mode();
let mut connectors = HashSet::new();
let res_handles = ControlDevice::resource_handles(self).chain_err(|| {
ErrorKind::DrmDev(format!("Error loading drm resources on {:?}", self.dev_path()))
})?;
for &con in res_handles.connectors() {
let con_info = connector::Info::load_from_device(self, con).chain_err(|| {
ErrorKind::DrmDev(format!("Error loading connector info on {:?}", self.dev_path()))
})?;
if let Some(enc) = con_info.current_encoder() {
let enc_info = encoder::Info::load_from_device(self, enc).chain_err(|| {
ErrorKind::DrmDev(format!("Error loading encoder info on {:?}", self.dev_path()))
})?;
if let Some(current_crtc) = enc_info.current_crtc() {
if crtc == current_crtc {
connectors.insert(con);
}
}
}
}
let state = State { mode, connectors };
let backend = Rc::new(LegacyDrmSurfaceInternal {
dev: self.dev.clone(),
crtc,
state: RwLock::new(state.clone()),
pending: RwLock::new(state),
logger: self.logger.new(o!("crtc" => format!("{:?}", crtc))),
});
self.backends.borrow_mut().insert(crtc, Rc::downgrade(&backend));
Ok(LegacyDrmSurface(backend))
}
fn process_events(&mut self) {
match crtc::receive_events(self) {
Ok(events) => {
for event in events {
if let crtc::Event::PageFlip(event) = event {
if self.active.load(Ordering::SeqCst) {
if self
.backends
.borrow()
.get(&event.crtc)
.iter()
.flat_map(|x| x.upgrade())
.next()
.is_some()
{
trace!(self.logger, "Handling event for backend {:?}", event.crtc);
if let Some(handler) = self.handler.as_ref() {
handler.borrow_mut().vblank(event.crtc);
}
} else {
self.backends.borrow_mut().remove(&event.crtc);
}
}
}
}
}
Err(err) => {
if let Some(handler) = self.handler.as_ref() {
handler.borrow_mut().error(
ResultExt::<()>::chain_err(Err(err), || {
ErrorKind::DrmDev(format!("Error processing drm events on {:?}", self.dev_path()))
})
.unwrap_err(),
);
}
}
}
}
fn resource_info<T: ResourceInfo>(&self, handle: T::Handle) -> Result<T> {
T::load_from_device(self, handle)
.chain_err(|| ErrorKind::DrmDev(format!("Error loading resource info on {:?}", self.dev_path())))
}
fn resource_handles(&self) -> Result<ResourceHandles> {
ControlDevice::resource_handles(self)
.chain_err(|| ErrorKind::DrmDev(format!("Error loading resource info on {:?}", self.dev_path())))
}
}
impl<A: AsRawFd + 'static> RawDevice for LegacyDrmDevice<A> {
type Surface = LegacyDrmSurface<A>;
}
impl<A: AsRawFd + 'static> Drop for LegacyDrmDevice<A> {
fn drop(&mut self) {
self.clear_handler();
}
}
|
mod apis;
mod backtest;
mod clock;
mod config;
mod simulation;
mod strategies;
mod studies;
mod trading;
use std::env;
fn main() {
let args: Vec<String> = env::args().map(|a| a.to_uppercase()).collect();
if args.len() < 2 {
eprintln!("Must provide at least one symbol to use");
return;
}
let env = config::init_env();
match args[1].as_str() {
"--BACKTEST" => {
println!("Backtesting");
if args[2] == "-V" {
backtest::run_backtest(&args[3..], &env, true);
} else {
backtest::run_backtest(&args[2..], &env, false);
}
}
"--SIM" => {
simulation::run_simulation(&args[2..], &env);
}
"--PAPER" => println!("Paper trading not implemented yet"),
_ => println!("Live trading not implemented yet"),
}
}
|
#[doc = "Register `CIDR2` reader"]
pub type R = crate::R<CIDR2_SPEC>;
#[doc = "Field `PREAMBLE` reader - component identification bits \\[23:16\\]"]
pub type PREAMBLE_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:7 - component identification bits \\[23:16\\]"]
#[inline(always)]
pub fn preamble(&self) -> PREAMBLE_R {
PREAMBLE_R::new((self.bits & 0xff) as u8)
}
}
#[doc = "DBGMCU CoreSight component identity register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cidr2::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CIDR2_SPEC;
impl crate::RegisterSpec for CIDR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cidr2::R`](R) reader structure"]
impl crate::Readable for CIDR2_SPEC {}
#[doc = "`reset()` method sets CIDR2 to value 0x05"]
impl crate::Resettable for CIDR2_SPEC {
const RESET_VALUE: Self::Ux = 0x05;
}
|
pub fn number_to_words(mut num: i32) -> String {
fn helper(num: usize) -> String {
let ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
let tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
let special = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
let tail = num % 100;
let mut s = if tail >= 20 {
if tail % 10 == 0 {
tens[tail / 10].to_string()
} else {
format!("{} {}", tens[tail / 10], ones[tail % 10])
}
} else if tail >= 10 {
special[tail - 10].to_string()
} else {
ones[tail].to_string()
};
if num >= 100 {
let hundred = num / 100;
s = if num % 100 == 0 {
format!("{} Hundred", ones[hundred])
} else {
format!("{} Hundred {}", ones[hundred], s)
};
}
s
}
if num == 0 {
"Zero".to_string()
} else {
let mut s = "".to_string();
let units = ["", "Thousand", "Million", "Billion"];
let mut counter = 0;
while num > 0 {
let mut tail = num % 1000;
if tail > 0 {
s = if counter == 0 {
helper(tail as usize)
} else {
if s.len() == 0 {
format!("{} {}", helper(tail as usize), units[counter])
} else {
format!("{} {} {}", helper(tail as usize), units[counter], s)
}
};
}
num /= 1000;
counter += 1;
}
s
}
} |
pub fn slugify(s: &String) -> String {
let filtered = s
.chars()
.filter(|c| c.is_alphanumeric() || c.is_whitespace())
.collect::<String>();
let mut slug = slug::slugify(filtered)
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '-')
.collect::<String>();
slug.truncate(50);
slug
}
pub fn escape_double_quote(s: &String) -> String {
s.replace("\"", "\\\"")
}
pub fn escape_new_line(s: &String) -> String {
s.replace("\n", "\\n")
}
pub fn escape_new_line_with_br(s: &String) -> String {
s.replace("\n", "<br>")
}
// @TODO-ZM: change this to get_searchable_words
pub fn get_words<'a>(paragraph: &'a str) -> impl Iterator<Item = &'a str> {
paragraph
.split(|c: char| !c.is_alphanumeric())
.into_iter()
.filter(|s| !s.is_empty())
}
// @TODO-ZM: filter out common words
pub fn get_searchable_words(paragraph: &String) -> Vec<String> {
paragraph
.split(|c: char| !c.is_alphanumeric())
.into_iter()
.map(|s| s.to_string())
.filter(|s| !s.is_empty())
.collect()
}
|
/*
Copyright 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------------------------------------------------------------------
*/
extern crate clap;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate log4rs;
#[macro_use]
extern crate serde_derive;
extern crate common;
extern crate serde_json;
extern crate toml;
use clap::{App, Arg};
use common::utils::read_file_as_string;
use ias_proxy_config::IasProxyConfig;
use log::LogLevelFilter;
use log4rs::{
append::{console::ConsoleAppender, file::FileAppender},
config::{Appender, Config, Root},
encode::pattern::PatternEncoder,
};
use std::process;
mod ias_proxy_config;
mod ias_proxy_server;
const DEFAULT_CONFIG_FILE: &str = "tests/packaging/ias_proxy.toml";
const LOG_FILE_PATH: &str = "/var/log/sawtooth-poet/ias-proxy.log";
/// Parse arguments and start the IAS proxy server, note that for IAS proxy to start successfully
/// config file input is must. If it's not input then a default file is read.
fn main() {
let matches = App::new("IAS Proxy Server")
.version("1.0.0")
.author("Intel Corporation")
.about("IAS proxy server")
.arg(
Arg::with_name("config")
.short("c")
.long("config")
.value_name("config")
.takes_value(true)
.help("Config file"),
)
.arg(
Arg::with_name("log-level")
.long("log-level")
.value_name("log-level")
.takes_value(true)
.help("Logging level"),
)
.arg(
Arg::with_name("log-file")
.long("log-file")
.value_name("log-file")
.takes_value(true)
.help("Log file"),
)
.arg(
Arg::with_name("verbose")
.short("v")
.long("verbose")
.value_name("verbose")
.multiple(true)
.help("Print debug information"),
)
.get_matches();
let log_level;
match matches.occurrences_of("verbose") {
0 => log_level = LogLevelFilter::Warn,
1 => log_level = LogLevelFilter::Info,
2 => log_level = LogLevelFilter::Debug,
3 | _ => log_level = LogLevelFilter::Trace,
}
let stdout = ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new(
"{d:22.22} {h({l:5.5})} | {({M}:{L}):30.30} | {m}{n}",
)))
.build();
let fileout = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new(
"{d:22.22} {h({l:5.5})} | {({M}:{L}):30.30} | {m}{n}",
)))
.build(LOG_FILE_PATH)
.expect("Could not build file appender");
let config = Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("fileout", Box::new(fileout)))
.build(
Root::builder()
.appender("stdout")
.appender("fileout")
.build(log_level),
)
.unwrap_or_else(|err| {
error!("{}", err);
process::exit(1);
});
log4rs::init_config(config).unwrap_or_else(|err| {
error!("{}", err);
process::exit(1);
});
// read configuration file, i.e. toml configuration file
let config_file = match matches.value_of("config") {
Some(config_present) => config_present,
None => {
info!("Config file is not input, using default configuration, use -h for help");
DEFAULT_CONFIG_FILE
}
};
let file_contents = read_file_as_string(config_file);
let config: IasProxyConfig = match toml::from_str(file_contents.as_str()) {
Ok(config_read) => config_read,
Err(err) => panic!("Error converting config file: {}", err),
};
// Get a proxy server instance and run it
let proxy_server = ias_proxy_server::get_proxy_server(&config);
proxy_server.run();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_deserialize_sample_file() {
let config_file = "src/tests/packaging/ias_proxy.toml";
let file_contents = read_file_as_string(config_file);
let config: IasProxyConfig = match toml::from_str(file_contents.as_str()) {
Ok(config_read) => config_read,
Err(err) => panic!("Error converting config file: {}", err),
};
assert_ne!(config.get_proxy_ip().len(), 0);
assert!(file_contents.contains(&config.get_proxy_ip()));
assert_ne!(config.get_proxy_port().len(), 0);
assert!(file_contents.contains(&config.get_proxy_port()));
assert_ne!(config.get_ias_url().len(), 0);
assert!(file_contents.contains(&config.get_ias_url()));
assert_ne!(config.get_spid_cert_file().len(), 0);
assert!(file_contents.contains(&config.get_spid_cert_file()));
}
}
|
use std::io::Write;
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn abs(number: i32) -> i32 {
if number < 0 {
return -number;
}
number
}
struct Person {
name: String,
age: u32,
}
impl Person {
fn new(name: &str, age: u32) -> Person {
Person {
name: String::from(name),
age: age,
}
}
fn say_name(&self) -> &Self {
println!("I am {}.", self.name);
self
}
fn say_age(&self) -> &Self {
println!("I am {} year(s) old.", self.age);
self
}
}
fn main() {
let p = Person::new("Taro", 20);
p.say_name().say_age();
print!("hello");
println!("hello {}", "world");
eprint!("hello {}", "error");
eprintln!("hello");
let mut w = Vec::new();
write!(&mut w, "{}", "ABC");
writeln!(&mut w, " is 123");
dbg!(w);
//panic!("it will panic");
let v = vec![1, 2, 3];
println!("defined in file: {}", file!());
println!("defined on line {}", line!());
println!("is test: {}", cfg!(unix));
println!("CARGO_HOME: {}", env!("CARGO_HOME"));
assert!(true);
assert_eq!(1, 1);
assert_ne!(1, 0);
debug_assert!(false);
debug_assert_eq!(1, 1);
debug_assert_ne!(1, 0);
} |
//! CORS support for Tsukuyomi.
#![doc(html_root_url = "https://docs.rs/tsukuyomi-cors/0.3.0-dev")]
#![deny(
missing_docs,
missing_debug_implementations,
nonstandard_style,
rust_2018_idioms,
rust_2018_compatibility,
unused
)]
#![forbid(clippy::unimplemented)]
use {
failure::Fail,
http::{
header::{
HeaderMap, //
HeaderName,
HeaderValue,
ACCESS_CONTROL_ALLOW_CREDENTIALS,
ACCESS_CONTROL_ALLOW_HEADERS,
ACCESS_CONTROL_ALLOW_METHODS,
ACCESS_CONTROL_ALLOW_ORIGIN,
ACCESS_CONTROL_MAX_AGE,
ACCESS_CONTROL_REQUEST_HEADERS,
ACCESS_CONTROL_REQUEST_METHOD,
ORIGIN,
},
HttpTryFrom, Method, Request, Response, StatusCode, Uri,
},
std::{collections::HashSet, sync::Arc, time::Duration},
tsukuyomi::{HttpError, Input},
};
/// A builder of `CORS`.
#[derive(Debug, Default)]
pub struct Builder {
origins: Option<HashSet<Uri>>,
methods: Option<HashSet<Method>>,
headers: Option<HashSet<HeaderName>>,
max_age: Option<Duration>,
allow_credentials: bool,
}
impl Builder {
/// Creates a `Builder` with the default configuration.
pub fn new() -> Self {
Self::default()
}
#[allow(missing_docs)]
pub fn allow_origin<U>(mut self, origin: U) -> http::Result<Self>
where
Uri: HttpTryFrom<U>,
{
let origin = Uri::try_from(origin).map_err(Into::into)?;
self.origins
.get_or_insert_with(Default::default)
.insert(origin);
Ok(self)
}
#[allow(missing_docs)]
pub fn allow_origins<U>(mut self, origins: impl IntoIterator<Item = U>) -> http::Result<Self>
where
Uri: HttpTryFrom<U>,
{
let origins = origins
.into_iter()
.map(Uri::try_from)
.collect::<Result<Vec<Uri>, _>>()
.map_err(Into::into)?;
self.origins
.get_or_insert_with(Default::default)
.extend(origins);
Ok(self)
}
#[allow(missing_docs)]
pub fn allow_method<M>(mut self, method: M) -> http::Result<Self>
where
Method: HttpTryFrom<M>,
{
let method = Method::try_from(method).map_err(Into::into)?;
self.methods
.get_or_insert_with(Default::default)
.insert(method);
Ok(self)
}
#[allow(missing_docs)]
pub fn allow_methods<M>(mut self, methods: impl IntoIterator<Item = M>) -> http::Result<Self>
where
Method: HttpTryFrom<M>,
{
let methods = methods
.into_iter()
.map(Method::try_from)
.collect::<Result<Vec<Method>, _>>()
.map_err(Into::into)?;
self.methods
.get_or_insert_with(Default::default)
.extend(methods);
Ok(self)
}
#[allow(missing_docs)]
pub fn allow_header<H>(mut self, header: H) -> http::Result<Self>
where
HeaderName: HttpTryFrom<H>,
{
let header = HeaderName::try_from(header).map_err(Into::into)?;
self.headers
.get_or_insert_with(Default::default)
.insert(header);
Ok(self)
}
#[allow(missing_docs)]
pub fn allow_headers<H>(mut self, headers: impl IntoIterator<Item = H>) -> http::Result<Self>
where
HeaderName: HttpTryFrom<H>,
{
let headers = headers
.into_iter()
.map(HeaderName::try_from)
.collect::<Result<Vec<HeaderName>, _>>()
.map_err(Into::into)?;
self.headers
.get_or_insert_with(Default::default)
.extend(headers);
Ok(self)
}
#[allow(missing_docs)]
pub fn allow_credentials(self, enabled: bool) -> Self {
Self {
allow_credentials: enabled,
..self
}
}
#[allow(missing_docs)]
pub fn max_age(self, max_age: Duration) -> Self {
Self {
max_age: Some(max_age),
..self
}
}
#[allow(missing_docs)]
pub fn build(self) -> CORS {
let methods = self.methods.unwrap_or_else(|| {
vec![Method::GET, Method::POST, Method::OPTIONS]
.into_iter()
.collect()
});
let methods_value = HeaderValue::from_shared(
methods
.iter()
.enumerate()
.fold(String::new(), |mut acc, (i, m)| {
if i > 0 {
acc += ",";
}
acc += m.as_str();
acc
})
.into(),
)
.expect("should be a valid header value");
let headers_value = self.headers.as_ref().map(|hdrs| {
HeaderValue::from_shared(
hdrs.iter()
.enumerate()
.fold(String::new(), |mut acc, (i, hdr)| {
if i > 0 {
acc += ",";
}
acc += hdr.as_str();
acc
})
.into(),
)
.expect("should be a valid header value")
});
CORS {
inner: Arc::new(Inner {
origins: self.origins,
methods,
methods_value,
headers: self.headers,
headers_value,
max_age: self.max_age,
allow_credentials: self.allow_credentials,
}),
}
}
}
/// The main type for providing the CORS filtering.
#[derive(Debug, Clone)]
pub struct CORS {
inner: Arc<Inner>,
}
impl Default for CORS {
fn default() -> Self {
Self::new()
}
}
impl CORS {
/// Create a new `CORS` with the default configuration.
pub fn new() -> Self {
Self::builder().build()
}
/// Create a builder of this type.
pub fn builder() -> Builder {
Builder::new()
}
}
mod impl_endpoint_for_cors {
use {
super::CORS,
http::{Response, StatusCode},
tsukuyomi::{
endpoint::Endpoint,
error::Error,
future::{Poll, TryFuture},
input::Input,
},
};
impl Endpoint<()> for CORS {
type Output = Response<()>;
type Error = Error;
type Future = CORSEndpointFuture;
fn apply(&self, _: ()) -> Self::Future {
CORSEndpointFuture { cors: self.clone() }
}
}
#[derive(Debug)]
pub struct CORSEndpointFuture {
cors: CORS,
}
impl TryFuture for CORSEndpointFuture {
type Ok = Response<()>;
type Error = Error;
fn poll_ready(&mut self, input: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> {
match self.cors.inner.validate_origin(input.request) {
Ok(Some(origin)) => self
.cors
.inner
.process_preflight_request(input.request, origin)
.map(Into::into)
.map_err(Into::into),
Ok(None) => Err(StatusCode::NOT_FOUND.into()),
Err(err) => Err(err.into()),
}
}
}
}
mod impl_modify_handler_for_cors {
use {
super::CORS,
http::Response,
tsukuyomi::{
error::Error,
future::{Async, Poll, TryFuture},
handler::{Handler, ModifyHandler},
input::Input,
util::Either,
},
};
/// The implementation of `Modifier` for processing CORS requests.
///
/// This modifier inserts the processing of CORS request for all `AsyncResult`s
/// returned from the handlers in the scope.
impl<H> ModifyHandler<H> for CORS
where
H: Handler,
H::Output: 'static,
{
type Output = Either<Response<()>, H::Output>;
type Error = Error;
type Handler = CORSHandler<H>;
fn modify(&self, handler: H) -> Self::Handler {
CORSHandler {
handler,
cors: self.clone(),
}
}
}
#[derive(Debug)]
pub struct CORSHandler<H> {
handler: H,
cors: CORS,
}
#[allow(clippy::type_complexity)]
impl<H: Handler> Handler for CORSHandler<H> {
type Output = Either<Response<()>, H::Output>;
type Error = Error;
type Handle = CORSHandle<H::Handle>;
#[inline]
fn handle(&self) -> Self::Handle {
CORSHandle {
cors: Some(self.cors.clone()),
handle: self.handler.handle(),
}
}
}
#[derive(Debug)]
pub struct CORSHandle<H: TryFuture> {
cors: Option<CORS>,
handle: H,
}
impl<H: TryFuture> TryFuture for CORSHandle<H> {
type Ok = Either<Response<()>, H::Ok>;
type Error = Error;
fn poll_ready(&mut self, input: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> {
if let Some(cors) = self.cors.take() {
if let Some(output) = cors.inner.process_request(input)? {
return Ok(Async::Ready(Either::Left(output)));
}
}
self.handle
.poll_ready(input)
.map(|x| x.map(Either::Right))
.map_err(Into::into)
}
}
}
#[derive(Debug)]
struct Inner {
origins: Option<HashSet<Uri>>,
methods: HashSet<Method>,
methods_value: HeaderValue,
headers: Option<HashSet<HeaderName>>,
headers_value: Option<HeaderValue>,
max_age: Option<Duration>,
allow_credentials: bool,
}
impl Inner {
fn validate_origin<T>(&self, request: &Request<T>) -> Result<Option<AllowedOrigin>, CORSError> {
let origin = match request.headers().get(ORIGIN) {
Some(origin) => origin,
None => return Ok(None),
};
let parsed_origin = {
let h_str = origin.to_str().map_err(|_| CORSErrorKind::InvalidOrigin)?;
let origin_uri: Uri = h_str.parse().map_err(|_| CORSErrorKind::InvalidOrigin)?;
if origin_uri.scheme_part().is_none() {
return Err(CORSErrorKind::InvalidOrigin.into());
}
if origin_uri.host().is_none() {
return Err(CORSErrorKind::InvalidOrigin.into());
}
origin_uri
};
if let Some(ref origins) = self.origins {
if !origins.contains(&parsed_origin) {
return Err(CORSErrorKind::DisallowedOrigin.into());
}
return Ok(Some(AllowedOrigin::Some(origin.clone())));
}
if self.allow_credentials {
Ok(Some(AllowedOrigin::Some(origin.clone())))
} else {
Ok(Some(AllowedOrigin::Any))
}
}
fn validate_request_method<T>(
&self,
request: &Request<T>,
) -> Result<Option<HeaderValue>, CORSError> {
match request.headers().get(ACCESS_CONTROL_REQUEST_METHOD) {
Some(h) => {
let method: Method = h
.to_str()
.map_err(|_| CORSErrorKind::InvalidRequestMethod)?
.parse()
.map_err(|_| CORSErrorKind::InvalidRequestMethod)?;
if self.methods.contains(&method) {
Ok(Some(self.methods_value.clone()))
} else {
Err(CORSErrorKind::DisallowedRequestMethod.into())
}
}
None => Ok(None),
}
}
fn validate_request_headers<T>(
&self,
request: &Request<T>,
) -> Result<Option<HeaderValue>, CORSError> {
match request.headers().get(ACCESS_CONTROL_REQUEST_HEADERS) {
Some(hdrs) => match self.headers {
Some(ref headers) => {
let mut request_headers = HashSet::new();
let hdrs_str = hdrs
.to_str()
.map_err(|_| CORSErrorKind::InvalidRequestHeaders)?;
for hdr in hdrs_str.split(',').map(|s| s.trim()) {
let hdr: HeaderName = hdr
.parse()
.map_err(|_| CORSErrorKind::InvalidRequestHeaders)?;
request_headers.insert(hdr);
}
if !headers.is_superset(&request_headers) {
return Err(CORSErrorKind::DisallowedRequestHeaders.into());
}
Ok(self.headers_value.clone())
}
None => Ok(Some(hdrs.clone())),
},
None => Ok(None),
}
}
fn process_preflight_request<T>(
&self,
request: &Request<T>,
origin: AllowedOrigin,
) -> Result<Response<()>, CORSError> {
let allow_methods = self.validate_request_method(request)?;
let allow_headers = self.validate_request_headers(request)?;
let mut response = Response::default();
*response.status_mut() = StatusCode::NO_CONTENT;
response
.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_ORIGIN, origin.into());
if let Some(allow_methods) = allow_methods {
response
.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_METHODS, allow_methods);
}
if let Some(allow_headers) = allow_headers {
response
.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_HEADERS, allow_headers);
}
if let Some(max_age) = self.max_age {
response
.headers_mut()
.insert(ACCESS_CONTROL_MAX_AGE, max_age.as_secs().into());
}
Ok(response)
}
fn process_simple_request<T>(
&self,
request: &Request<T>,
origin: AllowedOrigin,
hdrs: &mut HeaderMap,
) -> Result<(), CORSError> {
if !self.methods.contains(request.method()) {
return Err(CORSErrorKind::DisallowedRequestMethod.into());
}
hdrs.append(ACCESS_CONTROL_ALLOW_ORIGIN, origin.into());
if self.allow_credentials {
hdrs.append(
ACCESS_CONTROL_ALLOW_CREDENTIALS,
HeaderValue::from_static("true"),
);
}
Ok(())
}
fn process_request(&self, input: &mut Input<'_>) -> Result<Option<Response<()>>, CORSError> {
let origin = match self.validate_origin(input.request)? {
Some(origin) => origin,
None => return Ok(None), // do nothing
};
if input.request.method() == Method::OPTIONS {
self.process_preflight_request(input.request, origin)
.map(Some)
.map_err(Into::into)
} else {
let response_headers = input.response_headers.get_or_insert_with(Default::default);
self.process_simple_request(input.request, origin, response_headers)
.map(|_| None)
.map_err(Into::into)
}
}
}
#[derive(Debug, Clone)]
enum AllowedOrigin {
Some(HeaderValue),
Any,
}
impl Into<HeaderValue> for AllowedOrigin {
fn into(self) -> HeaderValue {
match self {
AllowedOrigin::Some(v) => v,
AllowedOrigin::Any => HeaderValue::from_static("*"),
}
}
}
#[allow(missing_docs)]
#[derive(Debug, Fail)]
#[fail(display = "Invalid CORS request: {}", kind)]
pub struct CORSError {
kind: CORSErrorKind,
}
impl CORSError {
#[allow(missing_docs)]
pub fn kind(&self) -> &CORSErrorKind {
&self.kind
}
}
impl From<CORSErrorKind> for CORSError {
fn from(kind: CORSErrorKind) -> Self {
Self { kind }
}
}
impl HttpError for CORSError {
fn status_code(&self) -> StatusCode {
StatusCode::FORBIDDEN
}
}
#[allow(missing_docs)]
#[derive(Debug, Fail)]
pub enum CORSErrorKind {
#[fail(display = "the provided Origin is not a valid value.")]
InvalidOrigin,
#[fail(display = "the provided Origin is not allowed.")]
DisallowedOrigin,
#[fail(display = "the provided Access-Control-Request-Method is not a valid value.")]
InvalidRequestMethod,
#[fail(display = "the provided Access-Control-Request-Method is not allowed.")]
DisallowedRequestMethod,
#[fail(display = "the provided Access-Control-Request-Headers is not a valid value.")]
InvalidRequestHeaders,
#[fail(display = "the provided Access-Control-Request-Headers is not allowed.")]
DisallowedRequestHeaders,
}
|
use simple_db::blockid::BlockId;
#[test]
fn test_display() {
let filename = String::from("test");
let blknum = 10;
let bi = BlockId::new(&filename, blknum);
assert_eq!(filename, bi.filename());
assert_eq!(blknum, bi.number());
assert_eq!(
format!("[file {}, block {}]", filename, blknum),
format!("{}", bi)
)
}
|
use super::{Pages, Pagination};
use crate::{custom_client::OsekaiRarityEntry, embeds::MedalRarityEmbed, BotResult};
use twilight_model::channel::Message;
pub struct MedalRarityPagination {
msg: Message,
pages: Pages,
ranking: Vec<OsekaiRarityEntry>,
}
impl MedalRarityPagination {
pub fn new(msg: Message, ranking: Vec<OsekaiRarityEntry>) -> Self {
Self {
msg,
pages: Pages::new(10, ranking.len()),
ranking,
}
}
}
#[async_trait]
impl Pagination for MedalRarityPagination {
type PageData = MedalRarityEmbed;
fn msg(&self) -> &Message {
&self.msg
}
fn pages(&self) -> Pages {
self.pages
}
fn pages_mut(&mut self) -> &mut Pages {
&mut self.pages
}
fn single_step(&self) -> usize {
self.pages.per_page
}
async fn build_page(&mut self) -> BotResult<Self::PageData> {
let page = self.page();
let idx = (page - 1) * self.pages.per_page;
let limit = self.ranking.len().min(idx + self.pages.per_page);
Ok(MedalRarityEmbed::new(
&self.ranking[idx..limit],
self.pages.index,
(page, self.pages.total_pages),
))
}
}
|
use inflector::cases::camelcase::is_camel_case;
pub fn abbreviate(phrase: &str) -> String {
// Filter out any special character requirements like - to be treated as space to consider abbrevation.
let phrase_filtered = phrase.replace("-", " ");
// Split word by space.
let word_iter = phrase_filtered.split_whitespace();
let mut chars = Vec::new();
for item in word_iter {
// Filter out non-alphabetic chars like - or any other special characters
let mut char_iter = item.chars().filter(|x| x.is_alphabetic());
let char = match char_iter.next() {
Some(x) => x,
None => ' '
};
// Error corner case when the word only contains special characters. If we need to check the length of iter, we need collect() above.
if char == ' ' {
continue;
}
// Push the first letter that is an alphabet in the word.
chars.push(char);
// Combine the string back again from iterator to check if the rest of the string is camelcase - special treatment for HyperText usecase.
let residue_chars_vec = char_iter.collect::<Vec<_>>();
let residue_string: String = residue_chars_vec.into_iter().collect();
// Check for camecase an dif if camelcase, filterout the rest of the uppercase leters to form a string.
if is_camel_case(&residue_string) {
let residue_string_camecase_chars: String = residue_string.chars().filter(|ch| ch.is_uppercase()).collect();
if residue_string_camecase_chars.len() > 0 {
chars.extend(residue_string_camecase_chars.chars());
}
}
}
// collect all the characters we have been accumlating, convert to string and to upper case.
let result = chars.into_iter().collect::<Vec<char>>();
let result_string: String = result.into_iter().collect();
result_string.to_uppercase()
}
|
use std::collections::BTreeMap;
pub fn transform(h: &BTreeMap<i32, Vec<char>>) -> BTreeMap<char, i32> {
h.iter().fold(BTreeMap::new(), |mut acc, (score, letters)| {
for c in letters {
acc.insert(c.to_lowercase().collect::<Vec<_>>()[0], *score);
}
acc
})
}
|
use anyhow::Result;
use itertools::Itertools;
use nom::{
branch::alt,
bytes::complete::tag,
combinator::{iterator, value},
IResult,
};
use std::{
collections::{HashMap, HashSet},
fs,
};
fn parse_direction(input: &str) -> IResult<&str, (isize, isize)> {
alt((
value((2, 0), tag("e")),
value((1, -1), tag("ne")),
value((1, 1), tag("se")),
value((-2, 0), tag("w")),
value((-1, -1), tag("nw")),
value((-1, 1), tag("sw")),
))(input)
}
fn walk(input: &str) -> (isize, isize) {
iterator(input, parse_direction).fold((0, 0), |(x, y), (x_offset, y_offset)| {
(x + x_offset, y + y_offset)
})
}
fn do_the_thing(input: &str, days: usize) -> usize {
let mut black_tiles =
input
.lines()
.map(|line| walk(line))
.fold(HashSet::new(), |mut acc, tile| {
if !acc.insert(tile) {
acc.remove(&tile);
}
acc
});
let neighbor_offsets = vec![(2, 0), (1, -1), (1, 1), (-2, 0), (-1, -1), (-1, 1)];
for _ in 0..days {
let new_black_tiles = black_tiles
.iter()
.cartesian_product(neighbor_offsets.iter())
.filter_map(|((x, y), (x_offset, y_offset))| {
let possible_white_tile = (x + x_offset, y + y_offset);
if black_tiles.contains(&possible_white_tile) {
None
} else {
Some(possible_white_tile)
}
})
.fold(HashMap::new(), |mut acc, tile| {
acc.entry(tile).and_modify(|count| *count += 1).or_insert(1);
acc
})
.into_iter()
.filter_map(|(tile, count)| if count == 2 { Some(tile) } else { None });
let stay_black_tiles = black_tiles
.iter()
.filter(|(x, y)| {
let count = neighbor_offsets
.iter()
.filter(|(x_offset, y_offset)| {
black_tiles.contains(&(x + x_offset, y + y_offset))
})
.count();
count == 1 || count == 2
})
.copied();
black_tiles = new_black_tiles.chain(stay_black_tiles).collect();
}
black_tiles.len()
}
fn main() -> Result<()> {
let input = fs::read_to_string("input.txt")?;
println!("{:?}", do_the_thing(&input, 100));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use test_case::test_case;
#[test_case(0 => 10)]
#[test_case(1 => 15)]
#[test_case(2 => 12)]
#[test_case(3 => 25)]
#[test_case(4 => 14)]
#[test_case(5 => 23)]
#[test_case(100 => 2208)]
fn first(days: usize) -> usize {
let input = "sesenwnenenewseeswwswswwnenewsewsw
neeenesenwnwwswnenewnwwsewnenwseswesw
seswneswswsenwwnwse
nwnwneseeswswnenewneswwnewseswneseene
swweswneswnenwsewnwneneseenw
eesenwseswswnenwswnwnwsewwnwsene
sewnenenenesenwsewnenwwwse
wenwwweseeeweswwwnwwe
wsweesenenewnwwnwsenewsenwwsesesenwne
neeswseenwwswnwswswnw
nenwswwsewswnenenewsenwsenwnesesenew
enewnwewneswsewnwswenweswnenwsenwsw
sweneswneswneneenwnewenewwneswswnese
swwesenesewenwneswnwwneseswwne
enesenwswwswneneswsenwnewswseenwsese
wnwnesenesenenwwnenwsewesewsesesew
nenewswnwewswnenesenwnesewesw
eneswnwswnwsenenwnwnwwseeswneewsenese
neswnwewnwnwseenwseesewsenwsweewe
wseweeenwnesenwwwswnew";
do_the_thing(&input, days)
}
#[test]
fn walker() {
assert_eq!(walk("esew"), (1, 1));
assert_eq!(walk("nwwswee"), (0, 0));
}
}
|
#[cfg(all(test, feature = "secp256k1"))]
mod test {
use cryptographer::rand::Rand;
use cryptographer::{x::secp256k1, Signer};
#[test]
fn sign_verify() {
let mut reader = Rand::new();
let priv_key = secp256k1::generate_key(&mut reader).unwrap();
let msg = [123u8; 32];
let sig = secp256k1::sign(&priv_key, &msg[..]).unwrap();
let pub_key = priv_key.public();
secp256k1::verify(&pub_key, &msg[..], &sig).unwrap();
}
}
|
// Crates
extern crate indicatif;
// Use
use indicatif::ProgressBar;
use std::env;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::process;
// Main
fn main() {
// Collect args
let args: Vec<String> = env::args().collect();
// Check index
if args.len() > 1 {
let path_arg = args[1].clone();
// Forms a path from a string
let path = Path::new(&path_arg);
let all_dir_paths = dir_list(&path).expect("Could not list directory!");
talk_a_walk(&path, &all_dir_paths).expect("Could not copy files!");
} else {
// Exit if no args
println!("Where the the path, human?");
process::exit(1);
}
}
// List all folders in a directory
fn dir_list(dir: &Path) -> Result<Vec<PathBuf>, io::Error> {
let mut all_dir_names = vec![];
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
all_dir_names.push(path);
}
}
}
Ok(all_dir_names)
}
// Go into each folder and move the files
fn talk_a_walk(copy_to_path: &Path, all_dir_paths: &Vec<PathBuf>) -> Result<(), io::Error> {
if all_dir_paths.len() > 0 {
// Create a progress bar
let pbar_total = all_dir_paths.len() as u64;
let pbar = ProgressBar::new(pbar_total);
// Walk the directories and copy files
for dir in all_dir_paths {
// Increment for each folder
pbar.inc(1);
// Entry is a file in dir
for entry in fs::read_dir(dir)? {
let entry = entry?.path();
let name = entry.file_name().unwrap();
let formatted_path = PathBuf::from(copy_to_path.join(name));
let new_path = Path::new(&formatted_path);
// Check if the file is not already there
if new_path.is_file() == false {
// Copy every old path to its new path in main directory
match fs::copy(&entry, &new_path) {
Ok(_) => {}
Err(_) => {
continue;
}
}
} else {
pbar.println(format!("File already there!: {:?}", name));
}
}
}
pbar.finish_with_message("Done!");
} else {
println!("No directories!");
}
Ok(())
}
|
use serde::Deserialize;
use serde::Serialize;
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Album {
pub catalog: String,
pub category: String,
pub link: String,
#[serde(rename = "media_format")]
pub media_format: String,
#[serde(rename = "release_date")]
pub release_date: String,
pub titles: Titles,
}
impl Album {
/// Id of the album that can be given to `get_album`.
pub fn album_id(&self) -> Option<u32> {
match self.link.split('/').last().map(|x| x.parse::<u32>()) {
Some(Ok(n)) => Some(n),
_ => None,
}
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Titles {
#[serde(rename = "en")]
pub english: String,
#[serde(rename = "jp")]
pub japenese: Option<String>,
#[serde(rename = "ja-latn")]
pub japenese_latin: String,
}
|
use kagura::prelude::*;
use std::{cell::RefCell, rc::Rc};
pub fn div<Msg: 'static>(
z_index: u64,
on_close: impl FnMut() -> Msg + 'static,
position: &[f64; 2],
attributes: Attributes,
events: Events,
children: Vec<Html>,
) -> Html {
let on_close = Rc::new(RefCell::new(Box::new(on_close)));
Html::div(
Attributes::new()
.class("fullscreen")
.style("z-index", z_index.to_string()),
Events::new()
.on_click({
let on_close = Rc::clone(&on_close);
move |e| {
e.stop_propagation();
(&mut *on_close.borrow_mut())()
}
})
.on_contextmenu({
let on_close = Rc::clone(&on_close);
move |e| {
e.prevent_default();
(&mut *on_close.borrow_mut())()
}
}),
vec![Html::div(
attributes
.class("pure-menu")
.style("position", "absolute")
.style("left", (position[0] - 5.0).to_string() + "px")
.style("top", (position[1] - 2.5).to_string() + "px"),
events,
children,
)],
)
}
|
use super::{common_home_args, parse_common_home_args};
use clap::{App, Arg, ArgMatches, SubCommand};
use comparators;
pub const SUB_HOME_COMPARE_AT: &str = "compare-at";
const ARG_PERIOD: &str = "n-periods";
/// Returns the home compare-at sub command
pub fn home_compare_at_subcommand<'a, 'b>() -> App<'a, 'b> {
SubCommand::with_name(SUB_HOME_COMPARE_AT)
.about("compute investement info for a point in time")
.arg(
Arg::with_name(ARG_PERIOD)
.takes_value(true)
.required(true)
.index(1),
).args(common_home_args().as_slice())
}
/// Execute the work and print results for the compare-at sub command
///
/// # Arguments
/// * `matches` - The command matches to retrieve the parameters
pub fn execute_home_compare_at<'a>(matches: &ArgMatches<'a>) {
let home_invest = parse_common_home_args(matches);
let at = matches
.value_of(ARG_PERIOD)
.unwrap()
.parse::<u32>()
.unwrap();
let (purchase, invest) = home_invest.capital_at(at);
println!(
"*** For a supply of {}, a loan of {} on {} years with a rate of {}%, \
purchase charges of {}%, annual charges of {}% and an home appreciation of {}% by year",
home_invest.supply,
home_invest.loan,
home_invest.years,
home_invest.loan_rate * 100_f32,
home_invest.purchase_charges * 100_f32,
home_invest.annual_charges * 100_f32,
home_invest.annual_appreciation_rate * 100_f32
);
println!(
"*** Compared to a rent of {}, an investement interest rate at {}%",
home_invest.rent,
home_invest.invest_rate * 100_f32
);
let years_round = format!("{}", at / comparators::PERIODICITY as u32);
let mut table = table!(["title", "at (periods)", "at (~years)", "value"]);
table.add_row(row![
"term price for home purchase",
"NONE",
"NONE",
format!("{:.02}", home_invest.loan_term_price())
]);
table.add_row(row![
"capital for home purchase",
at,
years_round,
format!("{:.02}", purchase)
]);
table.add_row(row![
"capital for renting",
at,
years_round,
format!("{:.02}", invest)
]);
table.add_row(row![
"Difference for home purchase",
at,
years_round,
format!("{:.02}", purchase - invest)
]);
table.printstd();
}
|
use std::process::Command;
use crate::{
revision_shortcut::RevisionShortcut,
select::{Entry, State},
version_control_actions::{handle_command, VersionControlActions},
};
fn str_to_state(s: &str) -> State {
match s {
"?" => State::Untracked,
"M" => State::Modified,
"A" => State::Added,
"R" => State::Deleted,
"!" => State::Missing,
"I" => State::Ignored,
"C" => State::Clean,
_ => State::Copied,
}
}
pub struct HgActions {
pub current_dir: String,
pub revision_shortcut: RevisionShortcut,
}
impl HgActions {
fn command(&self) -> Command {
let mut command = Command::new("hg");
command.current_dir(&self.current_dir[..]);
command
}
/// Disables user customizations for internal invocations
fn plain_command(&self) -> Command {
let mut command = self.command();
command.env("HGPLAIN", "");
command
}
}
impl<'a> VersionControlActions for HgActions {
fn set_root(&mut self) -> Result<(), String> {
let mut command = self.command();
let dir = handle_command(command.arg("root"))?;
let dir = dir
.lines()
.next()
.expect("Root directory is an empty string");
self.current_dir = dir.to_owned();
Ok(())
}
fn get_root(&self) -> &str {
&self.current_dir[..]
}
fn get_current_changed_files(&mut self) -> Result<Vec<Entry>, String> {
let output = handle_command(self.command().arg("status"))?;
let files = output
.trim()
.split('\n')
.map(|e| e.trim())
.filter(|e| e.len() > 1)
.map(|e| {
let (state, filename) = e.split_at(1);
Entry {
filename: String::from(filename.trim()),
selected: false,
state: str_to_state(state),
}
})
.collect();
Ok(files)
}
fn get_revision_changed_files(
&mut self,
target: &str,
) -> Result<Vec<Entry>, String> {
let target = self.revision_shortcut.get_hash(target).unwrap_or(target);
let output = handle_command(
self.command().arg("status").arg("--change").arg(target),
)?;
let files = output
.trim()
.split('\n')
.map(|e| e.trim())
.filter(|e| e.len() > 1)
.map(|e| {
let (state, filename) = e.split_at(1);
Entry {
filename: String::from(filename.trim()),
selected: false,
state: str_to_state(state),
}
})
.collect();
Ok(files)
}
fn version(&mut self) -> Result<String, String> {
handle_command(self.command().arg("--version"))
}
fn status(&mut self) -> Result<String, String> {
let mut output = String::new();
output.push_str(
&handle_command(
self.command().args(&["summary", "--color", "always"]),
)?[..],
);
output.push_str("\n");
output.push_str(
&handle_command(
self.command().args(&["status", "--color", "always"]),
)?[..],
);
Ok(output)
}
fn current_export(&mut self) -> Result<String, String> {
handle_command(self.command().args(&["export", "--color", "always"]))
}
fn log(&mut self, count: u32) -> Result<String, String> {
let count_str = format!("{}", count);
let hashes_output = handle_command(
self.plain_command()
.arg("log")
.arg("--template")
.arg("{node|short} ")
.arg("-l")
.arg(&count_str),
)?;
let hashes: Vec<_> = hashes_output
.split_whitespace()
.take(RevisionShortcut::max())
.map(String::from)
.collect();
self.revision_shortcut.update_hashes(hashes);
let template = "{label('green', if(topics, '[{topics}]'))} {label(ifeq(phase, 'secret', 'yellow', ifeq(phase, 'draft', 'yellow', 'red')), node|short)}{ifeq(branch, 'default', '', label('green', ' ({branch})'))}{bookmarks % ' {bookmark}{ifeq(bookmark, active, '*')}{bookmark}'}{label('yellow', tags % ' {tag}')} {label('magenta', author|person)} {desc|firstline|strip}";
let mut output = handle_command(
self.command()
.arg("log")
.arg("--graph")
.arg("--template")
.arg(template)
.arg("-l")
.arg(&count_str)
.arg("--color")
.arg("always"),
)?;
self.revision_shortcut.replace_occurrences(&mut output);
Ok(output)
}
fn current_diff_all(&mut self) -> Result<String, String> {
handle_command(self.command().arg("diff").arg("--color").arg("always"))
}
fn current_diff_selected(
&mut self,
entries: &Vec<Entry>,
) -> Result<String, String> {
let mut command = self.command();
command.arg("diff").arg("--color").arg("always").arg("--");
for e in entries.iter() {
if e.selected {
command.arg(&e.filename);
}
}
handle_command(&mut command)
}
fn revision_changes(&mut self, target: &str) -> Result<String, String> {
let target = self.revision_shortcut.get_hash(target).unwrap_or(target);
handle_command(
self.command()
.arg("status")
.arg("--change")
.arg(target)
.arg("--color")
.arg("always"),
)
}
fn revision_diff_all(&mut self, target: &str) -> Result<String, String> {
let target = self.revision_shortcut.get_hash(target).unwrap_or(target);
handle_command(
self.command()
.arg("diff")
.arg("--change")
.arg(target)
.arg("--color")
.arg("always"),
)
}
fn revision_diff_selected(
&mut self,
target: &str,
entries: &Vec<Entry>,
) -> Result<String, String> {
let target = self.revision_shortcut.get_hash(target).unwrap_or(target);
let mut command = self.command();
command
.arg("diff")
.arg("--change")
.arg(target)
.arg("--color")
.arg("always")
.arg("--");
for e in entries.iter() {
if e.selected {
command.arg(&e.filename);
}
}
handle_command(&mut command)
}
fn commit_all(&mut self, message: &str) -> Result<String, String> {
handle_command(
self.command()
.arg("commit")
.arg("--addremove")
.arg("-m")
.arg(message)
.arg("--color")
.arg("always"),
)
}
fn commit_selected(
&mut self,
message: &str,
entries: &Vec<Entry>,
) -> Result<String, String> {
let mut cmd = self.command();
cmd.arg("commit");
for e in entries.iter() {
if e.selected {
match e.state {
State::Missing | State::Deleted => {
handle_command(
self.command().arg("remove").arg(&e.filename),
)?;
}
State::Untracked => {
handle_command(
self.command().arg("add").arg(&e.filename),
)?;
}
_ => (),
}
cmd.arg(&e.filename);
}
}
handle_command(cmd.arg("-m").arg(message).arg("--color").arg("always"))
}
fn revert_all(&mut self) -> Result<String, String> {
let mut output = String::new();
output.push_str(&handle_command(self.command().args(&["revert", "-C", "--all"]))?[..]);
output.push_str("\n");
output.push_str(&handle_command(self.command().args(&["purge"]))?[..]);
Ok(output)
}
fn revert_selected(
&mut self,
entries: &Vec<Entry>,
) -> Result<String, String> {
let mut output = String::new();
let mut cmd = self.command();
cmd.arg("revert").arg("-C").arg("--color").arg("always");
let mut has_revert_file = false;
for e in entries.iter() {
if !e.selected {
continue;
}
match e.state {
State::Untracked => {
output.push_str(
&handle_command(
self.command().arg("purge").arg(&e.filename),
)?[..],
);
}
_ => {
has_revert_file = true;
cmd.arg(&e.filename);
}
}
}
if has_revert_file {
output.push_str(&handle_command(&mut cmd)?[..]);
}
Ok(output)
}
fn update(&mut self, target: &str) -> Result<String, String> {
let target = self.revision_shortcut.get_hash(target).unwrap_or(target);
handle_command(self.command().arg("update").arg(target))
}
fn merge(&mut self, target: &str) -> Result<String, String> {
let target = self.revision_shortcut.get_hash(target).unwrap_or(target);
handle_command(self.command().arg("merge").arg(target))
}
fn conflicts(&mut self) -> Result<String, String> {
handle_command(
self.command().args(&["resolve", "-l", "--color", "always"]),
)
}
fn take_other(&mut self) -> Result<String, String> {
handle_command(self.command().args(&[
"resolve",
"-a",
"-t",
"internal:other",
]))
}
fn take_local(&mut self) -> Result<String, String> {
handle_command(self.command().args(&[
"resolve",
"-a",
"-t",
"internal:local",
]))
}
fn fetch(&mut self) -> Result<String, String> {
self.pull()
}
fn pull(&mut self) -> Result<String, String> {
handle_command(self.command().arg("pull"))
}
fn push(&mut self) -> Result<String, String> {
handle_command(self.command().args(&["push", "--new-branch"]))
}
fn create_tag(&mut self, name: &str) -> Result<String, String> {
handle_command(self.command().arg("tag").arg(name).arg("-f"))
}
fn list_branches(&mut self) -> Result<String, String> {
handle_command(self.command().args(&["branches", "--color", "always"]))
}
fn create_branch(&mut self, name: &str) -> Result<String, String> {
handle_command(self.command().arg("branch").arg(name))
}
fn close_branch(&mut self, name: &str) -> Result<String, String> {
let changeset =
handle_command(self.command().args(&["identify", "--num"]))?;
self.update(name)?;
let mut output = String::new();
output.push_str(
&handle_command(self.command().args(&[
"commit",
"-m",
"\"close branch\"",
"--close-branch",
]))?[..],
);
output.push_str("\n");
output.push_str(&self.update(changeset.trim())?[..]);
Ok(output)
}
}
|
extern crate geom;
use geom::*;
#[test]
fn rect_split_row_mut() {
let mut r = Rect::new(0, 0, 10, 10);
let s = r.split_row_mut(5);
assert_eq!(r.top(), 0);
assert_eq!(r.left(), 0);
assert_eq!(r.bottom(), 4);
assert_eq!(r.right(), 9);
assert_eq!(s.top(), 5);
assert_eq!(s.left(), 0);
assert_eq!(s.bottom(), 9);
assert_eq!(s.right(), 9);
}
#[test]
fn rect_split_column_mut() {
let mut r = Rect::new(0, 0, 10, 10);
let s = r.split_column_mut(5);
assert_eq!(r.top(), 0);
assert_eq!(r.left(), 0);
assert_eq!(r.bottom(), 9);
assert_eq!(r.right(), 4);
assert_eq!(s.top(), 0);
assert_eq!(s.left(), 5);
assert_eq!(s.bottom(), 9);
assert_eq!(s.right(), 9);
}
#[test]
fn rect_from_points() {
let r = Point::default().rect(Point::new(4, 9));
let s = Rect::from_points(Point::default(), Point::new(4, 9));
assert_eq!(r, s);
assert_eq!(r.top(), 0);
assert_eq!(r.left(), 0);
assert_eq!(r.bottom(), 9);
assert_eq!(r.right(), 4);
}
#[test]
fn rect_from_new() {
let r = Rect::new(0, 0, 10, 5);
assert_eq!(r.top(), 0);
assert_eq!(r.left(), 0);
assert_eq!(r.bottom(), 4);
assert_eq!(r.right(), 9);
}
#[test]
fn rect_iter() {
let mut r = Rect::new(0, 0, 10, 15).iter();
assert_eq!(r.nth(0), Some(Point::new(0, 0))); // [0]
assert_eq!(r.nth(8), Some(Point::new(9, 0))); // [9]
assert_eq!(r.nth(0), Some(Point::new(0, 1))); // [10]
assert_eq!(r.last(), Some(Point::new(9, 14)));
}
#[test]
fn rect_iter_reverse() {
let mut r = Rect::new(0, 0, 10, 15).iter().rev();
assert_eq!(r.next(), Some(Point::new(9, 14))); // [149]
assert_eq!(r.nth(138), Some(Point::new(0, 1))); // [10]
assert_eq!(r.next(), Some(Point::new(9, 0))); // [9]
assert_eq!(r.last(), Some(Point::new(0, 0))); // [0]
}
#[test]
fn rect_iter_size_hint() {
assert_eq!(Rect::new(0, 0, 10, 15).iter().size_hint(), (150, Some(150)));
assert_eq!(Rect::new(0, 0, 1, 1).iter().size_hint(), (1, Some(1)));
let mut r = Rect::new(5000, -299, 10, 10).iter();
assert_eq!(r.size_hint(), (100, Some(100)));
r.nth(73);
assert_eq!(r.size_hint(), (26, Some(26)));
}
#[test]
fn rect_contains() {
let r = Rect::new(2, 3, 10, 15);
assert!(r.contains(Point::new(2, 3)));
assert!(r.contains(Point::new(5, 5)));
assert!(r.contains(Point::new(11, 17)));
assert_eq!(r.contains(Point::new(0, 0)), false);
assert_eq!(r.contains(Point::new(5, 0)), false);
assert_eq!(r.contains(Point::new(12, 17)), false);
}
#[test]
fn rect_rows() {
let r = Rect::new(4, 2, 12, 14);
for row in r.rows() {
for point in row {
assert!(r.contains(point), "{:?} not in Rect {:?}", point, r);
}
}
}
#[test]
fn rect_columns() {
let r = Rect::new(4, 2, 12, 14);
for row in r.columns() {
for point in row {
assert!(r.contains(point), "{:?} not in Rect {:?}", point, r);
}
}
}
#[test]
fn point_operators() {
let a = Point::new(3, 6);
let b = Point::new(7, 4);
assert_eq!(a - a, Point::default());
assert_eq!(a + b, Point::new(10, 10));
assert_eq!(a - b, Point::new(-4, 2));
assert_eq!(a + 7, Point::new(10, 13));
assert_eq!(a - 3, Point::new(0, 3));
let f_a = Point::new(4.14, 4.50);
let f_b = Point::new(1.42, 0.11);
assert_eq!(f_a - f_a, Point::default());
assert_eq!(f_a + f_b, Point::new(5.56, 4.61));
assert_eq!(f_a + 1.0, Point::new(5.14, 5.50));
assert!(f_a - 1.0 != Point::new(3.14, 3.51));
}
|
use crate::io::load_input;
use std::collections::HashSet;
pub fn day1_1() {
let input = load_input("day1");
let mut sum = 0;
for line in input {
let n: i32 = line.parse().unwrap();
sum += n;
}
info!("Result of day1_1: {}", sum);
}
pub fn day1_2() {
let input = load_input("day1");
let mut sum = 0;
let mut reached_sums = HashSet::new();
reached_sums.insert(sum);
for line in input.iter().cycle() {
let n: i32 = line.parse().unwrap();
sum += n;
if reached_sums.contains(&sum) {
break;
} else {
reached_sums.insert(sum);
}
}
info!("Result of day1_2: {}", sum);
} |
/// PBKDF2 implementation from *ring*
pub use self::ring_pbkdf2::Pbkdf2;
mod ring_pbkdf2 {
use primitives::{Primitive, PrimitiveImpl};
use sod::Sod;
use ring::pbkdf2;
use serde_mcf::Hashes;
use std::fmt;
use std::num::NonZeroU32;
/// Struct holding `PBKDF2` parameters.
///
/// This implementation is backed by `ring`.
pub struct Pbkdf2 {
iterations: NonZeroU32,
algorithm: &'static pbkdf2::Algorithm,
}
impl Pbkdf2 {
/// Create a new PBKDF2 instance using defaults.
pub fn default() -> Primitive {
Primitive(Sod::Static(&DEFAULT))
}
/// Create a new PBKDF2 instance.
#[allow(clippy::new_ret_no_self)]
pub fn new(iterations: u32, algorithm: &'static pbkdf2::Algorithm) -> Primitive {
Self::new_impl(iterations, algorithm).into()
}
fn new_impl(iterations: u32, algorithm: &'static pbkdf2::Algorithm) -> Self {
Self {
iterations: NonZeroU32::new(iterations).expect("iterations must be greater than 0"),
algorithm,
}
}
}
static DEFAULT: Pbkdf2 = Pbkdf2 {
iterations: unsafe { NonZeroU32::new_unchecked(10_000) },
algorithm: &pbkdf2::PBKDF2_HMAC_SHA256,
};
impl ::primitives::PrimitiveImpl for Pbkdf2 {
/// Compute the scrypt hash
fn compute<'a>(&'a self, password: &[u8], salt: &[u8]) -> Vec<u8> {
let mut hash = vec![0_u8; 32];
pbkdf2::derive(*self.algorithm, self.iterations, salt, password, &mut hash);
hash
}
/// Convert parameters into a vector of (key, value) tuples
/// for serializing.
fn params_as_vec(&self) -> Vec<(&'static str, String)> {
vec![("n", self.iterations.to_string())]
}
fn hash_id(&self) -> Hashes {
match self.algorithm {
a if a == &pbkdf2::PBKDF2_HMAC_SHA1 => Hashes::Pbkdf2Sha1,
a if a == &pbkdf2::PBKDF2_HMAC_SHA256 => Hashes::Pbkdf2Sha256,
a if a == &pbkdf2::PBKDF2_HMAC_SHA512 => Hashes::Pbkdf2Sha512,
_ => panic!("unexpected digest algorithm"),
}
}
}
impl fmt::Debug for Pbkdf2 {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{:?}, iterations: {}", self.hash_id(), self.iterations)
}
}
}
#[cfg(test)]
mod test {
use hashing::*;
use ring::pbkdf2;
use serde_mcf;
#[test]
fn sanity_check() {
let password = "hunter2";
let params = super::Pbkdf2::default();
println!("{:?}", params);
let salt = ::get_salt();
let hash = params.compute(password.as_bytes(), &salt);
let hash2 = params.compute(password.as_bytes(), &salt);
assert_eq!(hash, hash2);
let out = Output {
alg: Algorithm::Single(params),
salt,
hash,
};
println!("{:?}", serde_mcf::to_string(&out).unwrap());
}
macro_rules! primitive_round_trip {
($prim:expr) => {
let hash = serde_mcf::to_string(&$prim.hash(&"hunter2")).unwrap();
let _output: Output = serde_mcf::from_str(&hash).unwrap();
};
}
#[test]
fn pbkdf2_params() {
let params = Algorithm::Single(super::Pbkdf2::new(1_000, &pbkdf2::PBKDF2_HMAC_SHA1));
primitive_round_trip!(params);
let params = Algorithm::Single(super::Pbkdf2::new(1_000, &pbkdf2::PBKDF2_HMAC_SHA256));
primitive_round_trip!(params);
let params = Algorithm::Single(super::Pbkdf2::new(1_000, &pbkdf2::PBKDF2_HMAC_SHA512));
primitive_round_trip!(params);
}
}
#[cfg(feature = "bench")]
mod ring_bench {
#[allow(unused_imports)]
use super::*;
benches!(Pbkdf2);
}
|
use std::{
cmp::Ordering,
collections::{HashMap, HashSet},
fs::File,
path::PathBuf,
};
use assembly_fdb::{
common::Latin1Str,
mem::{Database, Row, RowHeaderIter, Table, Tables},
};
use color_eyre::eyre::{eyre, WrapErr};
use mapr::Mmap;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Options {
/// Path to the CDClient
file: PathBuf,
}
fn get_table<'a>(tables: Tables<'a>, name: &str) -> color_eyre::Result<Table<'a>> {
let table = tables
.by_name(name)
.ok_or_else(|| eyre!("Missing table '{}'", name))??;
Ok(table)
}
fn get_column_index(table: Table<'_>, name: &str) -> color_eyre::Result<usize> {
let index = table
.column_iter()
.position(|col| col.name() == name)
.ok_or_else(|| eyre!("Missing columns '{}'.'{}'", table.name(), name))?;
Ok(index)
}
fn match_action_key(key: &str) -> bool {
matches!(
key,
"action"
| "behavior 1"
| "behavior 2"
| "miss action"
| "blocked action"
| "on_fail_blocked"
| "action_false"
| "action_true"
| "start_action"
| "behavior 3"
| "bahavior 2"
| "behavior 4"
| "on_success"
| "behavior 5"
| "chain_action"
| "behavior 0"
| "behavior 6"
| "behavior 7"
| "behavior 8"
| "on_fail_armor"
| "behavior"
| "break_action"
| "double_jump_action"
| "ground_action"
| "jump_action"
| "hit_action"
| "hit_action_enemy"
| "timeout_action"
| "air_action"
| "falling_action"
| "jetpack_action"
| "spawn_fail_action"
| "action_failed"
| "action_consumed"
| "blocked_action"
| "on_fail_immune"
| "moving_action"
| "behavior 10"
| "behavior 9"
)
}
struct BehaviorParameter<'a> {
inner: Row<'a>,
}
impl<'a> BehaviorParameter<'a> {
fn parameter_id(&self) -> &'a Latin1Str {
self.inner
.field_at(1) // bp_col_parameter_id
.unwrap()
.into_opt_text()
.unwrap()
}
fn int_value(&self) -> i32 {
self.inner
.field_at(2) // bp_col_value
.unwrap()
.into_opt_float()
.unwrap() as i32
}
}
struct RowFinder<'a> {
inner: RowHeaderIter<'a>,
behavior_id: i32,
}
impl<'a> RowFinder<'a> {
fn new(behavior_parameter: Table<'a>, behavior_id: i32) -> Self {
let bp_bucket_index = behavior_id as usize % behavior_parameter.bucket_count();
let bp_bucket = behavior_parameter.bucket_at(bp_bucket_index).unwrap();
Self {
inner: bp_bucket.row_iter(),
behavior_id,
}
}
}
impl<'a> Iterator for RowFinder<'a> {
type Item = BehaviorParameter<'a>;
fn next(&mut self) -> Option<Self::Item> {
for row in &mut self.inner {
let behavior_id = row
.field_at(0) // bp_col_behavior_id
.unwrap()
.into_opt_integer()
.unwrap();
if behavior_id == self.behavior_id {
return Some(BehaviorParameter { inner: row });
}
}
None
}
}
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let opts = Options::from_args();
// Load the database file
let file = File::open(&opts.file)
.wrap_err_with(|| format!("Failed to open input file '{}'", opts.file.display()))?;
let mmap = unsafe { Mmap::map(&file)? };
let buffer: &[u8] = &mmap;
// Start using the database
let db = Database::new(buffer);
// Find table
let tables = db.tables()?;
let skill_behavior = get_table(tables, "SkillBehavior")?;
//let sb_col_skill_id = get_column_index(skill_behavior, "skillID")?;
let sb_col_behavior_id = get_column_index(skill_behavior, "behaviorID")?;
let behavior_parameter = get_table(tables, "BehaviorParameter")?;
let bp_col_behavior_id = get_column_index(behavior_parameter, "behaviorID")?;
assert_eq!(bp_col_behavior_id, 0);
let bp_col_parameter_id = get_column_index(behavior_parameter, "parameterID")?;
assert_eq!(bp_col_parameter_id, 1);
let bp_col_value = get_column_index(behavior_parameter, "value")?;
assert_eq!(bp_col_value, 2);
//let behavior_template = get_table(tables, "BehaviorTemplate")?;
//let bt_col_behavior_id = get_column_index(behavior_template, "behaviorID")?;
//let bt_col_template_id = get_column_index(behavior_template, "templateID")?;
let mut root_behaviors = HashSet::new();
for row in skill_behavior.row_iter() {
let behavior_id = row
.field_at(sb_col_behavior_id)
.unwrap()
.into_opt_integer()
.unwrap();
root_behaviors.insert(behavior_id);
}
let mut behavior_root: HashMap<i32, i32> = HashMap::new();
let mut stack = Vec::new();
let mut soft_roots = HashSet::new();
let mut conflicts = HashSet::new();
let mut conflicting_roots = HashSet::new();
for &root in &root_behaviors {
stack.push(root);
while let Some(node) = stack.pop() {
if let Some(&check_root) = behavior_root.get(&node) {
// We already know the root of that node, now we need to check whether it's the same
match (&check_root).cmp(&root) {
Ordering::Less => {
// OOPS
conflicts.insert((check_root, root));
conflicting_roots.insert(check_root);
conflicting_roots.insert(root);
soft_roots.insert(node);
}
Ordering::Equal => {}
Ordering::Greater => {
// OOPS
conflicts.insert((root, check_root));
conflicting_roots.insert(check_root);
conflicting_roots.insert(root);
soft_roots.insert(node);
}
}
} else {
behavior_root.insert(node, root);
// Now add all possible child nodes to the stack
let iter = RowFinder::new(behavior_parameter, node);
for bp in iter {
let parameter_id = bp.parameter_id().decode();
if match_action_key(parameter_id.as_ref()) {
let value = bp.int_value();
if value > 0 {
stack.push(value);
}
}
}
}
}
}
for &conflict in &conflicts {
println!("{:?}", conflict);
}
println!("Count: {}", conflicts.len());
for &conflict in &conflicting_roots {
println!("{:?}", conflict);
}
println!("Count: {}", conflicting_roots.len());
let partition_roots: HashSet<i32> = root_behaviors.union(&soft_roots).copied().collect();
behavior_root.clear();
for &root in &root_behaviors {
stack.push(root);
while let Some(node) = stack.pop() {
if let Some(&check_root) = behavior_root.get(&node) {
// We already know the root of that node, now we need to check whether it's the same
if check_root != root {
panic!("Caught! {} {} {}", node, root, check_root);
}
} else if (node != root) && partition_roots.contains(&node) {
panic!("FOo");
} else {
behavior_root.insert(node, root);
// Now add all possible child nodes to the stack
let iter = RowFinder::new(behavior_parameter, node);
for bp in iter {
let parameter_id = bp.parameter_id().decode();
if match_action_key(parameter_id.as_ref()) {
let value = bp.int_value();
if value > 0 && !partition_roots.contains(&value) {
stack.push(value);
}
}
}
}
}
}
for &part_root in &partition_roots {
if let Some(&_check_root) = behavior_root.get(&part_root) {
panic!("Foo");
}
}
Ok(())
}
|
use std::cmp;
use regex::Regex;
fn main() {
let list: Vec<Instruction> = include_str!("input.txt")
.lines()
.map(parse_line_to_instruction)
.collect();
// We could use the Part 2 code for part 1 but I'd already written it...
let mut g = Grid3d::new();
for ins in &list {
if is_small(&ins) {
for x in ins.min_x..=ins.max_x {
for y in ins.min_y..=ins.max_y {
for z in ins.min_z..=ins.max_z {
g.set(ins.on, x, y, z);
}
}
}
}
}
println!("Part 1: {}", g.count_trues());
let mut cuboids: Vec<Cuboid> = Vec::new();
for ins in &list {
let mut new_cuboids: Vec<Cuboid> = Vec::new();
for existing in &cuboids {
new_cuboids.append(&mut existing.create_cuboids_by_subtracting(Cuboid::from(ins.min_x, ins.max_x, ins.min_y, ins.max_y, ins.min_z, ins.max_z)).clone());
}
if ins.on {
new_cuboids.push(Cuboid::from(ins.min_x, ins.max_x, ins.min_y, ins.max_y, ins.min_z, ins.max_z));
}
cuboids = new_cuboids;
}
println!("Part 2: {}", cuboids.iter().fold(0, |iter, item| iter + item.volume()));
}
#[derive(Clone)]
struct Cuboid {
min_x: i64,
max_x: i64,
min_y: i64,
max_y: i64,
min_z: i64,
max_z: i64
}
impl Cuboid {
fn from(min_x: i64, max_x: i64, min_y: i64, max_y: i64, min_z: i64, max_z: i64) -> Cuboid {
Cuboid { min_x, max_x, min_y, max_y, min_z, max_z }
}
fn create_cuboids_by_subtracting(&self, subtract: Cuboid) -> Vec<Cuboid> {
if !self.overlaps(&subtract) {
return vec![self.clone()];
}
let mut new_cuboids = Vec::new();
if subtract.min_x > self.min_x {
new_cuboids.push(Cuboid::from(self.min_x, subtract.min_x - 1, self.min_y, self.max_y, self.min_z, self.max_z));
}
if subtract.max_x < self.max_x {
new_cuboids.push(Cuboid::from(subtract.max_x + 1, self.max_x, self.min_y, self.max_y, self.min_z, self.max_z));
}
let new_min_x = cmp::max(self.min_x, subtract.min_x);
let new_max_x = cmp::min(self.max_x, subtract.max_x);
if subtract.min_y > self.min_y {
new_cuboids.push(Cuboid::from(new_min_x, new_max_x, self.min_y, subtract.min_y - 1, self.min_z, self.max_z));
}
if subtract.max_y < self.max_y {
new_cuboids.push(Cuboid::from(new_min_x, new_max_x, subtract.max_y + 1, self.max_y, self.min_z, self.max_z));
}
let new_min_y = cmp::max(self.min_y, subtract.min_y);
let new_max_y = cmp::min(self.max_y, subtract.max_y);
if subtract.min_z > self.min_z {
new_cuboids.push(Cuboid::from(new_min_x, new_max_x, new_min_y, new_max_y, self.min_z, subtract.min_z - 1));
}
if subtract.max_z < self.max_z {
new_cuboids.push(Cuboid::from(new_min_x, new_max_x, new_min_y, new_max_y, subtract.max_z + 1, self.max_z));
}
new_cuboids
}
fn overlaps(&self, other: &Cuboid) -> bool {
other.min_x <= self.max_x && self.min_x <= other.max_x
&& other.min_y <= self.max_y && self.min_y <= other.max_y
&& other.min_z <= self.max_z && self.min_z <= other.max_z
}
fn volume(&self) -> i64 {
(1 + self.max_x - self.min_x) * (1 + self.max_y - self.min_y) * (1 + self.max_z - self.min_z)
}
}
struct Instruction {
on: bool,
min_x: i64,
max_x: i64,
min_y: i64,
max_y: i64,
min_z: i64,
max_z: i64
}
fn is_small(ins: &Instruction) -> bool {
ins.min_x >= -50 && ins.max_x <= 50 && ins.min_y >= -50 && ins.max_y <= 50 && ins.min_z >= -50 && ins.max_z <= 50
}
fn parse_line_to_instruction(str: &str) -> Instruction {
let re = Regex::new(r"^(on|off) x=([\-0-9]*)..([\-0-9]*),y=([\-0-9]*)..([\-0-9]*),z=([\-0-9]*)..([\-0-9]*)$").unwrap();
let cap = re.captures_iter(str).next().unwrap();
//println!("On: {} Xm: {} X: {} Ym: {} Y: {} Zm: {} Z: {}", &cap[1], &cap[2], &cap[3], &cap[4], &cap[5], &cap[6], &cap[7]);
Instruction {
on: &cap[1] == "on",
min_x: str::parse::<i64>(&cap[2]).unwrap(),
max_x: str::parse::<i64>(&cap[3]).unwrap(),
min_y: str::parse::<i64>(&cap[4]).unwrap(),
max_y: str::parse::<i64>(&cap[5]).unwrap(),
min_z: str::parse::<i64>(&cap[6]).unwrap(),
max_z: str::parse::<i64>(&cap[7]).unwrap(),
}
}
struct Grid3d {
top_left_near: Vec<Vec<Vec<bool>>>,
top_right_near: Vec<Vec<Vec<bool>>>,
bottom_left_near: Vec<Vec<Vec<bool>>>,
bottom_right_near: Vec<Vec<Vec<bool>>>,
top_left_far: Vec<Vec<Vec<bool>>>,
top_right_far: Vec<Vec<Vec<bool>>>,
bottom_left_far: Vec<Vec<Vec<bool>>>,
bottom_right_far: Vec<Vec<Vec<bool>>>
}
impl Grid3d {
fn new() -> Grid3d {
Grid3d {
top_left_near: vec![vec![vec![false; 1]; 1]; 1],
top_right_near: vec![vec![vec![false; 1]; 1]; 1],
bottom_left_near: vec![vec![vec![false; 1]; 1]; 1],
bottom_right_near: vec![vec![vec![false; 1]; 1]; 1],
top_left_far: vec![vec![vec![false; 1]; 1]; 1],
top_right_far: vec![vec![vec![false; 1]; 1]; 1],
bottom_left_far: vec![vec![vec![false; 1]; 1]; 1],
bottom_right_far: vec![vec![vec![false; 1]; 1]; 1],
}
}
fn set(&mut self, b: bool, x: i64, y: i64, z: i64) {
let xx = x.abs() as usize;
let yy = y.abs() as usize;
let zz = z.abs() as usize;
if x >= 0 && y >= 0 && z >= 0 {
// bottom right near
resize_grid_vec(&mut self.bottom_right_near, xx, yy, zz);
self.bottom_right_near[xx][yy][zz] = b;
} else if x < 0 && y >= 0 && z >= 0 {
// bottom left near
resize_grid_vec(&mut self.bottom_left_near, xx, yy, zz);
self.bottom_left_near[xx][yy][zz] = b;
} else if x >= 0 && y < 0 && z >= 0 {
// top right near
resize_grid_vec(&mut self.top_right_near, xx, yy, zz);
self.top_right_near[xx][yy][zz] = b;
} else if x < 0 && y < 0 && z >= 0 {
// top left near
resize_grid_vec(&mut self.top_left_near, xx, yy, zz);
self.top_left_near[xx][yy][zz] = b;
} else if x >= 0 && y >= 0 && z < 0 {
// bottom right far
resize_grid_vec(&mut self.bottom_right_far, xx, yy, zz);
self.bottom_right_far[xx][yy][zz] = b;
} else if x < 0 && y >= 0 && z < 0 {
// bottom left far
resize_grid_vec(&mut self.bottom_left_far, xx, yy, zz);
self.bottom_left_far[xx][yy][zz] = b;
} else if x >= 0 && y < 0 && z < 0 {
// top right far
resize_grid_vec(&mut self.top_right_far, xx, yy, zz);
self.top_right_far[xx][yy][zz] = b;
} else if x < 0 && y < 0 && z < 0 {
// top left far
resize_grid_vec(&mut self.top_left_far, xx, yy, zz);
self.top_left_far[xx][yy][zz] = b;
}
}
fn get(&mut self, x: i64, y: i64, z: i64) -> bool {
let xx = x.abs() as usize;
let yy = y.abs() as usize;
let zz = z.abs() as usize;
if x >= 0 && y >= 0 && z >= 0 {
// bottom right near
resize_grid_vec(&mut self.bottom_right_near, xx, yy, zz);
return self.bottom_right_near[xx][yy][zz];
} else if x < 0 && y >= 0 && z >= 0 {
// bottom left near
resize_grid_vec(&mut self.bottom_left_near, xx, yy, zz);
return self.bottom_left_near[xx][yy][zz];
} else if x >= 0 && y < 0 && z >= 0 {
// top right near
resize_grid_vec(&mut self.top_right_near, xx, yy, zz);
return self.top_right_near[xx][yy][zz];
} else if x < 0 && y < 0 && z >= 0 {
// top left near
resize_grid_vec(&mut self.top_left_near, xx, yy, zz);
return self.top_left_near[xx][yy][zz];
} else if x >= 0 && y >= 0 && z < 0 {
// bottom right far
resize_grid_vec(&mut self.bottom_right_far, xx, yy, zz);
return self.bottom_right_far[xx][yy][zz];
} else if x < 0 && y >= 0 && z < 0 {
// bottom left far
resize_grid_vec(&mut self.bottom_left_far, xx, yy, zz);
return self.bottom_left_far[xx][yy][zz];
} else if x >= 0 && y < 0 && z < 0 {
// top right far
resize_grid_vec(&mut self.top_right_far, xx, yy, zz);
return self.top_right_far[xx][yy][zz];
} else if x < 0 && y < 0 && z < 0 {
// top left far
resize_grid_vec(&mut self.top_left_far, xx, yy, zz);
return self.top_left_far[xx][yy][zz];
}
return false;
}
fn count_trues(&self) -> u64 {
count_trues(&self.bottom_left_near)
+ count_trues(&self.bottom_right_near)
+ count_trues(&self.top_left_near)
+ count_trues(&self.top_right_near)
+ count_trues(&self.bottom_left_far)
+ count_trues(&self.bottom_right_far)
+ count_trues(&self.top_left_far)
+ count_trues(&self.top_right_far)
}
}
fn resize_grid_vec(arr: &mut Vec<Vec<Vec<bool>>>, xx: usize, yy: usize, zz: usize) {
if arr.len() <= xx {
arr.resize(xx + 1, Vec::new());
}
if arr[xx].len() <= yy {
arr[xx].resize(yy + 1, Vec::new());
}
if arr[xx][yy].len() <= zz {
arr[xx][yy].resize(zz + 1, false);
}
}
fn count_trues(list: &Vec<Vec<Vec<bool>>>) -> u64 {
let mut count = 0;
for x in 0..list.len() {
for y in 0..list[x].len() {
for z in 0..list[x][y].len() {
if list[x][y][z] {
count += 1;
}
}
}
}
count
} |
use crate::contract::{handle, init, query};
use cosmwasm_std::testing::{mock_env, MockApi, MockStorage, MOCK_CONTRACT_ADDR, mock_dependencies, MockQuerier};
use cosmwasm_std::{Binary, CosmosMsg, Decimal, Extern, HumanAddr, Uint128, WasmMsg, from_binary, to_vec};
use cw20::{Cw20HandleMsg};
use spectrum_protocol::common::OrderBy;
use spectrum_protocol::platform::{BoardsResponse, ConfigInfo, ExecuteMsg, HandleMsg, PollInfo, PollStatus, PollsResponse, QueryMsg, StateInfo, VoteOption, VoterInfo, VotersResponse};
const VOTING_TOKEN: &str = "voting_token";
const TEST_CREATOR: &str = "creator";
const TEST_VOTER: &str = "voter1";
const TEST_VOTER_2: &str = "voter2";
const DEFAULT_QUORUM: u64 = 30u64;
const DEFAULT_THRESHOLD: u64 = 50u64;
const DEFAULT_VOTING_PERIOD: u64 = 10000u64;
const DEFAULT_EFFECTIVE_DELAY: u64 = 10000u64;
const DEFAULT_EXPIRATION_PERIOD: u64 = 20000u64;
#[test]
fn test() {
let mut deps = mock_dependencies(20, &[]);
let config = test_config(&mut deps);
let (weight, weight_2, total_weight) = test_board(&mut deps);
test_poll_executed(&mut deps, &config, weight, weight_2, total_weight);
test_poll_low_quorum(&mut deps, total_weight);
test_poll_low_threshold(&mut deps, total_weight);
test_poll_expired(&mut deps);
}
fn test_config(deps: &mut Extern<MockStorage, MockApi, MockQuerier>) -> ConfigInfo {
// test init & read config & read state
let env = mock_env(TEST_CREATOR, &[]);
let mut config = ConfigInfo {
owner: HumanAddr::from(MOCK_CONTRACT_ADDR),
quorum: Decimal::percent(120u64),
threshold: Decimal::percent(DEFAULT_THRESHOLD),
voting_period: 0,
effective_delay: 0,
expiration_period: 0,
};
// validate quorum
let res = init(deps, env.clone(), config.clone());
assert!(res.is_err());
// validate threshold
config.quorum = Decimal::percent(DEFAULT_QUORUM);
config.threshold = Decimal::percent(120u64);
let res = init(deps, env.clone(), config.clone());
assert!(res.is_err());
// success init
config.threshold = Decimal::percent(DEFAULT_THRESHOLD);
let res = init(deps, env.clone(), config.clone());
assert!(res.is_ok());
// read config
let msg = QueryMsg::config {};
let res: ConfigInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res, config.clone());
// read state
let msg = QueryMsg::state { };
let res: StateInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(
res,
StateInfo {
poll_count: 0,
total_weight: 0,
}
);
// alter config, validate owner
let msg = HandleMsg::update_config {
owner: None,
quorum: None,
threshold: None,
voting_period: Some(DEFAULT_VOTING_PERIOD),
effective_delay: Some(DEFAULT_EFFECTIVE_DELAY),
expiration_period: Some(DEFAULT_EXPIRATION_PERIOD),
};
let res = handle(deps, env.clone(), msg.clone());
assert!(res.is_err());
// success
let env = mock_env(MOCK_CONTRACT_ADDR, &[]);
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
let msg = QueryMsg::config {};
let res: ConfigInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
config.voting_period = DEFAULT_VOTING_PERIOD;
config.effective_delay = DEFAULT_EFFECTIVE_DELAY;
config.expiration_period = DEFAULT_EXPIRATION_PERIOD;
assert_eq!(res, config.clone());
// alter config, validate value
let msg = HandleMsg::update_config {
owner: None,
quorum: None,
threshold: Some(Decimal::percent(120u64)),
voting_period: None,
effective_delay: None,
expiration_period: None,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_err());
config
}
fn test_board(
deps: &mut Extern<MockStorage, MockApi, MockQuerier>,
) -> (u32, u32, u32) {
// stake, error
let env = mock_env(TEST_VOTER, &[]);
let weight = 25u32;
let total_weight = weight;
let msg = HandleMsg::upsert_board {
address: HumanAddr::from(TEST_VOTER),
weight,
};
let res = handle(deps, env.clone(), msg.clone());
assert!(res.is_err());
let env = mock_env(MOCK_CONTRACT_ADDR, &[]);
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// read state
let msg = QueryMsg::state { };
let res: StateInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.total_weight, total_weight);
// query boards
let msg = QueryMsg::boards {};
let res: BoardsResponse = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.boards[0].weight, weight);
// stake voter2, error (0)
let weight_2 = 75u32;
let total_weight = total_weight + weight_2;
let msg = HandleMsg::upsert_board {
address: HumanAddr::from(TEST_VOTER_2),
weight: weight_2,
};
let res = handle(deps, env.clone(), msg.clone());
assert!(res.is_ok());
// read state
let msg = QueryMsg::state { };
let res: StateInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.total_weight, total_weight);
// query boards
let msg = QueryMsg::boards {};
let res: BoardsResponse = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.boards[1].weight, weight);
assert_eq!(res.boards[0].weight, weight_2);
(weight, weight_2, total_weight)
}
fn test_poll_executed(
deps: &mut Extern<MockStorage, MockApi, MockQuerier>,
config: &ConfigInfo,
weight: u32,
weight_2: u32,
total_weight: u32,
) {
// start poll
let env = mock_env(TEST_VOTER, &[]);
let execute_msg = ExecuteMsg::execute {
contract: HumanAddr::from(VOTING_TOKEN),
msg: String::from_utf8(
to_vec(&Cw20HandleMsg::Burn {
amount: Uint128(123),
})
.unwrap(),
)
.unwrap(),
};
let msg = HandleMsg::poll_start {
title: "title".to_string(),
description: "description".to_string(),
link: None,
execute_msgs: vec![execute_msg.clone()],
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// read state
let msg = QueryMsg::state { };
let res: StateInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.poll_count, 1u64);
let poll = PollInfo {
id: 1u64,
creator: HumanAddr::from(TEST_VOTER),
status: PollStatus::in_progress,
end_height: env.block.height + config.voting_period,
title: "title".to_string(),
description: "description".to_string(),
link: None,
execute_msgs: vec![execute_msg.clone()],
yes_votes: 0u32,
no_votes: 0u32,
total_balance_at_end_poll: None,
};
// query polls
let msg = QueryMsg::polls {
filter: None,
start_after: None,
limit: None,
order_by: None,
};
let res: PollsResponse = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(
res,
PollsResponse {
polls: vec![poll.clone()]
}
);
// get poll
let msg = QueryMsg::poll { poll_id: 1 };
let res: PollInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res, poll);
// vote failed (id not found)
let env = mock_env(TEST_VOTER, &[]);
let msg = HandleMsg::poll_vote {
poll_id: 2,
vote: VoteOption::yes,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_err());
// vote success
let msg = HandleMsg::poll_vote {
poll_id: 1,
vote: VoteOption::yes,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// get poll
let msg = QueryMsg::poll { poll_id: 1 };
let res: PollInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.yes_votes, weight);
assert_eq!(res.no_votes, 0u32);
// vote failed (duplicate)
let msg = HandleMsg::poll_vote {
poll_id: 1,
vote: VoteOption::yes,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_err());
// end poll failed (voting period not end)
let msg = HandleMsg::poll_end { poll_id: 1 };
let res = handle(deps, env.clone(), msg);
assert!(res.is_err());
// vote 2
let env = mock_env(TEST_VOTER_2, &[]);
let msg = HandleMsg::poll_vote {
poll_id: 1,
vote: VoteOption::yes,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// query voters
let msg = QueryMsg::voters {
poll_id: 1,
start_after: None,
limit: None,
order_by: None,
};
let res: VotersResponse = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(
res,
VotersResponse {
voters: vec![
(
HumanAddr::from(TEST_VOTER_2),
VoterInfo {
vote: VoteOption::yes,
balance: weight_2,
}
),
(
HumanAddr::from(TEST_VOTER),
VoterInfo {
vote: VoteOption::yes,
balance: weight,
}
),
]
}
);
// end poll success
let mut env = mock_env(TEST_VOTER_2, &[]);
env.block.height = env.block.height + DEFAULT_VOTING_PERIOD;
let msg = HandleMsg::poll_end { poll_id: 1 };
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// get poll
let msg = QueryMsg::poll { poll_id: 1 };
let res: PollInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.status, PollStatus::passed);
assert_eq!(res.total_balance_at_end_poll, Some(total_weight));
// end poll failed (not in progress)
let msg = HandleMsg::poll_end { poll_id: 1 };
let res = handle(deps, env.clone(), msg);
assert!(res.is_err());
// execute failed (wait period)
let msg = HandleMsg::poll_execute { poll_id: 1 };
let res = handle(deps, env.clone(), msg.clone());
assert!(res.is_err());
// execute success
env.block.height = env.block.height + DEFAULT_EFFECTIVE_DELAY;
let res = handle(deps, env.clone(), msg);
let (contract_addr, msg) = match execute_msg {
ExecuteMsg::execute { contract, msg } => (contract, msg),
};
assert!(res.is_ok());
assert_eq!(
res.unwrap().messages[0],
CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr,
msg: Binary(msg.into_bytes()),
send: vec![],
})
);
// get poll
let msg = QueryMsg::poll { poll_id: 1 };
let res: PollInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.status, PollStatus::executed);
// execute failed (status)
let msg = HandleMsg::poll_execute { poll_id: 1 };
let res = handle(deps, env.clone(), msg);
assert!(res.is_err());
}
fn test_poll_low_quorum(
deps: &mut Extern<MockStorage, MockApi, MockQuerier>,
total_weight: u32,
) {
// start poll2
let env = mock_env(TEST_VOTER, &[]);
let msg = HandleMsg::poll_start {
title: "title".to_string(),
description: "description".to_string(),
link: None,
execute_msgs: vec![],
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// vote poll2
let env = mock_env(TEST_VOTER, &[]);
let msg = HandleMsg::poll_vote {
poll_id: 2,
vote: VoteOption::yes,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// vote poll failed (expired)
let mut env = mock_env(TEST_VOTER, &[]);
env.block.height = env.block.height + DEFAULT_VOTING_PERIOD;
let msg = HandleMsg::poll_vote {
poll_id: 2,
vote: VoteOption::no,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_err());
// end poll success
let msg = HandleMsg::poll_end { poll_id: 2 };
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// get poll
let msg = QueryMsg::poll { poll_id: 2 };
let res: PollInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.status, PollStatus::rejected);
assert_eq!(
res.total_balance_at_end_poll,
Some(total_weight)
);
}
fn test_poll_low_threshold(
deps: &mut Extern<MockStorage, MockApi, MockQuerier>,
total_weight: u32,
) {
// start poll3
let env = mock_env(TEST_VOTER, &[]);
let msg = HandleMsg::poll_start {
title: "title".to_string(),
description: "description".to_string(),
link: None,
execute_msgs: vec![],
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// vote poll3
let env = mock_env(TEST_VOTER, &[]);
let msg = HandleMsg::poll_vote {
poll_id: 3,
vote: VoteOption::yes,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// vote poll3 as no
let env = mock_env(TEST_VOTER_2, &[]);
let msg = HandleMsg::poll_vote {
poll_id: 3,
vote: VoteOption::no,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// end poll success
let mut env = mock_env(TEST_CREATOR, &[]);
env.block.height = env.block.height + DEFAULT_VOTING_PERIOD;
let msg = HandleMsg::poll_end { poll_id: 3 };
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// get poll
let msg = QueryMsg::poll { poll_id: 3 };
let res: PollInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.status, PollStatus::rejected);
assert_eq!(
res.total_balance_at_end_poll,
Some(total_weight)
);
}
fn test_poll_expired(
deps: &mut Extern<MockStorage, MockApi, MockQuerier>,
) {
// start poll
let env = mock_env(TEST_VOTER, &[]);
let execute_msg = ExecuteMsg::execute {
contract: HumanAddr::from(VOTING_TOKEN),
msg: String::from_utf8(
to_vec(&Cw20HandleMsg::Burn {
amount: Uint128(123),
})
.unwrap(),
)
.unwrap(),
};
let msg = HandleMsg::poll_start {
title: "title".to_string(),
description: "description".to_string(),
link: None,
execute_msgs: vec![execute_msg.clone()],
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// vote success
let env = mock_env(TEST_VOTER, &[]);
let msg = HandleMsg::poll_vote {
poll_id: 4,
vote: VoteOption::yes,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// vote 2
let env = mock_env(TEST_VOTER_2, &[]);
let msg = HandleMsg::poll_vote {
poll_id: 4,
vote: VoteOption::yes,
};
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// end poll success
let mut env = mock_env(TEST_CREATOR, &[]);
env.block.height = env.block.height + DEFAULT_VOTING_PERIOD;
let msg = HandleMsg::poll_end { poll_id: 4 };
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// expired failed (wait period)
env.block.height = env.block.height + DEFAULT_EFFECTIVE_DELAY;
let msg = HandleMsg::poll_expire { poll_id: 4 };
let res = handle(deps, env.clone(), msg.clone());
assert!(res.is_err());
// execute success
env.block.height = env.block.height + DEFAULT_EFFECTIVE_DELAY;
let res = handle(deps, env.clone(), msg);
assert!(res.is_ok());
// get poll
let msg = QueryMsg::poll { poll_id: 4 };
let res: PollInfo = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.status, PollStatus::expired);
// expired failed (status)
let msg = HandleMsg::poll_expire { poll_id: 4 };
let res = handle(deps, env.clone(), msg);
assert!(res.is_err());
// query polls
let msg = QueryMsg::polls {
filter: Some(PollStatus::rejected),
start_after: None,
limit: None,
order_by: Some(OrderBy::Asc),
};
let res: PollsResponse = from_binary(&query(deps, msg).unwrap()).unwrap();
assert_eq!(res.polls[0].id, 2);
assert_eq!(res.polls[1].id, 3);
}
|
use testutil::*;
use seven_client::voice::{Voice, VoiceParams};
mod testutil;
fn client() -> Voice {
Voice::new(get_client())
}
fn params() -> VoiceParams {
VoiceParams {
from: Option::from("seven.io".to_string()),
text: "HI2U!".to_string(),
to: "+49179876543210".to_string(),
xml: None,
}
}
#[test]
fn text() {
assert!(client().text(params()).is_ok());
}
#[test]
fn json() {
assert!(client().json(params()).is_ok());
}
|
use clap::{App, Arg, ArgMatches, SubCommand};
use futures::{StreamExt, TryStreamExt};
use k8s_openapi::api::core::v1::{Event, Secret};
use kube::api::{ListParams, WatchEvent};
use kube::client::APIClient;
use kube::runtime::Informer;
use kube::{Api, Resource};
use oauth2::prelude::*;
use oauth2::{RefreshToken, TokenResponse};
use anyhow::anyhow;
use crate::common::KubeCrud;
use crate::{CredentialConfiguration, Credentials, Targets, Watcher};
pub struct Runner<'a> {
client: APIClient,
targets: Targets,
secret_name: &'a str,
scope: &'a str,
client_id: Option<&'a str>,
client_secret: Option<&'a str>,
username: Option<&'a str>,
}
impl<'a> From<&'a Runner<'a>> for CredentialConfiguration<'a> {
fn from(w: &'a Runner<'a>) -> Self {
CredentialConfiguration::new(w.secret_name, &w.targets)
}
}
impl Runner<'_> {
pub fn subcommand(name: &str) -> App {
SubCommand::with_name(name)
.about("The in-cluster refresh service using a refresh token secret created by 'add'")
.arg(
Arg::with_name("secret_name")
.value_name("SECRET NAME")
.help("The name of the dockerconfigjson secret to create/update")
.required(true)
.index(1),
)
.arg(
Arg::with_name("oauth_scope")
.long("oauth-scope")
.value_name("SCOPE")
.takes_value(true)
.default_value(crate::oauth::GCRCRED_HELPER_SCOPE)
.hidden(true)
.help("The token scope to request"),
)
.arg(
Arg::with_name("oauth_client_id")
.long("oauth-client-id")
.value_name("ID")
.takes_value(true)
.requires_all(&["client_secret", "username"])
.hidden(true)
.help("The client_id to be used when performing the OAuth2 Authorization Code grant flow."),
)
.arg(
Arg::with_name("oauth_client_secret")
.long("oauth-client-secret")
.value_name("NAME")
.takes_value(true)
.hidden(true)
.help("The client_secret to be used when performing the OAuth2 Authorization Code grant flow."),
)
.arg(
Arg::with_name("oauth_username")
.long("oauth-username")
.value_name("NAME")
.takes_value(true)
.hidden(true)
.help("The username to pair with the authorization code"),
)
}
/// Main entry point for the watcher
pub async fn run(
client: APIClient,
targets: Targets,
matches: &ArgMatches<'_>,
) -> anyhow::Result<()> {
let runner = Runner {
client,
targets,
secret_name: matches.value_of("secret_name").expect("SECRET NAME"),
scope: matches.value_of("oauth_scope").expect("SCOPE"),
client_id: matches.value_of("oauth_client_id"),
client_secret: matches.value_of("oauth_client_secret"),
username: matches.value_of("oauth_username"),
};
info!("Target secret: {}", runner.secret_name);
// Follow the resource in all namespaces
let resource = Resource::all::<Event>();
// Create our informer and start listening
let lp = ListParams::default();
let ei = Informer::new(runner.client.clone(), lp, resource);
loop {
while let Some(event) = ei.poll().await?.boxed().try_next().await? {
runner.handle(event).await?;
}
}
}
fn refresh_token_name(&self) -> String {
format!("{}-refresh-token", self.secret_name)
}
async fn refresh_token(&self) -> anyhow::Result<RefreshToken> {
let secret_name = self.refresh_token_name();
info!("Fetching referesh token from {}", secret_name);
let secrets: Api<Secret> = Api::namespaced(self.client.clone(), self.targets.namespace());
if let Ok(secret) = secrets.get(&secret_name).await {
if secret.data.is_none() {
Err(anyhow!(
"Refresh token secret {} is missing data entry",
secret_name
))
} else if let Some(token) = secret.data.unwrap().get("refresh_token") {
let token = String::from_utf8(token.0.clone())?;
Ok(RefreshToken::new(token))
} else {
Err(anyhow!(
"Refresh token secret {} is missing its token",
secret_name
))
}
} else {
Err(anyhow!("Refresh token {} is missing", secret_name))
}
}
/// Event handler
async fn handle(&self, event: WatchEvent<Event>) -> anyhow::Result<()> {
match event {
WatchEvent::Added(event) => {
if Watcher::is_recent_gcr_auth_failure(&event) {
info!("{}", event.message.unwrap_or_else(|| "".into()));
let refresh_token = self.refresh_token().await?;
let token_response = crate::oauth::refresh(
self.client_id,
self.client_secret,
self.scope,
&refresh_token,
)?;
Credentials::from_access_token(token_response.access_token(), self.username)
.as_secret(self.into())
.upsert(&self.client, self.targets.namespace(), self.secret_name)
.await
} else {
Ok(())
}
}
_ => Ok(()),
}
}
}
|
use alloc::vec::Vec;
use core::{cmp::Ordering, mem};
use util::{impl_md_flow, uint_from_bytes, Hash};
use crate::{
consts::{
{f1, f2, f3, f4}, {H256, K128_LEFT, K128_RIGHT, R_LEFT, R_RIGHT, S_LEFT, S_RIGHT},
},
{round_left_128, round_right_128},
};
pub struct Ripemd256 {
status: [u32; 8],
}
impl Ripemd256 {
pub fn new() -> Self {
Self::default()
}
#[inline(always)]
#[allow(clippy::needless_late_init)]
fn compress(&mut self, x: &[u32; 16]) {
let mut t;
let [mut a_left, mut b_left, mut c_left, mut d_left] = [
self.status[0],
self.status[1],
self.status[2],
self.status[3],
];
let [mut a_right, mut b_right, mut c_right, mut d_right] = [
self.status[4],
self.status[5],
self.status[6],
self.status[7],
];
// Round 1
round_left_128!(
t, a_left, b_left, c_left, d_left, f1, x, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15
);
round_right_128!(
t, a_right, b_right, c_right, d_right, f4, x, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15
);
mem::swap(&mut a_left, &mut a_right);
// Round 2
round_left_128!(
t, a_left, b_left, c_left, d_left, f2, x, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31
);
round_right_128!(
t, a_right, b_right, c_right, d_right, f3, x, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31
);
mem::swap(&mut b_left, &mut b_right);
// Round 3
round_left_128!(
t, a_left, b_left, c_left, d_left, f3, x, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47
);
round_right_128!(
t, a_right, b_right, c_right, d_right, f2, x, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47
);
mem::swap(&mut c_left, &mut c_right);
// Round 4
round_left_128!(
t, a_left, b_left, c_left, d_left, f4, x, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63
);
round_right_128!(
t, a_right, b_right, c_right, d_right, f1, x, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63
);
mem::swap(&mut d_left, &mut d_right);
self.status[0] = self.status[0].wrapping_add(a_left);
self.status[1] = self.status[1].wrapping_add(b_left);
self.status[2] = self.status[2].wrapping_add(c_left);
self.status[3] = self.status[3].wrapping_add(d_left);
self.status[4] = self.status[4].wrapping_add(a_right);
self.status[5] = self.status[5].wrapping_add(b_right);
self.status[6] = self.status[6].wrapping_add(c_right);
self.status[7] = self.status[7].wrapping_add(d_right);
}
}
impl Default for Ripemd256 {
#[rustfmt::skip]
fn default() -> Self {
Self {
status: H256,
}
}
}
impl Hash for Ripemd256 {
fn hash_to_bytes(&mut self, message: &[u8]) -> Vec<u8> {
impl_md_flow!(u32 => self, message, from_le_bytes, to_le_bytes);
self.status
.iter()
.flat_map(|word| word.to_le_bytes().to_vec())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::Ripemd256;
use dev_util::impl_test;
const OFFICIAL: [(&[u8], &str); 9] = [
// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
(
"".as_bytes(),
"02ba4c4e5f8ecd1877fc52d64d30e37a2d9774fb1e5d026380ae0168e3c5522d",
),
(
"a".as_bytes(),
"f9333e45d857f5d90a91bab70a1eba0cfb1be4b0783c9acfcd883a9134692925",
),
(
"abc".as_bytes(),
"afbd6e228b9d8cbbcef5ca2d03e6dba10ac0bc7dcbe4680e1e42d2e975459b65",
),
(
"message digest".as_bytes(),
"87e971759a1ce47a514d5c914c392c9018c7c46bc14465554afcdf54a5070c0e",
),
(
"abcdefghijklmnopqrstuvwxyz".as_bytes(),
"649d3034751ea216776bf9a18acc81bc7896118a5197968782dd1fd97d8d5133",
),
(
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes(),
"3843045583aac6c8c8d9128573e7a9809afb2a0f34ccc36ea9e72f16f6368e3f",
),
(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".as_bytes(),
"5740a408ac16b720b84424ae931cbb1fe363d1d0bf4017f1a89f7ea6de77a0b8",
),
(
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
.as_bytes(),
"06fdcc7a409548aaf91368c06a6275b553e3f099bf0ea4edfd6778df89a890dd",
),
(
&[0x61; 1000000],
"ac953744e10e31514c150d4d8d7b677342e33399788296e43ae4850ce4f97978",
),
];
impl_test!(Ripemd256, official, OFFICIAL, Ripemd256::default());
}
|
pub fn parse(data: &str) -> usize {
data.lines().map(|line| {
let row: Vec<usize> = line.split_whitespace().map(|chr| {
chr.parse::<usize>().unwrap()
}).collect();
for i in 0..row.len() {
for j in 0..row.len() {
if i == j {
continue
}
if row[i] % row[j] == 0 {
return row[i] / row[j];
}
if row[j] % row[i] == 0 {
return row[j] / row[i];
}
}
}
0
}).sum()
}
#[cfg(test)]
mod tests {
use super::parse;
#[test]
fn day02_part2_test1() {
let input: &str = "5 9 2 8\n9 4 7 3\n3 8 6 5";
assert_eq!(9, parse(input));
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - DMA mode register"]
pub eth_dmamr: ETH_DMAMR,
#[doc = "0x04 - System bus mode register"]
pub eth_dmasbmr: ETH_DMASBMR,
#[doc = "0x08 - Interrupt status register"]
pub eth_dmaisr: ETH_DMAISR,
#[doc = "0x0c - Debug status register"]
pub eth_dmadsr: ETH_DMADSR,
_reserved4: [u8; 0x10],
#[doc = "0x20 - AXI4 transmit channel ACE control register"]
pub eth_dmaa4tx_acr: ETH_DMAA4TX_ACR,
#[doc = "0x24 - AXI4 receive channel ACE control register"]
pub eth_dmaa4rx_acr: ETH_DMAA4RX_ACR,
#[doc = "0x28 - AXI4 descriptor ACE control register"]
pub eth_dmaa4dacr: ETH_DMAA4DACR,
_reserved7: [u8; 0xd4],
#[doc = "0x100 - Channel 0 control register"]
pub eth_dmac0cr: ETH_DMAC0CR,
#[doc = "0x104 - Channel 0 transmit control register"]
pub eth_dmac0tx_cr: ETH_DMAC0TX_CR,
#[doc = "0x108 - Channel receive control register"]
pub eth_dmac0rx_cr: ETH_DMAC0RX_CR,
_reserved10: [u8; 0x08],
#[doc = "0x114 - Channel i Tx descriptor list address register"]
pub eth_dmac0tx_dlar: ETH_DMAC0TX_DLAR,
_reserved11: [u8; 0x04],
#[doc = "0x11c - Channel Rx descriptor list address register"]
pub eth_dmac0rx_dlar: ETH_DMAC0RX_DLAR,
#[doc = "0x120 - Channel Tx descriptor tail pointer register"]
pub eth_dmac0tx_dtpr: ETH_DMAC0TX_DTPR,
_reserved13: [u8; 0x04],
#[doc = "0x128 - Channel Rx descriptor tail pointer register"]
pub eth_dmac0rx_dtpr: ETH_DMAC0RX_DTPR,
#[doc = "0x12c - Channel Tx descriptor ring length register"]
pub eth_dmac0tx_rlr: ETH_DMAC0TX_RLR,
#[doc = "0x130 - Channel Rx descriptor ring length register"]
pub eth_dmac0rx_rlr: ETH_DMAC0RX_RLR,
#[doc = "0x134 - Channel interrupt enable register"]
pub eth_dmac0ier: ETH_DMAC0IER,
#[doc = "0x138 - Channel Rx interrupt watchdog timer register"]
pub eth_dmac0rx_iwtr: ETH_DMAC0RX_IWTR,
#[doc = "0x13c - Channel i slot function control status register"]
pub eth_dmac0sfcsr: ETH_DMAC0SFCSR,
_reserved19: [u8; 0x04],
#[doc = "0x144 - Channel current application transmit descriptor register"]
pub eth_dmac0catx_dr: ETH_DMAC0CATX_DR,
_reserved20: [u8; 0x04],
#[doc = "0x14c - Channel 0 current application receive descriptor register"]
pub eth_dmac0carx_dr: ETH_DMAC0CARX_DR,
_reserved21: [u8; 0x04],
#[doc = "0x154 - Channel 0 current application transmit buffer register"]
pub eth_dmac0catx_br: ETH_DMAC0CATX_BR,
_reserved22: [u8; 0x04],
#[doc = "0x15c - Channel current application receive buffer register"]
pub eth_dmac0carx_br: ETH_DMAC0CARX_BR,
#[doc = "0x160 - Channel status register"]
pub eth_dmac0sr: ETH_DMAC0SR,
_reserved24: [u8; 0x08],
#[doc = "0x16c - Channel missed frame count register"]
pub eth_dmac0mfcr: ETH_DMAC0MFCR,
_reserved25: [u8; 0x10],
#[doc = "0x180 - Channel 1 control register"]
pub eth_dmac1cr: ETH_DMAC1CR,
#[doc = "0x184 - Channel 1 transmit control register"]
pub eth_dmac1tx_cr: ETH_DMAC1TX_CR,
_reserved27: [u8; 0x0c],
#[doc = "0x194 - Channel i Tx descriptor list address register"]
pub eth_dmac1tx_dlar: ETH_DMAC1TX_DLAR,
_reserved28: [u8; 0x08],
#[doc = "0x1a0 - Channel Tx descriptor tail pointer register"]
pub eth_dmac1tx_dtpr: ETH_DMAC1TX_DTPR,
_reserved29: [u8; 0x08],
#[doc = "0x1ac - Channel Tx descriptor ring length register"]
pub eth_dmac1tx_rlr: ETH_DMAC1TX_RLR,
_reserved30: [u8; 0x04],
#[doc = "0x1b4 - Channel interrupt enable register"]
pub eth_dmac1ier: ETH_DMAC1IER,
_reserved31: [u8; 0x04],
#[doc = "0x1bc - Channel i slot function control status register"]
pub eth_dmac1sfcsr: ETH_DMAC1SFCSR,
_reserved32: [u8; 0x04],
#[doc = "0x1c4 - Channel current application transmit descriptor register"]
pub eth_dmac1catx_dr: ETH_DMAC1CATX_DR,
_reserved33: [u8; 0x0c],
#[doc = "0x1d4 - Channel 0 current application transmit buffer register"]
pub eth_dmac1catx_br: ETH_DMAC1CATX_BR,
_reserved34: [u8; 0x08],
#[doc = "0x1e0 - Channel status register"]
pub eth_dmac1sr: ETH_DMAC1SR,
_reserved35: [u8; 0x08],
#[doc = "0x1ec - Channel missed frame count register"]
pub eth_dmac1mfcr: ETH_DMAC1MFCR,
}
#[doc = "ETH_DMAMR (rw) register accessor: DMA mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmamr::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 [`eth_dmamr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmamr`]
module"]
pub type ETH_DMAMR = crate::Reg<eth_dmamr::ETH_DMAMR_SPEC>;
#[doc = "DMA mode register"]
pub mod eth_dmamr;
#[doc = "ETH_DMASBMR (rw) register accessor: System bus mode register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmasbmr::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 [`eth_dmasbmr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmasbmr`]
module"]
pub type ETH_DMASBMR = crate::Reg<eth_dmasbmr::ETH_DMASBMR_SPEC>;
#[doc = "System bus mode register"]
pub mod eth_dmasbmr;
#[doc = "ETH_DMAISR (r) register accessor: Interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmaisr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmaisr`]
module"]
pub type ETH_DMAISR = crate::Reg<eth_dmaisr::ETH_DMAISR_SPEC>;
#[doc = "Interrupt status register"]
pub mod eth_dmaisr;
#[doc = "ETH_DMADSR (r) register accessor: Debug status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmadsr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmadsr`]
module"]
pub type ETH_DMADSR = crate::Reg<eth_dmadsr::ETH_DMADSR_SPEC>;
#[doc = "Debug status register"]
pub mod eth_dmadsr;
#[doc = "ETH_DMAA4TxACR (rw) register accessor: AXI4 transmit channel ACE control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmaa4tx_acr::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 [`eth_dmaa4tx_acr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmaa4tx_acr`]
module"]
pub type ETH_DMAA4TX_ACR = crate::Reg<eth_dmaa4tx_acr::ETH_DMAA4TX_ACR_SPEC>;
#[doc = "AXI4 transmit channel ACE control register"]
pub mod eth_dmaa4tx_acr;
#[doc = "ETH_DMAA4RxACR (rw) register accessor: AXI4 receive channel ACE control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmaa4rx_acr::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 [`eth_dmaa4rx_acr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmaa4rx_acr`]
module"]
pub type ETH_DMAA4RX_ACR = crate::Reg<eth_dmaa4rx_acr::ETH_DMAA4RX_ACR_SPEC>;
#[doc = "AXI4 receive channel ACE control register"]
pub mod eth_dmaa4rx_acr;
#[doc = "ETH_DMAA4DACR (rw) register accessor: AXI4 descriptor ACE control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmaa4dacr::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 [`eth_dmaa4dacr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmaa4dacr`]
module"]
pub type ETH_DMAA4DACR = crate::Reg<eth_dmaa4dacr::ETH_DMAA4DACR_SPEC>;
#[doc = "AXI4 descriptor ACE control register"]
pub mod eth_dmaa4dacr;
#[doc = "ETH_DMAC0CR (rw) register accessor: Channel 0 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0cr::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 [`eth_dmac0cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0cr`]
module"]
pub type ETH_DMAC0CR = crate::Reg<eth_dmac0cr::ETH_DMAC0CR_SPEC>;
#[doc = "Channel 0 control register"]
pub mod eth_dmac0cr;
#[doc = "ETH_DMAC1CR (rw) register accessor: Channel 1 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1cr::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 [`eth_dmac1cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1cr`]
module"]
pub type ETH_DMAC1CR = crate::Reg<eth_dmac1cr::ETH_DMAC1CR_SPEC>;
#[doc = "Channel 1 control register"]
pub mod eth_dmac1cr;
#[doc = "ETH_DMAC0TxCR (rw) register accessor: Channel 0 transmit control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0tx_cr::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 [`eth_dmac0tx_cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0tx_cr`]
module"]
pub type ETH_DMAC0TX_CR = crate::Reg<eth_dmac0tx_cr::ETH_DMAC0TX_CR_SPEC>;
#[doc = "Channel 0 transmit control register"]
pub mod eth_dmac0tx_cr;
#[doc = "ETH_DMAC1TxCR (rw) register accessor: Channel 1 transmit control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1tx_cr::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 [`eth_dmac1tx_cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1tx_cr`]
module"]
pub type ETH_DMAC1TX_CR = crate::Reg<eth_dmac1tx_cr::ETH_DMAC1TX_CR_SPEC>;
#[doc = "Channel 1 transmit control register"]
pub mod eth_dmac1tx_cr;
#[doc = "ETH_DMAC0RxCR (rw) register accessor: Channel receive control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0rx_cr::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 [`eth_dmac0rx_cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0rx_cr`]
module"]
pub type ETH_DMAC0RX_CR = crate::Reg<eth_dmac0rx_cr::ETH_DMAC0RX_CR_SPEC>;
#[doc = "Channel receive control register"]
pub mod eth_dmac0rx_cr;
#[doc = "ETH_DMAC0TxDLAR (rw) register accessor: Channel i Tx descriptor list address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0tx_dlar::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 [`eth_dmac0tx_dlar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0tx_dlar`]
module"]
pub type ETH_DMAC0TX_DLAR = crate::Reg<eth_dmac0tx_dlar::ETH_DMAC0TX_DLAR_SPEC>;
#[doc = "Channel i Tx descriptor list address register"]
pub mod eth_dmac0tx_dlar;
#[doc = "ETH_DMAC1TxDLAR (rw) register accessor: Channel i Tx descriptor list address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1tx_dlar::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 [`eth_dmac1tx_dlar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1tx_dlar`]
module"]
pub type ETH_DMAC1TX_DLAR = crate::Reg<eth_dmac1tx_dlar::ETH_DMAC1TX_DLAR_SPEC>;
#[doc = "Channel i Tx descriptor list address register"]
pub mod eth_dmac1tx_dlar;
#[doc = "ETH_DMAC0RxDLAR (rw) register accessor: Channel Rx descriptor list address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0rx_dlar::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 [`eth_dmac0rx_dlar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0rx_dlar`]
module"]
pub type ETH_DMAC0RX_DLAR = crate::Reg<eth_dmac0rx_dlar::ETH_DMAC0RX_DLAR_SPEC>;
#[doc = "Channel Rx descriptor list address register"]
pub mod eth_dmac0rx_dlar;
#[doc = "ETH_DMAC0TxDTPR (rw) register accessor: Channel Tx descriptor tail pointer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0tx_dtpr::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 [`eth_dmac0tx_dtpr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0tx_dtpr`]
module"]
pub type ETH_DMAC0TX_DTPR = crate::Reg<eth_dmac0tx_dtpr::ETH_DMAC0TX_DTPR_SPEC>;
#[doc = "Channel Tx descriptor tail pointer register"]
pub mod eth_dmac0tx_dtpr;
#[doc = "ETH_DMAC1TxDTPR (rw) register accessor: Channel Tx descriptor tail pointer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1tx_dtpr::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 [`eth_dmac1tx_dtpr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1tx_dtpr`]
module"]
pub type ETH_DMAC1TX_DTPR = crate::Reg<eth_dmac1tx_dtpr::ETH_DMAC1TX_DTPR_SPEC>;
#[doc = "Channel Tx descriptor tail pointer register"]
pub mod eth_dmac1tx_dtpr;
#[doc = "ETH_DMAC0RxDTPR (rw) register accessor: Channel Rx descriptor tail pointer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0rx_dtpr::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 [`eth_dmac0rx_dtpr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0rx_dtpr`]
module"]
pub type ETH_DMAC0RX_DTPR = crate::Reg<eth_dmac0rx_dtpr::ETH_DMAC0RX_DTPR_SPEC>;
#[doc = "Channel Rx descriptor tail pointer register"]
pub mod eth_dmac0rx_dtpr;
#[doc = "ETH_DMAC0TxRLR (rw) register accessor: Channel Tx descriptor ring length register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0tx_rlr::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 [`eth_dmac0tx_rlr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0tx_rlr`]
module"]
pub type ETH_DMAC0TX_RLR = crate::Reg<eth_dmac0tx_rlr::ETH_DMAC0TX_RLR_SPEC>;
#[doc = "Channel Tx descriptor ring length register"]
pub mod eth_dmac0tx_rlr;
#[doc = "ETH_DMAC1TxRLR (rw) register accessor: Channel Tx descriptor ring length register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1tx_rlr::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 [`eth_dmac1tx_rlr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1tx_rlr`]
module"]
pub type ETH_DMAC1TX_RLR = crate::Reg<eth_dmac1tx_rlr::ETH_DMAC1TX_RLR_SPEC>;
#[doc = "Channel Tx descriptor ring length register"]
pub mod eth_dmac1tx_rlr;
#[doc = "ETH_DMAC0RxRLR (rw) register accessor: Channel Rx descriptor ring length register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0rx_rlr::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 [`eth_dmac0rx_rlr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0rx_rlr`]
module"]
pub type ETH_DMAC0RX_RLR = crate::Reg<eth_dmac0rx_rlr::ETH_DMAC0RX_RLR_SPEC>;
#[doc = "Channel Rx descriptor ring length register"]
pub mod eth_dmac0rx_rlr;
#[doc = "ETH_DMAC0IER (rw) register accessor: Channel interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0ier::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 [`eth_dmac0ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0ier`]
module"]
pub type ETH_DMAC0IER = crate::Reg<eth_dmac0ier::ETH_DMAC0IER_SPEC>;
#[doc = "Channel interrupt enable register"]
pub mod eth_dmac0ier;
#[doc = "ETH_DMAC1IER (rw) register accessor: Channel interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1ier::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 [`eth_dmac1ier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1ier`]
module"]
pub type ETH_DMAC1IER = crate::Reg<eth_dmac1ier::ETH_DMAC1IER_SPEC>;
#[doc = "Channel interrupt enable register"]
pub mod eth_dmac1ier;
#[doc = "ETH_DMAC0RxIWTR (rw) register accessor: Channel Rx interrupt watchdog timer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0rx_iwtr::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 [`eth_dmac0rx_iwtr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0rx_iwtr`]
module"]
pub type ETH_DMAC0RX_IWTR = crate::Reg<eth_dmac0rx_iwtr::ETH_DMAC0RX_IWTR_SPEC>;
#[doc = "Channel Rx interrupt watchdog timer register"]
pub mod eth_dmac0rx_iwtr;
#[doc = "ETH_DMAC0SFCSR (rw) register accessor: Channel i slot function control status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0sfcsr::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 [`eth_dmac0sfcsr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0sfcsr`]
module"]
pub type ETH_DMAC0SFCSR = crate::Reg<eth_dmac0sfcsr::ETH_DMAC0SFCSR_SPEC>;
#[doc = "Channel i slot function control status register"]
pub mod eth_dmac0sfcsr;
#[doc = "ETH_DMAC1SFCSR (rw) register accessor: Channel i slot function control status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1sfcsr::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 [`eth_dmac1sfcsr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1sfcsr`]
module"]
pub type ETH_DMAC1SFCSR = crate::Reg<eth_dmac1sfcsr::ETH_DMAC1SFCSR_SPEC>;
#[doc = "Channel i slot function control status register"]
pub mod eth_dmac1sfcsr;
#[doc = "ETH_DMAC0CATxDR (r) register accessor: Channel current application transmit descriptor register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0catx_dr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0catx_dr`]
module"]
pub type ETH_DMAC0CATX_DR = crate::Reg<eth_dmac0catx_dr::ETH_DMAC0CATX_DR_SPEC>;
#[doc = "Channel current application transmit descriptor register"]
pub mod eth_dmac0catx_dr;
#[doc = "ETH_DMAC1CATxDR (r) register accessor: Channel current application transmit descriptor register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1catx_dr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1catx_dr`]
module"]
pub type ETH_DMAC1CATX_DR = crate::Reg<eth_dmac1catx_dr::ETH_DMAC1CATX_DR_SPEC>;
#[doc = "Channel current application transmit descriptor register"]
pub mod eth_dmac1catx_dr;
#[doc = "ETH_DMAC0CARxDR (r) register accessor: Channel 0 current application receive descriptor register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0carx_dr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0carx_dr`]
module"]
pub type ETH_DMAC0CARX_DR = crate::Reg<eth_dmac0carx_dr::ETH_DMAC0CARX_DR_SPEC>;
#[doc = "Channel 0 current application receive descriptor register"]
pub mod eth_dmac0carx_dr;
#[doc = "ETH_DMAC0CATxBR (r) register accessor: Channel 0 current application transmit buffer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0catx_br::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0catx_br`]
module"]
pub type ETH_DMAC0CATX_BR = crate::Reg<eth_dmac0catx_br::ETH_DMAC0CATX_BR_SPEC>;
#[doc = "Channel 0 current application transmit buffer register"]
pub mod eth_dmac0catx_br;
#[doc = "ETH_DMAC1CATxBR (r) register accessor: Channel 0 current application transmit buffer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1catx_br::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1catx_br`]
module"]
pub type ETH_DMAC1CATX_BR = crate::Reg<eth_dmac1catx_br::ETH_DMAC1CATX_BR_SPEC>;
#[doc = "Channel 0 current application transmit buffer register"]
pub mod eth_dmac1catx_br;
#[doc = "ETH_DMAC0CARxBR (r) register accessor: Channel current application receive buffer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0carx_br::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0carx_br`]
module"]
pub type ETH_DMAC0CARX_BR = crate::Reg<eth_dmac0carx_br::ETH_DMAC0CARX_BR_SPEC>;
#[doc = "Channel current application receive buffer register"]
pub mod eth_dmac0carx_br;
#[doc = "ETH_DMAC0SR (rw) register accessor: Channel status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0sr::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 [`eth_dmac0sr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0sr`]
module"]
pub type ETH_DMAC0SR = crate::Reg<eth_dmac0sr::ETH_DMAC0SR_SPEC>;
#[doc = "Channel status register"]
pub mod eth_dmac0sr;
#[doc = "ETH_DMAC1SR (rw) register accessor: Channel status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1sr::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 [`eth_dmac1sr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1sr`]
module"]
pub type ETH_DMAC1SR = crate::Reg<eth_dmac1sr::ETH_DMAC1SR_SPEC>;
#[doc = "Channel status register"]
pub mod eth_dmac1sr;
#[doc = "ETH_DMAC0MFCR (r) register accessor: Channel missed frame count register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac0mfcr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac0mfcr`]
module"]
pub type ETH_DMAC0MFCR = crate::Reg<eth_dmac0mfcr::ETH_DMAC0MFCR_SPEC>;
#[doc = "Channel missed frame count register"]
pub mod eth_dmac0mfcr;
#[doc = "ETH_DMAC1MFCR (r) register accessor: Channel missed frame count register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_dmac1mfcr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eth_dmac1mfcr`]
module"]
pub type ETH_DMAC1MFCR = crate::Reg<eth_dmac1mfcr::ETH_DMAC1MFCR_SPEC>;
#[doc = "Channel missed frame count register"]
pub mod eth_dmac1mfcr;
|
use super::churn::Matcher;
use super::event::Event;
use time;
use regex::Regex;
static TimeStamp: Regex = regex!(r"\d{2}:\d{2}");
static Mode: Regex = regex!(r"@&%+!\s");
static Nick: Regex = regex!(r"A-Za-z\[\]\\`_\^\{\|\}");
pub struct Irssi;
impl Matcher for Irssi {
fn regular(&self, input: &str) -> Option<Event> {
match input {
"hehehe" => {
let t = time::now_utc();
Some(Event::Message(t, "ding", "dong"))
},
_ => None
}
}
fn kick(&self, input: &str) -> Option<Event> {
match input {
"hahaha" => {
Some(Event::Kick(time::now_utc(), "herp", "derp", "go away"))
},
_ => None
}
}
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SRAMMODE {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct DPREFETCH_CACHER {
bits: bool,
}
impl DPREFETCH_CACHER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct DPREFETCHR {
bits: bool,
}
impl DPREFETCHR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct IPREFETCH_CACHER {
bits: bool,
}
impl IPREFETCH_CACHER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct IPREFETCHR {
bits: bool,
}
impl IPREFETCHR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Proxy"]
pub struct _DPREFETCH_CACHEW<'a> {
w: &'a mut W,
}
impl<'a> _DPREFETCH_CACHEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _DPREFETCHW<'a> {
w: &'a mut W,
}
impl<'a> _DPREFETCHW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _IPREFETCH_CACHEW<'a> {
w: &'a mut W,
}
impl<'a> _IPREFETCH_CACHEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _IPREFETCHW<'a> {
w: &'a mut W,
}
impl<'a> _IPREFETCHW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 5 - Secondary prefetch feature that will cache prefetched data across bus waitstates (requires DPREFETCH to be set)."]
#[inline]
pub fn dprefetch_cache(&self) -> DPREFETCH_CACHER {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
};
DPREFETCH_CACHER { bits }
}
#[doc = "Bit 4 - When set, data bus accesses to the SRAM banks will be prefetched (normally 2 cycle read access). Use of this mode bit is only recommended if the work flow has a large number of sequential accesses."]
#[inline]
pub fn dprefetch(&self) -> DPREFETCHR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
DPREFETCHR { bits }
}
#[doc = "Bit 1 - Secondary prefetch feature that will cache prefetched data across bus waitstates (requires IPREFETCH to be set)."]
#[inline]
pub fn iprefetch_cache(&self) -> IPREFETCH_CACHER {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
};
IPREFETCH_CACHER { bits }
}
#[doc = "Bit 0 - When set, instruction accesses to the SRAM banks will be prefetched (normally 2 cycle read access). Generally, this mode bit should be set for improved performance when executing instructions from SRAM."]
#[inline]
pub fn iprefetch(&self) -> IPREFETCHR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
};
IPREFETCHR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 5 - Secondary prefetch feature that will cache prefetched data across bus waitstates (requires DPREFETCH to be set)."]
#[inline]
pub fn dprefetch_cache(&mut self) -> _DPREFETCH_CACHEW {
_DPREFETCH_CACHEW { w: self }
}
#[doc = "Bit 4 - When set, data bus accesses to the SRAM banks will be prefetched (normally 2 cycle read access). Use of this mode bit is only recommended if the work flow has a large number of sequential accesses."]
#[inline]
pub fn dprefetch(&mut self) -> _DPREFETCHW {
_DPREFETCHW { w: self }
}
#[doc = "Bit 1 - Secondary prefetch feature that will cache prefetched data across bus waitstates (requires IPREFETCH to be set)."]
#[inline]
pub fn iprefetch_cache(&mut self) -> _IPREFETCH_CACHEW {
_IPREFETCH_CACHEW { w: self }
}
#[doc = "Bit 0 - When set, instruction accesses to the SRAM banks will be prefetched (normally 2 cycle read access). Generally, this mode bit should be set for improved performance when executing instructions from SRAM."]
#[inline]
pub fn iprefetch(&mut self) -> _IPREFETCHW {
_IPREFETCHW { w: self }
}
}
|
fn main() {
// mutable borrow
let mut s1 = String::from("Hello!");
let s2 = &mut s1; // mutable borrow occurs here
s2.push('!');
println!("s2 = {}", s2);
println!("s1 = {}", s1);
} |
extern crate wiringpi;
use wiringpi::pin::Value::{High, Low};
use wiringpi::time::delay;
fn main() {
// Example code for a HC-SR04 Ultrasonic Ranging Module
//
// http://www.micropik.com/PDF/HCSR04.pdf
//
// Assumes 'trigger' is connected to pin 0 and 'echo' to pin 1.
//
let pi = wiringpi::setup();
let trigger = pi.output_pin(0);
let echo = pi.input_pin(1);
loop {
trigger.digital_write(Low);
delay(1);
trigger.digital_write(High);
delay(1);
trigger.digital_write(Low);
let mut counter = 0;
loop {
match echo.digital_read() {
High => { break; }
Low => {}
}
}
loop {
match echo.digital_read() {
High => { counter = counter + 1; }
Low => { break; }
}
}
println!("distance: {}", counter);
}
}
|
use cpx2::interface::gen_whitespace;
use std::collections::HashMap;
#[test]
fn txt() {
let regex = regex::Regex::new(r#".*?"#).unwrap();
let mut haystack = "apple \"fuckk\" apple bryg apple bruh ".to_string();
let matched = haystack.match_indices("apple").collect::<Vec<_>>();
let index_vec = matched.into_iter().map(|x| x.0).collect::<Vec<usize>>();
index_vec.iter().for_each(|idx| {
haystack.replace_range(idx..&5, "Bruha");
});
println!("NEWHAY {}", haystack);
}
fn replace_haystack(haystack: &mut String, target: &str, replace_with: &str) {
let matched = haystack.match_indices(target).collect::<Vec<_>>();
let index_vec = matched.into_iter().map(|x| x.0).collect::<Vec<usize>>();
index_vec.iter().for_each(|idx| {
haystack.replace_range(idx + 1..(idx + target.len()), replace_with);
});
}
#[test]
fn capture() {
let re = regex::Regex::new(r"\d++").unwrap();
let haystack = "1239 931y0 920asdsdw13 92a dsd19 123asda8 1w23";
for found in re.find_iter(haystack) {
println!("{:?}", (found.start(), found.end()));
}
}
#[test]
fn test() {
let mut new_hs = "|0|apple birb tree tree pa tree".to_string();
replace_haystack(&mut new_hs, "tree", "apple");
println!("{}", new_hs);
// assert_eq!("apple birb apple apple pa apple",new_hs);
let bordered = incb_text_border(&new_hs);
display(bordered);
}
fn incb_text_border(txt: &str) -> Vec<String> {
let lines = txt.lines();
let width = 160;
println!("{}",width);
let mut ovi = Vec::new();
let mut template = String::new();
template.push('+');
for _ in 0..width {
template.push_str("-")
}
template.push('+');
let bottom = template.clone();
ovi.push(template);
txt.lines().into_iter().for_each(|line| {
let longest = width;
let repeater = longest - line.len();
let c = format!("|{}{}|", line, " ".repeat(repeater as usize));
ovi.push(c.clone());
});
ovi.push(bottom);
println!("{:?}", ovi);
ovi
// println!("|{}|",txt);
}
fn incb_text_border_using_vec(txt: Vec<String>) -> Vec<String> {
let mut max = txt.get(0).unwrap();
for (_, ct) in txt.iter().enumerate() {
if ct.len() > max.len() {
max = ct;
}
}
let width = max.len() as i32;
let mut ovi = Vec::new();
let mut template = String::new();
println!("{}", width);
template.push('+');
for _ in 0..width {
template.push_str("-")
}
template.push('+');
let bottom = template.clone();
ovi.push(template);
txt.into_iter().for_each(|line| {
let longest = width;
let repeater = longest - (line.len() as i32);
let c = format!("|{}{}|", line, " ".repeat(repeater as usize));
ovi.push(c.clone());
});
ovi.push(bottom);
ovi
// println!("|{}|",txt);
}
#[cfg(test)]
mod practical_test {
use super::*;
use cpx2::interface::components;
use std::fs::File;
use std::io::Read;
use std::io::{self, BufReader};
#[test]
fn practical() -> io::Result<()> {
let big_txt = File::open("./big.txt")?;
let mut result = String::new();
let mut buffer = BufReader::new(big_txt);
buffer.read_to_string(&mut result)?;
let parsed =
incb_text_border_using_vec(result.lines().into_iter().map(|x| x.trim().to_string()).collect());
// let parsed = incb_text_border(&result);
display(parsed);
Ok(())
}
}
fn display(tmp: Vec<String>) {
tmp.iter().for_each(|line| println!("{}", line));
}
|
// Copyright 2020 The VectorDB Authors.
//
// Code is licensed under Apache License, Version 2.0.
#[derive(Debug)]
pub struct VariablePlanner {
pub val: String,
}
impl VariablePlanner {
pub fn new(v: impl AsRef<str>) -> Self {
VariablePlanner {
val: v.as_ref().to_string(),
}
}
pub fn name(&self) -> &str {
"VariablePlanner"
}
}
mod tests {
#[test]
fn test_variable_planner() {
use super::*;
assert_eq!("VariablePlanner", VariablePlanner::new("").name());
assert_eq!("a", VariablePlanner::new("a").val);
}
}
|
use ndarray::{Array1, Array2, Axis, Slice};
use serde::Deserialize;
use std::error::Error;
use std::fs::File;
use std::time::SystemTime;
use learn_rs::Tree;
#[derive(Debug, Deserialize)]
struct BostonRecord {
crim: f64,
zn: f64,
indus: f64,
chas: f64,
nox: f64,
rm: f64,
age: f64,
dis: f64,
rad: f64,
tax: f64,
ptratio: f64,
b: f64,
lstat: f64,
medv: f64,
}
struct BostonDataSet {
features: Array2<f64>,
labels: Array1<f64>,
}
impl BostonDataSet {
pub fn from(records: Vec<BostonRecord>) -> Self {
let mut features = Vec::with_capacity(records.len());
let mut labels = Vec::with_capacity(records.len());
for r in records {
let feats = &[
r.crim, r.zn, r.indus, r.chas, r.nox, r.rm, r.age, r.dis, r.rad, r.tax, r.ptratio,
r.b, r.lstat,
];
features.push(feats.clone());
labels.push(r.medv);
}
Self {
features: Array2::from(features),
labels: Array1::from(labels),
}
}
}
fn main() -> Result<(), Box<dyn Error>> {
let file_path = "data/boston.csv";
let file = File::open(file_path)?;
let mut rdr = csv::Reader::from_reader(file);
let mut bfr = Vec::new();
for result in rdr.deserialize() {
let record: BostonRecord = result?;
bfr.push(record);
}
let dataset = BostonDataSet::from(bfr);
println!("Dataset size: {}", &dataset.features.nrows());
let train_dataset = BostonDataSet {
features: dataset
.features
.slice_axis(Axis(0), Slice::from(0..450))
.to_owned(),
labels: dataset
.labels
.slice_axis(Axis(0), Slice::from(0..450))
.to_owned(),
};
let test_dataset = BostonDataSet {
features: dataset
.features
.slice_axis(Axis(0), Slice::from(450..))
.to_owned(),
labels: dataset
.labels
.slice_axis(Axis(0), Slice::from(450..))
.to_owned(),
};
let start_training = SystemTime::now();
let decision_tree = Tree::new(
train_dataset.features.clone(),
train_dataset.labels.clone(),
5,
7,
);
let end_training = start_training.elapsed().unwrap().as_millis();
println!("Training took {} ms", end_training);
let start_prediction = SystemTime::now();
let yhat_train = train_dataset
.features
.map_axis(Axis(1), |x| decision_tree.predict(x.to_owned()));
let yhat_test = test_dataset
.features
.map_axis(Axis(1), |x| decision_tree.predict(x.to_owned()));
let prediction_duration = start_prediction.elapsed().unwrap().as_millis();
println!("Prediction took {} ms", prediction_duration);
println!("yhat train shape: {:?}", yhat_train.shape());
println!("yhat test shape: {:?}", yhat_test.shape());
let mae_train = (&yhat_train - &train_dataset.labels)
.map(|y| y.abs())
.mean()
.unwrap();
let mae_test = (&yhat_test - &test_dataset.labels)
.map(|y| y.abs())
.mean()
.unwrap();
println!("Tree size: {}", &decision_tree.size());
println!("MAE Train: {:?}", mae_train);
println!("MAE Test: {:?}", mae_test);
Ok(())
}
|
use crate::{
ast_types::{
boxed_val::BoxedValue,
break_ast::{
Break,
BreakBase,
},
convert_tokens_into_arguments,
convert_tokens_into_res_expressions,
expression::{
Expression,
ExpressionBase,
},
fn_call::{
FnCall,
FnCallBase,
},
fn_def::{
FnDefinition,
FnDefinitionBase,
},
get_assignment_token_fn,
get_tokens_from_to_fn,
if_ast::{
IfConditional,
IfConditionalBase,
},
module::Module,
return_ast::ReturnStatement,
var_assign::{
VarAssignment,
VarAssignmentBase,
},
var_def::{
VarDefinition,
VarDefinitionBase,
},
while_block::{
While,
WhileBase,
},
},
runtime::{
downcast_val,
get_methods_in_type,
resolve_reference,
value_to_string,
values_to_strings,
},
stack::{
FunctionDef,
FunctionsContainer,
Stack,
VariableDef,
},
types::{
BoxedPrimitiveValue,
IndexedTokenList,
LinesList,
Token,
TokensList,
},
utils::{
errors,
Directions,
Ops,
},
};
use regex::Regex;
use std::{
collections::HashMap,
fs,
sync::Mutex,
};
use uuid::Uuid;
pub mod ast_types;
pub mod primitive_values;
pub mod runtime;
pub mod stack;
pub mod types;
pub mod utils;
use primitive_values::string::StringVal;
/*
* Split the text by the passed regex but also keep these words which are removed when splitting
*/
fn split<'a>(r: &'a Regex, text: &'a str) -> Vec<&'a str> {
let mut result = Vec::new();
let mut last = 0;
for (index, matched) in text.match_indices(r) {
if last != index {
result.push(&text[last..index]);
}
result.push(matched);
last = index + matched.len();
}
if last < text.len() {
result.push(&text[last..]);
}
result
}
/*
* Transform the code into lines
*/
fn get_lines(code: String) -> LinesList {
let mut lines = Vec::new();
// Every line
for line in code.split('\n') {
// Ignore // comments
if line.starts_with("//") {
continue;
}
let mut line_ast = Vec::new();
let re = Regex::new(r#"([\s+,.:])|("(.*?)")|([()])"#).unwrap();
// Every detected word
for word in split(&re, line) {
// Prevent empty words
if word.trim() != "" {
line_ast.push(String::from(word.trim()));
}
}
lines.push(line_ast);
}
lines
}
/*
* Trasnform a list of lines into a tokens list
*/
fn transform_into_tokens(lines: LinesList) -> TokensList {
let mut tokens = Vec::new();
for (i, line) in lines.iter().enumerate() {
for word in line {
let token_type: Ops = match word.as_str() {
"let" => Ops::VarDef,
"=" => Ops::LeftAssign,
"(" => Ops::OpenParent,
")" => Ops::CloseParent,
"fn" => Ops::FnDef,
"{" => Ops::OpenBlock,
"}" => Ops::CloseBlock,
"if" => Ops::IfConditional,
"==" => Ops::EqualCondition,
"return" => Ops::Return,
"." => Ops::PropAccess,
"," => Ops::CommaDelimiter,
"while" => Ops::WhileDef,
"!=" => Ops::NotEqualCondition,
"import" => Ops::Import,
"from" => Ops::FromModule,
"break" => Ops::Break,
_ => Ops::Reference,
};
let ast_token = Token {
ast_type: token_type,
value: word.clone(),
line: i + 1,
};
tokens.push(ast_token);
}
}
tokens
}
/*
* Transform the code into a list of tokens
*/
pub fn get_tokens(code: String) -> TokensList {
let lines = self::get_lines(code);
self::transform_into_tokens(lines)
}
/*
* Create a ast tree from some tokens
*/
pub fn move_tokens_into_ast(tokens: TokensList, ast_tree: &Mutex<Expression>, filedir: String) {
let mut ast_tree = ast_tree.lock().unwrap();
// Closure version of above
let get_tokens_from_to = |from: usize, to: Ops| -> IndexedTokenList {
get_tokens_from_to_fn(from, to, tokens.clone(), Directions::LeftToRight)
};
// Get all the tokens in a group (expression blocks, arguments)
let get_tokens_in_group_of = |from: usize, open_tok: Ops, close_tok: Ops| -> TokensList {
let mut found_tokens = Vec::new();
let mut count = 0;
let mut token_n = from;
while token_n < tokens.len() {
let token = tokens[token_n].clone();
if token.ast_type == open_tok {
count += 1;
} else if token.ast_type == close_tok {
count -= 1;
}
if count == 0 {
break;
} else if token_n > from {
found_tokens.push(token.clone());
}
token_n += 1;
}
found_tokens
};
let get_assignment_token = |val: String, token_n: usize| -> (usize, BoxedValue) {
get_assignment_token_fn(val, token_n, tokens.clone(), Directions::LeftToRight)
};
let mut token_n = 0;
while token_n < tokens.len() {
let current_token = &tokens[token_n];
match current_token.ast_type {
// Break statement
Ops::Break => {
let break_ast = Break::new();
ast_tree.body.push(Box::new(break_ast));
token_n += 1;
}
// Import statement
Ops::Import => {
let module_name = &tokens[token_n + 1].value;
let module_direction = &tokens[token_n + 2];
let module_origin = &tokens[token_n + 3].value;
/*
* import x from "./x.ham"
*
* module_name: x
* module_direction: from
* module_origin= "./x.ham"
*/
if module_direction.ast_type != Ops::FromModule {
errors::raise_error(
errors::CODES::UnexpectedKeyword,
vec![module_direction.value.clone()],
)
}
// Module's path
let filepath = format!("{}/{}", filedir, module_origin.replace('"', ""));
// Module's code
let filecontent = fs::read_to_string(filepath.as_str());
if let Ok(filecontent) = filecontent {
let tokens = get_tokens(filecontent);
// Move all the tokens into a expression
let scope_tree = Mutex::new(Expression::new());
move_tokens_into_ast(tokens.clone(), &scope_tree, filedir.clone());
// Copy all root-functions (public by default) from the expression body to the vector
let mut public_functions = Vec::new();
for op in scope_tree.lock().unwrap().body.iter() {
if op.get_type() == Ops::FnDef {
public_functions
.push(downcast_val::<FnDefinition>(op.as_self()).clone());
}
}
let module = Module {
name: module_name.to_string(),
functions: public_functions,
};
ast_tree.body.push(Box::new(module));
} else {
errors::raise_error(errors::CODES::ModuleNotFound, vec![filepath])
}
token_n += 4
}
// While block
Ops::WhileDef => {
// Get the if condition tokens
let condition_tokens = get_tokens_from_to(token_n + 1, Ops::OpenBlock);
// Transform those tokens into result expressions
let exprs = convert_tokens_into_res_expressions(
condition_tokens
.clone()
.iter()
.map(|(_, token)| token.clone())
.collect(),
);
// Scope tree
let scope_tree = Mutex::new(Expression::new());
// Ignore the if conditions and {
let open_block_index = token_n + condition_tokens.len() + 1;
// Get all tokens inside the if block
let block_tokens =
get_tokens_in_group_of(open_block_index, Ops::OpenBlock, Ops::CloseBlock);
// Move the tokens into the tree
move_tokens_into_ast(block_tokens.clone(), &scope_tree, filedir.clone());
// Ignore the whilte body
token_n = block_tokens.len() + open_block_index + 1;
// Create a while definition
let body = &scope_tree.lock().unwrap().body.clone();
let ast_token = While::new(exprs.clone(), body.to_vec());
ast_tree.body.push(Box::new(ast_token));
}
// Return statement
Ops::Return => {
let next_token = tokens[token_n + 1].clone();
let (size, return_val) =
get_assignment_token(next_token.value.clone(), token_n + 1);
let ast_token = ReturnStatement { value: return_val };
ast_tree.body.push(Box::new(ast_token));
token_n += 2 + size;
}
// If statement
Ops::IfConditional => {
// Get the if condition tokens
let condition_tokens = get_tokens_from_to(token_n + 1, Ops::OpenBlock);
// Transform those tokens into result expressions
let exprs = convert_tokens_into_res_expressions(
condition_tokens
.clone()
.iter()
.map(|(_, token)| token.clone())
.collect(),
);
// Scope tree
let scope_tree = Mutex::new(Expression::new());
// Ignore the if conditions and {
let open_block_index = token_n + condition_tokens.len() + 1;
// Get all tokens inside the if block
let block_tokens =
get_tokens_in_group_of(open_block_index, Ops::OpenBlock, Ops::CloseBlock);
// Move the tokens into the tree
move_tokens_into_ast(block_tokens.clone(), &scope_tree, filedir.clone());
// Ignore the block body
token_n = block_tokens.len() + open_block_index + 1;
// Create a if block definition
let body = &scope_tree.lock().unwrap().body.clone();
let ast_token = IfConditional::new(exprs.clone(), body.to_vec());
ast_tree.body.push(Box::new(ast_token));
}
// Property access
Ops::PropAccess => {
let previous_token = tokens[token_n - 1].clone();
let next_token = tokens[token_n + 1].clone();
if next_token.ast_type == Ops::Reference {
let after_next_token = tokens[token_n + 2].clone();
let reference_type = match after_next_token.ast_type {
Ops::OpenParent => Ops::FnCall,
_ => Ops::Invalid,
};
match reference_type {
/*
* Call to functions from variables
*/
Ops::FnCall => {
let mut ast_token =
FnCall::new(next_token.value.clone(), Some(previous_token.value));
// Ignore itself and the (
let starting_token = token_n + 2;
let arguments_tokens = get_tokens_in_group_of(
starting_token,
Ops::OpenParent,
Ops::CloseParent,
);
let arguments = convert_tokens_into_arguments(arguments_tokens.clone());
token_n += 2 + arguments_tokens.len();
ast_token.arguments = arguments;
ast_tree.body.push(Box::new(ast_token));
}
/*
* TODO: Access properties from varibles
*/
Ops::Reference => {}
_ => (),
};
}
}
// Function definition
Ops::FnDef => {
let def_name = String::from(&tokens[token_n + 1].value.clone());
// Scope tree
let scope_tree = Mutex::new(Expression::new());
// Ignore function name and the (
let starting_token = token_n + 2;
// Get function arguments, WIP
let arguments: Vec<String> =
get_tokens_in_group_of(starting_token, Ops::OpenParent, Ops::CloseParent)
.iter()
.map(|token| token.value.clone())
.collect();
// Ignore function name, (, arguments and )
let open_block_index = starting_token + arguments.len() + 2;
// Get all tokens inside the function block
let block_tokens =
get_tokens_in_group_of(open_block_index, Ops::OpenBlock, Ops::CloseBlock);
// Move the tokens into the tree
move_tokens_into_ast(block_tokens.clone(), &scope_tree, filedir.clone());
// Ignore the function body
token_n = block_tokens.len() + open_block_index + 1;
// Create a function definition
let body = &scope_tree.lock().unwrap().body.clone();
let ast_token = FnDefinition::new(def_name, body.to_vec(), arguments);
ast_tree.body.push(Box::new(ast_token));
}
// Variable definition
Ops::VarDef => {
let next_token = tokens[token_n + 1].clone();
// Variable name
let def_name = next_token.value.clone();
// Value token position
let val_index = token_n + 3;
// Stringified value
let def_value = String::from(&tokens[val_index].value.clone());
let (size, assignment) = get_assignment_token(def_value, val_index);
let ast_token = VarDefinition::new(def_name, assignment);
ast_tree.body.push(Box::new(ast_token));
token_n += size + 3;
}
// References (fn calls, variable reassignation...)
Ops::Reference => {
let reference_type = {
if token_n < tokens.len() - 1 {
let next_token = &tokens[token_n + 1];
match next_token.ast_type {
Ops::OpenParent => Ops::FnCall,
Ops::LeftAssign => Ops::VarAssign,
_ => Ops::Invalid,
}
} else {
Ops::Invalid
}
};
match reference_type {
Ops::VarAssign => {
let token_after_equal = tokens[token_n + 2].clone();
let (size, assignment) =
get_assignment_token(token_after_equal.value.clone(), token_n + 2);
let ast_token = VarAssignment::new(current_token.value.clone(), assignment);
ast_tree.body.push(Box::new(ast_token));
token_n += 2 + size;
}
Ops::FnCall => {
let mut ast_token = FnCall::new(current_token.value.clone(), None);
// Ignore itself and the (
let starting_token = token_n + 1;
let arguments_tokens = get_tokens_in_group_of(
starting_token,
Ops::OpenParent,
Ops::CloseParent,
);
let arguments = convert_tokens_into_arguments(arguments_tokens.clone());
token_n += 3 + arguments_tokens.len();
ast_token.arguments = arguments;
ast_tree.body.push(Box::new(ast_token));
}
_ => {
token_n += 1;
}
}
}
_ => {
token_n += 1;
}
}
}
}
/*
* Shorthand to create a function definition
*/
fn get_function_from_def(function: &FnDefinition) -> FunctionDef {
FunctionDef {
name: function.def_name.clone(),
body: function.body.clone(),
arguments: function.arguments.clone(),
cb: |args, args_vals, body, stack, ast| {
let expr = Expression::from_body(body.clone());
let expr_id = expr.expr_id.clone();
for (i, arg) in args_vals.iter().enumerate() {
let arg_name = args[i].clone();
let var_id = stack.lock().unwrap().reseve_index();
stack.lock().unwrap().push_variable(VariableDef {
name: arg_name,
value: arg.value.clone(),
val_type: arg.interface,
expr_id: expr_id.clone(),
functions: get_methods_in_type(arg.interface),
var_id,
})
}
let return_val = run_ast(&Mutex::new(expr), stack);
stack.lock().unwrap().drop_ops_from_id(expr_id);
if let Some(return_val) = return_val {
resolve_reference(stack, return_val.interface, return_val.value, &ast)
} else {
return_val
}
},
// TODO: Move away from Uuid
expr_id: Uuid::new_v4().to_string(),
}
}
/*
* Execute a AST tree
*/
pub fn run_ast(ast: &Mutex<Expression>, stack: &Mutex<Stack>) -> Option<BoxedValue> {
let ast = ast.lock().unwrap();
// Closure version of resolve_reference
let resolve_ref = |val_type: Ops, ref_val: BoxedPrimitiveValue| -> Option<BoxedValue> {
resolve_reference(stack, val_type, ref_val, &ast)
};
// Check if a conditional is true or not
let eval_condition =
|condition_code: Ops, left_val: BoxedValue, right_val: BoxedValue| -> bool {
let left_val = resolve_ref(left_val.interface, left_val.value.clone());
let right_val = resolve_ref(right_val.interface, right_val.value.clone());
if let (Some(left_val), Some(right_val)) = (left_val, right_val) {
match condition_code {
// Handle !=
Ops::NotEqualCondition => {
let left_val = value_to_string(left_val, stack).unwrap();
let right_val = value_to_string(right_val, stack).unwrap();
left_val != right_val
}
// Handle ==
Ops::EqualCondition => {
let left_val = value_to_string(left_val, stack).unwrap();
let right_val = value_to_string(right_val, stack).unwrap();
left_val == right_val
}
_ => false,
}
} else {
false
}
};
for operation in &ast.body {
match operation.get_type() {
/*
* Handle breaks
*/
Ops::Break => {
return Some(BoxedValue {
interface: Ops::Break,
value: Box::new(StringVal("break".to_string())),
})
}
/*
* Handle module definitions
*/
Ops::Module => {
let module = downcast_val::<Module>(operation.as_self());
let var_id = stack.lock().unwrap().reseve_index();
let mut functions = HashMap::new();
for function in &module.functions {
let mut function = function.clone();
function.arguments.insert(0, "_".to_string());
functions.insert(function.def_name.clone(), get_function_from_def(&function));
}
// Push the variable into the stack
stack.lock().unwrap().push_variable(VariableDef {
name: module.name.clone(),
val_type: Ops::String,
value: Box::new(StringVal(module.name.clone())),
expr_id: ast.expr_id.clone(),
functions,
var_id,
});
}
/*
* Handle if block
*/
Ops::WhileDef => {
let while_block = downcast_val::<While>(operation.as_self());
let check_while = |while_block: &While| -> Option<BoxedValue> {
/*
* Evaluate all conditions,
* If all they return true then execute the IF's expression block
*/
let mut true_count = 0;
for condition in while_block.conditions.clone() {
let res =
eval_condition(condition.relation, condition.left, condition.right);
if res {
true_count += 1;
}
}
if true_count == while_block.conditions.len() {
let expr = Expression::from_body(while_block.body.clone());
let expr_id = expr.expr_id.clone();
// Execute the expression block
let if_block_return = run_ast(&Mutex::new(expr), stack);
/*
* While's loop will stop when something is returned forcefully
*/
if let Some(if_block_return) = if_block_return {
return Some(if_block_return);
}
// Clean the expression definitions from the stack
stack.lock().unwrap().drop_ops_from_id(expr_id);
Some(BoxedValue {
value: Box::new(StringVal("while".to_string())),
interface: Ops::WhileDef,
})
} else {
None
}
};
let mut stopped = false;
while !stopped {
let res = check_while(while_block);
if let Some(res) = res {
match res.interface {
Ops::WhileDef => {
// Ignore non-returning whiles
}
Ops::Break => {
// Simply stop the while
stopped = true;
}
_ => {
// Stop and return the value
return Some(res);
}
}
} else {
stopped = true;
}
}
}
/*
* Handle return statements
*/
Ops::Return => {
let statement = downcast_val::<ReturnStatement>(operation.as_self());
// Type of return
let return_type = statement.value.interface;
// Value returning
let return_val = statement.value.value.clone();
// Pimitive value to return
let return_val = resolve_ref(return_type, return_val);
return return_val;
}
/*
* Handle if statements
*/
Ops::IfConditional => {
let if_statement = downcast_val::<IfConditional>(operation.as_self());
/*
* Evaluate all conditions,
* If all they return true then execute the IF's expression block
*/
let mut true_count = 0;
for condition in if_statement.conditions.clone() {
let res = eval_condition(condition.relation, condition.left, condition.right);
if res {
true_count += 1;
}
}
if true_count == if_statement.conditions.len() {
let expr = Expression::from_body(if_statement.body.clone());
let expr_id = expr.expr_id.clone();
// Execute the expression block
let if_block_return = run_ast(&Mutex::new(expr), stack);
if let Some(if_block_return) = if_block_return {
return Some(if_block_return);
}
// Clean the expression definitions from the stack
stack.lock().unwrap().drop_ops_from_id(expr_id.clone());
}
}
/*
* Handle function definitions
*/
Ops::FnDef => {
let function = downcast_val::<FnDefinition>(operation.as_self());
stack
.lock()
.unwrap()
.push_function(get_function_from_def(function));
}
/*
* Handle variables definitions
*/
Ops::VarDef => {
let variable = downcast_val::<VarDefinition>(operation.as_self());
let val_type = variable.assignment.interface;
let ref_val = variable.assignment.value.clone();
let var_ref = resolve_ref(val_type, ref_val);
if let Some(var_ref) = var_ref {
// Take a id for the stack
let var_id = stack.lock().unwrap().reseve_index();
// Push the variable into the stack
stack.lock().unwrap().push_variable(VariableDef {
name: variable.def_name.clone(),
val_type: var_ref.interface,
value: var_ref.value,
expr_id: ast.expr_id.clone(),
functions: get_methods_in_type(var_ref.interface),
var_id,
});
}
}
/*
* Handle variable assignments
*/
Ops::VarAssign => {
let variable = downcast_val::<VarAssignment>(operation.as_self());
let is_pointer = variable.var_name.starts_with('&');
let variable_name = if is_pointer {
// Remove & from it's name
let mut variable_name = variable.var_name.clone();
variable_name.remove(0);
variable_name
} else {
variable.var_name.clone()
};
let ref_val = resolve_ref(
variable.assignment.interface,
variable.assignment.value.clone(),
);
if let Some(ref_val) = ref_val {
stack.lock().unwrap().modify_var(variable_name, ref_val);
}
}
/*
* Handle function calls
*/
Ops::FnCall => {
let fn_call = downcast_val::<FnCall>(operation.as_self());
let is_referenced = fn_call.reference_to.is_some();
let function = if is_referenced {
let reference_to = fn_call.reference_to.as_ref().unwrap();
let variable = stack
.lock()
.unwrap()
.get_variable_by_name(reference_to.as_str());
variable
.unwrap()
.get_function_by_name(fn_call.fn_name.as_str())
} else {
stack
.lock()
.unwrap()
.get_function_by_name(fn_call.fn_name.as_str())
};
// If the calling function is found
if let Some(function) = function {
let mut arguments = Vec::new();
if is_referenced {
let reference_to = fn_call.reference_to.as_ref().unwrap();
arguments.push(BoxedValue {
interface: Ops::String,
value: Box::new(StringVal(reference_to.to_string())),
});
}
for argument in &fn_call.arguments {
let arg_ref = resolve_ref(argument.interface, argument.value.clone());
if let Some(arg_ref) = arg_ref {
arguments.push(arg_ref);
} else {
// Broken argument
}
}
let res_func = (function.cb)(
function.arguments,
arguments.clone(),
function.body,
&stack,
&ast,
);
if let Some(ret_val) = res_func {
let val_stringified = value_to_string(ret_val, stack);
if let Ok(val_stringified) = val_stringified {
// The function returned something that ends up not being used, throw error
errors::raise_error(
errors::CODES::ReturnedValueNotUsed,
vec![
val_stringified,
fn_call.fn_name.clone(),
values_to_strings(arguments, stack).join(" "),
],
)
}
} else {
// No value returned, OK
}
}
}
_ => {
panic!("Unhandled code operation")
}
}
}
None
}
|
//! Compare the speed of rand implementations
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use libafl::bolts::rands::{
Lehmer64Rand, Rand, RomuDuoJrRand, RomuTrioRand, XorShift64Rand, Xoshiro256StarRand,
};
fn criterion_benchmark(c: &mut Criterion) {
let mut xorshift = XorShift64Rand::with_seed(1);
let mut xoshiro = Xoshiro256StarRand::with_seed(1);
let mut romu = RomuDuoJrRand::with_seed(1);
let mut lehmer = Lehmer64Rand::with_seed(1);
let mut romu_trio = RomuTrioRand::with_seed(1);
c.bench_function("xorshift", |b| b.iter(|| black_box(xorshift.next())));
c.bench_function("xoshiro", |b| b.iter(|| black_box(xoshiro.next())));
c.bench_function("romu", |b| b.iter(|| black_box(romu.next())));
c.bench_function("romu_trio", |b| b.iter(|| black_box(romu_trio.next())));
c.bench_function("lehmer", |b| b.iter(|| black_box(lehmer.next())));
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
use generics:: {
Summary,
Test,
Tweet,
};
#[derive(Debug)]
struct Point<T, U> {
x: T,
y: U,
}
impl<T, U> Point<T, U> {
fn x(&self) -> &T {
&self.x
}
fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
Point {
x: self.x,
y: other.y,
}
}
}
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &elem in list {
if elem > largest {
largest = elem;
}
}
largest
}
fn main() {
let nums = vec![34, 50, 25, 100, 65];
println!("Largest number is: {}", largest(&nums));
let chars = vec!['y', 'm', 'a', 'q'];
println!("Largest char is: {}", largest(&chars));
let pi = Point { x: 2, y: 4 };
let pf = Point { x: 2.5, y: 4.1 };
let pif = Point { x: 2, y: 4.1 };
let pfi = Point { x: 2.5, y: 4 };
println!("Test - pi: {:#?}, pf: {:#?}, pif: {:#?}, pfi: {:#?}", pi, pf, pif, pfi);
println!("pf.x = {}", pf.x());
println!("pi mixup pf == pif: {:#?}", pi.mixup(pf));
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());
let test = Test{};
println!("new test avialable: {}", test.summarize());
}
|
//! Manages a group of threads that all have the same return type and can be [join()]ed as a unit.
//!
//! The implementation uses a [mpsc channel] internaly so that children (spawned threads) can notify
//! the parent (owner of a [`ThreadGroup`]) that they are finished without the parent having to use
//! a blocking [`std::thread::JoinHandle.join()`] call.
//!
//! # Examples
//! ```rust
//! use std::thread::sleep;
//! use std::time::Duration;
//! use threadgroup::{JoinError, ThreadGroup};
//!
//! // Initialize a group of threads returning `u32`.
//! let mut tg: ThreadGroup<u32> = ThreadGroup::new();
//!
//! // Start a bunch of threads that'll return or panic after a while
//! tg.spawn::<_,u32>(|| {sleep(Duration::new(0,3000000));2});
//! tg.spawn::<_,u32>(|| {sleep(Duration::new(0,1500000));panic!()});
//! tg.spawn::<_,u32>(|| {sleep(Duration::new(10,0));3});
//! tg.spawn::<_,u32>(|| {sleep(Duration::new(0,1000000));1});
//!
//! // Join them in the order they finished
//! assert_eq!(1, tg.join().unwrap());
//! assert_eq!(JoinError::Panicked, tg.join().unwrap_err());
//! assert_eq!(2, tg.join().unwrap());
//! assert_eq!(JoinError::Timeout, tg.join_timeout(Duration::new(0,10000)).unwrap_err());
//! ```
//! [join()]: struct.ThreadGroup.html#method.join
//! [`ThreadGroup`]: struct.ThreadGroup.html
//! [mpsc channel]: https://doc.rust-lang.org/stable/std/sync/mpsc/index.html
//! [`std::thread::JoinHandle.join()`]: https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.join
//#![doc(html_playground_url = "https://play.rust-lang.org/")]
//#![doc(include = "README.md")]
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, RecvError, RecvTimeoutError, Sender};
use std::thread;
use std::thread::{JoinHandle, ThreadId};
use std::time::Duration;
/// Possible error returns from [`join()`] and [`join_timeout()`].
/// [`join()`]: struct.ThreadGroup.html#method.join
/// [`join_timeout()`]: struct.ThreadGroup.html#method.join_timeout
#[derive(Debug,PartialEq)]
pub enum JoinError {
/// Thread list is empty, nothing to join.
AllDone,
/// Joined thread has panicked, no result available.
Panicked,//FIXME: include panic::PanicInfo
/// No thread has finished yet.
Timeout,
/// Internal channel got disconnected (should not happen, only included for completeness).
Disconnected,
}
/// Holds the collection of threads and the notification channel.
/// All public functions operate on this struct.
pub struct ThreadGroup<T> {
tx: Sender<ThreadId>,
rx: Receiver<ThreadId>,
handles: Vec<JoinHandle<T>>,
}
/// Sends current thread id on its channel when it gets out of scope.
struct SendOnDrop {
tx: Sender<ThreadId>,
}
impl Drop for SendOnDrop {
fn drop(&mut self) {
self.tx.send(thread::current().id()).unwrap();
}
}
// TODO: Allow passing something during spawn() that'll be returned during join()
// TODO: check threads.len() on drop()
// TODO: join_all()
// TODO: iter() or into_iter()
impl<T> ThreadGroup<T> {
/// Initialize a group of threads returning `T`.
/// # Examples
/// ```rust
/// use threadgroup::ThreadGroup;
/// // spawning and joining require the struct to be mutable, and you'll need to provide type hints.
/// let mut tg: ThreadGroup<u32> = ThreadGroup::new();
/// ```
pub fn new() -> ThreadGroup<T> {
let (tx, rx): (Sender<ThreadId>, Receiver<ThreadId>) = mpsc::channel();
ThreadGroup::<T>{tx: tx, rx: rx, handles: vec![]}
}
/// Spawn a new thread, adding it to the ThreadGroup.
///
/// Operates like [`std::thread::spawn()`], but modifies the ThreadGroup instead of returning a [`JoinHandle`].
/// # Examples
/// ```rust
/// use std::time::Duration;
/// use std::thread::sleep;
/// use threadgroup::{JoinError, ThreadGroup};
/// let mut tg: ThreadGroup<u32> = ThreadGroup::new();
/// tg.spawn::<_,u32>(|| {sleep(Duration::new(0,1000000));1});
/// ```
/// [`std::thread::spawn()`]: https://doc.rust-lang.org/stable/std/thread/fn.spawn.html
/// [`JoinHandle`]: https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html
// FIXME: Is there a way to remove the need to specify the type when calling spawn() ?
// The ThreadGroup has type T and we know that R is the same type, but the compiler doesn't see that.
pub fn spawn<F, R>(&mut self, f: F)
where
F: FnOnce() -> T,
F: Send + 'static,
R: Send + 'static,
T: Send + 'static,
{
let thread_tx = self.tx.clone();
let jh: JoinHandle<T> = thread::spawn(move || {
let _sender = SendOnDrop{tx: thread_tx.clone()};
f()
});
self.handles.push(jh);
}
/// Return count of threads that have been [`spawn()`]ed but not yet [`join()`]ed.
/// [`spawn()`]: struct.ThreadGroup.html#method.spawn
/// [`join()`]: struct.ThreadGroup.html#method.join
pub fn len(&self) -> usize {
self.handles.len()
}
/// Check if there is any thread not yet [`join()`]ed.
/// [`join()`]: struct.ThreadGroup.html#method.join
pub fn is_empty(&self) -> bool {
self.handles.is_empty()
}
/// Join one thread of the ThreadGroup.
///
/// Operates like [`std::thread::JoinHandle.join()`], but picks the first thread that
/// terminates.
/// # Examples
/// ```rust
/// use threadgroup::ThreadGroup;
/// let mut tg: ThreadGroup<u32> = ThreadGroup::new();
/// while !tg.is_empty() {
/// match tg.join() {
/// Ok(ret) => println!("Thread returned {}", ret),
/// Err(e) => panic!("Oh noes !"),
/// }
/// }
/// ```
/// [`std::thread::JoinHandle.join()`]: https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.join
pub fn join(&mut self) -> Result<T, JoinError> {
match self.handles.is_empty() {
true => Err(JoinError::AllDone),
false => match self.rx.recv() {
Ok(id) => self.do_join(id),
Err(RecvError{}) => Err(JoinError::Disconnected)
}
}
}
/// Try to join one thread of the ThreadGroup.
///
/// Operates like [`std::thread::JoinHandle.join()`], but picks the first thread that terminates
/// and gives up if the timeout is reached.
/// # Examples
/// ```rust
/// use std::time::Duration;
/// use threadgroup::{JoinError, ThreadGroup};
/// let mut tg: ThreadGroup<u32> = ThreadGroup::new();
/// for _ in 0..10 {
/// if let Err(JoinError::Timeout) = tg.join_timeout(Duration::new(0,10000)) {
/// println!("Still working...");
/// }
/// }
/// ```
/// [`std::thread::JoinHandle.join()`]: https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.join
pub fn join_timeout(&mut self, timeout: Duration) -> Result<T, JoinError> {
match self.handles.is_empty() {
true => Err(JoinError::AllDone),
false => match self.rx.recv_timeout(timeout) {
Ok(id) => self.do_join(id),
Err(RecvTimeoutError::Timeout) => Err(JoinError::Timeout),
Err(RecvTimeoutError::Disconnected) => Err(JoinError::Disconnected)
}
}
}
/// Find a thread by its id.
// TODO: replace with https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#method.remove_item
fn find(&self, id: ThreadId) -> Option<usize> {
for (i,jh) in self.handles.iter().enumerate() {
if jh.thread().id() == id {
return Some(i)
}
}
None
}
/// Actual [`JoinHandle.join()`] once we know that the thread has finished.
/// [`JoinHandle.join()`]: https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html#method.join
fn do_join(&mut self, id: ThreadId) -> Result<T, JoinError> {
// We need to separately find and remove the JoinHandle from the vector in order to not upset the borrow checker
let i = self.find(id).unwrap();
match self.handles.remove(i).join() {
Ok(ret) => Ok(ret),
Err(_) => Err(JoinError::Panicked),
}
}
}
#[cfg(test)]
mod tests {
use std::thread::sleep;
use std::time::Duration;
use ::{JoinError, ThreadGroup};
#[test]
fn empty_group() {
let mut tg: ThreadGroup<u32> = ThreadGroup::new();
assert!(tg.is_empty());
assert_eq!(tg.len(), 0);
assert_eq!(JoinError::AllDone, tg.join().unwrap_err());
}
#[test]
fn basic_join() {
let mut tg: ThreadGroup<u32> = ThreadGroup::new();
tg.spawn::<_,u32>(|| {sleep(Duration::new(0,1000000));1});
tg.spawn::<_,u32>(|| {sleep(Duration::new(0,3000000));3});
tg.spawn::<_,u32>(|| {sleep(Duration::new(0,2000000));2});
assert_eq!(1, tg.join().unwrap());
assert_eq!(2, tg.join().unwrap());
assert_eq!(3, tg.join().unwrap());
assert_eq!(JoinError::AllDone, tg.join().unwrap_err());
}
#[test]
fn panic_join() {
let mut tg: ThreadGroup<u32> = ThreadGroup::new();
tg.spawn::<_,u32>(|| {sleep(Duration::new(0,1500000));panic!()});
tg.spawn::<_,u32>(|| {sleep(Duration::new(0,1000000));1});
assert_eq!(1, tg.join().unwrap());
assert_eq!(JoinError::Panicked, tg.join().unwrap_err());
assert_eq!(JoinError::AllDone, tg.join().unwrap_err());
}
#[test]
fn timeout_join() {
let mut tg: ThreadGroup<u32> = ThreadGroup::new();
tg.spawn::<_,u32>(|| {sleep(Duration::new(1000000,0));2});
tg.spawn::<_,u32>(|| {sleep(Duration::new(0,1000000));1});
let t = Duration::new(1,0);
assert_eq!(1, tg.join_timeout(t).unwrap());
assert_eq!(JoinError::Timeout, tg.join_timeout(t).unwrap_err());
assert!(!tg.is_empty());
assert_eq!(tg.len(), 1);
}
}
|
extern crate good_bye;
fn main() {
println!("Hello, world!");
good_bye::say();
}
|
use std::collections::BTreeMap;
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt::Debug;
#[derive(Clone, Debug)]
struct LoudVec<T>(Vec<T>, String);
impl<T: Debug> LoudVec<T> {
fn new(name: impl Into<String>) -> Self {
Self(vec![], name.into())
}
fn push(&mut self, value: T) {
print!("{}: Push {:?}; ", self.1, value);
self.0.push(value);
println!("vector is now {:?}", self.0);
}
fn pop(&mut self) -> Option<T> {
let value = self.0.pop();
println!("{}: Pop {:?}; vector is now {:?}", self.1, value, self.0);
value
}
}
impl<T> ::std::ops::Deref for LoudVec<T> {
type Target = Vec<T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> ::std::ops::DerefMut for LoudVec<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> IntoIterator for LoudVec<T> {
type Item = T;
type IntoIter = <Vec<T> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
struct Promise {
data: RefCell<Option<Result<(), String>>>,
children: RefCell<Vec<(Box<dyn FnOnce(&mut Modules)>, Box<dyn FnOnce(&mut Modules, String)>)>>,
}
impl Promise {
fn new(modules: &mut Modules) -> Rc<Self> {
let result = Rc::new(Self {
data: RefCell::new(None),
children: RefCell::new(Vec::new()),
});
modules.record(result.clone());
result
}
fn resolve(&self) {
let mut cell = self.data.borrow_mut();
assert_eq!(*cell, None);
*cell = Some(Ok(()));
}
fn reject(&self, error: String) {
let mut cell = self.data.borrow_mut();
assert_eq!(*cell, None);
*cell = Some(Err(error));
}
fn then(&self, resolve: Box<dyn FnOnce(&mut Modules)>, reject: Box<dyn FnOnce(&mut Modules, String)>) {
let mut children = self.children.borrow_mut();
children.push((resolve, reject));
}
fn tick(&self, modules: &mut Modules) {
if let Some(result) = &*self.data.borrow() {
println!("Tick: result={:?}, calling {} children", result, self.children.borrow().len());
for (resolve, reject) in self.children.borrow_mut().drain(..) {
match result {
Ok(()) => resolve(modules),
Err(e) => reject(modules, e.clone()),
}
}
}
}
}
impl std::fmt::Debug for Promise {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
"Promise".fmt(f)
}
}
#[derive(PartialOrd, Ord, PartialEq, Eq, Debug, Copy, Clone)]
enum Sync {
Sync,
Async,
}
#[derive(PartialOrd, Ord, PartialEq, Eq, Debug)]
enum Status {
Unlinked,
Linking,
Linked,
Evaluating,
Evaluated,
}
#[derive(Debug)]
struct Module {
name: String,
broken: bool,
status: Status,
error: Option<String>,
dfs_index : Option<usize>,
dfs_anc_index: Option<usize>,
requested: Vec<String>,
async_: Sync,
async_evaluating: bool,
apm: Option<LoudVec<String>>,
pad: Option<usize>,
promise: Option<Rc<Promise>>
}
#[derive(Debug)]
enum EvalResult {
Index(usize),
Error(String),
}
impl Module {
fn new(name: String, async_: Sync, requested: Vec<String>, broken: bool) -> Self {
Module {
name,
broken,
status: Status::Unlinked,
error: None,
dfs_index: None,
dfs_anc_index: None,
requested,
async_,
async_evaluating: false,
apm: None,
pad: None,
promise: None,
}
}
fn set_status(&mut self, status: Status) {
println!("Setting {} status from {:?} to {:?}", self.name, self.status, status);
assert!(status > self.status);
self.status = status;
}
fn set_anc_index(&mut self, dfs_anc_index: usize) {
println!("Setting [[DFSAncestorIndex]] for {} from {:?} to {}", self.name, self.dfs_anc_index, dfs_anc_index);
self.dfs_anc_index = Some(dfs_anc_index);
}
fn execute_module_sync(&self) -> Result<(), String> {
println!("execute_module_sync: {}", self.name);
assert_eq!(self.async_, Sync::Sync);
if self.broken {
Err(format!("Module {} failed sync", self.name))
} else {
Ok(())
}
}
fn execute_module_async(&self, capability: Rc<Promise>) {
println!("execute_module_async: {}", self.name);
assert_eq!(self.async_, Sync::Async);
if self.broken {
capability.reject(format!("Module {} failed async", self.name));
} else {
capability.resolve();
}
}
}
struct Modules {
modules: BTreeMap<String, Module>,
execution_order: Vec<String>,
promises: Vec<Rc<Promise>>,
}
impl Modules {
fn new() -> Self {
Modules {
modules: BTreeMap::new(),
execution_order: Vec::new(),
promises: Vec::new(),
}
}
fn record(&mut self, promise: Rc<Promise>) {
self.promises.push(promise);
}
fn tick(&mut self) {
for promise in self.promises.clone() {
promise.tick(self);
}
}
fn get(&self, name: &str) -> &Module {
self.modules.get(name).unwrap()
}
fn get_mut(&mut self, name: &str) -> &mut Module {
self.modules.get_mut(name).unwrap()
}
fn insert(&mut self, name: String, async_: Sync, requested: Vec<String>, broken: bool) {
self.modules.insert(name.clone(), Module::new(name, async_, requested, broken));
}
fn cycle_root(&self, module: &str) -> String {
println!("Fetching cycle root of {}", module);
assert_eq!(self.get(module).status, Status::Evaluated);
let mut module = module.to_owned();
if self.get(&module).apm.as_ref().unwrap().is_empty() {
return module;
}
while self.get(&module).dfs_index.unwrap() > self.get(&module).dfs_anc_index.unwrap() {
assert!(!self.get(&module).apm.as_ref().unwrap().is_empty(), "APM for {} is empty", module);
let next = self.get(&module).apm.as_ref().unwrap()[0].to_owned();
assert!(self.get(&next).dfs_anc_index.unwrap() <= self.get(&module).dfs_anc_index.unwrap());
module = next;
println!(" >> {}", module);
}
assert_eq!(self.get(&module).dfs_index, self.get(&module).dfs_anc_index);
println!(" result={}", module);
module
}
fn inner_module_linking(&mut self, name: &str, stack: &mut LoudVec<String>, index: usize) -> usize {
match &self.get(name).status {
// Step 2.
| s @ Status::Linking
| s @ Status::Linked
| s @ Status::Evaluated
=> {
println!("inner_module_linking: short circuit for {} with {:?}", name, s);
return index;
},
// Step 3.
| Status::Unlinked
=> (),
| s
=> panic!("Wrong status for {}: {:?}", name, s),
};
// Step 4.
self.get_mut(name).set_status(Status::Linking);
// Step 5.
self.get_mut(name).dfs_index = Some(index);
// Step 6.
self.get_mut(name).set_anc_index(index);
// Step 7.
let mut index = index + 1;
// Step 8.
stack.push(name.to_owned());
// Step 9.
for required in self.get(name).requested.clone() {
index = self.inner_module_linking(&required, stack, index);
match &self.get(&required).status {
| Status::Linking
=> {
assert!(stack.contains(&required));
let dfs_anc_index = self.get(name).dfs_anc_index.unwrap().min(self.get(&required).dfs_anc_index.unwrap());
self.get_mut(name).set_anc_index(dfs_anc_index);
},
| Status::Linked
| Status::Evaluated
=> {
assert!(!stack.contains(&required));
},
| s
=> panic!("Wrong status for {}: {:?}", required, s),
};
if self.get(&required).async_ == Sync::Async {
self.get_mut(name).async_ = Sync::Async;
}
}
// Step 10.
// Step 11.
assert_eq!(stack.iter().filter(|s| **s == name).count(), 1);
// Step 12.
assert!(self.get(name).dfs_anc_index.unwrap() <=
self.get(name).dfs_index.unwrap());
// Step 13.
if self.get(name).dfs_anc_index.unwrap() == self.get(name).dfs_index.unwrap() {
let mut done = false;
while !done {
let required = stack.pop().unwrap();
self.get_mut(&required).set_status(Status::Linked);
done = required == name;
}
}
// Step 14.
index
}
fn link(&mut self, name: &str) {
assert!(self.get(name).status != Status::Linking && self.get(name).status != Status::Evaluating);
let mut stack = LoudVec::new("Link stack");
self.inner_module_linking(name, &mut stack, 0);
match self.get(name).status {
| Status::Linked
| Status::Evaluated
=> (),
| ref s
=> panic!("Wrong status for {}: {:?}", name, s),
}
assert!(stack.is_empty());
}
fn fulfilled(&mut self, name: &str) {
println!("Fulfilled({})", name);
// Step 1.
match self.get(name).status {
| Status::Evaluated
=> (),
| ref s
=> panic!("Wrong status for {}: {:?}", name, s),
}
// Step 2.
if !self.get(name).async_evaluating {
// XXX why?
assert!(self.get(name).error.is_some());
return;
}
// Step 3.
assert!(self.get(name).error.is_none());
// Step 4.
self.get_mut(name).async_evaluating = false;
// Step 5.
for m in self.get(name).apm.clone().unwrap() {
println!(" > parent module {:?}", self.get(&m));
if self.get(name).dfs_index.unwrap() != self.get(name).dfs_anc_index.unwrap() {
assert!(self.get(&m).dfs_anc_index.unwrap() <= self.get(name).dfs_anc_index.unwrap());
}
assert!(self.get(&m).pad.unwrap() > 0);
*self.get_mut(&m).pad.as_mut().unwrap() -= 1;
if self.get(&m).pad.unwrap() == 0 && self.get(&m).error.is_none() {
assert!(self.get(&m).async_evaluating);
let root = self.cycle_root(&m);
if self.get(&root).error.is_some() {
return;
}
if self.get(&m).async_ == Sync::Async {
self.execute_cyclic_module(&m);
} else {
self.execution_order.push(m.to_owned());
let result = self.get(&m).execute_module_sync();
match result {
Ok(()) => self.fulfilled(&m),
Err(e) => self.rejected(&m, &e),
}
}
}
}
if let Some(promise) = self.get(name).promise.clone() {
assert_eq!(self.get(name).dfs_index, self.get(name).dfs_anc_index);
promise.resolve();
}
}
fn rejected(&mut self, name: &str, error: &str) {
println!("Rejected({})", name);
// Step 1.
match self.get(name).status {
| Status::Evaluated
=> (),
| ref s
=> panic!("Wrong status for {}: {:?}", name, s),
}
// Step 2.
if !self.get(name).async_evaluating {
// XXX why?
assert!(self.get(name).error.is_some());
return;
}
// Step 3.
assert_eq!(self.get(name).error, None);
// Step 4.
self.get_mut(name).error = Some(error.to_owned());
// Step 5.
self.get_mut(name).async_evaluating = false;
// Step 6.
for m in self.get(name).apm.clone().unwrap() {
if self.get(name).dfs_index.unwrap() != self.get(name).dfs_anc_index.unwrap() {
assert_eq!(self.get(&m).dfs_anc_index.unwrap(), self.get(name).dfs_anc_index.unwrap());
}
self.rejected(&m, error);
}
if let Some(promise) = self.get(name).promise.clone() {
assert_eq!(self.get(name).dfs_index, self.get(name).dfs_anc_index);
promise.reject(error.to_owned());
}
}
fn execute_cyclic_module(&mut self, name: &str) {
println!("Execute cyclic module: {}", name);
match &self.get(name).status {
| Status::Evaluating
| Status::Evaluated
=> (),
| s
=> panic!("Wrong status for {}: {:?}", name, s),
}
self.get_mut(name).async_evaluating = true;
self.execution_order.push(name.to_owned());
if self.get(name).async_ == Sync::Sync {
let result = self.get(name).execute_module_sync();
match result {
Ok(()) => self.fulfilled(name),
Err(e) => self.rejected(name, &e),
}
} else {
let capability = Promise::new(self);
let name1 = name.to_owned();
let name2 = name.to_owned();
capability.then(
Box::new(move |modules| modules.fulfilled(&name1)),
Box::new(move |modules, error| modules.rejected(&name2, &error)),
);
self.get(name).execute_module_async(capability.clone());
}
}
fn inner_module_evaluation(&mut self, name: &str, stack: &mut LoudVec<String>, index: usize) -> EvalResult {
match &self.get(name).status {
// Step 2.
| Status::Evaluated
=> {
return match &self.get(name).error {
Some(error) => EvalResult::Error(error.clone()),
None => EvalResult::Index(index)
};
},
// Step 3.
| Status::Evaluating
=> return EvalResult::Index(index),
// Step 4.
| Status::Linked
=> (),
| s
=> panic!("Wrong status for {}: {:?}", name, s),
}
// Step 5.
self.get_mut(name).set_status(Status::Evaluating);
// Step 6.
self.get_mut(name).dfs_index = Some(index);
// Step 7.
self.get_mut(name).set_anc_index(index);
// Step 8.
self.get_mut(name).pad = Some(0);
// Step 9.
self.get_mut(name).apm = Some(LoudVec::new(format!("{}.[[AsyncParentModules]]", name)));
// Step 10.
let mut index = index + 1;
// Step 11.
stack.push(name.to_owned());
// Step 12.
for required in self.get(name).requested.clone() {
index = match self.inner_module_evaluation(&required, stack, index) {
EvalResult::Error(error) => return EvalResult::Error(error),
EvalResult::Index(index) => index,
};
let required = match &self.get(&required).status {
| Status::Evaluating
=> {
assert!(stack.contains(&required));
let dfs_anc_index = self.get(name).dfs_anc_index.unwrap().min(self.get(&required).dfs_anc_index.unwrap());
self.get_mut(name).set_anc_index(dfs_anc_index);
required
},
| Status::Evaluated
=> {
assert!(!stack.contains(&required));
let root = self.cycle_root(&required);
assert_eq!(self.get(&root).status, Status::Evaluated);
if let Some(error) = &self.get(&required).error {
return EvalResult::Error(error.clone());
}
root
},
| s
=> panic!("Wrong status for {}: {:?}", required, s),
};
println!("Considering registering async dependency {} -> {}", name, required);
println!(" module = {:?}", self.get(&name));
println!(" required = {:?}", self.get(&required));
if self.get(&required).async_evaluating {
*self.get_mut(name).pad.as_mut().unwrap() += 1;
self.get_mut(&required).apm.as_mut().unwrap().push(name.to_owned());
}
}
// Step 14
println!("{}.PAD = {}", name, self.get(&name).pad.unwrap());
if self.get(&name).pad.unwrap() > 0 {
self.get_mut(&name).async_evaluating = true;
} else if self.get(&name).async_ == Sync::Async {
self.execute_cyclic_module(name);
} else {
self.execution_order.push(name.to_owned());
let result = self.get(name).execute_module_sync();
match result {
Ok(()) => (),
Err(e) => return EvalResult::Error(e),
}
}
// Step 15.
assert_eq!(stack.iter().filter(|s| **s == name).count(), 1);
// Step 16.
assert!(self.get(name).dfs_anc_index.unwrap() <=
self.get(name).dfs_index.unwrap());
// Step 17.
if self.get(name).dfs_anc_index.unwrap() == self.get(name).dfs_index.unwrap() {
let mut done = false;
while !done {
let required = stack.pop().unwrap();
self.get_mut(&required).set_status(Status::Evaluated);
done = required == name;
}
}
// Step 18.
EvalResult::Index(index)
}
fn evaluate(&mut self, name: &str) -> Rc<Promise> {
let name = match &self.get(name).status {
| Status::Linked
=> name.to_owned(),
// Step 3.
| Status::Evaluated
=> self.cycle_root(name),
// Step 2.
| s
=> panic!("Wrong status for {}: {:?}", name, s),
};
// Step 4.
if let Some(promise) = self.get(&name).promise.clone() {
return promise;
}
// Step 5.
let mut stack = LoudVec::new("Evaluate stack");
// Step 6.
let promise = Promise::new(self);
// Step 7.
self.get_mut(&name).promise = Some(promise.clone());
// Step 8.
let result = self.inner_module_evaluation(&name, &mut stack, 0);
println!("Result for {}: {:?}", name, result);
match result {
// Step 9.
EvalResult::Error(e) => {
println!("Found error with stack {:?}", stack);
for m in stack.iter() {
assert_eq!(self.get(&m).status, Status::Evaluating);
self.get_mut(&m).set_status(Status::Evaluated);
match &self.get(&m).error {
Some(err) => assert_eq!(err, &e),
None => (),
}
self.get_mut(&m).error = Some(e.clone());
}
let r = promise.data.borrow().is_none();
if r {
promise.reject(e.clone());
}
assert_eq!(self.get(&name).status, Status::Evaluated);
assert!(self.get(&name).error.is_some());
assert_eq!(*self.get(&name).error.as_ref().unwrap(), e);
},
// Step 10.
EvalResult::Index(_) => {
assert!(self.get(&name).status == Status::Evaluated);
assert!(self.get(&name).error.is_none());
assert!(stack.is_empty());
if !self.get(&name).async_evaluating {
promise.resolve();
}
},
}
// Step 11.
promise
}
}
fn run(modules: &mut Modules, name: &str) -> Rc<Promise> {
println!(">>> Link");
modules.link(name);
for (k, v) in &mut modules.modules {
println!("Module {}: DFSIndex={:?} DFSAncestorIndex={:?} Async={:?}", k, v.dfs_index, v.dfs_anc_index, v.async_);
}
println!(">>> Evaluate");
let promise = modules.evaluate(name);
for (k, v) in &modules.modules {
assert_ne!(v.status, Status::Evaluating, "{}", k);
println!("{:?}", v);
}
println!("=================");
promise
}
#[cfg(test)]
fn check(modules: &mut Modules, expected: &[(&[&str], &[&str])]) {
let mut all_started: Vec<&str> = vec![];
let mut all_finished: Vec<&str> = vec![];
for (started, finished) in expected {
all_started.extend(*started);
all_finished.extend(*finished);
assert_eq!(modules.execution_order, all_started);
for m in modules.modules.values() {
assert_eq!(m.async_evaluating, !all_finished.contains(&&*m.name));
assert_eq!(m.status, Status::Evaluated);
assert!(m.error.is_none());
}
modules.tick();
}
}
#[test]
fn example1() {
println!("Example 1");
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["A".to_owned(), "D".to_owned(), "E".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec![], false);
modules.insert("D".to_owned(), Sync::Async, vec![], false);
modules.insert("E".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["D", "E", "C"], &[]),
(&["B"], &["D", "E", "C"]),
(&["A"], &["B"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example2() {
println!("Example 2");
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["A".to_owned()], false);
modules.insert("C".to_owned(), Sync::Sync, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["B", "C"], &["C"]),
(&["A"], &["B"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example2b() {
println!("Example 2");
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["A".to_owned(), "C".to_owned()], false);
modules.insert("C".to_owned(), Sync::Sync, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["C", "B"], &["C"]),
(&["A"], &["B"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example3() {
println!("Example 3");
let mut modules = Modules::new();
modules.insert("B".to_owned(), Sync::Sync, vec![], true);
run(&mut modules, "B");
}
#[test]
fn example4() {
println!("Example 4");
let mut modules = Modules::new();
// modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned(), "D".to_owned()], false);
// modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["C".to_owned()], false);
// modules.insert("B".to_owned(), Sync::Sync, vec!["C".to_owned()], false);
modules.insert("C".to_owned(), Sync::Sync, vec![], true);
// modules.insert("D".to_owned(), Sync::Sync, vec![], false);
run(&mut modules, "B");
modules.evaluate("B");
// modules.evaluate("C");
// modules.evaluate("D");
}
#[test]
fn example5() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["D"], &[]),
(&["B", "C"], &["D"]),
(&["A"], &["B", "C"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example6() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["A".to_owned()], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["B"], &[]),
(&["A"], &["B"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example7() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["A".to_owned(), "C".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["C"], &[]),
(&["B"], &["C"]),
(&["A"], &["B"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example_single_broken_sync() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Sync, vec![], true);
run(&mut modules, "A");
assert_eq!(modules.execution_order, &[
"A".to_owned(),
]);
for m in modules.modules.values() {
assert_eq!(m.status, Status::Evaluated);
assert!(m.error.is_some());
}
}
#[test]
fn example_single_broken_async() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec![], true);
run(&mut modules, "A");
assert_eq!(modules.execution_order, &[
"A".to_owned(),
]);
for m in modules.modules.values() {
assert_eq!(m.status, Status::Evaluated);
assert!(m.error.is_none());
}
modules.tick();
for m in modules.modules.values() {
assert_eq!(m.status, Status::Evaluated);
assert!(m.error.is_some());
}
}
#[test]
fn example_guy() {
println!("Example Guy");
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned(), "E".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec!["A".to_owned()], false);
modules.insert("E".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["D", "E"], &[]),
(&["B", "C"], &["D", "E"]),
(&["A"], &["B", "C"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example_common_dep() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["D"], &[]),
(&["B", "C"], &["D"]),
(&["A"], &["B", "C"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example_common_dep_cycle() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec!["A".to_owned()], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["D"], &[]),
(&["B", "C"], &["D"]),
(&["A"], &["B", "C"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example_common_dep_cycle_2() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec!["A".to_owned(), "F".to_owned()], false);
modules.insert("F".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["F"], &[]),
(&["D"], &["F"]),
(&["B", "C"], &["D"]),
(&["A"], &["B", "C"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example_common_dep_cycle_2b() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec!["A".to_owned(), "F".to_owned()], false);
modules.insert("F".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "F");
assert_eq!(modules.execution_order, &[
"F".to_owned(),
]);
assert_eq!(modules.modules["F"].status, Status::Evaluated);
assert!(modules.modules["F"].async_evaluating);
modules.tick();
assert_eq!(modules.modules["F"].status, Status::Evaluated);
assert!(!modules.modules["F"].async_evaluating);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["F", "D"], &["F"]),
(&["B", "C"], &["D"]),
(&["A"], &["B", "C"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example_common_dep_cycle_2c() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec!["A".to_owned(), "F".to_owned()], false);
modules.insert("F".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "F");
assert_eq!(modules.execution_order, &[
"F".to_owned(),
]);
assert_eq!(modules.modules["F"].status, Status::Evaluated);
assert!(modules.modules["F"].async_evaluating);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["F"], &[]),
(&["D"], &["F"]),
(&["B", "C"], &["D"]),
(&["A"], &["B", "C"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example_common_dep_cycle_2d() {
let mut modules = Modules::new();
modules.insert("E".to_owned(), Sync::Async, vec!["A".to_owned()], false);
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec!["A".to_owned(), "F".to_owned()], false);
modules.insert("F".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "F");
assert_eq!(modules.execution_order, &[
"F".to_owned(),
]);
assert_eq!(modules.modules["F"].status, Status::Evaluated);
assert!(modules.modules["F"].async_evaluating);
run(&mut modules, "E");
let expected: &[(&[&str], &[&str])] = &[
(&["F"], &[]),
(&["D"], &["F"]),
(&["B", "C"], &["D"]),
(&["A"], &["B", "C"]),
(&["E"], &["A"]),
(&[], &["E"]),
];
check(&mut modules, expected);
}
#[test]
fn example_common_dep_cycle_3() {
let mut modules = Modules::new();
modules.insert("E".to_owned(), Sync::Async, vec!["A".to_owned()], false);
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec!["A".to_owned(), "F".to_owned()], false);
modules.insert("F".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "E");
let expected: &[(&[&str], &[&str])] = &[
(&["F"], &[]),
(&["D"], &["F"]),
(&["B", "C"], &["D"]),
(&["A"], &["B", "C"]),
(&["E"], &["A"]),
(&[], &["E"]),
];
check(&mut modules, expected);
}
#[test]
fn spec_example_1() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Sync, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Sync, vec!["C".to_owned()], false);
modules.insert("C".to_owned(), Sync::Sync, vec![], false);
let promise = run(&mut modules, "A");
assert!(promise.data.borrow().as_ref().unwrap().is_ok());
let expected: &[(&[&str], &[&str])] = &[
(&["C", "B", "A"], &["C", "B", "A"]),
(&[], &[]),
];
check(&mut modules, expected);
}
#[test]
fn spec_example_2() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Sync, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Sync, vec!["C".to_owned()], true);
modules.insert("C".to_owned(), Sync::Sync, vec![], false);
let promise = run(&mut modules, "A");
assert!(promise.data.borrow().as_ref().unwrap().is_err());
assert_eq!(modules.execution_order, &[
"C".to_owned(),
"B".to_owned(),
]);
for m in modules.modules.values() {
assert_eq!(m.status, Status::Evaluated);
assert!(!m.async_evaluating);
assert_eq!(m.error.is_none(), m.name == "C");
}
}
#[test]
fn spec_example_3() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Sync, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Sync, vec!["A".to_owned()], false);
modules.insert("C".to_owned(), Sync::Sync, vec![], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["B", "C", "A"], &["B", "C", "A"]),
(&[], &[]),
];
check(&mut modules, expected);
}
#[test]
fn spec_example_4() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Sync, vec!["B".to_owned(), "C".to_owned()], true);
modules.insert("B".to_owned(), Sync::Sync, vec!["A".to_owned()], false);
modules.insert("C".to_owned(), Sync::Sync, vec![], false);
run(&mut modules, "A");
assert_eq!(modules.execution_order, &[
"B".to_owned(),
"C".to_owned(),
"A".to_owned(),
]);
for m in modules.modules.values() {
assert_eq!(m.status, Status::Evaluated);
assert!(!m.async_evaluating);
assert_eq!(m.error.is_none(), m.name == "C");
}
}
#[test]
fn spec_example_4_modified() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Sync, vec!["B".to_owned()], true);
modules.insert("B".to_owned(), Sync::Sync, vec!["A".to_owned()], false);
run(&mut modules, "A");
assert_eq!(modules.execution_order, &[
"B".to_owned(),
"A".to_owned(),
]);
for m in modules.modules.values() {
assert_eq!(m.status, Status::Evaluated);
assert!(!m.async_evaluating);
assert_eq!(m.error.is_none(), m.name == "C");
}
}
#[test]
fn example_cycle() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Sync, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "B");
assert_eq!(modules.execution_order, &[
"B".to_owned(),
]);
assert_eq!(modules.modules["B"].status, Status::Evaluated);
modules.tick();
assert_eq!(modules.modules["B"].status, Status::Evaluated);
modules.link("A");
modules.evaluate("A");
let expected: &[(&[&str], &[&str])] = &[
(&["B", "A"], &["B"]),
(&[], &["A"]),
];
check(&mut modules, expected);
}
#[test]
fn example_super_cycle() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["C".to_owned()], false);
modules.insert("C".to_owned(), Sync::Async, vec!["D".to_owned(), "E".to_owned()], false);
modules.insert("D".to_owned(), Sync::Async, vec!["F".to_owned()], false);
modules.insert("E".to_owned(), Sync::Async, vec!["A".to_owned()], false);
modules.insert("F".to_owned(), Sync::Async, vec!["B".to_owned()], false);
run(&mut modules, "A");
let expected: &[(&[&str], &[&str])] = &[
(&["F", "E"], &[]),
(&["D"], &["F", "E"]),
(&["C"], &["D"]),
(&["B"], &["C"]),
(&["A"], &["B"]),
(&[], &["A"]),
];
assert_eq!(modules.cycle_root("F"), "A");
check(&mut modules, expected);
}
#[test]
fn two_step() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Async, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec![], false);
run(&mut modules, "B");
assert_eq!(modules.execution_order, &[
"B".to_owned(),
]);
assert_eq!(modules.modules["B"].status, Status::Evaluated);
assert!(modules.modules["B"].async_evaluating);
modules.tick();
assert_eq!(modules.modules["B"].status, Status::Evaluated);
assert!(!modules.modules["B"].async_evaluating);
run(&mut modules, "A");
assert_eq!(modules.modules["A"].status, Status::Evaluated);
assert!(modules.modules["A"].async_evaluating);
modules.tick();
assert_eq!(modules.modules["A"].status, Status::Evaluated);
assert!(!modules.modules["A"].async_evaluating);
}
#[test]
fn cycle_error_persistence() {
let mut modules = Modules::new();
modules.insert("A".to_owned(), Sync::Sync, vec!["B".to_owned(), "C".to_owned()], false);
modules.insert("B".to_owned(), Sync::Async, vec!["A".to_owned()], true);
modules.insert("C".to_owned(), Sync::Sync, vec![], true);
run(&mut modules, "A");
let error = modules.modules["C"].error.clone();
assert!(error.is_some());
for m in modules.modules.values() {
assert_eq!(m.status, Status::Evaluated);
assert_eq!(m.error, error);
}
}
#[test]
fn synchronous_cycles_121() {
let mut modules = Modules::new();
modules.insert("Top".to_owned(), Sync::Sync, vec!["A".to_owned(), "B".to_owned()], false);
modules.insert("A".to_owned(), Sync::Sync, vec!["B".to_owned()], false);
modules.insert("B".to_owned(), Sync::Sync, vec!["A".to_owned()], false);
run(&mut modules, "Top");
let expected: &[(&[&str], &[&str])] = &[
(&["B", "A", "Top"], &["B", "A", "Top"]),
];
check(&mut modules, expected);
}
fn main() {
}
|
extern crate anthologion;
use anthologion::psalter;
fn main() {
println!("Hello");
let psalm = psalter::get_psalm(1);
println!("{}", psalm.to_string());
}
|
#[macro_use]
extern crate trackable;
#[macro_use]
extern crate lazy_static;
use clap::{App, Arg};
use dialoguer::{theme::ColorfulTheme, Select};
use indicatif::ProgressBar;
use m3u8_rs::{playlist::MasterPlaylist, playlist::MediaPlaylist, playlist::Playlist};
use mpeg2ts::ts::{ReadTsPacket, TsPacketReader, TsPacketWriter, WriteTsPacket};
use std::{fs::File, io::Read, path::Path};
lazy_static! {
static ref CLIENT: reqwest::Client = reqwest::Client::new();
}
struct M3U8 {
input_buffer: Vec<u8>,
output_file_name: String,
}
impl M3U8 {
/// Creation
// Process a M3U8 path in the file system
pub fn from_fs<P: AsRef<Path>, U: Into<String>>(path: P, ofn: U) -> Self {
let mut file = File::open(path).unwrap();
let mut input_buffer: Vec<u8> = Vec::new();
file.read_to_end(&mut input_buffer).unwrap();
Self {
input_buffer,
output_file_name: ofn.into(),
}
}
// Process a M3U8 path from a URL
pub fn from_url<U: Into<String>>(_url: U, _output_file_name: U) -> Self {
unimplemented!()
}
// Process straight from a byte array
pub fn from_memory<U: Into<String>>(input_buffer: Vec<u8>, ofn: U) -> Self {
Self {
input_buffer,
output_file_name: ofn.into(),
}
}
/// Utils
fn download_ts(uri: &String) -> Result<Vec<u8>, reqwest::Error> {
let mut buffer: Vec<u8> = Vec::new();
CLIENT.get(uri).send()?.read_to_end(&mut buffer).unwrap();
Ok(buffer)
}
fn download_m3u8(uri: &String) -> Result<Vec<u8>, reqwest::Error> {
let text = reqwest::get(uri)?.text()?;
Ok(Vec::from(text.as_bytes()))
}
/// Processing
fn process_master_playlist(&mut self, mp: &MasterPlaylist) {
let mut variants: Vec<&String> = Vec::new();
let mut uris: Vec<&String> = Vec::new();
for variant in &mp.variants {
match &variant.resolution {
Some(r) => {
variants.push(&r);
uris.push(&variant.uri);
}
_ => {}
}
}
variants.reverse();
uris.reverse();
let selection = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Choose a resolution to download")
.default(0)
.items(&variants[..])
.interact()
.unwrap();
let m3u8_buffer = Self::download_m3u8(uris[selection]).unwrap();
let mut m3u8 = M3U8::from_memory(m3u8_buffer, self.output_file_name.clone());
m3u8.process();
}
fn process_media_playlist(&mut self, mp: &MediaPlaylist) {
let pb = ProgressBar::new(mp.segments.len() as u64);
let output_file = File::create(&self.output_file_name).unwrap();
let mut writer = TsPacketWriter::new(output_file);
for segment in &mp.segments {
let buffer = Self::download_ts(&segment.uri);
let mem = match buffer {
Ok(b) => b,
e => panic!("Error when downloading stream blobs: {:#?}", e),
};
let mut reader = TsPacketReader::new(mem.as_slice());
while let Some(packet) = track_try_unwrap!(reader.read_ts_packet()) {
track_try_unwrap!(writer.write_ts_packet(&packet));
}
pb.inc(1);
}
pb.finish_with_message("Finished downloading!")
}
pub fn process(&mut self) {
match m3u8_rs::parse_playlist_res(&self.input_buffer) {
Ok(Playlist::MasterPlaylist(pl)) => self.process_master_playlist(&pl),
Ok(Playlist::MediaPlaylist(pl)) => self.process_media_playlist(&pl),
Err(e) => println!("Error: {:#?}", e),
}
}
}
fn main() {
let matches = App::new("m3u8-dl")
.version("0.101")
.about("Downloads m3u8 playlist video/audio from file or net")
.arg(
Arg::with_name("file")
.short("f")
.long("file")
.value_name("FILE")
.help("Load a m3u8 file from the file system"),
)
.arg(
Arg::with_name("url")
.short("u")
.long("url")
.value_name("URL")
.help("Load a m3u8 file from a URL"),
)
.arg(
Arg::with_name("path")
.short("p")
.long("path")
.value_name("PATH")
.default_value("output.ts")
.help("Specify the output of the downloaded video"),
)
.get_matches();
match matches.value_of("file") {
Some(path) => {
let mut m3u8 = M3U8::from_fs(path, matches.value_of("path").unwrap());
m3u8.process();
}
None => {}
}
match matches.value_of("url") {
Some(url) => {
let mut m3u8 = M3U8::from_url(url, matches.value_of("path").unwrap());
m3u8.process();
}
None => {}
}
}
|
use serde_derive::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MinerConfig {
pub rpc_url: String,
pub poll_interval: u64,
pub block_on_submit: bool,
pub threads: usize,
} |
use bindgen::builder;
use std::env;
use std::path::PathBuf;
fn main() {
let root_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
let library_dir: PathBuf = root_dir.join("cxop");
println!(
"cargo:rustc-link-search=native={}",
library_dir.to_str().unwrap()
);
println!("cargo:rustc-link-search=native=C:/Windows/System32");
// Link the static XOPSupport and dynamically link the imported Igor functions.
// Note: We also need to link in some standard windows libraries.
println!("cargo:rustc-link-lib=dylib=version");
println!("cargo:rustc-link-lib=dylib=Comdlg32");
println!("cargo:rustc-link-lib=dylib=User32");
println!("cargo:rustc-link-lib=static=XOPSupport64");
println!("cargo:rustc-link-lib=dylib=IGOR64");
// Stop the host from rebuilding when not needed.
println!("cargo:rerun-if-changed=build.rs");
let bindings = builder()
.header("wrapper.h")
.clang_args(vec!["-DWINIGOR","-DIGOR64","-D_WIN64","-xc++","-Icxop"])
.detect_include_paths(true)
.layout_tests(false)
.ctypes_prefix("libc")
.raw_line("use libc;")
.generate()
.expect("Failed to generate bindings.");
//
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
} |
use framework::{App, Canvas};
mod framework;
struct Counter {
count: isize,
}
impl App for Counter {
type State = isize;
fn init() -> Self {
Self {
count: 0,
}
}
fn draw(&mut self) {
let canvas = Canvas::new();
canvas.draw_rect(0.0, 0.0, 300 as f32, 100 as f32);
canvas.draw_str(&format!("Count: {}", self.count), 40.0, 50.0);
}
fn on_click(&mut self) {
self.count += 1;
}
fn get_state(&self) -> Self::State {
self.count
}
fn set_state(&mut self, state: Self::State) {
self.count = state;
}
}
app!(Counter);
|
pub mod glulx;
|
//! Contains the error type used by `Server`
use crate::BoxError;
use std::net::AddrParseError;
use thiserror::Error;
/// Error returned by the [`Server.listen`](crate::Server::listen()) method
#[derive(Error, Debug)]
#[error("server error: {msg}")]
pub struct ServerError {
msg: String,
#[source]
source: BoxError,
}
impl ServerError {
fn new<E: std::error::Error + Send + Sync + 'static>(msg: impl Into<String>, source: E) -> ServerError {
ServerError {
msg: msg.into(),
source: Box::new(source),
}
}
}
impl From<AddrParseError> for ServerError {
fn from(e: AddrParseError) -> Self {
ServerError::new("could not parse address", e)
}
}
impl From<std::io::Error> for ServerError {
fn from(e: std::io::Error) -> Self {
ServerError::new("io error", e)
}
}
impl From<super::tls::ConfigError> for ServerError {
fn from(e: super::tls::ConfigError) -> Self {
ServerError::new(format!("error with TLS configuration: {}", e), e)
}
}
#[derive(Error, Debug)]
#[error("shutdown error: {msg}")]
pub struct ShutdownError {
pub msg: String,
}
impl From<ShutdownError> for ServerError {
fn from(e: ShutdownError) -> Self {
ServerError::new("shutdown error", e)
}
}
|
use super::{Token, TokenFilter, TokenStream};
use rust_stemmers::{self, Algorithm};
use std::sync::Arc;
/// `Stemmer` token filter. Currently only English is supported.
/// Tokens are expected to be lowercased beforehands.
#[derive(Clone)]
pub struct Stemmer {
stemmer_algorithm: Arc<Algorithm>,
}
impl Stemmer {
/// Creates a new Stemmer `TokenFilter`.
pub fn new() -> Stemmer {
Stemmer {
stemmer_algorithm: Arc::new(Algorithm::English),
}
}
}
impl<TailTokenStream> TokenFilter<TailTokenStream> for Stemmer
where
TailTokenStream: TokenStream,
{
type ResultTokenStream = StemmerTokenStream<TailTokenStream>;
fn transform(&self, token_stream: TailTokenStream) -> Self::ResultTokenStream {
let inner_stemmer = rust_stemmers::Stemmer::create(Algorithm::English);
StemmerTokenStream::wrap(inner_stemmer, token_stream)
}
}
pub struct StemmerTokenStream<TailTokenStream>
where
TailTokenStream: TokenStream,
{
tail: TailTokenStream,
stemmer: rust_stemmers::Stemmer,
}
impl<TailTokenStream> TokenStream for StemmerTokenStream<TailTokenStream>
where
TailTokenStream: TokenStream,
{
fn token(&self) -> &Token {
self.tail.token()
}
fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
fn advance(&mut self) -> bool {
if self.tail.advance() {
// TODO remove allocation
let stemmed_str: String = self.stemmer.stem(&self.token().text).into_owned();
self.token_mut().text.clear();
self.token_mut().text.push_str(&stemmed_str);
true
} else {
false
}
}
}
impl<TailTokenStream> StemmerTokenStream<TailTokenStream>
where
TailTokenStream: TokenStream,
{
fn wrap(
stemmer: rust_stemmers::Stemmer,
tail: TailTokenStream,
) -> StemmerTokenStream<TailTokenStream> {
StemmerTokenStream { tail, stemmer }
}
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// SyntheticsApiTestConfig : Configuration object for a Synthetic API test.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyntheticsApiTestConfig {
/// Array of assertions used for the test.
#[serde(rename = "assertions")]
pub assertions: Vec<crate::models::SyntheticsAssertion>,
/// Array of variables used for the test.
#[serde(rename = "configVariables", skip_serializing_if = "Option::is_none")]
pub config_variables: Option<Vec<crate::models::SyntheticsConfigVariable>>,
#[serde(rename = "request", skip_serializing_if = "Option::is_none")]
pub request: Option<Box<crate::models::SyntheticsTestRequest>>,
/// When the test subtype is `multi`, the steps of the test.
#[serde(rename = "steps", skip_serializing_if = "Option::is_none")]
pub steps: Option<Vec<crate::models::SyntheticsApiStep>>,
}
impl SyntheticsApiTestConfig {
/// Configuration object for a Synthetic API test.
pub fn new(assertions: Vec<crate::models::SyntheticsAssertion>) -> SyntheticsApiTestConfig {
SyntheticsApiTestConfig {
assertions,
config_variables: None,
request: None,
steps: None,
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.