text stringlengths 8 4.13M |
|---|
use criterion::{criterion_group, criterion_main, Criterion};
//use printer_geo::{geo::*, stl::*};
//use rayon::prelude::*;
// TODO: update benchmarks
pub fn criterion_benchmark(_c: &mut Criterion) {
/*
let stl = load_stl("3DBenchy.stl");
let triangles = to_triangles3d(&stl);
let tri_vk = to_tri_vk(&triangles);
let vk = init_vk();
let mut group = c.benchmark_group("BBox");
group.bench_function("iter bboxes", |b| {
b.iter(|| {
let _bboxes: Vec<Line3d> = triangles.iter().map(|x| x.bbox()).collect();
})
});
group.bench_function("par_iter bboxes", |b| {
b.iter(|| {
let _bboxes: Vec<Line3d> = triangles.par_iter().map(|x| x.bbox()).collect();
})
});
*/
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
use std::io::{self, Write, BufRead, BufReader};
use std::net::{TcpListener, TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::thread;
#[allow(unused_imports)]
use super::{Tracker, Request, Response};
pub struct ThreadedListener {
listener: TcpListener,
tracker: Arc<Tracker>,
}
impl ThreadedListener {
pub fn new<S: ToSocketAddrs>(addr: S, tracker: Tracker) -> Result<ThreadedListener, io::Error> {
Ok(ThreadedListener {
listener: try!(TcpListener::bind(addr)),
tracker: Arc::new(tracker),
})
}
pub fn run(&self) {
for stream in self.listener.incoming() {
match stream {
Ok(stream) => {
let conn_tracker = self.tracker.clone();
thread::spawn(move|| {
let peer_addr = stream.peer_addr();
info!("New connection from {:?}", peer_addr);
match handle_connection(stream, conn_tracker) {
Ok(_) => {},
Err(e) => {
error!("Error handling connection from {:?}: {}", peer_addr, e);
}
}
info!("Shutting down connection from {:?}", peer_addr);
});
},
Err(e) => {
error!("Connection failed: {}", e);
}
}
}
}
}
fn handle_connection(mut writer: TcpStream, tracker: Arc<Tracker>) -> Result<(), io::Error> {
let reader = BufReader::new(try!(writer.try_clone()));
for line in reader.split(b'\n') {
let mut line = try!(line);
if line.last() == Some(&b'\r') { line.pop(); }
let response = Response::from(tracker.handle_bytes(line.as_ref()));
try!(writer.write_all(&response.render()));
}
Ok(())
}
|
use azure_core::prelude::*;
use azure_storage::blob::prelude::*;
use azure_storage::core::prelude::*;
use futures::stream::StreamExt;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
// First we retrieve the account name and master key from environment variables.
let account =
std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
let master_key =
std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!");
let container = std::env::args()
.nth(1)
.expect("please specify container name as command line parameter");
let blob = std::env::args()
.nth(2)
.expect("please specify blob name as command line parameter");
let http_client = new_http_client();
let storage_account_client =
StorageAccountClient::new_access_key(http_client.clone(), &account, &master_key);
let storage_client = storage_account_client.as_storage_client();
let blob = storage_client
.as_container_client(&container)
.as_blob_client(&blob);
// 1024 G, 512 H and 2048 I
let mut buf: Vec<u8> = Vec::with_capacity(1024 * 4);
for _ in 0..1024 {
buf.push(71);
}
for _ in 0..512 {
buf.push(72);
}
for _ in 0..2048 {
buf.push(73);
}
let content = std::str::from_utf8(&buf)?.to_owned();
println!("content == {}", content);
let _response = blob.put_block_blob(buf.clone()).execute().await?;
let whole = blob.get().execute().await?;
assert_eq!(whole.data.len(), buf.len());
let chunk0 = blob.get().range(Range::new(0, 1024)).execute().await?;
assert_eq!(chunk0.data.len(), 1024);
for i in 0..1024 {
assert_eq!(chunk0.data[i], 71);
}
let chunk1 = blob.get().range(Range::new(1024, 1536)).execute().await?;
assert_eq!(chunk1.data.len(), 512);
for i in 0..512 {
assert_eq!(chunk1.data[i], 72);
}
let chunk2 = blob.get().range(Range::new(1536, 3584)).execute().await?;
assert_eq!(chunk2.data.len(), 2048);
for i in 0..2048 {
assert_eq!(chunk2.data[i], 73);
}
let mut stream = Box::pin(blob.get().stream(512));
println!("\nStreaming");
let mut chunk: usize = 0;
while let Some(value) = stream.next().await {
let value = value?.data;
println!("received {:?} bytes", value.len());
println!("received {}", std::str::from_utf8(&value)?);
for i in 0..512 {
assert_eq!(
value[i],
match chunk {
0 | 1 => 71,
2 => 72,
_ => 73,
}
);
}
chunk += 1;
}
for dropped_suffix_len in &[3usize, 1] {
println!("dropped_suffix_len == {}", dropped_suffix_len);
}
Ok(())
}
|
use glium::Display;
use glium::texture::{PixelValue, RawImage2d, SrgbTexture2d, ToClientFormat};
use image;
use index_pool::IndexPool;
use std::borrow::Cow;
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TextureId(usize);
#[derive(Default)]
pub struct TextureManager {
id_pool: IndexPool,
textures: HashMap<TextureId, Texture>,
name_to_id: HashMap<String, TextureId>,
id_to_name: HashMap<TextureId, String>,
}
impl TextureManager {
pub fn new() -> Self {
Default::default()
}
pub fn load(&mut self, display: &Display, asset: &str) -> TextureId {
if let Some(id) = self.name_to_id(asset) {
return id;
}
self.insert(asset, Texture::load_from_asset(display, asset))
}
pub fn insert(&mut self, name: &str, texture: Texture) -> TextureId {
let id = TextureId(self.id_pool.new_id());
self.textures.insert(id, texture);
self.name_to_id.insert(name.into(), id);
self.id_to_name.insert(id, name.into());
id
}
pub fn update(&mut self, id: TextureId, texture: Texture) {
self.textures.insert(id, texture);
}
pub fn remove(&mut self, id: TextureId) -> Option<Texture> {
if self.id_pool.return_id(id.0).is_err() {
eprintln!("[WARNING] texture was already removed (or never existed?)");
}
if let Some(name) = self.id_to_name.get(&id) {
self.name_to_id.remove(name);
}
self.id_to_name.remove(&id);
self.textures.remove(&id)
}
pub fn name_to_id(&self, name: &str) -> Option<TextureId> {
self.name_to_id.get(name).cloned()
}
pub fn id_to_name(&self, id: TextureId) -> Option<&str> {
self.id_to_name.get(&id).map(|s| &s[..])
}
pub fn get(&self, id: TextureId) -> &Texture {
&self.textures[&id]
}
}
pub struct Texture {
pub tex: SrgbTexture2d,
}
impl Texture {
pub fn from_rgba<'a, C, T>(display: &Display, data: C, dimensions: (u32, u32)) -> Texture
where
C: Into<Cow<'a, [T]>>,
T: ToClientFormat + PixelValue,
{
let data = data.into();
let raw_image = RawImage2d::from_raw_rgba(data.into_owned(), dimensions);
let texture = SrgbTexture2d::new(display, raw_image).unwrap();
Texture { tex: texture }
}
pub fn load_from_asset(display: &Display, asset: &str) -> Texture {
let mut path = PathBuf::from("./resources");
path.push(asset);
let image = image::open(path)
.map_err(|e| panic!("Failed to open image {:?}\n {}", asset, e))
.unwrap()
.to_rgba();
let dimensions = image.dimensions();
Texture::from_rgba(display, image.into_raw(), dimensions)
}
}
|
use cgmath::{Point3, Vector3, Matrix4, SquareMatrix, Transform, Matrix};
use rayon::prelude::*;
use crate::chr0::Chr0;
use crate::fighter::Fighter;
use crate::mdl0::bones::Bone;
use crate::sakurai::{SectionScript, ExternalSubroutine};
use crate::sakurai::fighter_data::misc_section::{HurtBox, BoneRefs};
use crate::sakurai::fighter_data::{FighterAttributes, AnimationFlags};
use crate::script_ast::{
ScriptAst,
HitBoxArguments,
SpecialHitBoxArguments,
GrabBoxArguments,
HurtBoxState,
EdgeSlide,
AngleFlip,
HitBoxEffect,
HitBoxSound,
HitBoxSseType,
GrabTarget,
LedgeGrabEnable,
};
use crate::script_runner::{ScriptRunner, ChangeSubaction, ScriptCollisionBox, VelModify};
use crate::init_hack_script::init_hack_script;
/// The HighLevelFighter stores processed Fighter data in a format that is easy to read from.
/// If brawllib_rs eventually implements the ability to modify character files via modifying Fighter and its children, then HighLevelFighter WILL NOT support that.
#[derive(Serialize, Clone, Debug)]
pub struct HighLevelFighter {
pub name: String,
pub internal_name: String,
pub attributes: FighterAttributes,
pub actions: Vec<HighLevelAction>,
pub subactions: Vec<HighLevelSubaction>,
pub scripts_fragment_fighter: Vec<ScriptAst>,
pub scripts_fragment_common: Vec<ScriptAst>,
pub scripts_section: Vec<SectionScriptAst>,
}
impl HighLevelFighter {
/// Processes data from an &Fighter and stores it in a HighLevelFighter
// TODO: Maybe expose a `multithreaded` argument so caller can disable multithread and run its own multithreading on the entire `HighLevelFighter::new`.
// Because rayon uses a threadpool we arent at risk of it hammering the system by spawning too many threads.
// However it may be ineffecient due to overhead of spawning threads for every action.
// Will need to benchmark any such changes.
pub fn new(fighter: &Fighter) -> HighLevelFighter {
info!("Generating HighLevelFighter for {}", fighter.cased_name);
let fighter_sakurai = fighter.get_fighter_sakurai().unwrap();
let fighter_sakurai_common = fighter.get_fighter_sakurai_common().unwrap();
let fighter_data = fighter.get_fighter_data().unwrap();
let fighter_data_common = fighter.get_fighter_data_common().unwrap();
let fighter_data_common_scripts = fighter.get_fighter_data_common_scripts();
let attributes = fighter_data.attributes.clone();
let fighter_animations = fighter.get_animations();
let fragment_scripts_fighter: Vec<_> = fighter_sakurai.fragment_scripts.iter().map(|x| ScriptAst::new(x)).collect();
let subaction_main: Vec<_> = fighter_data.subaction_main .iter().map(|x| ScriptAst::new(x)).collect();
let subaction_gfx: Vec<_> = fighter_data.subaction_gfx .iter().map(|x| ScriptAst::new(x)).collect();
let subaction_sfx: Vec<_> = fighter_data.subaction_sfx .iter().map(|x| ScriptAst::new(x)).collect();
let subaction_other: Vec<_> = fighter_data.subaction_other .iter().map(|x| ScriptAst::new(x)).collect();
let fragment_scripts_common: Vec<_> = fighter_sakurai_common.fragment_scripts.iter().map(|x| ScriptAst::new(x)).collect();
let scripts_section: Vec<_> = fighter_data_common_scripts.iter().map(|x| SectionScriptAst::new(x, &fighter_sakurai.external_subroutines)).collect();
let entry_actions_common: Vec<_> = fighter_data_common.entry_actions.iter().map(|x| ScriptAst::new(x)).collect();
let entry_actions: Vec<_> = fighter_data .entry_actions.iter().map(|x| ScriptAst::new(x)).collect();
let exit_actions_common: Vec<_> = fighter_data_common.exit_actions .iter().map(|x| ScriptAst::new(x)).collect();
let exit_actions: Vec<_> = fighter_data .exit_actions .iter().map(|x| ScriptAst::new(x)).collect();
let mut fighter_scripts = vec!();
for script in fragment_scripts_fighter.iter()
.chain(subaction_main.iter())
.chain(subaction_gfx.iter())
.chain(subaction_sfx.iter())
.chain(subaction_other.iter())
.chain(entry_actions.iter())
.chain(exit_actions.iter())
{
fighter_scripts.push(script);
}
let mut common_scripts = vec!();
for script in fragment_scripts_common.iter()
.chain(scripts_section.iter().map(|x| &x.script))
.chain(entry_actions_common.iter())
.chain(exit_actions_common.iter())
{
common_scripts.push(script);
}
let mut subaction_scripts = vec!();
for i in 0..subaction_main.len() {
subaction_scripts.push(HighLevelScripts {
script_main: subaction_main[i].clone(),
script_gfx: subaction_gfx[i].clone(),
script_sfx: subaction_sfx[i].clone(),
script_other: subaction_other[i].clone(),
});
}
let mut actions = vec!();
for i in 0..entry_actions_common.len() {
let name = crate::action_names::action_name(i);
let entry_action_override = fighter_data.entry_action_overrides.iter().find(|x| x.action_id == i as u32);
let (script_entry, script_entry_common) = if let Some(action_override) = entry_action_override {
(ScriptAst::new(&action_override.script), false)
} else {
(entry_actions_common[i].clone(), true)
};
let exit_action_override = fighter_data.exit_action_overrides.iter().find(|x| x.action_id == i as u32);
let (script_exit, script_exit_common) = if let Some(action_override) = exit_action_override {
(ScriptAst::new(&action_override.script), false)
} else {
(exit_actions_common[i].clone(), true)
};
actions.push(HighLevelAction { name, script_entry, script_exit, script_entry_common, script_exit_common });
}
for i in 0..entry_actions.len() {
actions.push(HighLevelAction {
name: crate::action_names::action_name(0x112 + i),
script_entry: entry_actions[i].clone(),
script_entry_common: false,
script_exit: exit_actions[i].clone(),
script_exit_common: false,
});
}
let subactions = if let Some(first_bone) = fighter.get_bones() {
// TODO: After fixing a bug, where a huge amount of needless work was being done, parallelizing this doesnt get us as much.
// It might be better for the caller of HighLevelFighter::new() to do the parallelization.
subaction_scripts.into_par_iter().enumerate().map(|(i, scripts)| {
let subaction_flags = &fighter_data.subaction_flags[i];
let actual_name = subaction_flags.name.clone();
// create a unique name for this subaction
let mut count = 0;
for j in 0..i {
if fighter_data.subaction_flags[j].name == actual_name {
count += 1;
}
}
let name = if count == 0 {
actual_name.clone()
} else {
format!("{}_{}", actual_name, count)
};
let animation_flags = subaction_flags.animation_flags.clone();
let chr0 = fighter_animations.iter().find(|x| x.name == actual_name);
let subaction_scripts = vec!(&scripts.script_main, &scripts.script_gfx, &scripts.script_sfx, &scripts.script_other);
let init_hack_script = init_hack_script(&fighter.cased_name, &actual_name);
let mut frames: Vec<HighLevelFrame> = vec!();
let mut prev_animation_xyz_offset = Vector3::new(0.0, 0.0, 0.0);
let mut script_runner = ScriptRunner::new(i, &fighter.wiird_frame_speed_modifiers, &subaction_scripts, &fighter_scripts, &common_scripts, &scripts_section, &init_hack_script, &fighter_data, actual_name.clone());
let mut iasa = None;
let mut prev_hit_boxes: Option<Vec<PositionHitBox>> = None;
if let Some(chr0) = chr0 {
let num_frames = match actual_name.as_ref() {
"JumpSquat" => attributes.jump_squat_frames as f32,
"LandingAirN" => attributes.nair_landing_lag,
"LandingAirF" => attributes.fair_landing_lag,
"LandingAirB" => attributes.bair_landing_lag,
"LandingAirHi" => attributes.uair_landing_lag,
"LandingAirLw" => attributes.dair_landing_lag,
"LandingLight" => attributes.light_landing_lag, // TODO: This needs +1 do the others?!?!?
"LandingHeavy" => attributes.normal_landing_lag,
_ => chr0.num_frames as f32
};
let mut x_vel = 0.0;
let mut y_vel = 0.0;
let mut x_pos = 0.0;
let mut y_pos = 0.0;
while script_runner.animation_index < num_frames {
let chr0_frame_index = script_runner.animation_index * chr0.num_frames as f32 / num_frames; // map frame count between [0, chr0.num_frames]
let (animation_xyz_offset, frame_bones) = HighLevelFighter::transform_bones(
&first_bone,
&fighter_data.misc.bone_refs,
Matrix4::<f32>::identity(),
Matrix4::<f32>::identity(),
chr0,
chr0_frame_index as i32,
animation_flags,
fighter_data.attributes.size
);
let animation_xyz_offset = animation_xyz_offset.unwrap_or(Vector3::new(0.0, 0.0, 0.0));
// TODO: should DisableMovement affect xyz_offset from transform_bones?????
// script runner x-axis is equivalent to model z-axis
let animation_xyz_velocity = animation_xyz_offset - prev_animation_xyz_offset;
prev_animation_xyz_offset = animation_xyz_offset;
let x_vel_modify = script_runner.x_vel_modify.clone();
let y_vel_modify = script_runner.y_vel_modify.clone();
let x_vel_temp = animation_xyz_velocity.z;
let y_vel_temp = animation_xyz_velocity.y;
match x_vel_modify {
VelModify::Set (vel) => x_vel = vel,
VelModify::Add (vel) => x_vel += vel,
VelModify::None => { }
}
match y_vel_modify {
VelModify::Set (vel) => y_vel = vel,
VelModify::Add (vel) => y_vel += vel,
VelModify::None => { }
}
x_pos += x_vel + x_vel_temp;
y_pos += y_vel + y_vel_temp;
let hurt_boxes = gen_hurt_boxes(&frame_bones, &fighter_data.misc.hurt_boxes, &script_runner, fighter_data.attributes.size);
let hit_boxes: Vec<_> = script_runner.hitboxes.iter().filter(|x| x.is_some()).map(|x| x.clone().unwrap()).collect();
let hit_boxes = gen_hit_boxes(&frame_bones, &hit_boxes, fighter_data.attributes.size);
let mut hl_hit_boxes = vec!();
for next in &hit_boxes {
let mut prev_pos = None;
let mut prev_size = None;
let mut prev_values = None;
if next.interpolate {
if let &Some(ref prev_hit_boxes) = &prev_hit_boxes {
for prev_hit_box in prev_hit_boxes {
if prev_hit_box.hitbox_id == next.hitbox_id {
// A bit hacky, but we need to undo the movement that occured this frame to get the correct hitbox interpolation
prev_pos = Some(prev_hit_box.hitbox_position - Vector3::new(0.0, y_vel, x_vel));
prev_size = Some(prev_hit_box.size);
prev_values = Some(prev_hit_box.values.clone());
}
}
}
}
// abuse the hitbox interpolation fields to create stretch hitboxes
if next.values.stretches_to_bone() {
prev_pos = Some(next.bone_position);
prev_size = Some(next.size);
prev_values = Some(next.values.clone());
}
hl_hit_boxes.push(HighLevelHitBox {
hitbox_id: next.hitbox_id,
prev_pos,
prev_size,
prev_values,
next_pos: next.hitbox_position,
next_size: next.size,
next_values: next.values.clone(),
});
}
hl_hit_boxes.sort_by_key(|x| x.hitbox_id);
let mut option_ecb = None;
for misc_ecb in &fighter_data.misc.ecbs {
let min_ecb = ECB {
// This implementation is just a guess from my observations that:
// * The higher the min_width the higher the right ecb point.
// * The higher the min_width the lower the left ecb point.
// * When further than all bones, both points move equally far apart.
// * When further than all bones, actions that affect the ecb horizontally no longer affect the ecb e.g. marth jab
left: -misc_ecb.min_width / 2.0, // TODO: Should I divide by 2.0 here?
right: misc_ecb.min_width / 2.0, // TODO: Should I divide by 2.0 here?
top: -10000.0,
bottom: 10000.0,
transn_x: 0.0,
transn_y: 0.0,
};
let mut ecb = gen_ecb(&frame_bones, &misc_ecb.bones, &fighter_data.misc.bone_refs, min_ecb);
// This implementation is just a guess from my observations that:
// * The higher the min_height the higher the top ecb point.
// * The higher the min_height the lower the bottom ecb point, capping out at transN.
// * Actions such as crouching, lower the height of the top ecb point.
let middle_y = (ecb.top + ecb.bottom) / 2.0;
let new_top = middle_y + misc_ecb.min_height / 2.0;
let new_bottom = middle_y - misc_ecb.min_height / 2.0;
if new_top > ecb.top {
ecb.top = new_top;
}
if new_bottom < ecb.bottom {
ecb.bottom = new_bottom;
}
if ecb.bottom < ecb.transn_y {
ecb.bottom = ecb.transn_y
}
option_ecb = Some(ecb);
}
let ecb = option_ecb.unwrap();
let weight_dependent_speed = match actual_name.as_ref() {
"ThrowLw" => attributes.weight_dependent_throw_down,
"ThrowHi" => attributes.weight_dependent_throw_up,
"ThrowF" => attributes.weight_dependent_throw_forward,
"ThrowB" => attributes.weight_dependent_throw_backward,
_ => false,
};
let mut throw = None;
if let Some(ref specify_throw) = script_runner.throw {
if script_runner.throw_activate {
throw = Some(HighLevelThrow {
damage: specify_throw.damage,
trajectory: specify_throw.trajectory,
kbg: specify_throw.kbg,
wdsk: specify_throw.wdsk,
bkb: specify_throw.bkb,
effect: specify_throw.effect.clone(),
sfx: specify_throw.sfx.clone(),
grab_target: specify_throw.grab_target.clone(),
i_frames: specify_throw.i_frames,
weight_dependent_speed,
});
}
}
let ledge_grab_box = if script_runner.ledge_grab_enable.enabled() {
// The first misc.ledge_grabs entry seems to be used for everything, not sure what the other entries are for.
if let Some(ledge_grab_box) = fighter_data.misc.ledge_grab_boxes.get(0) {
let left = if let LedgeGrabEnable::EnableInFrontAndBehind = script_runner.ledge_grab_enable {
ecb.left - ledge_grab_box.x_padding
} else {
ledge_grab_box.x_left
};
Some(Extent {
left,
right: ecb.right + ledge_grab_box.x_padding,
up: ledge_grab_box.y + ledge_grab_box.height,
down: ledge_grab_box.y,
})
} else {
None
}
} else {
None
};
frames.push(HighLevelFrame {
throw,
ecb,
x_pos,
y_pos,
x_vel_modify,
y_vel_modify,
x_vel_temp,
y_vel_temp,
ledge_grab_box,
hurt_boxes,
hit_boxes: hl_hit_boxes,
interruptible: script_runner.interruptible,
landing_lag: script_runner.landing_lag,
edge_slide: script_runner.edge_slide.clone(),
reverse_direction: script_runner.reverse_direction.clone(),
airbourne: script_runner.airbourne,
hitbox_sets_rehit: script_runner.hitbox_sets_rehit,
slope_contour_stand: script_runner.slope_contour_stand,
slope_contour_full: script_runner.slope_contour_full,
rumble: script_runner.rumble,
rumble_loop: script_runner.rumble_loop,
grab_interrupt_damage: script_runner.grab_interrupt_damage,
});
if iasa.is_none() && script_runner.interruptible {
iasa = Some(script_runner.frame_count)
}
script_runner.step();
prev_hit_boxes = Some(hit_boxes);
if let ChangeSubaction::Continue = script_runner.change_subaction { } else { break }
}
}
if iasa.is_none() {
iasa = match actual_name.as_ref() {
"LandingAirN" | "LandingAirF" |
"LandingAirB" | "LandingAirHi" |
"LandingAirLw" | "LandingLight" |
"LandingHeavy" | "LandingFallSpecial"
=> Some(script_runner.frame_count),
_ => None
}
};
let landing_lag = match actual_name.as_ref() {
"AttackAirN" => Some(attributes.nair_landing_lag),
"AttackAirF" => Some(attributes.fair_landing_lag),
"AttackAirB" => Some(attributes.bair_landing_lag),
"AttackAirHi" => Some(attributes.uair_landing_lag),
"AttackAirLw" => Some(attributes.dair_landing_lag),
_ => None,
};
let bad_interrupts = script_runner.bad_interrupts.len() > 0;
HighLevelSubaction { name, iasa, landing_lag, frames, animation_flags, scripts, bad_interrupts }
}).collect()
} else {
vec!()
};
HighLevelFighter {
internal_name: fighter.cased_name.clone(),
name: crate::fighter_maps::fighter_name(&fighter.cased_name),
scripts_fragment_fighter: fragment_scripts_fighter,
scripts_fragment_common: fragment_scripts_common,
scripts_section,
attributes,
actions,
subactions,
}
}
/// Generates a tree of BoneTransforms from the specified animation frame applied on the passed tree of bones
/// The resulting matrices are independent of its parent bones matrix.
/// Returns a tuple containing:
/// 0. The MOVES_CHARACTER offset if enabled. this is used by e.g. Ness's double jump
/// 1. The BoneTransforms tree.
fn transform_bones(bone: &Bone, bone_refs: &BoneRefs, parent_transform: Matrix4<f32>, parent_transform_hitbox: Matrix4<f32>, chr0: &Chr0, frame: i32, animation_flags: AnimationFlags, size: f32) -> (Option<Vector3<f32>>, BoneTransforms) {
let moves_character = animation_flags.contains(AnimationFlags::MOVES_CHARACTER);
// by default the bones tpose transformation is used.
let mut transform_normal = parent_transform * bone.gen_transform();
let mut transform_hitbox = parent_transform_hitbox * bone.gen_transform_rot_only();
// if the animation specifies a transform for the bone, override the models default tpose transform.
let mut offset = None;
for chr0_child in &chr0.children {
if chr0_child.name == bone.name {
let transform = parent_transform * chr0_child.get_transform(chr0.loop_value, frame);
if moves_character && bone.index == bone_refs.trans_n {
// in this case TransN is not part of the animation but instead used to move the character in game.
assert!(offset.is_none());
offset = Some(Vector3::new(transform.w.x, transform.w.y, transform.w.z));
// TODO: Should this case modify transform_normal rot and scale?
}
else {
// The animation specifies a transform for this bone, and its not used for character movement. USE IT!
transform_normal = transform;
transform_hitbox = parent_transform_hitbox * chr0_child.get_transform_rot_only(chr0.loop_value, frame);
}
}
}
// Ignore any transformations from the models tpose TopN bone or the animations TopN bone.
// Furthermore we make use of this bone to apply a scale to the entire model.
if bone.name == "TopN" {
transform_normal = Matrix4::from_scale(size);
transform_hitbox = Matrix4::identity();
}
// do the same for all children bones
let mut children = vec!();
for child in bone.children.iter() {
let (moves, processed_child) = HighLevelFighter::transform_bones(child, bone_refs, transform_normal, transform_hitbox, chr0, frame, animation_flags, size);
children.push(processed_child);
if let Some(moves) = moves {
assert!(offset.is_none());
offset = Some(moves);
}
}
let bone = BoneTransforms {
index: bone.index,
transform_normal,
transform_hitbox,
children,
};
(offset, bone)
}
}
pub struct BoneTransforms {
pub index: i32,
pub transform_normal: Matrix4<f32>,
pub transform_hitbox: Matrix4<f32>,
pub children: Vec<BoneTransforms>,
}
#[derive(Serialize, Clone, Debug)]
pub struct HighLevelAction {
pub name: String,
pub script_entry: ScriptAst,
pub script_exit: ScriptAst,
/// This is needed to determine where Goto/Subroutine events are pointing
pub script_entry_common: bool,
/// This is needed to determine where Goto/Subroutine events are pointing
pub script_exit_common: bool,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct HighLevelSubaction {
pub name: String,
pub iasa: Option<usize>,
pub frames: Vec<HighLevelFrame>,
pub landing_lag: Option<f32>,
pub animation_flags: AnimationFlags,
pub scripts: HighLevelScripts,
/// A hack where bad interrupts are ignored was used to process this subaction
pub bad_interrupts: bool,
}
impl HighLevelSubaction {
/// Furthest point of a hitbox, starting from the bps
/// Furthest values across all frames
pub fn hit_box_extent(&self) -> Extent {
let mut extent = Extent::new();
for frame in &self.frames {
let mut new_extent = frame.hit_box_extent();
new_extent.up += frame.y_pos;
new_extent.down += frame.y_pos;
new_extent.left += frame.x_pos;
new_extent.right += frame.x_pos;
extent.extend(&new_extent);
}
extent
}
/// Furthest point of a hurtbox, starting from the bps
/// Furthest values across all frames
pub fn hurt_box_extent(&self) -> Extent {
let mut extent = Extent::new();
for frame in &self.frames {
let mut new_extent = frame.hurt_box_extent();
new_extent.up += frame.y_pos;
new_extent.down += frame.y_pos;
new_extent.left += frame.x_pos;
new_extent.right += frame.x_pos;
extent.extend(&new_extent);
}
extent
}
/// Furthest point of a ledge grab box, starting from the bps
/// Furthest values across all frames
pub fn ledge_grab_box_extent(&self) -> Extent {
let mut extent = Extent::new();
for frame in &self.frames {
if let Some(ref ledge_grab_box) = frame.ledge_grab_box {
let mut new_extent = ledge_grab_box.clone();
new_extent.up += frame.y_pos;
new_extent.down += frame.y_pos;
new_extent.left += frame.x_pos;
new_extent.right += frame.x_pos;
extent.extend(&new_extent);
}
}
extent
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct HighLevelScripts {
pub script_main: ScriptAst,
pub script_gfx: ScriptAst,
pub script_sfx: ScriptAst,
pub script_other: ScriptAst,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct HighLevelThrow {
// TODO: I imagine the bone is used to determine the location the character is thrown from.
// Transform the bone into an xy offset.
pub damage: i32,
pub trajectory: i32,
pub kbg: i32,
pub wdsk: i32,
pub bkb: i32,
pub effect: HitBoxEffect,
pub sfx: HitBoxSound,
pub grab_target: GrabTarget,
pub i_frames: i32,
pub weight_dependent_speed: bool,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct HighLevelFrame {
pub hurt_boxes: Vec<HighLevelHurtBox>,
pub hit_boxes: Vec<HighLevelHitBox>,
pub ledge_grab_box: Option<Extent>,
pub x_pos: f32,
pub y_pos: f32,
pub interruptible: bool,
pub edge_slide: EdgeSlide,
pub reverse_direction: bool,
pub airbourne: bool,
pub landing_lag: bool,
pub ecb: ECB,
pub hitbox_sets_rehit: [bool; 10],
pub slope_contour_stand: Option<i32>,
pub slope_contour_full: Option<(i32, i32)>,
pub rumble: Option<(i32, i32)>,
pub rumble_loop: Option<(i32, i32)>,
pub grab_interrupt_damage: Option<i32>,
pub throw: Option<HighLevelThrow>,
/// Affects the next frames velocity
pub x_vel_modify: VelModify,
/// Affects the next frames velocity
pub y_vel_modify: VelModify,
/// Does not affect the next frames velocity
pub x_vel_temp: f32,
/// Does not affect the next frames velocity
pub y_vel_temp: f32,
}
impl HighLevelFrame {
/// Furthest point of a hitbox, starting from the bps
pub fn hit_box_extent(&self) -> Extent {
let mut extent = Extent::new();
for hit_box in &self.hit_boxes {
if let (Some(pos), Some(size)) = (hit_box.prev_pos, hit_box.prev_size) {
let new_extent = Extent {
up: pos.y + size,
down: pos.y - size,
left: pos.z - size,
right: pos.z + size,
};
extent.extend(&new_extent);
}
let pos = hit_box.next_pos;
let size = hit_box.next_size;
let new_extent = Extent {
up: pos.y + size,
down: pos.y - size,
left: pos.z - size,
right: pos.z + size,
};
extent.extend(&new_extent);
}
extent
}
/// Furthest point of a hurtbox, starting from the bps
pub fn hurt_box_extent(&self) -> Extent {
let mut extent = Extent::new();
for hurt_box in &self.hurt_boxes {
let bone_matrix = hurt_box.bone_matrix.clone();
let prev = hurt_box.hurt_box.offset;
let next = hurt_box.hurt_box.stretch;
let radius = hurt_box.hurt_box.radius;
extent.extend(&HighLevelFrame::sphere_extent(prev, radius, bone_matrix));
extent.extend(&HighLevelFrame::sphere_extent(next, radius, bone_matrix));
}
extent
}
/// https://stackoverflow.com/questions/4368961/calculating-an-aabb-for-a-transformed-sphere
fn sphere_extent(sphere_location: Vector3<f32>, radius: f32, transform: Matrix4<f32>) -> Extent {
let scale = Matrix4::from_scale(radius);
let transform = transform * Matrix4::from_translation(sphere_location.clone()) * scale;
let mut s = Matrix4::from_scale(1.0);
s.w.w = -1.0;
if let Some(s_inverse) = s.invert() {
let r = transform * s_inverse * transform.transpose();
Extent {
up: (r.y.w - (r.y.w * r.y.w - r.w.w * r.y.y).sqrt()) / r.w.w,
down: (r.y.w + (r.y.w * r.y.w - r.w.w * r.y.y).sqrt()) / r.w.w,
left: (r.z.w + (r.z.w * r.z.w - r.w.w * r.z.z).sqrt()) / r.w.w,
right: (r.z.w - (r.z.w * r.z.w - r.w.w * r.z.z).sqrt()) / r.w.w,
}
} else {
Extent::new()
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Extent {
pub left: f32,
pub right: f32,
pub up: f32,
pub down: f32,
//pub extents: Vec<Extent>,
}
impl Extent {
pub fn new() -> Extent {
Extent {
left: 0.0,
right: 0.0,
up: 0.0,
down: 0.0,
}
}
pub fn extend(&mut self, other: &Extent) {
if other.left < self.left && !self.left.is_nan() {
self.left = other.left;
}
if other.right > self.right && !self.right.is_nan() {
self.right = other.right;
}
if other.up > self.up && !self.up.is_nan() {
self.up = other.up;
}
if other.down < self.down && !self.down.is_nan() {
self.down = other.down;
}
// Enable for debugging extents
//if other.extents.len() == 0 {
// self.extents.push(other.clone());
//}
//else {
// self.extents.extend(other.extents.clone());
//}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct HighLevelHurtBox {
pub bone_matrix: Matrix4<f32>,
pub hurt_box: HurtBox,
pub state: HurtBoxState,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum CollisionBoxValues {
Hit (HitBoxValues),
Grab (GrabBoxValues),
}
impl CollisionBoxValues {
pub(crate) fn from_hitbox(args: &HitBoxArguments, damage: f32) -> CollisionBoxValues {
CollisionBoxValues::Hit(HitBoxValues {
hitbox_id: args.hitbox_id,
set_id: args.set_id,
damage: damage,
trajectory: args.trajectory,
wdsk: args.wdsk,
kbg: args.kbg,
shield_damage: args.shield_damage,
bkb: args.bkb,
size: args.size,
tripping_rate: args.tripping_rate,
hitlag_mult: args.hitlag_mult,
sdi_mult: args.sdi_mult,
effect: args.effect.clone(),
sound_level: args.sound_level,
sound: args.sound.clone(),
ground: args.ground,
aerial: args.aerial,
sse_type: args.sse_type.clone(),
clang: args.clang,
direct: args.direct,
rehit_rate: 0, // TODO: ?
angle_flipping: AngleFlip::AttackerPosition,
stretches_to_bone: false,
can_hit1: true,
can_hit2: true,
can_hit3: true,
can_hit4: true,
can_hit5: true,
can_hit6: true,
can_hit7: true,
can_hit8: true,
can_hit9: true,
can_hit10: true,
can_hit11: true,
can_hit12: true,
can_hit13: true,
enabled: true,
can_be_shielded: true,
can_be_reflected: false,
can_be_absorbed: false,
remain_grabbed: false,
ignore_invincibility: false,
freeze_frame_disable: false,
flinchless: false,
})
}
pub(crate) fn from_special_hitbox(special_args: &SpecialHitBoxArguments, damage: f32) -> CollisionBoxValues {
let args = &special_args.hitbox_args;
CollisionBoxValues::Hit(HitBoxValues {
hitbox_id: args.hitbox_id,
set_id: args.set_id,
damage: damage,
trajectory: args.trajectory,
wdsk: args.wdsk,
kbg: args.kbg,
shield_damage: args.shield_damage,
bkb: args.bkb,
size: args.size,
tripping_rate: args.tripping_rate,
hitlag_mult: args.hitlag_mult,
sdi_mult: args.sdi_mult,
effect: args.effect.clone(),
sound_level: args.sound_level,
sound: args.sound.clone(),
ground: args.ground,
aerial: args.aerial,
sse_type: args.sse_type.clone(),
clang: args.clang,
direct: args.direct,
rehit_rate: special_args.rehit_rate,
angle_flipping: special_args.angle_flipping.clone(),
stretches_to_bone: special_args.stretches_to_bone,
can_hit1: special_args.can_hit1,
can_hit2: special_args.can_hit2,
can_hit3: special_args.can_hit3,
can_hit4: special_args.can_hit4,
can_hit5: special_args.can_hit5,
can_hit6: special_args.can_hit6,
can_hit7: special_args.can_hit7,
can_hit8: special_args.can_hit8,
can_hit9: special_args.can_hit9,
can_hit10: special_args.can_hit10,
can_hit11: special_args.can_hit11,
can_hit12: special_args.can_hit12,
can_hit13: special_args.can_hit13,
enabled: special_args.enabled,
can_be_shielded: special_args.can_be_shielded,
can_be_reflected: special_args.can_be_reflected,
can_be_absorbed: special_args.can_be_absorbed,
remain_grabbed: special_args.remain_grabbed,
ignore_invincibility: special_args.ignore_invincibility,
freeze_frame_disable: special_args.freeze_frame_disable,
flinchless: special_args.flinchless,
})
}
pub(crate) fn from_grabbox(args: &GrabBoxArguments) -> CollisionBoxValues {
CollisionBoxValues::Grab(GrabBoxValues {
hitbox_id: args.hitbox_id,
size: args.size,
set_action: args.set_action,
target: args.target.clone(),
unk: args.unk.clone(),
})
}
pub(crate) fn stretches_to_bone(&self) -> bool {
match self {
CollisionBoxValues::Hit(values) => values.stretches_to_bone,
CollisionBoxValues::Grab(_) => false,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GrabBoxValues {
pub hitbox_id: i32,
pub size: f32,
pub set_action: i32,
pub target: GrabTarget,
pub unk: Option<i32>,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct HitBoxValues {
pub hitbox_id: u8,
pub set_id: u8,
pub damage: f32,
pub trajectory: i32,
pub wdsk: i16,
pub kbg: i16,
pub shield_damage: i16,
pub bkb: i16,
pub size: f32,
pub tripping_rate: f32,
pub hitlag_mult: f32,
pub sdi_mult: f32,
pub effect: HitBoxEffect,
pub sound_level: u8,
pub sound: HitBoxSound,
pub ground: bool,
pub aerial: bool,
pub sse_type: HitBoxSseType,
pub clang: bool,
pub direct: bool,
pub rehit_rate: i32,
pub angle_flipping: AngleFlip,
pub stretches_to_bone: bool,
pub can_hit1: bool,
pub can_hit2: bool,
pub can_hit3: bool,
pub can_hit4: bool,
pub can_hit5: bool,
pub can_hit6: bool,
pub can_hit7: bool,
pub can_hit8: bool,
pub can_hit9: bool,
pub can_hit10: bool,
pub can_hit11: bool,
pub can_hit12: bool,
pub can_hit13: bool,
pub enabled: bool,
pub can_be_shielded: bool,
pub can_be_reflected: bool,
pub can_be_absorbed: bool,
pub remain_grabbed: bool,
pub ignore_invincibility: bool,
pub freeze_frame_disable: bool,
pub flinchless: bool,
}
impl HitBoxValues {
pub fn can_hit_fighter(&self) -> bool {
self.can_hit1
}
pub fn can_hit_waddle_dee_doo(&self) -> bool {
self.can_hit1 && self.can_hit12
}
pub fn can_hit_pikmin(&self) -> bool {
self.can_hit1 && self.can_hit12
}
pub fn can_hit_sse(&self) -> bool {
self.can_hit2
}
pub fn can_hit_gyro(&self) -> bool {
self.can_hit4 && self.can_hit11
}
pub fn can_hit_snake_grenade(&self) -> bool {
self.can_hit4 && self.can_hit11
}
pub fn can_hit_mr_saturn(&self) -> bool {
self.can_hit4 && self.can_hit11
}
pub fn can_hit_stage_non_wall_ceiling_floor(&self) -> bool {
self.can_hit7 && self.can_hit11
}
pub fn can_hit_wall_ceiling_floor(&self) -> bool {
self.can_hit8 && self.can_hit11
}
pub fn can_hit_link_bomb(&self) -> bool {
self.can_hit9 && self.can_hit10
}
pub fn can_hit_bobomb(&self) -> bool {
self.can_hit9 && self.can_hit10
}
}
#[derive(Clone, Debug)]
struct PositionHitBox {
pub values: CollisionBoxValues,
pub hitbox_id: u8,
pub size: f32,
pub interpolate: bool,
pub hitbox_position: Point3<f32>,
pub bone_position: Point3<f32>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct HighLevelHitBox {
pub hitbox_id: u8,
/// This value doesnt take into account the distance travelled by the character that HighLevelFighter doesnt know about e.g. due to velocity from previous subaction
pub prev_pos: Option<Point3<f32>>,
pub prev_size: Option<f32>,
pub prev_values: Option<CollisionBoxValues>,
pub next_pos: Point3<f32>,
pub next_size: f32,
pub next_values: CollisionBoxValues,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ECB {
pub left: f32,
pub right: f32,
pub top: f32,
pub bottom: f32,
pub transn_x: f32,
pub transn_y: f32,
}
fn gen_ecb(bone: &BoneTransforms, ecb_bones: &[i32], bone_refs: &BoneRefs, mut ecb: ECB) -> ECB {
for ecb_bone in ecb_bones {
if bone.index == *ecb_bone {
let x = bone.transform_normal.w.z;
let y = bone.transform_normal.w.y;
if x < ecb.left {
ecb.left = x;
}
if x > ecb.right {
ecb.right = x;
}
if y < ecb.bottom {
ecb.bottom = y;
}
if y > ecb.top {
ecb.top = y;
}
}
}
if bone.index == bone_refs.trans_n {
ecb.transn_x = bone.transform_normal.w.z;
ecb.transn_y = bone.transform_normal.w.y;
}
for child in bone.children.iter() {
ecb = gen_ecb(child, ecb_bones, bone_refs, ecb);
}
ecb
}
fn gen_hurt_boxes(bone: &BoneTransforms, hurt_boxes: &[HurtBox], script_runner: &ScriptRunner, fighter_size: f32) -> Vec<HighLevelHurtBox> {
let hurtbox_state_all = &script_runner.hurtbox_state_all;
let hurtbox_states = &script_runner.hurtbox_states;
let invisible_bones = &script_runner.invisible_bones;
let mut hl_hurt_boxes = vec!();
for hurt_box in hurt_boxes {
if bone.index == get_bone_index(hurt_box.bone_index as i32) {
let state = if let Some(state) = hurtbox_states.get(&bone.index) {
state
} else {
hurtbox_state_all
}.clone();
if invisible_bones.iter().all(|x| get_bone_index(*x) != bone.index) {
let mut hurt_box = hurt_box.clone();
hurt_box.offset *= fighter_size;
hurt_box.stretch *= fighter_size;
// dont multiply radius as that will be multiplied by the bone_matrix
hl_hurt_boxes.push(HighLevelHurtBox {
bone_matrix: bone.transform_normal,
hurt_box,
state,
});
}
}
}
for child in bone.children.iter() {
hl_hurt_boxes.extend(gen_hurt_boxes(child, hurt_boxes, script_runner, fighter_size));
}
hl_hurt_boxes
}
fn gen_hit_boxes(bone: &BoneTransforms, hit_boxes: &[ScriptCollisionBox], fighter_size: f32) -> Vec<PositionHitBox> {
let mut pos_hit_boxes = vec!();
for hit_box in hit_boxes.iter() {
if bone.index == get_bone_index(hit_box.bone_index as i32) {
let offset = Point3::new(hit_box.x_offset, hit_box.y_offset, hit_box.z_offset);
let offset = bone.transform_hitbox.transform_point(offset);
let bone_position = Point3::new(
bone.transform_normal.w.x,
bone.transform_normal.w.y,
bone.transform_normal.w.z,
);
let hitbox_position = Point3::new(
bone_position.x + offset.x,
bone_position.y + offset.y,
bone_position.z + offset.z,
);
let size = if hit_box.values.stretches_to_bone() {
hit_box.size * fighter_size
} else {
hit_box.size
};
pos_hit_boxes.push(PositionHitBox {
values: hit_box.values.clone(),
hitbox_id: hit_box.hitbox_id,
interpolate: hit_box.interpolate,
size,
hitbox_position,
bone_position,
});
}
}
for child in bone.children.iter() {
pos_hit_boxes.extend(gen_hit_boxes(child, hit_boxes, fighter_size));
}
pos_hit_boxes
}
// This is a basic (incorrect) implementation to handle wario and kirby's weird bone indices.
// Refer to https://github.com/libertyernie/brawltools/blob/83b79a571d84efc1884950204852a14eab58060e/Ikarus/Moveset%20Entries/MovesetNode.cs#L261
pub fn get_bone_index(index: i32) -> i32 {
if index >= 400 {
index - 400
} else {
index
}
}
#[derive(Serialize, Clone, Debug)]
pub struct SectionScriptAst {
pub name: String,
pub script: ScriptAst,
pub callers: Vec<i32>,
}
impl SectionScriptAst {
fn new(section_script: &SectionScript, external_subroutines: &[ExternalSubroutine]) -> SectionScriptAst {
SectionScriptAst {
name: section_script.name.clone(),
script: ScriptAst::new(§ion_script.script),
callers: external_subroutines.iter().find(|x| x.name == section_script.name).map(|x| x.offsets.clone()).unwrap_or_default(),
}
}
}
|
extern crate rustty;
use rustty::{
Terminal,
Event,
};
use rustty::ui::core::{
Painter,
Widget,
ButtonResult,
HorizontalAlign,
VerticalAlign
};
use rustty::ui::{
StdButton,
Dialog,
Label,
};
fn create_maindlg() -> Dialog {
let mut maindlg = Dialog::new(60, 10);
maindlg.draw_box();
let mut b1 = StdButton::new("Quit", 'q', ButtonResult::Ok);
b1.pack(&maindlg, HorizontalAlign::Left, VerticalAlign::Bottom, (4, 2));
let mut b2 = StdButton::new("Foo", 'f', ButtonResult::Custom(1));
b2.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Bottom, (0, 2));
let mut b3 = StdButton::new("Bar", 'b', ButtonResult::Custom(2));
b3.pack(&maindlg, HorizontalAlign::Right, VerticalAlign::Bottom, (4, 2));
maindlg.add_button(b1);
maindlg.add_button(b2);
maindlg.add_button(b3);
maindlg
}
fn main() {
let mut term = Terminal::new().unwrap();
let mut maindlg = create_maindlg();
maindlg.pack(&term, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0));
'main: loop {
while let Some(Event::Key(ch)) = term.get_event(0).unwrap() {
match maindlg.result_for_key(ch) {
Some(ButtonResult::Ok) => break 'main,
Some(ButtonResult::Custom(i)) => {
let msg = if i == 1 { "Foo!" } else { "Bar!" };
let mut label = Label::from_str(msg);
label.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0));
maindlg.add_label(label);
},
_ => {},
}
}
maindlg.draw(&mut term);
term.swap_buffers().unwrap();
}
}
|
use crate::config::cache::delete_version;
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use clap::Clap;
/// Deletes a specific versioned cache of dfx.
#[derive(Clap)]
#[clap(name("delete"))]
pub struct CacheDeleteOpts {
#[clap(long)]
version: Option<String>,
}
pub fn exec(env: &dyn Environment, opts: CacheDeleteOpts) -> DfxResult {
match opts.version {
Some(v) => delete_version(v.as_str()).map(|_| {}),
_ => env.get_cache().delete(),
}
}
|
mod command_manager;
use command_manager::CommandManager;
mod commands;
use serenity::prelude::*;
use std::env;
#[tokio::main]
async fn main() {
let token = env::var("DISCORD_TOKEN").expect("Environment Variable for DISCORD_TOKEN NOT Set");
let mut command_manager = CommandManager::new();
// register command here, in exec_command, and in help
// consider adding a command_manager.validate() that checks
// that each command is set up and has provided all info
// necessary. also check that roles in all commands are valid
command_manager.register(&["ping", "test"], 0, 0, &[]);
command_manager.register(&["help", "info"], 0, 1, &[]);
command_manager.register(&["delete_channel"], 0, 0, &["Admin"]);
command_manager.register(&["off"], 0, 0, &["Admin"]);
let mut client = Client::builder(token)
.event_handler(command_manager)
.await
.expect("client creation");
if let Err(e) = client.start().await {
println!("Error While Running Client: {}", e);
}
}
|
//! Seat global utilities
//!
//! This module provides you with utilities for handling the seat globals
//! and the associated input Wayland objects.
//!
//! ## How to use it
//!
//! ### Initialization
//!
//! ```
//! # extern crate wayland_server;
//! # #[macro_use] extern crate smithay;
//! use smithay::wayland::seat::{Seat, CursorImageRole};
//! # use smithay::wayland::compositor::compositor_init;
//!
//! // You need to insert the `CursorImageRole` into your roles, to handle requests from clients
//! // to set a surface as a cursor image
//! define_roles!(Roles => [CursorImage, CursorImageRole]);
//!
//! # fn main(){
//! # let mut event_loop = wayland_server::calloop::EventLoop::<()>::new().unwrap();
//! # let mut display = wayland_server::Display::new(event_loop.handle());
//! # let (compositor_token, _, _) = compositor_init::<Roles, _, _>(&mut display, |_, _, _| {}, None);
//! // insert the seat:
//! let (seat, seat_global) = Seat::new(
//! &mut display, // the display
//! "seat-0".into(), // the name of the seat, will be advertized to clients
//! compositor_token.clone(), // the compositor token
//! None // insert a logger here
//! );
//! # }
//! ```
//!
//! ### Run usage
//!
//! Once the seat is initialized, you can add capabilities to it.
//!
//! Currently, only pointer and keyboard capabilities are supported by
//! smithay.
//!
//! You can add these capabilities via methods of the [`Seat`](::wayland::seat::Seat) struct:
//! [`add_keyboard`](::wayland::seat::Seat::add_keyboard), [`add_pointer`](::wayland::seat::Seat::add_pointer).
//! These methods return handles that can be cloned and sent across thread, so you can keep one around
//! in your event-handling code to forward inputs to your clients.
use std::{cell::RefCell, rc::Rc};
mod keyboard;
mod pointer;
pub use self::{
keyboard::{keysyms, Error as KeyboardError, KeyboardHandle, Keysym, ModifiersState, XkbConfig},
pointer::{
AxisFrame, CursorImageRole, CursorImageStatus, PointerGrab, PointerHandle, PointerInnerHandle,
},
};
use crate::wayland::compositor::{roles::Role, CompositorToken};
use wayland_commons::utils::UserDataMap;
use wayland_server::{
protocol::{wl_seat, wl_surface},
Display, Global, NewResource,
};
struct Inner {
pointer: Option<PointerHandle>,
keyboard: Option<KeyboardHandle>,
known_seats: Vec<wl_seat::WlSeat>,
}
pub(crate) struct SeatRc {
inner: RefCell<Inner>,
user_data: UserDataMap,
pub(crate) log: ::slog::Logger,
name: String,
}
impl Inner {
fn compute_caps(&self) -> wl_seat::Capability {
let mut caps = wl_seat::Capability::empty();
if self.pointer.is_some() {
caps |= wl_seat::Capability::Pointer;
}
if self.keyboard.is_some() {
caps |= wl_seat::Capability::Keyboard;
}
caps
}
fn send_all_caps(&self) {
let capabilities = self.compute_caps();
for seat in &self.known_seats {
seat.capabilities(capabilities);
}
}
}
/// A Seat handle
///
/// This struct gives you access to the control of the
/// capabilities of the associated seat.
///
/// It is directly inserted in the event loop by its [`new`](Seat::new) method.
///
/// This is an handle to the inner logic, it can be cloned.
///
/// See module-level documentation for details of use.
#[derive(Clone)]
pub struct Seat {
pub(crate) arc: Rc<SeatRc>,
}
impl Seat {
/// Create a new seat global
///
/// A new seat global is created with given name and inserted
/// into this event loop.
///
/// You are provided with the state token to retrieve it (allowing
/// you to add or remove capabilities from it), and the global handle,
/// in case you want to remove it.
pub fn new<R, L>(
display: &mut Display,
name: String,
token: CompositorToken<R>,
logger: L,
) -> (Seat, Global<wl_seat::WlSeat>)
where
R: Role<CursorImageRole> + 'static,
L: Into<Option<::slog::Logger>>,
{
let log = crate::slog_or_stdlog(logger);
let arc = Rc::new(SeatRc {
inner: RefCell::new(Inner {
pointer: None,
keyboard: None,
known_seats: Vec::new(),
}),
log: log.new(o!("smithay_module" => "seat_handler", "seat_name" => name.clone())),
name,
user_data: UserDataMap::new(),
});
let seat = Seat { arc: arc.clone() };
let global = display.create_global(5, move |new_seat, _version| {
let seat = implement_seat(new_seat, arc.clone(), token.clone());
let mut inner = arc.inner.borrow_mut();
if seat.as_ref().version() >= 2 {
seat.name(arc.name.clone());
}
seat.capabilities(inner.compute_caps());
inner.known_seats.push(seat);
});
(seat, global)
}
/// Attempt to retrieve a [`Seat`] from an existing resource
pub fn from_resource(seat: &wl_seat::WlSeat) -> Option<Seat> {
seat.as_ref()
.user_data::<Rc<SeatRc>>()
.cloned()
.map(|arc| Seat { arc })
}
/// Acces the `UserDataMap` associated with this `Seat`
pub fn user_data(&self) -> &UserDataMap {
&self.arc.user_data
}
/// Adds the pointer capability to this seat
///
/// You are provided a [`PointerHandle`], which allows you to send input events
/// to this pointer. This handle can be cloned.
///
/// Calling this method on a seat that already has a pointer capability
/// will overwrite it, and will be seen by the clients as if the
/// mouse was unplugged and a new one was plugged.
///
/// You need to provide a compositor token, as well as a callback that will be notified
/// whenever a client requests to set a custom cursor image.
///
/// # Examples
///
/// ```
/// # extern crate wayland_server;
/// # #[macro_use] extern crate smithay;
/// #
/// # use smithay::wayland::{seat::{Seat, CursorImageRole}, compositor::compositor_init};
/// #
/// # define_roles!(Roles => [CursorImage, CursorImageRole]);
/// #
/// # fn main(){
/// # let mut event_loop = wayland_server::calloop::EventLoop::<()>::new().unwrap();
/// # let mut display = wayland_server::Display::new(event_loop.handle());
/// # let (compositor_token, _, _) = compositor_init::<Roles, _, _>(&mut display, |_, _, _| {}, None);
/// # let (mut seat, seat_global) = Seat::new(
/// # &mut display,
/// # "seat-0".into(),
/// # compositor_token.clone(),
/// # None
/// # );
/// let pointer_handle = seat.add_pointer(
/// compositor_token.clone(),
/// |new_status| { /* a closure handling requests from clients tot change the cursor icon */ }
/// );
/// # }
/// ```
pub fn add_pointer<R, F>(&mut self, token: CompositorToken<R>, cb: F) -> PointerHandle
where
R: Role<CursorImageRole> + 'static,
F: FnMut(CursorImageStatus) + 'static,
{
let mut inner = self.arc.inner.borrow_mut();
let pointer = self::pointer::create_pointer_handler(token, cb);
if inner.pointer.is_some() {
// there is already a pointer, remove it and notify the clients
// of the change
inner.pointer = None;
inner.send_all_caps();
}
inner.pointer = Some(pointer.clone());
inner.send_all_caps();
pointer
}
/// Access the pointer of this seat if any
pub fn get_pointer(&self) -> Option<PointerHandle> {
self.arc.inner.borrow_mut().pointer.clone()
}
/// Remove the pointer capability from this seat
///
/// Clients will be appropriately notified.
pub fn remove_pointer(&mut self) {
let mut inner = self.arc.inner.borrow_mut();
if inner.pointer.is_some() {
inner.pointer = None;
inner.send_all_caps();
}
}
/// Adds the keyboard capability to this seat
///
/// You are provided a [`KeyboardHandle`], which allows you to send input events
/// to this keyboard. This handle can be cloned.
///
/// You also provide a Model/Layout/Variant/Options specification of the
/// keymap to be used for this keyboard, as well as any repeat-info that
/// will be forwarded to the clients.
///
/// Calling this method on a seat that already has a keyboard capability
/// will overwrite it, and will be seen by the clients as if the
/// keyboard was unplugged and a new one was plugged.
///
/// # Examples
///
/// ```no_run
/// # extern crate smithay;
/// # use smithay::wayland::seat::{Seat, XkbConfig};
/// # let mut seat: Seat = unimplemented!();
/// let keyboard = seat
/// .add_keyboard(
/// XkbConfig {
/// layout: "de",
/// variant: "nodeadkeys",
/// ..XkbConfig::default()
/// },
/// 1000,
/// 500,
/// |seat, focus| {
/// /* This closure is called whenever the keyboard focus
/// * changes, with the new focus as argument */
/// }
/// )
/// .expect("Failed to initialize the keyboard");
/// ```
pub fn add_keyboard<F>(
&mut self,
xkb_config: keyboard::XkbConfig<'_>,
repeat_delay: i32,
repeat_rate: i32,
mut focus_hook: F,
) -> Result<KeyboardHandle, KeyboardError>
where
F: FnMut(&Seat, Option<&wl_surface::WlSurface>) + 'static,
{
let me = self.clone();
let mut inner = self.arc.inner.borrow_mut();
let keyboard = self::keyboard::create_keyboard_handler(
xkb_config,
repeat_delay,
repeat_rate,
&self.arc.log,
move |focus| focus_hook(&me, focus),
)?;
if inner.keyboard.is_some() {
// there is already a keyboard, remove it and notify the clients
// of the change
inner.keyboard = None;
inner.send_all_caps();
}
inner.keyboard = Some(keyboard.clone());
inner.send_all_caps();
Ok(keyboard)
}
/// Access the keyboard of this seat if any
pub fn get_keyboard(&self) -> Option<KeyboardHandle> {
self.arc.inner.borrow_mut().keyboard.clone()
}
/// Remove the keyboard capability from this seat
///
/// Clients will be appropriately notified.
pub fn remove_keyboard(&mut self) {
let mut inner = self.arc.inner.borrow_mut();
if inner.keyboard.is_some() {
inner.keyboard = None;
inner.send_all_caps();
}
}
/// Checks whether a given [`WlSeat`](wl_seat::WlSeat) is associated with this [`Seat`]
pub fn owns(&self, seat: &wl_seat::WlSeat) -> bool {
let inner = self.arc.inner.borrow_mut();
inner.known_seats.iter().any(|s| s.as_ref().equals(seat.as_ref()))
}
}
impl ::std::cmp::PartialEq for Seat {
fn eq(&self, other: &Seat) -> bool {
Rc::ptr_eq(&self.arc, &other.arc)
}
}
fn implement_seat<R>(
new_seat: NewResource<wl_seat::WlSeat>,
arc: Rc<SeatRc>,
token: CompositorToken<R>,
) -> wl_seat::WlSeat
where
R: Role<CursorImageRole> + 'static,
{
let dest_arc = arc.clone();
new_seat.implement_closure(
move |request, seat| {
let arc = seat.as_ref().user_data::<Rc<SeatRc>>().unwrap();
let inner = arc.inner.borrow_mut();
match request {
wl_seat::Request::GetPointer { id } => {
let pointer = self::pointer::implement_pointer(id, inner.pointer.as_ref(), token.clone());
if let Some(ref ptr_handle) = inner.pointer {
ptr_handle.new_pointer(pointer);
} else {
// we should send a protocol error... but the protocol does not allow
// us, so this pointer will just remain inactive ¯\_(ツ)_/¯
}
}
wl_seat::Request::GetKeyboard { id } => {
let keyboard = self::keyboard::implement_keyboard(id, inner.keyboard.as_ref());
if let Some(ref kbd_handle) = inner.keyboard {
kbd_handle.new_kbd(keyboard);
} else {
// same as pointer, should error but cannot
}
}
wl_seat::Request::GetTouch { id: _ } => {
// TODO
}
wl_seat::Request::Release => {
// Our destructors already handle it
}
_ => unreachable!(),
}
},
Some(move |seat: wl_seat::WlSeat| {
dest_arc
.inner
.borrow_mut()
.known_seats
.retain(|s| !s.as_ref().equals(&seat.as_ref()));
}),
arc,
)
}
|
#[doc = "Register `BOOT_CURR` reader"]
pub type R = crate::R<BOOT_CURR_SPEC>;
#[doc = "Field `BOOT_ADD0` reader - Boot address 0"]
pub type BOOT_ADD0_R = crate::FieldReader<u16>;
#[doc = "Field `BOOT_ADD1` reader - Boot address 1"]
pub type BOOT_ADD1_R = crate::FieldReader<u16>;
impl R {
#[doc = "Bits 0:15 - Boot address 0"]
#[inline(always)]
pub fn boot_add0(&self) -> BOOT_ADD0_R {
BOOT_ADD0_R::new((self.bits & 0xffff) as u16)
}
#[doc = "Bits 16:31 - Boot address 1"]
#[inline(always)]
pub fn boot_add1(&self) -> BOOT_ADD1_R {
BOOT_ADD1_R::new(((self.bits >> 16) & 0xffff) as u16)
}
}
#[doc = "FLASH register with boot address\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`boot_curr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct BOOT_CURR_SPEC;
impl crate::RegisterSpec for BOOT_CURR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`boot_curr::R`](R) reader structure"]
impl crate::Readable for BOOT_CURR_SPEC {}
#[doc = "`reset()` method sets BOOT_CURR to value 0"]
impl crate::Resettable for BOOT_CURR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::path::PathBuf;
use std::fs;
use clap::{App, Arg};
use archiver::config;
use archiver::ctx::Ctx;
use archiver::mountable;
use archiver::cli;
fn cli_opts<'a, 'b>() -> App<'a, 'b> {
cli::base_opts()
.about("Smoke test the mounting infrastructure")
.arg(Arg::with_name("LABEL")
.help("Label of the device to test mount")
.required(true)
.index(1))
}
fn main() {
archiver::cli::run(|| {
let matches = cli_opts().get_matches();
let cfg = config::Config::from_file(matches.value_of("config").unwrap_or("archiver.toml"));
let ctx = Ctx::create_without_lock(cfg?)?;
let mut pb = PathBuf::from("/dev/disk/by-label");
pb.push(matches.value_of("LABEL").expect("no label"));
let mp = mountable::UdisksMounter::mount(pb)?;
for file in fs::read_dir(mp.path())? {
println!(" {:?}", &file?);
}
Ok(())
});
}
|
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_185"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/libsass-closed-issues/issue_185/hoisting.hrx"
#[test]
#[ignore] // wrong result
fn hoisting() {
assert_eq!(
rsass(
"@media only screen {\
\n .foo {\
\n content: bar;\
\n\
\n @media (min-width: 1337px) {\
\n content: baz;\
\n }\
\n\
\n content: foo;\
\n }\
\n}\
\n\
\n$foo: \"(min-width: 0) and (max-width: 599px), (min-width: 600px) and (max-width: 899px)\";\
\n@media #{$foo} {\
\n $bar: \"(min-width: 0) and (max-width: 599px)\";\
\n @media #{$bar} {\
\n .foo {\
\n content: bar;\
\n }\
\n }\
\n}\
\n"
)
.unwrap(),
"@media only screen {\
\n .foo {\
\n content: bar;\
\n content: foo;\
\n }\
\n}\
\n@media only screen and (min-width: 1337px) {\
\n .foo {\
\n content: baz;\
\n }\
\n}\
\n@media (min-width: 0) and (max-width: 599px) and (min-width: 0) and (max-width: 599px), (min-width: 600px) and (max-width: 899px) and (min-width: 0) and (max-width: 599px) {\
\n .foo {\
\n content: bar;\
\n }\
\n}\
\n"
);
}
// From "sass-spec/spec/libsass-closed-issues/issue_185/media_level_4.hrx"
#[test]
#[ignore] // wrong result
fn media_level_4() {
assert_eq!(
rsass(
".foo {\
\n @media (pointer: none) {\
\n content: foo;\
\n\
\n @media (scripting) {\
\n content: baz;\
\n\
\n @media (light-level: dim) {\
\n content: bar;\
\n }\
\n }\
\n }\
\n}\
\n"
)
.unwrap(),
"@media (pointer: none) {\
\n .foo {\
\n content: foo;\
\n }\
\n}\
\n@media (pointer: none) and (scripting) {\
\n .foo {\
\n content: baz;\
\n }\
\n}\
\n@media (pointer: none) and (scripting) and (light-level: dim) {\
\n .foo {\
\n content: bar;\
\n }\
\n}\
\n"
);
}
// From "sass-spec/spec/libsass-closed-issues/issue_185/media_wrapper_selector.hrx"
#[test]
#[ignore] // wrong result
fn media_wrapper_selector() {
assert_eq!(
rsass(
"@media all {\
\n .bar { content: baz; }\
\n\
\n @media (min-width: 1337px) {\
\n .foo { content: bar; }\
\n }\
\n}\
\n\
\n@media all {\
\n .bar { content: baz; }\
\n\
\n @media (min-width: 1337px) {\
\n .baz { content: foo; }\
\n\
\n @media (max-width: 42em) {\
\n .foo { content: bar; }\
\n }\
\n }\
\n}\
\n"
)
.unwrap(),
"@media all {\
\n .bar {\
\n content: baz;\
\n }\
\n}\
\n@media (min-width: 1337px) {\
\n .foo {\
\n content: bar;\
\n }\
\n}\
\n@media all {\
\n .bar {\
\n content: baz;\
\n }\
\n}\
\n@media (min-width: 1337px) {\
\n .baz {\
\n content: foo;\
\n }\
\n}\
\n@media (min-width: 1337px) and (max-width: 42em) {\
\n .foo {\
\n content: bar;\
\n }\
\n}\
\n"
);
}
// From "sass-spec/spec/libsass-closed-issues/issue_185/merge_no_repeat.hrx"
#[test]
#[ignore] // wrong result
fn merge_no_repeat() {
assert_eq!(
rsass(
".foo {\
\n content: foo;\
\n\
\n @media only screen and (min-width: 1337px) {\
\n content: bar;\
\n\
\n @media only screen and (max-width: 42em) {\
\n content: baz;\
\n }\
\n }\
\n}\
\n"
)
.unwrap(),
".foo {\
\n content: foo;\
\n}\
\n@media only screen and (min-width: 1337px) {\
\n .foo {\
\n content: bar;\
\n }\
\n}\
\n@media only screen and (min-width: 1337px) and (max-width: 42em) {\
\n .foo {\
\n content: baz;\
\n }\
\n}\
\n"
);
}
// Ignoring "mixin.hrx", not expected to work yet.
// From "sass-spec/spec/libsass-closed-issues/issue_185/selector_wrapper_media.hrx"
#[test]
#[ignore] // wrong result
fn selector_wrapper_media() {
assert_eq!(
rsass(
".foo {\
\n @media all {\
\n content: baz;\
\n\
\n @media (min-width: 1337px) {\
\n content: bar;\
\n }\
\n }\
\n}\
\n\
\n.foo {\
\n @media all {\
\n content: baz;\
\n\
\n @media (min-width: 1337px) {\
\n content: foo;\
\n\
\n @media (max-width: 42em) {\
\n content: bar;\
\n }\
\n }\
\n }\
\n}\
\n"
)
.unwrap(),
"@media all {\
\n .foo {\
\n content: baz;\
\n }\
\n}\
\n@media (min-width: 1337px) {\
\n .foo {\
\n content: bar;\
\n }\
\n}\
\n@media all {\
\n .foo {\
\n content: baz;\
\n }\
\n}\
\n@media (min-width: 1337px) {\
\n .foo {\
\n content: foo;\
\n }\
\n}\
\n@media (min-width: 1337px) and (max-width: 42em) {\
\n .foo {\
\n content: bar;\
\n }\
\n}\
\n"
);
}
|
use vecmath::*;
pub fn encoder_sub(a: i16, b: i16) -> i16 {
const RANGE : i16 = 4096;
let c = a.wrapping_sub(b) % RANGE;
if c < -RANGE/2 {
c + RANGE
} else if c > RANGE/2 {
c - RANGE
} else {
c
}
}
pub fn vec2_encoder_sub(a: Vector2<i16>, b: Vector2<i16>) -> Vector2<i16> {
[ encoder_sub(a[0], b[0]), encoder_sub(a[1], b[1]) ]
}
|
extern crate clang;
extern crate clang_sys;
extern crate futures;
#[macro_use]
extern crate log;
extern crate log4rs;
extern crate lsp_rs;
extern crate ls_service;
extern crate tokio_core;
extern crate tokio_stdio;
#[cfg( windows )]
extern crate kernel32;
#[cfg( windows )]
extern crate winapi;
mod parent_process;
mod handler;
use ls_service::{
service
};
use tokio_core::reactor::{
Core
};
use tokio_stdio::stdio::{
Stdio
};
fn main( ) {
log4rs::init_file( "log4rs.yml", Default::default( ) ).unwrap( );
let mut core = Core::new( ).unwrap( );
let message_handler = handler::DynamicMessageHandler::new( core.handle( ) );
let io = Stdio::new( 1024, 1024 );
info!( "Starting service on stdin/stdout." );
let service_handle = service::start_service( core.handle( ), message_handler, io );
match core.run( service_handle.get_shutdown_future( ).clone( ) ) {
Ok( _ ) => {
info!( "Service terminated cleanly." );
},
Err( error ) => {
info!( "Service terminated with error {:?}", error );
}
}
}
|
use surf::http::Method;
use crate::framework::endpoint::Endpoint;
use super::Tunnel;
/// Delete a tunnel
/// https://api.cloudflare.com/#argo-tunnel-delete-argo-tunnel
#[derive(Debug)]
pub struct DeleteTunnel<'a> {
pub account_identifier: &'a str,
pub tunnel_id: &'a str,
}
impl<'a> Endpoint<Tunnel> for DeleteTunnel<'a> {
fn method(&self) -> Method {
Method::Delete
}
fn path(&self) -> String {
format!(
"accounts/{}/tunnels/{}",
self.account_identifier, self.tunnel_id
)
}
}
|
use std::collections::HashMap;
pub fn brackets_are_balanced(string: &str) -> bool {
let mut stack = vec![];
let brackets: HashMap<char, char> = [('(', ')'), ('{', '}'), ('[', ']')]
.iter()
.cloned()
.collect();
for c in string.chars() {
if !brackets.contains_key(&c) && !brackets.values().any(|&x| x == c) {
continue;
}
if brackets.contains_key(&c) {
stack.push(c);
continue;
}
match stack.pop() {
Some(b) if brackets[&b] == c => continue,
_ => return false,
}
}
stack.is_empty()
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - FLASH access control register"]
pub acr: ACR,
#[doc = "0x04 - FLASH non-secure key register"]
pub nskeyr: NSKEYR,
#[doc = "0x08 - FLASH secure key register"]
pub seckeyr: SECKEYR,
#[doc = "0x0c - FLASH option key register"]
pub optkeyr: OPTKEYR,
#[doc = "0x10 - FLASH non-secure OBK key register"]
pub nsobkkeyr: NSOBKKEYR,
#[doc = "0x14 - FLASH secure OBK key register"]
pub secobkkeyr: SECOBKKEYR,
#[doc = "0x18 - FLASH operation status register"]
pub opsr: OPSR,
#[doc = "0x1c - FLASH option control register"]
pub optcr: OPTCR,
#[doc = "0x20 - FLASH non-secure status register"]
pub nssr: NSSR,
#[doc = "0x24 - FLASH secure status register"]
pub secsr: SECSR,
#[doc = "0x28 - FLASH non-secure control register"]
pub nscr: NSCR,
#[doc = "0x2c - FLASH secure control register"]
pub seccr: SECCR,
#[doc = "0x30 - FLASH non-secure clear control register"]
pub nsccr: NSCCR,
#[doc = "0x34 - FLASH secure clear control register"]
pub secccr: SECCCR,
_reserved14: [u8; 0x04],
#[doc = "0x3c - FLASH privilege configuration register"]
pub privcfgr: PRIVCFGR,
#[doc = "0x40 - FLASH non-secure OBK configuration register"]
pub nsobkcfgr: NSOBKCFGR,
#[doc = "0x44 - FLASH secure OBK configuration register"]
pub secobkcfgr: SECOBKCFGR,
#[doc = "0x48 - FLASH HDP extension register"]
pub hdpextr: HDPEXTR,
_reserved18: [u8; 0x04],
#[doc = "0x50 - FLASH option status register"]
pub optsr_cur: OPTSR_CUR,
#[doc = "0x54 - FLASH option status register"]
pub optsr_prg: OPTSR_PRG,
_reserved20: [u8; 0x08],
#[doc = "0x60 - FLASH non-secure EPOCH register"]
pub nsepochr_cur: NSEPOCHR_CUR,
_reserved21: [u8; 0x04],
#[doc = "0x68 - FLASH secure EPOCH register"]
pub secepochr_cur: SECEPOCHR_CUR,
_reserved22: [u8; 0x04],
#[doc = "0x70 - FLASH option status register 2"]
pub optsr2_cur: OPTSR2_CUR,
#[doc = "0x74 - FLASH option status register 2"]
pub optsr2_prg: OPTSR2_PRG,
_reserved24: [u8; 0x08],
#[doc = "0x80 - FLASH non-secure boot register"]
pub nsbootr_cur: NSBOOTR_CUR,
#[doc = "0x84 - FLASH non-secure boot register"]
pub nsbootr_prg: NSBOOTR_PRG,
#[doc = "0x88 - FLASH secure boot register"]
pub secbootr_cur: SECBOOTR_CUR,
#[doc = "0x8c - FLASH secure boot register"]
pub bootr_prg: BOOTR_PRG,
#[doc = "0x90 - FLASH non-secure OTP block lock"]
pub otpblr_cur: OTPBLR_CUR,
#[doc = "0x94 - FLASH non-secure OTP block lock"]
pub otpblr_prg: OTPBLR_PRG,
_reserved30: [u8; 0x08],
#[doc = "0xa0 - FLASH secure block based register for Bank 1"]
pub secbb1r1: SECBB1R1,
#[doc = "0xa4 - FLASH secure block based register for Bank 1"]
pub secbb1r2: SECBB1R2,
#[doc = "0xa8 - FLASH secure block based register for Bank 1"]
pub secbb1r3: SECBB1R3,
#[doc = "0xac - FLASH secure block based register for Bank 1"]
pub secbb1r4: SECBB1R4,
_reserved34: [u8; 0x10],
#[doc = "0xc0 - FLASH privilege block based register for Bank 1"]
pub privbb1r1: PRIVBB1R1,
#[doc = "0xc4 - FLASH privilege block based register for Bank 1"]
pub privbb1r2: PRIVBB1R2,
#[doc = "0xc8 - FLASH privilege block based register for Bank 1"]
pub privbb1r3: PRIVBB1R3,
#[doc = "0xcc - FLASH privilege block based register for Bank 1"]
pub privbb1r4: PRIVBB1R4,
_reserved38: [u8; 0x10],
#[doc = "0xe0 - FLASH security watermark for Bank 1"]
pub secwm1r_cur: SECWM1R_CUR,
#[doc = "0xe4 - FLASH security watermark for Bank 1"]
pub secwm1r_prg: SECWM1R_PRG,
#[doc = "0xe8 - FLASH write sector group protection for Bank 1"]
pub wrp1r_cur: WRP1R_CUR,
#[doc = "0xec - FLASH write sector group protection for Bank 1"]
pub wrp1r_prg: WRP1R_PRG,
#[doc = "0xf0 - FLASH data sector configuration Bank 1"]
pub edata1r_cur: EDATA1R_CUR,
#[doc = "0xf4 - FLASH data sector configuration Bank 1"]
pub edata1r_prg: EDATA1R_PRG,
#[doc = "0xf8 - FLASH HDP Bank 1 configuration"]
pub hdp1r_cur: HDP1R_CUR,
#[doc = "0xfc - FLASH HDP Bank 1 configuration"]
pub hdp1r_prg: HDP1R_PRG,
#[doc = "0x100 - FLASH ECC correction register"]
pub ecccorr: ECCCORR,
#[doc = "0x104 - FLASH ECC detection register"]
pub eccdetr: ECCDETR,
#[doc = "0x108 - FLASH ECC data"]
pub eccdr: ECCDR,
_reserved49: [u8; 0x94],
#[doc = "0x1a0 - FLASH secure block-based register for Bank 2"]
pub secbb2r1: SECBB2R1,
#[doc = "0x1a4 - FLASH secure block-based register for Bank 2"]
pub secbb2r2: SECBB2R2,
#[doc = "0x1a8 - FLASH secure block-based register for Bank 2"]
pub secbb2r3: SECBB2R3,
#[doc = "0x1ac - FLASH secure block-based register for Bank 2"]
pub secbb2r4: SECBB2R4,
_reserved53: [u8; 0x10],
#[doc = "0x1c0 - FLASH privilege block-based register for Bank 2"]
pub privbb2r1: PRIVBB2R1,
#[doc = "0x1c4 - FLASH privilege block-based register for Bank 2"]
pub privbb2r2: PRIVBB2R2,
#[doc = "0x1c8 - FLASH privilege block-based register for Bank 2"]
pub privbb2r3: PRIVBB2R3,
#[doc = "0x1cc - FLASH privilege block-based register for Bank 2"]
pub privbb2r4: PRIVBB2R4,
_reserved57: [u8; 0x10],
#[doc = "0x1e0 - FLASH security watermark for Bank 2"]
pub secwm2r_cur: SECWM2R_CUR,
#[doc = "0x1e4 - FLASH security watermark for Bank 2"]
pub secwm2r_prg: SECWM2R_PRG,
#[doc = "0x1e8 - FLASH write sector group protection for Bank 2"]
pub wrp2r_cur: WRP2R_CUR,
#[doc = "0x1ec - FLASH write sector group protection for Bank 2"]
pub wrp2r_prg: WRP2R_PRG,
#[doc = "0x1f0 - FLASH data sectors configuration Bank 2"]
pub edata2r_cur: EDATA2R_CUR,
#[doc = "0x1f4 - FLASH data sector configuration Bank 2"]
pub edata2r_prg: EDATA2R_PRG,
#[doc = "0x1f8 - FLASH HDP Bank 2 configuration"]
pub hdp2r_cur: HDP2R_CUR,
#[doc = "0x1fc - FLASH HDP Bank 2 configuration"]
pub hdp2r_prg: HDP2R_PRG,
}
#[doc = "ACR (rw) register accessor: FLASH access control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`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 [`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 [`acr`]
module"]
pub type ACR = crate::Reg<acr::ACR_SPEC>;
#[doc = "FLASH access control register"]
pub mod acr;
#[doc = "NSKEYR (w) register accessor: FLASH non-secure key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`nskeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`nskeyr`]
module"]
pub type NSKEYR = crate::Reg<nskeyr::NSKEYR_SPEC>;
#[doc = "FLASH non-secure key register"]
pub mod nskeyr;
#[doc = "SECKEYR (w) register accessor: FLASH secure key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`seckeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`seckeyr`]
module"]
pub type SECKEYR = crate::Reg<seckeyr::SECKEYR_SPEC>;
#[doc = "FLASH secure key register"]
pub mod seckeyr;
#[doc = "OPTKEYR (w) register accessor: FLASH option key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`optkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optkeyr`]
module"]
pub type OPTKEYR = crate::Reg<optkeyr::OPTKEYR_SPEC>;
#[doc = "FLASH option key register"]
pub mod optkeyr;
#[doc = "NSOBKKEYR (w) register accessor: FLASH non-secure OBK key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`nsobkkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`nsobkkeyr`]
module"]
pub type NSOBKKEYR = crate::Reg<nsobkkeyr::NSOBKKEYR_SPEC>;
#[doc = "FLASH non-secure OBK key register"]
pub mod nsobkkeyr;
#[doc = "SECOBKKEYR (w) register accessor: FLASH secure OBK key register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`secobkkeyr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`secobkkeyr`]
module"]
pub type SECOBKKEYR = crate::Reg<secobkkeyr::SECOBKKEYR_SPEC>;
#[doc = "FLASH secure OBK key register"]
pub mod secobkkeyr;
#[doc = "OPSR (r) register accessor: FLASH operation status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`opsr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`opsr`]
module"]
pub type OPSR = crate::Reg<opsr::OPSR_SPEC>;
#[doc = "FLASH operation status register"]
pub mod opsr;
#[doc = "OPTCR (rw) register accessor: FLASH option control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optcr::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 [`optcr::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 [`optcr`]
module"]
pub type OPTCR = crate::Reg<optcr::OPTCR_SPEC>;
#[doc = "FLASH option control register"]
pub mod optcr;
#[doc = "NSSR (r) register accessor: FLASH non-secure status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`nssr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`nssr`]
module"]
pub type NSSR = crate::Reg<nssr::NSSR_SPEC>;
#[doc = "FLASH non-secure status register"]
pub mod nssr;
#[doc = "SECSR (r) register accessor: FLASH secure status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secsr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`secsr`]
module"]
pub type SECSR = crate::Reg<secsr::SECSR_SPEC>;
#[doc = "FLASH secure status register"]
pub mod secsr;
#[doc = "NSCR (rw) register accessor: FLASH non-secure control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`nscr::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 [`nscr::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 [`nscr`]
module"]
pub type NSCR = crate::Reg<nscr::NSCR_SPEC>;
#[doc = "FLASH non-secure control register"]
pub mod nscr;
#[doc = "SECCR (rw) register accessor: FLASH secure control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`seccr::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 [`seccr::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 [`seccr`]
module"]
pub type SECCR = crate::Reg<seccr::SECCR_SPEC>;
#[doc = "FLASH secure control register"]
pub mod seccr;
#[doc = "NSCCR (w) register accessor: FLASH non-secure clear control register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`nsccr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`nsccr`]
module"]
pub type NSCCR = crate::Reg<nsccr::NSCCR_SPEC>;
#[doc = "FLASH non-secure clear control register"]
pub mod nsccr;
#[doc = "SECCCR (w) register accessor: FLASH secure clear control register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`secccr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`secccr`]
module"]
pub type SECCCR = crate::Reg<secccr::SECCCR_SPEC>;
#[doc = "FLASH secure clear control register"]
pub mod secccr;
#[doc = "PRIVCFGR (rw) register accessor: FLASH privilege configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privcfgr::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 [`privcfgr::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 [`privcfgr`]
module"]
pub type PRIVCFGR = crate::Reg<privcfgr::PRIVCFGR_SPEC>;
#[doc = "FLASH privilege configuration register"]
pub mod privcfgr;
#[doc = "NSOBKCFGR (rw) register accessor: FLASH non-secure OBK configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`nsobkcfgr::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 [`nsobkcfgr::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 [`nsobkcfgr`]
module"]
pub type NSOBKCFGR = crate::Reg<nsobkcfgr::NSOBKCFGR_SPEC>;
#[doc = "FLASH non-secure OBK configuration register"]
pub mod nsobkcfgr;
#[doc = "SECOBKCFGR (rw) register accessor: FLASH secure OBK configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secobkcfgr::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 [`secobkcfgr::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 [`secobkcfgr`]
module"]
pub type SECOBKCFGR = crate::Reg<secobkcfgr::SECOBKCFGR_SPEC>;
#[doc = "FLASH secure OBK configuration register"]
pub mod secobkcfgr;
#[doc = "HDPEXTR (rw) register accessor: FLASH HDP extension register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hdpextr::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 [`hdpextr::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 [`hdpextr`]
module"]
pub type HDPEXTR = crate::Reg<hdpextr::HDPEXTR_SPEC>;
#[doc = "FLASH HDP extension register"]
pub mod hdpextr;
#[doc = "OPTSR_CUR (r) register accessor: FLASH option status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optsr_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optsr_cur`]
module"]
pub type OPTSR_CUR = crate::Reg<optsr_cur::OPTSR_CUR_SPEC>;
#[doc = "FLASH option status register"]
pub mod optsr_cur;
#[doc = "OPTSR_PRG (rw) register accessor: FLASH option status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optsr_prg::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 [`optsr_prg::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 [`optsr_prg`]
module"]
pub type OPTSR_PRG = crate::Reg<optsr_prg::OPTSR_PRG_SPEC>;
#[doc = "FLASH option status register"]
pub mod optsr_prg;
#[doc = "NSEPOCHR_CUR (r) register accessor: FLASH non-secure EPOCH register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`nsepochr_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`nsepochr_cur`]
module"]
pub type NSEPOCHR_CUR = crate::Reg<nsepochr_cur::NSEPOCHR_CUR_SPEC>;
#[doc = "FLASH non-secure EPOCH register"]
pub mod nsepochr_cur;
#[doc = "SECEPOCHR_CUR (r) register accessor: FLASH secure EPOCH register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secepochr_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`secepochr_cur`]
module"]
pub type SECEPOCHR_CUR = crate::Reg<secepochr_cur::SECEPOCHR_CUR_SPEC>;
#[doc = "FLASH secure EPOCH register"]
pub mod secepochr_cur;
#[doc = "OPTSR2_CUR (r) register accessor: FLASH option status register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optsr2_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`optsr2_cur`]
module"]
pub type OPTSR2_CUR = crate::Reg<optsr2_cur::OPTSR2_CUR_SPEC>;
#[doc = "FLASH option status register 2"]
pub mod optsr2_cur;
#[doc = "OPTSR2_PRG (rw) register accessor: FLASH option status register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`optsr2_prg::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 [`optsr2_prg::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 [`optsr2_prg`]
module"]
pub type OPTSR2_PRG = crate::Reg<optsr2_prg::OPTSR2_PRG_SPEC>;
#[doc = "FLASH option status register 2"]
pub mod optsr2_prg;
#[doc = "NSBOOTR_CUR (r) register accessor: FLASH non-secure boot register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`nsbootr_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`nsbootr_cur`]
module"]
pub type NSBOOTR_CUR = crate::Reg<nsbootr_cur::NSBOOTR_CUR_SPEC>;
#[doc = "FLASH non-secure boot register"]
pub mod nsbootr_cur;
#[doc = "NSBOOTR_PRG (rw) register accessor: FLASH non-secure boot register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`nsbootr_prg::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 [`nsbootr_prg::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 [`nsbootr_prg`]
module"]
pub type NSBOOTR_PRG = crate::Reg<nsbootr_prg::NSBOOTR_PRG_SPEC>;
#[doc = "FLASH non-secure boot register"]
pub mod nsbootr_prg;
#[doc = "SECBOOTR_CUR (r) register accessor: FLASH secure boot register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbootr_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`secbootr_cur`]
module"]
pub type SECBOOTR_CUR = crate::Reg<secbootr_cur::SECBOOTR_CUR_SPEC>;
#[doc = "FLASH secure boot register"]
pub mod secbootr_cur;
#[doc = "BOOTR_PRG (rw) register accessor: FLASH secure boot register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bootr_prg::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 [`bootr_prg::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 [`bootr_prg`]
module"]
pub type BOOTR_PRG = crate::Reg<bootr_prg::BOOTR_PRG_SPEC>;
#[doc = "FLASH secure boot register"]
pub mod bootr_prg;
#[doc = "OTPBLR_CUR (r) register accessor: FLASH non-secure OTP block lock\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`otpblr_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`otpblr_cur`]
module"]
pub type OTPBLR_CUR = crate::Reg<otpblr_cur::OTPBLR_CUR_SPEC>;
#[doc = "FLASH non-secure OTP block lock"]
pub mod otpblr_cur;
#[doc = "OTPBLR_PRG (rw) register accessor: FLASH non-secure OTP block lock\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`otpblr_prg::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 [`otpblr_prg::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 [`otpblr_prg`]
module"]
pub type OTPBLR_PRG = crate::Reg<otpblr_prg::OTPBLR_PRG_SPEC>;
#[doc = "FLASH non-secure OTP block lock"]
pub mod otpblr_prg;
#[doc = "SECBB1R1 (rw) register accessor: FLASH secure block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb1r1::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 [`secbb1r1::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 [`secbb1r1`]
module"]
pub type SECBB1R1 = crate::Reg<secbb1r1::SECBB1R1_SPEC>;
#[doc = "FLASH secure block based register for Bank 1"]
pub mod secbb1r1;
#[doc = "SECBB1R2 (rw) register accessor: FLASH secure block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb1r2::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 [`secbb1r2::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 [`secbb1r2`]
module"]
pub type SECBB1R2 = crate::Reg<secbb1r2::SECBB1R2_SPEC>;
#[doc = "FLASH secure block based register for Bank 1"]
pub mod secbb1r2;
#[doc = "SECBB1R3 (rw) register accessor: FLASH secure block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb1r3::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 [`secbb1r3::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 [`secbb1r3`]
module"]
pub type SECBB1R3 = crate::Reg<secbb1r3::SECBB1R3_SPEC>;
#[doc = "FLASH secure block based register for Bank 1"]
pub mod secbb1r3;
#[doc = "SECBB1R4 (rw) register accessor: FLASH secure block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb1r4::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 [`secbb1r4::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 [`secbb1r4`]
module"]
pub type SECBB1R4 = crate::Reg<secbb1r4::SECBB1R4_SPEC>;
#[doc = "FLASH secure block based register for Bank 1"]
pub mod secbb1r4;
#[doc = "PRIVBB1R1 (rw) register accessor: FLASH privilege block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privbb1r1::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 [`privbb1r1::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 [`privbb1r1`]
module"]
pub type PRIVBB1R1 = crate::Reg<privbb1r1::PRIVBB1R1_SPEC>;
#[doc = "FLASH privilege block based register for Bank 1"]
pub mod privbb1r1;
#[doc = "PRIVBB1R2 (rw) register accessor: FLASH privilege block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privbb1r2::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 [`privbb1r2::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 [`privbb1r2`]
module"]
pub type PRIVBB1R2 = crate::Reg<privbb1r2::PRIVBB1R2_SPEC>;
#[doc = "FLASH privilege block based register for Bank 1"]
pub mod privbb1r2;
#[doc = "PRIVBB1R3 (rw) register accessor: FLASH privilege block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privbb1r3::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 [`privbb1r3::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 [`privbb1r3`]
module"]
pub type PRIVBB1R3 = crate::Reg<privbb1r3::PRIVBB1R3_SPEC>;
#[doc = "FLASH privilege block based register for Bank 1"]
pub mod privbb1r3;
#[doc = "PRIVBB1R4 (rw) register accessor: FLASH privilege block based register for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privbb1r4::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 [`privbb1r4::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 [`privbb1r4`]
module"]
pub type PRIVBB1R4 = crate::Reg<privbb1r4::PRIVBB1R4_SPEC>;
#[doc = "FLASH privilege block based register for Bank 1"]
pub mod privbb1r4;
#[doc = "SECWM1R_CUR (r) register accessor: FLASH security watermark for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secwm1r_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`secwm1r_cur`]
module"]
pub type SECWM1R_CUR = crate::Reg<secwm1r_cur::SECWM1R_CUR_SPEC>;
#[doc = "FLASH security watermark for Bank 1"]
pub mod secwm1r_cur;
#[doc = "SECWM1R_PRG (rw) register accessor: FLASH security watermark for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secwm1r_prg::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 [`secwm1r_prg::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 [`secwm1r_prg`]
module"]
pub type SECWM1R_PRG = crate::Reg<secwm1r_prg::SECWM1R_PRG_SPEC>;
#[doc = "FLASH security watermark for Bank 1"]
pub mod secwm1r_prg;
#[doc = "WRP1R_CUR (r) register accessor: FLASH write sector group protection for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wrp1r_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`wrp1r_cur`]
module"]
pub type WRP1R_CUR = crate::Reg<wrp1r_cur::WRP1R_CUR_SPEC>;
#[doc = "FLASH write sector group protection for Bank 1"]
pub mod wrp1r_cur;
#[doc = "WRP1R_PRG (rw) register accessor: FLASH write sector group protection for Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wrp1r_prg::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 [`wrp1r_prg::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 [`wrp1r_prg`]
module"]
pub type WRP1R_PRG = crate::Reg<wrp1r_prg::WRP1R_PRG_SPEC>;
#[doc = "FLASH write sector group protection for Bank 1"]
pub mod wrp1r_prg;
#[doc = "EDATA1R_CUR (r) register accessor: FLASH data sector configuration Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`edata1r_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`edata1r_cur`]
module"]
pub type EDATA1R_CUR = crate::Reg<edata1r_cur::EDATA1R_CUR_SPEC>;
#[doc = "FLASH data sector configuration Bank 1"]
pub mod edata1r_cur;
#[doc = "EDATA1R_PRG (rw) register accessor: FLASH data sector configuration Bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`edata1r_prg::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 [`edata1r_prg::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 [`edata1r_prg`]
module"]
pub type EDATA1R_PRG = crate::Reg<edata1r_prg::EDATA1R_PRG_SPEC>;
#[doc = "FLASH data sector configuration Bank 1"]
pub mod edata1r_prg;
#[doc = "HDP1R_CUR (r) register accessor: FLASH HDP Bank 1 configuration\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hdp1r_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hdp1r_cur`]
module"]
pub type HDP1R_CUR = crate::Reg<hdp1r_cur::HDP1R_CUR_SPEC>;
#[doc = "FLASH HDP Bank 1 configuration"]
pub mod hdp1r_cur;
#[doc = "HDP1R_PRG (rw) register accessor: FLASH HDP Bank 1 configuration\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hdp1r_prg::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 [`hdp1r_prg::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 [`hdp1r_prg`]
module"]
pub type HDP1R_PRG = crate::Reg<hdp1r_prg::HDP1R_PRG_SPEC>;
#[doc = "FLASH HDP Bank 1 configuration"]
pub mod hdp1r_prg;
#[doc = "ECCCORR (rw) register accessor: FLASH ECC correction register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ecccorr::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 [`ecccorr::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 [`ecccorr`]
module"]
pub type ECCCORR = crate::Reg<ecccorr::ECCCORR_SPEC>;
#[doc = "FLASH ECC correction register"]
pub mod ecccorr;
#[doc = "ECCDETR (rw) register accessor: FLASH ECC detection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eccdetr::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 [`eccdetr::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 [`eccdetr`]
module"]
pub type ECCDETR = crate::Reg<eccdetr::ECCDETR_SPEC>;
#[doc = "FLASH ECC detection register"]
pub mod eccdetr;
#[doc = "ECCDR (r) register accessor: FLASH ECC data\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eccdr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eccdr`]
module"]
pub type ECCDR = crate::Reg<eccdr::ECCDR_SPEC>;
#[doc = "FLASH ECC data"]
pub mod eccdr;
#[doc = "SECBB2R1 (rw) register accessor: FLASH secure block-based register for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb2r1::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 [`secbb2r1::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 [`secbb2r1`]
module"]
pub type SECBB2R1 = crate::Reg<secbb2r1::SECBB2R1_SPEC>;
#[doc = "FLASH secure block-based register for Bank 2"]
pub mod secbb2r1;
#[doc = "SECBB2R2 (rw) register accessor: FLASH secure block-based register for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb2r2::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 [`secbb2r2::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 [`secbb2r2`]
module"]
pub type SECBB2R2 = crate::Reg<secbb2r2::SECBB2R2_SPEC>;
#[doc = "FLASH secure block-based register for Bank 2"]
pub mod secbb2r2;
#[doc = "SECBB2R3 (rw) register accessor: FLASH secure block-based register for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb2r3::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 [`secbb2r3::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 [`secbb2r3`]
module"]
pub type SECBB2R3 = crate::Reg<secbb2r3::SECBB2R3_SPEC>;
#[doc = "FLASH secure block-based register for Bank 2"]
pub mod secbb2r3;
#[doc = "SECBB2R4 (rw) register accessor: FLASH secure block-based register for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbb2r4::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 [`secbb2r4::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 [`secbb2r4`]
module"]
pub type SECBB2R4 = crate::Reg<secbb2r4::SECBB2R4_SPEC>;
#[doc = "FLASH secure block-based register for Bank 2"]
pub mod secbb2r4;
#[doc = "PRIVBB2R1 (rw) register accessor: FLASH privilege block-based register for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privbb2r1::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 [`privbb2r1::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 [`privbb2r1`]
module"]
pub type PRIVBB2R1 = crate::Reg<privbb2r1::PRIVBB2R1_SPEC>;
#[doc = "FLASH privilege block-based register for Bank 2"]
pub mod privbb2r1;
#[doc = "PRIVBB2R2 (rw) register accessor: FLASH privilege block-based register for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privbb2r2::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 [`privbb2r2::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 [`privbb2r2`]
module"]
pub type PRIVBB2R2 = crate::Reg<privbb2r2::PRIVBB2R2_SPEC>;
#[doc = "FLASH privilege block-based register for Bank 2"]
pub mod privbb2r2;
#[doc = "PRIVBB2R3 (rw) register accessor: FLASH privilege block-based register for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privbb2r3::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 [`privbb2r3::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 [`privbb2r3`]
module"]
pub type PRIVBB2R3 = crate::Reg<privbb2r3::PRIVBB2R3_SPEC>;
#[doc = "FLASH privilege block-based register for Bank 2"]
pub mod privbb2r3;
#[doc = "PRIVBB2R4 (rw) register accessor: FLASH privilege block-based register for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privbb2r4::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 [`privbb2r4::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 [`privbb2r4`]
module"]
pub type PRIVBB2R4 = crate::Reg<privbb2r4::PRIVBB2R4_SPEC>;
#[doc = "FLASH privilege block-based register for Bank 2"]
pub mod privbb2r4;
#[doc = "SECWM2R_CUR (r) register accessor: FLASH security watermark for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secwm2r_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`secwm2r_cur`]
module"]
pub type SECWM2R_CUR = crate::Reg<secwm2r_cur::SECWM2R_CUR_SPEC>;
#[doc = "FLASH security watermark for Bank 2"]
pub mod secwm2r_cur;
#[doc = "SECWM2R_PRG (rw) register accessor: FLASH security watermark for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secwm2r_prg::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 [`secwm2r_prg::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 [`secwm2r_prg`]
module"]
pub type SECWM2R_PRG = crate::Reg<secwm2r_prg::SECWM2R_PRG_SPEC>;
#[doc = "FLASH security watermark for Bank 2"]
pub mod secwm2r_prg;
#[doc = "WRP2R_CUR (r) register accessor: FLASH write sector group protection for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wrp2r_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`wrp2r_cur`]
module"]
pub type WRP2R_CUR = crate::Reg<wrp2r_cur::WRP2R_CUR_SPEC>;
#[doc = "FLASH write sector group protection for Bank 2"]
pub mod wrp2r_cur;
#[doc = "WRP2R_PRG (rw) register accessor: FLASH write sector group protection for Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wrp2r_prg::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 [`wrp2r_prg::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 [`wrp2r_prg`]
module"]
pub type WRP2R_PRG = crate::Reg<wrp2r_prg::WRP2R_PRG_SPEC>;
#[doc = "FLASH write sector group protection for Bank 2"]
pub mod wrp2r_prg;
#[doc = "EDATA2R_CUR (r) register accessor: FLASH data sectors configuration Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`edata2r_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`edata2r_cur`]
module"]
pub type EDATA2R_CUR = crate::Reg<edata2r_cur::EDATA2R_CUR_SPEC>;
#[doc = "FLASH data sectors configuration Bank 2"]
pub mod edata2r_cur;
#[doc = "EDATA2R_PRG (rw) register accessor: FLASH data sector configuration Bank 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`edata2r_prg::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 [`edata2r_prg::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 [`edata2r_prg`]
module"]
pub type EDATA2R_PRG = crate::Reg<edata2r_prg::EDATA2R_PRG_SPEC>;
#[doc = "FLASH data sector configuration Bank 2"]
pub mod edata2r_prg;
#[doc = "HDP2R_CUR (r) register accessor: FLASH HDP Bank 2 configuration\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hdp2r_cur::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hdp2r_cur`]
module"]
pub type HDP2R_CUR = crate::Reg<hdp2r_cur::HDP2R_CUR_SPEC>;
#[doc = "FLASH HDP Bank 2 configuration"]
pub mod hdp2r_cur;
#[doc = "HDP2R_PRG (rw) register accessor: FLASH HDP Bank 2 configuration\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hdp2r_prg::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 [`hdp2r_prg::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 [`hdp2r_prg`]
module"]
pub type HDP2R_PRG = crate::Reg<hdp2r_prg::HDP2R_PRG_SPEC>;
#[doc = "FLASH HDP Bank 2 configuration"]
pub mod hdp2r_prg;
|
use log::info;
fn main() {
env_logger::init();
info!("start");
println!("Hello, world!");
info!("finish");
}
|
#[macro_use]
extern crate nom;
use std::str;
use nom::{digit, space};
use std::fs::File;
use std::io::Read;
use std::collections::HashSet;
named!(
program<i32>,
map_res!(map_res!(digit, str::from_utf8), str::parse)
);
named!(
peers<HashSet<i32>>,
map!(
separated_nonempty_list_complete!(tag!(", "), digit),
|vec: Vec<_>| vec.into_iter()
.map(|v| str::from_utf8(v).unwrap())
.map(|s| str::parse::<i32>(s).unwrap())
.collect()
)
);
named!(
program_peers<(i32, HashSet<i32>)>,
do_parse!(p: program >> space >> tag!("<->") >> space >> ps: peers >> (p, ps))
);
fn main() {
let path = "input.txt";
let mut input = File::open(path).expect("Unable to open file!");
let mut input_txt = String::new();
match input.read_to_string(&mut input_txt) {
Err(_) => return,
Ok(n) => println!("Read {} bytes", n),
}
let mut programs = Vec::new();
for line in input_txt.lines() {
let (_, peers) = program_peers(line.as_bytes()).unwrap().1;
programs.push(peers);
}
println!(
"Number of programs connected to program `0` is: {:?}",
get_connected_programs(0, &programs).len()
);
println!("Number of groups: {:?}", get_num_of_groups(&programs));
}
fn get_num_of_groups(programs: &[HashSet<i32>]) -> i32 {
let mut remaining_progs = (0i32..programs.len() as i32)
.into_iter()
.collect::<HashSet<_>>();
remaining_progs = remaining_progs
.difference(&get_connected_programs(0, &programs))
.cloned()
.collect::<HashSet<_>>();
let mut groups = 1;
while remaining_progs.len() != 0 {
let prog_id = *remaining_progs.iter().take(1).next().unwrap();
let connected_progrs = get_connected_programs(prog_id, &programs);
remaining_progs = remaining_progs
.difference(&connected_progrs)
.cloned()
.collect::<HashSet<_>>();
groups += 1;
}
groups
}
// we can use a tree to do this, an extra dependency should be added
fn get_connected_programs(program: i32, programs: &[HashSet<i32>]) -> HashSet<i32> {
// Tracks already visited programs
let mut seen_programs = HashSet::new();
// We start tracking with program `program`
seen_programs.insert(program);
// Holds all the programs that communicate up to program `program`
let mut conn_progs = programs[program as usize]
.iter()
.cloned()
.collect::<HashSet<_>>();
conn_progs.extend(seen_programs.iter());
loop {
let mut peers: HashSet<i32> = HashSet::new();
let diff = conn_progs
.difference(&seen_programs)
.cloned()
.collect::<HashSet<_>>();
for p in &diff {
peers.extend(programs[*p as usize].iter());
}
seen_programs.extend(diff);
conn_progs.extend(peers.iter());
if seen_programs.len() == conn_progs.len() {
break;
}
}
conn_progs
}
|
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::borrow::Cow;
use syn::visit;
use syn::{Fields, Lifetime};
use synstructure::{BindingInfo, Structure};
pub(crate) fn derive(mut s: Structure) -> TokenStream {
let tape_lt = s
.ast()
.generics
.lifetimes()
.find(|def| def.lifetime.ident == "tape")
.map_or_else(
|| Cow::Owned(Lifetime::new("'tape", Span::call_site())),
|def| Cow::Borrowed(&def.lifetime),
);
let (builtin_tape_lt, generated_tape_lt) = match &tape_lt {
Cow::Owned(lt) => (None, Some(lt)),
Cow::Borrowed(lt) => (Some(*lt), None),
};
let has_type_params = s.ast().generics.type_params().next().is_some();
let body = if builtin_tape_lt.is_none() && !has_type_params {
quote! { core::fmt::Debug::fmt(self, fmt) }
} else {
let mut type_classifier = TypeClassifier::new(builtin_tape_lt);
let match_arms = s.variants().iter().map(|v| {
let ctor = v.ast().ident.to_string();
let pat = v.pat();
let expr = match v.ast().fields {
Fields::Named(..) => {
let unfinished = v.bindings().iter().fold(
quote! { core::fmt::Formatter::debug_struct(fmt, #ctor) },
|acc, b| {
let name = b.ast().ident.as_ref().unwrap().to_string();
let field_expr = type_classifier.field_expr(b);
quote! {
core::fmt::DebugStruct::field(
&mut #acc,
#name,
#field_expr
)
}
},
);
quote! { core::fmt::DebugStruct::finish(#unfinished) }
}
Fields::Unnamed(..) => {
let unfinished = v.bindings().iter().fold(
quote! { core::fmt::Formatter::debug_tuple(fmt, #ctor) },
|acc, b| {
let field_expr = type_classifier.field_expr(b);
quote! {
core::fmt::DebugTuple::field(
&mut #acc,
#field_expr
)
}
},
);
quote! { core::fmt::DebugTuple::finish(#unfinished) }
}
Fields::Unit => quote! { fmt.write_str(#ctor) },
};
quote! { #pat => #expr }
});
quote! { match *self { #(#match_arms)* } }
};
s.underscore_const(true).gen_impl(quote! {
gen impl<#generated_tape_lt> naam::debug_info::Dump<#tape_lt> for @Self {
fn dump(
&self,
fmt: &mut core::fmt::Formatter,
dumper: naam::debug_info::Dumper<#tape_lt>,
) -> core::fmt::Result {
#body
}
}
})
}
struct TypeClassifier<'a> {
tape_lt: Option<&'a Lifetime>,
should_use_debug_bridge: bool,
}
impl<'a> TypeClassifier<'a> {
fn new(tape_lt: Option<&'a Lifetime>) -> Self {
Self {
tape_lt,
should_use_debug_bridge: false,
}
}
fn field_expr(&mut self, b: &BindingInfo<'_>) -> TokenStream {
if b.referenced_ty_params().is_empty() && !self.has_tape_lifetime_param(b) {
return quote! { #b };
}
quote! { &naam::debug_info::Dumper::debug(dumper, #b) }
}
fn has_tape_lifetime_param(&mut self, b: &BindingInfo<'_>) -> bool {
if self.tape_lt.is_none() {
return false;
}
self.should_use_debug_bridge = false;
visit::Visit::visit_type(self, &b.ast().ty);
self.should_use_debug_bridge
}
}
impl<'ast> visit::Visit<'ast> for TypeClassifier<'_> {
fn visit_lifetime(&mut self, lt: &'ast Lifetime) {
self.should_use_debug_bridge |= self.tape_lt == Some(lt);
visit::visit_lifetime(self, lt);
}
}
|
use std::num::ParseIntError;
fn main() {
// test1: test_shortest
}
/// Option<T>
/// Option<T>类型属于枚举体, 包括两个可边的变体 Some(T None 作为可选值,
/// Option<T>可以被使用在多种场景中。比如可边的结构体、可选的函数参数 可选的结构体
/// 字段、可空的指针、占位(如在 HashMap 中解决 remove 问题)等。
fn get_shortest(name: Vec<&str>) -> Option<&str> {
if name.len() > 0{
let mut shortest = name[0];
for name in name.iter(){
if name.len() < shortest.len() {
shortest = *name;
}
}
Some(shortest)
}else{
None
}
}
// map和and_then的区别是and_then返回的不会像map一样包装一层Some
fn get_shortest_length(names: Vec<&str>) -> Option<usize>{
get_shortest(names).map(|name| (name.len()))
}
fn show_shortest(names: Vec<&str>)->&str{
match get_shortest(names) {
Some(shortest) => shortest,
None => "Not found",
}
}
/// unwrap方法可以取出包含于Some内部的值, 但是遇到None就会引发panic
fn show_shortest_v1(names: Vec<&str>)->&str{
get_shortest(names).unwrap()
}
///unwrap_or是对match匹配包装的语法糖, 可以制定处理None返回的值.
fn show_shortest_v2(names: Vec<&str>)->&str{
get_shortest(names).unwrap_or("Not found")
}
/// 与unwrap_or类似, 区别是他的参数是一个FnOnce->T闭包
fn show_shortest_v3(names: Vec<&str>)->&str{
get_shortest(names).unwrap_or_else(|| ("Not found"))
}
///在遇到None值时会引发panic, 并且可以传入参数展示指定的异常消息.
fn show_shortest_v4(names: Vec<&str>)->&str{
get_shortest(names).expect("Not found")
}
fn square(number_str: &str) -> Result<i32, ParseIntError>{
number_str.parse::<i32>().map(|n| n.pow(2))
}
#[test]
fn square_test(){
match square("10"){
Ok(n) => assert_eq!(n,100),
Err(err) => println!("Error: {:?}",err),
}
}
#[test]
fn test_shortest(){
assert_eq!(show_shortest(vec!["you","are","foolish"]), "you");
assert_eq!(show_shortest_v1(vec!["you","are","foolish"]), "you");
assert_eq!(show_shortest_v2(vec!["you","are","foolish"]), "you");
assert_eq!(show_shortest_v3(vec!["you","are","foolish"]), "you");
assert_eq!(show_shortest_v4(vec!["you","are","foolish"]), "you");
assert_eq!(show_shortest(Vec::new()), "Not found");
assert_eq!(show_shortest_v2(Vec::new()), "Not found");
assert_eq!(show_shortest_v3(Vec::new()), "Not found");
assert_eq!(get_shortest_length(vec!["you","are","foolish"]), Some(3));
assert_eq!(get_shortest_length(Vec::new () ) , None) ;
}
#[test]
fn test_shortest_panic(){
assert_eq!(show_shortest_v4(Vec::new()), "Not found");
assert_eq!(show_shortest_v1(Vec::new()), "Not found");
}
|
// Copyright 2018 Fredrik Portström <https://portstrom.com>
// This is free software distributed under the terms specified in
// the file LICENSE at the top-level directory of this distribution.
pub fn parse_examples<'a>(
context: &mut ::Context<'a>,
template_node: &::Node,
parameters: &[::Parameter],
nodes: &[::Node<'a>],
output: &mut Option<Vec<::Example<'a>>>,
) -> usize {
::parse_list_items_generic(
context,
template_node,
parameters,
nodes,
output,
|context, list_item| parse_example(context, list_item),
)
}
fn parse_example<'a>(
context: &mut ::Context<'a>,
list_item: &::DefinitionListItem<'a>,
) -> Option<::Example<'a>> {
let mut example = vec![];
let mut has_text = false;
let mut translation = vec![];
let mut iterator = list_item.nodes.iter();
while let Some(node) = iterator.next() {
match node {
::Node::Italic { .. } => example.push(::Flowing::Italic),
::Node::Tag { name, .. } if name == "ref" => {
::add_warning(context, node, ::WarningMessage::Supplementary);
example.push(::Flowing::Reference);
}
::Node::Text { value, .. } => {
has_text = true;
example.push(::Flowing::Text {
value: ::Cow::Borrowed(value),
});
}
::Node::DefinitionList { items, .. } => {
if let [list_item @ ::DefinitionListItem {
type_: ::Details, ..
}] = items.as_slice()
{
if list_item.nodes.is_empty() {
::add_warning(context, list_item, ::WarningMessage::Empty);
} else {
translation = list_item
.nodes
.iter()
.map(|node| match node {
::Node::Italic { .. } => ::Flowing::Italic,
::Node::Text { value, .. } => ::Flowing::Text {
value: ::Cow::Borrowed(value),
},
_ => {
::create_unknown(context, node, ::WarningMessage::Unrecognized)
}
})
.collect();
}
} else {
::add_warning(context, node, ::WarningMessage::ValueUnrecognized);
}
while let Some(node) = iterator.next() {
::add_warning(context, node, ::WarningMessage::Unrecognized);
}
break;
}
_ => example.push(::create_unknown(
context,
node,
::WarningMessage::Unrecognized,
)),
}
}
if has_text {
Some(::Example {
example,
translation,
})
} else {
::add_warning(context, list_item, ::WarningMessage::Empty);
None
}
}
|
use serenity::model::gateway::Ready;
use serenity::model::id::ChannelId;
use serenity::prelude::*;
use std::thread;
use player::PlayerManager;
use server::Server;
use voice::Receiver;
use voice::VoiceManager;
pub struct Handler;
impl EventHandler for Handler {
fn ready(&self, ctx: Context, ready: Ready) {
println!("{} is connected!", ready.user.name);
let manager_lock = ctx.data.lock().get::<VoiceManager>().cloned().unwrap();
let mut manager = manager_lock.lock();
let channel = ChannelId(385205936819666968);
match manager.join(385205936819666964, channel) {
Some(handler) => {
let ret = Receiver::new(ctx.data.lock().get::<PlayerManager>().cloned().unwrap());
handler.listen(Some(Box::new(ret)));
thread::spawn(move || {
let server = Server::new(ctx.data.lock().get::<PlayerManager>().cloned().unwrap());
server.run();
});
},
None => {
println!("Failed to connect to voice channel");
}
}
}
}
|
#[doc = "Reader of register ELSR0"]
pub type R = crate::R<u32, super::ELSR0>;
#[doc = "Reader of field `ELSR0`"]
pub type ELSR0_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - end of interrupt status"]
#[inline(always)]
pub fn elsr0(&self) -> ELSR0_R {
ELSR0_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
/// ##arp.rs
/// Functions for parsing and generating ARP protocol messages
///
use crate::util::{ipv4_to_str, mac_to_str};
use log::{error};
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::{FromPrimitive, ToPrimitive};
// ref: http://www.networksorcery.com/enp/protocol/arp.htm
#[derive(Copy, Clone, PartialEq, FromPrimitive, ToPrimitive, Debug)]
#[repr(u16)]
pub enum ArpHardwareType {
Reserved = 0,
Ethernet = 1,
ExperimentalEthernet = 2,
Ax25 = 3,
ProNetTokenRing = 4,
Chaos = 5,
Ieee802 = 6,
Arcnet = 7,
Hyperchannel = 8,
Lanstar = 9,
AutonetShortAddr = 10,
LocalTalk = 11,
LocalNet = 12,
Ultralink = 13,
Smds = 14,
FrameRelay = 15,
Atm = 16,
Hdlc = 17,
FibreChannel = 18,
Atm2 = 19,
SerialLine = 20,
Atm3 = 21,
MilStd_188_220 = 22,
Metricom = 23,
Ieee1394_1995 = 24,
Mapos = 25,
Twinaxial = 26,
Eui64 = 27,
Hiparp = 28,
IpArpIso7816_3 = 29,
ArpSec = 30,
IpsecTunnel = 31,
Infiniband = 32,
CaiTia102P25 = 33,
WiegandIfc = 34,
PureIp = 35,
HwExp1 = 36,
// 37 - 255 NOT set
HwExp2 = 256,
// 257 - 65534
ReservedEnd = 65535,
}
impl ArpHardwareType {
pub fn from_bytes(b: &[u8]) -> ArpHardwareType {
let type_val = u16::to_be((b[1] as u16) << 8 | b[0] as u16);
match ArpHardwareType::from_u16(type_val) {
Some(val) => val,
None => {
error!("invalid/unhandled hardware type: {:02X}", type_val);
ArpHardwareType::ReservedEnd
}
}
}
}
impl Default for ArpHardwareType {
fn default() -> Self {
ArpHardwareType::ReservedEnd
}
}
#[derive(Copy, Clone, PartialEq, FromPrimitive, Debug)]
#[repr(u16)]
pub enum ArpProtoType {
NotSet = 0,
Ip = 0x0800,
}
impl ArpProtoType {
fn from_bytes(b: &[u8]) -> ArpProtoType {
let type_val = u16::to_be((b[1] as u16) << 8 | b[0] as u16);
match ArpProtoType::from_u16(type_val) {
Some(val) => val,
None => {
error!("invalid/unhandled proto type: {:02X}", type_val);
ArpProtoType::NotSet
}
}
}
}
impl Default for ArpProtoType {
fn default() -> Self {
ArpProtoType::NotSet
}
}
#[derive(Copy, Clone, PartialEq, FromPrimitive, Debug)]
#[repr(u16)]
pub enum ArpOpcode {
Reserved = 0,
Request = 1,
Reply = 2,
RequestReverse = 3,
ReplyReverse = 4,
DrarpRequest = 5,
DrarpReply = 6,
DrarpError = 7,
InArpRequest = 8,
InArpReply = 9,
MarsRequest = 10,
MarsMulti = 11,
MarsMserv = 12,
// 13-65534
ReservedEnd = 65535,
}
impl Default for ArpOpcode {
fn default() -> Self {
ArpOpcode::Reserved
}
}
impl ArpOpcode {
fn from_bytes(b: &[u8]) -> ArpOpcode {
let type_val = u16::to_be((b[1] as u16) << 8 | b[0] as u16);
match ArpOpcode::from_u16(type_val) {
Some(val) => val,
None => {
error!("invalid/unhandled opcode: {:02X}", type_val);
ArpOpcode::Reserved
}
}
}
}
#[derive(Copy, Clone, Default)]
#[repr(C)]
pub struct ArpPacket {
pub hw_type: ArpHardwareType,
pub proto_type: ArpProtoType,
pub hw_addr_len: u8,
pub proto_addr_len: u8,
pub opcode: ArpOpcode,
pub snd_hw_addr: [u8; 6],
pub snd_proto_addr: [u8; 4],
pub tgt_hw_addr: [u8; 6],
pub tgt_proto_addr: [u8; 4],
}
impl ArpPacket {
pub fn new(raw_arp_hdr: &[u8]) -> ArpPacket {
let mut x: ArpPacket = Default::default();
x.hw_type = ArpHardwareType::from_bytes(&raw_arp_hdr[0..]);
x.proto_type = ArpProtoType::from_bytes(&raw_arp_hdr[2..]);
x.hw_addr_len = raw_arp_hdr[4];
x.proto_addr_len = raw_arp_hdr[5];
x.opcode = ArpOpcode::from_bytes(&raw_arp_hdr[6..]);
x.snd_hw_addr.copy_from_slice(&raw_arp_hdr[8..14]);
x.snd_proto_addr.copy_from_slice(&raw_arp_hdr[14..18]);
x.tgt_hw_addr.copy_from_slice(&raw_arp_hdr[18..24]);
x.tgt_proto_addr.copy_from_slice(&raw_arp_hdr[24..28]);
x
}
pub fn to_string(self) -> String {
format!("hw type: {:?}, proto type: {:?}, hw addr len: {}, proto addr len : {}, opcode: {:?}, snd hw addr: {:?}, snd proto addr: {:?}, tgt hw addr: {:?}, tgt proto addr: {:?}", self.hw_type, self.proto_type, self.hw_addr_len, self.proto_addr_len, self.opcode, mac_to_str(&self.snd_hw_addr), ipv4_to_str(&self.snd_proto_addr), mac_to_str(&self.tgt_hw_addr), ipv4_to_str(&self.tgt_proto_addr))
}
}
|
extern crate mongodb;
use bson::{bson, doc};
use mongodb::{options::ClientOptions, Client};
use std::{
fs::File,
io::{stdin, stdout, BufReader, Write},
};
#[tokio::main]
pub async fn scraping(url: &str, dist: &str) -> Result<reqwest::StatusCode, Box<dyn std::error::Error>> {
let response = reqwest::get(url).await?;
let status = response.status();
let body = response.text().await?;
println!("status: {:?}", status);
// println!("{:?}", body);
let mut file = File::create(dist)?;
file.write_all(body.as_bytes())?;
file.sync_all()?;
Ok(status)
}
fn mongodb_driver() -> mongodb::Client {
let mut client_options = ClientOptions::parse("mongodb://localhost:27017").unwrap();
client_options.app_name = Some("My app".to_string());
Client::with_options(client_options).unwrap()
}
fn db() -> mongodb::Database {
let client = mongodb_driver();
client.database("calagator")
}
pub fn coll(coll_name: &str) -> mongodb::Collection {
db().collection(coll_name)
}
pub fn read_file(file: File) -> csv::Reader<std::io::BufReader<std::fs::File>> {
csv::Reader::from_reader(BufReader::new(file.try_clone().unwrap()))
}
pub fn display(coll_name: &str) {
let coll = coll(coll_name);
let cursor = coll.find(None, None).unwrap();
let mut count = 0;
for doc in cursor {
println!("\n{}", doc.unwrap());
count += 1;
}
println!("Total {:?} events displayed", count);
}
fn month_choose() -> &'static str {
loop{
println!("Enter the number (ex:1 to Jan, 2 to Feb) of the month: ");
print!("\n> ");
let input = user_input();
let command = input.trim().split_whitespace().next().unwrap();
match &*command {
"1" => return "Jan",
"2" => return "Feb",
"3" => return "Mar",
"4" => return "Apr",
"5" => return "May",
"6" => return "Jun",
"7" => return "Jul",
"8" => return "Aug",
"9" => return "Sep",
"10" => return "Oct",
"11" => return "Nov",
"12" => return "Dec",
_ => println!("[{}]: command not found, please try again!",command),
}
}
}
pub fn search(coll_name: &str, field: &str) {
let coll = coll(coll_name);
if field == "1" {
for doc in coll.find(None,None).unwrap() {
println!("{}", doc.unwrap());
}
}
else if coll_name == "calendar" && field == "4" {
let month = month_choose();
println!("Enter the number (ex:1 to First day, 2 to Second day) of the day: ");
print!("\n> ");
let input = user_input();
let temp = input.trim().split_whitespace().next().unwrap();
println!("Enter the number (ex:1995, 2000, 2020) of the year: ");
print!("\n> ");
let input = user_input();
let tempy = input.trim().split_whitespace().next().unwrap();
let filter = doc!{"month":month,"day":temp,"year":tempy};
let cursor = coll.find(filter,None).unwrap();
for result in cursor {
match result {
Ok(document) => println!("\nDocument: {:?}", document),
Err(e) => println!("Error! {:?}", e),
}
}
}
else if coll_name == "events" && field == "all" {
println!("Enter the number of start time: ");
print!("\n> ");
let input = user_input();
let temp = input.trim();
println!("Enter the number of end time: ");
print!("\n> ");
let input = user_input();
let tempy = input.trim();
let filter = doc!{"start_time":temp,"end_time":tempy,};
let cursor = coll.find(filter,None).unwrap();
for result in cursor {
match result {
Ok(document) => println!("\nDocument: {:?}",document),
Err(e) => println!("Error! {:?}", e),
}
}
}
else if coll_name == "venues" && field == "all" {
println!("Enter the number of latitude: ");
print!("\n> ");
let input = user_input();
let temp = input.trim();
println!("Enter the number of longitude: ");
print!("\n> ");
let input = user_input();
let tempy = input.trim();
let filter = doc!{"latitude":temp,"longitude":tempy,};
let cursor = coll.find(filter,None).unwrap();
for result in cursor {
match result {
Ok(document) => println!("\nDocument: {:?}",document),
Err(e) => println!("Error! {:?}", e),
}
}
}
else {
print!("\nPlease enter the {} plan to search: " ,field);
let find_input = user_input();
let find = find_input.trim();
let filter = doc! { field: find };
let cursor = coll.find(filter, None).unwrap();
for result in cursor {
match result {
Ok(document) => println!("\nDocument: {:?}", document),
Err(e) => println!("Error! {:?}", e),
}
}
}
}
pub fn delete(coll_name: &str, field: &str){
let coll = coll(coll_name);
print!("\nPlease enter the {} plan to delete: " ,field);
let find_input = user_input();
let find = find_input.trim();
match coll.delete_one(doc! {field: find}, None) {
Ok(_) => println!("Item deleted!"),
Err(e) => println!("Error! {:?}",e),
}
}
pub fn user_input() -> std::string::String {
stdout().flush().unwrap();
let mut input = String::new();
stdin().read_line(&mut input).expect("Failed to read line");
//print!("{:?}", input);
if input == "\n" {
input = "0".to_string();
}
input
}
#[test]
fn database_connection_test() {
let client = mongodb_driver();
let coll = client.database("calagator").collection("venues");
coll.insert_one(doc! { "id": "1"}, None).unwrap();
let db_name = client.list_database_names(None).unwrap();
let check = (&db_name).into_iter().any(|v| v == "calagator");
assert_eq!(check, true);
}
#[test]
fn database_connection_failed() {
let client = mongodb_driver();
let db_name = client.list_database_names(None).unwrap();
let check = (&db_name).into_iter().any(|v| v == "not_exist");
assert_ne!(check, true);
}
#[test]
fn collection_connection_test() {
let db = db();
let coll = db.collection("venues");
coll.insert_one(doc! { "id": "1"}, None).unwrap();
let coll_name = db.list_collection_names(None).unwrap();
let check = (&coll_name).into_iter().any(|v| v == "venues");
assert_eq!(check, true);
}
#[test]
fn collection_connection_failed() {
let client = db();
let coll_name = client.list_collection_names(None).unwrap();
let check = (&coll_name).into_iter().any(|v| v == "not_exist");
assert_ne!(check, true);
}
#[test]
fn scraping_html_test() {
let html = scraping("https://calagator.org", "assets/calendar.html").unwrap();
assert_eq!(html.as_u16(), 200);
}
#[test]
fn scraping_json_test() {
let json = scraping("https://calagator.org/events.json", "assets/events.json").unwrap();
assert_eq!(json.as_u16(), 200);
}
|
#[doc = "Reader of register FM_CTL"]
pub type R = crate::R<u32, super::FM_CTL>;
#[doc = "Writer for register FM_CTL"]
pub type W = crate::W<u32, super::FM_CTL>;
#[doc = "Register FM_CTL `reset()`'s with value 0"]
impl crate::ResetValue for super::FM_CTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `FM_MODE`"]
pub type FM_MODE_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `FM_MODE`"]
pub struct FM_MODE_W<'a> {
w: &'a mut W,
}
impl<'a> FM_MODE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `FM_SEQ`"]
pub type FM_SEQ_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `FM_SEQ`"]
pub struct FM_SEQ_W<'a> {
w: &'a mut W,
}
impl<'a> FM_SEQ_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);
self.w
}
}
#[doc = "Reader of field `DAA_MUX_SEL`"]
pub type DAA_MUX_SEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DAA_MUX_SEL`"]
pub struct DAA_MUX_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> DAA_MUX_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 16)) | (((value as u32) & 0x7f) << 16);
self.w
}
}
#[doc = "Reader of field `IF_SEL`"]
pub type IF_SEL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IF_SEL`"]
pub struct IF_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> IF_SEL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `WR_EN`"]
pub type WR_EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WR_EN`"]
pub struct WR_EN_W<'a> {
w: &'a mut W,
}
impl<'a> WR_EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - Flash macro mode selection: '0': Normal functional mode. '1': Sets 'pre-program control bit' for soft pre-program operation of all selected SONOS cells. the control bit is cleared by the HW after any program operation. '2': Sets ... '15': TBD"]
#[inline(always)]
pub fn fm_mode(&self) -> FM_MODE_R {
FM_MODE_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 8:9 - Flash macro sequence select: '0': TBD '1': TBD '2': TBD '3': TBD"]
#[inline(always)]
pub fn fm_seq(&self) -> FM_SEQ_R {
FM_SEQ_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 16:22 - Direct memory cell access address."]
#[inline(always)]
pub fn daa_mux_sel(&self) -> DAA_MUX_SEL_R {
DAA_MUX_SEL_R::new(((self.bits >> 16) & 0x7f) as u8)
}
#[doc = "Bit 24 - Interface selection. Specifies the interface that is used for flash memory read operations: '0': R interface is used (default value). In this case, the flash memory address is provided as part of the R signal interface. '1': C interface is used. In this case, the flash memory address is provided by FM_MEM_ADDR (the page address) and by the C interface access offset in the FM_MEM_DATA structure."]
#[inline(always)]
pub fn if_sel(&self) -> IF_SEL_R {
IF_SEL_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - '0': normal mode '1': Fm Write Enable"]
#[inline(always)]
pub fn wr_en(&self) -> WR_EN_R {
WR_EN_R::new(((self.bits >> 25) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:3 - Flash macro mode selection: '0': Normal functional mode. '1': Sets 'pre-program control bit' for soft pre-program operation of all selected SONOS cells. the control bit is cleared by the HW after any program operation. '2': Sets ... '15': TBD"]
#[inline(always)]
pub fn fm_mode(&mut self) -> FM_MODE_W {
FM_MODE_W { w: self }
}
#[doc = "Bits 8:9 - Flash macro sequence select: '0': TBD '1': TBD '2': TBD '3': TBD"]
#[inline(always)]
pub fn fm_seq(&mut self) -> FM_SEQ_W {
FM_SEQ_W { w: self }
}
#[doc = "Bits 16:22 - Direct memory cell access address."]
#[inline(always)]
pub fn daa_mux_sel(&mut self) -> DAA_MUX_SEL_W {
DAA_MUX_SEL_W { w: self }
}
#[doc = "Bit 24 - Interface selection. Specifies the interface that is used for flash memory read operations: '0': R interface is used (default value). In this case, the flash memory address is provided as part of the R signal interface. '1': C interface is used. In this case, the flash memory address is provided by FM_MEM_ADDR (the page address) and by the C interface access offset in the FM_MEM_DATA structure."]
#[inline(always)]
pub fn if_sel(&mut self) -> IF_SEL_W {
IF_SEL_W { w: self }
}
#[doc = "Bit 25 - '0': normal mode '1': Fm Write Enable"]
#[inline(always)]
pub fn wr_en(&mut self) -> WR_EN_W {
WR_EN_W { w: self }
}
}
|
pub mod accounting;
pub mod accounting_grpc;
|
#![allow(proc_macro_derive_resolution_fallback)]
use diesel;
use diesel::prelude::*;
use schema::urls;
use urls::entity::Url;
pub fn all(connection: &PgConnection) -> QueryResult<Vec<Url>> {
urls::table.load::<Url>(&*connection)
}
pub fn get(id: i32, connection: &PgConnection) -> QueryResult<Url> {
urls::table.find(id).get_result::<Url>(connection)
}
pub fn insert(url: Url, connection: &PgConnection) -> QueryResult<Url> {
diesel::insert_into(urls::table)
.values(&InsertableUrl::from_url(url))
.get_result(connection)
}
pub fn update(id: i32, url: Url, connection: &PgConnection) -> QueryResult<Url> {
diesel::update(urls::table.find(id))
.set(&url)
.get_result(connection)
}
pub fn delete(id: i32, connection: &PgConnection) -> QueryResult<usize> {
diesel::delete(urls::table.find(id))
.execute(connection)
}
#[derive(Insertable)]
#[table_name = "urls"]
struct InsertableUrl {
folder_id: i32,
url: String,
status: bool,
}
impl InsertableUrl {
fn from_url(url: Url) -> InsertableUrl {
InsertableUrl {
folder_id: url.folder_id,
url: url.url,
status: url.status,
}
}
} |
use std::collections::HashMap;
use std::collections::HashSet;
use std::iter::FromIterator;
use super::file_loader;
pub fn run(part: i32) {
let input = file_loader::load_file("3.input");
//println!("File content: {:?}\n", input);
let result = with_input(&input, part as u32);
println!("Answer = {}", result);
}
fn with_input(input: &str, part: u32) -> i32 {
let paths: Vec<&str> = input.lines().collect();
//println!("Paths: {:?}\n", paths);
let direction_map: HashMap<&str, (i32, i32)> = [
("L", (-1, 0)),
("R", ( 1, 0)),
("U", ( 0, 1)),
("D", ( 0, -1))
].iter().cloned().collect();
let mut path_points: Vec<HashMap<usize, (i32, i32)>> = Vec::new();
for path in paths {
let elements: Vec<&str> = path.split(',').collect();
//println!("Elements: {:?}", elements);
let mut points: HashMap<usize, (i32, i32)> = HashMap::new();
let mut current: (i32, i32) = (0, 0);
let mut steps = 0;
for item in elements {
let dir = &item[0..1];
let dir_tuple = direction_map[dir];
let amount_str: &str = &item[1..];
//println!("Amount string: {:?}", amount_str);
let amount: i32 = amount_str.parse::<i32>().unwrap();
//println!("Direction: {}, amount: {}", dir, amount);
for _ in 0..amount {
steps += 1;
current = (current.0 + dir_tuple.0, current.1 + dir_tuple.1);
points.insert(steps, current);
//println!("Inserting: {:?}", current);
}
//println!("Points: {:?}", points);
}
path_points.push(points);
}
if part == 1 {
let points1: HashSet<&(i32, i32)> = HashSet::from_iter(path_points[0].values());
let points2: HashSet<&(i32, i32)> = HashSet::from_iter(path_points[1].values());
let intersections = points1.intersection(&points2);
//println!("Intersections: {:?}", intersections);
let manhatten_distance: i32 = intersections
.map(|pp| (pp.0.abs(), pp.1.abs()))
.map(|pp| (pp.0 + pp.1))
.min()
.unwrap();
return manhatten_distance;
} else {
let map_one: &HashMap<usize, (i32, i32)> = &path_points[0];
let map_two: &HashMap<usize, (i32, i32)> = &path_points[1];
let map_one_values: HashSet<&(i32, i32)> = HashSet::from_iter(map_one.values());
let map_two_values: HashSet<&(i32, i32)> = HashSet::from_iter(map_two.values());
let intersections = map_one_values.intersection(&map_two_values);
let mut lowest = 0;
for i in intersections {
let mut steps_one: usize = 0;
let mut steps_two: usize = 0;
for (key, value) in map_one.iter() {
if value == *i {
steps_one = *key;
}
}
for (key, value) in map_two.iter() {
if value == *i {
steps_two = *key;
}
}
if lowest == 0 || steps_one + steps_two < lowest {
lowest = steps_one + steps_two;
}
}
return lowest as i32;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example1_part1() {
assert_eq!(with_input("R8,U5,L5,D3\nU7,R6,D4,L4", 1), 6);
}
#[test]
fn example2_part1() {
assert_eq!(with_input("R75,D30,R83,U83,L12,D49,R71,U7,L72\nU62,R66,U55,R34,D71,R55,D58,R83", 1), 159);
}
#[test]
fn example3_part1() {
assert_eq!(with_input("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\nU98,R91,D20,R16,D67,R40,U7,R15,U6,R7", 1), 135);
}
#[test]
fn example1_part2() {
assert_eq!(with_input("R8,U5,L5,D3\nU7,R6,D4,L4", 2), 30);
}
#[test]
fn example2_part2() {
assert_eq!(with_input("R75,D30,R83,U83,L12,D49,R71,U7,L72\nU62,R66,U55,R34,D71,R55,D58,R83", 2), 610);
}
#[test]
fn example3_part2() {
assert_eq!(with_input("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\nU98,R91,D20,R16,D67,R40,U7,R15,U6,R7", 2), 410);
}
} |
/*
* Copyright 2017-2018 Ben Ashford
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
//! Error handling
use std::{error, fmt, io};
use futures::sync::{mpsc, oneshot};
use resp;
#[derive(Debug)]
pub enum Error {
/// A non-specific internal error that prevented an operation from completing
Internal(String),
/// An IO error occurred
IO(io::Error),
/// A RESP parsing/serialising error occurred
RESP(String, Option<resp::RespValue>),
/// A remote error
Remote(String),
/// End of stream - not necesserially an error if you're anticipating it
EndOfStream,
/// An unexpected error. In this context "unexpected" means
/// "unexpected because we check ahead of time", it used to maintain the type signature of
/// chains of futures; but it occurring at runtime should be considered a catastrophic
/// failure.
///
/// If any error is propagated this way that needs to be handled, then it should be made into
/// a proper option.
Unexpected(String),
}
pub fn internal<T: Into<String>>(msg: T) -> Error {
Error::Internal(msg.into())
}
pub fn resp<T: Into<String>>(msg: T, resp: resp::RespValue) -> Error {
Error::RESP(msg.into(), Some(resp))
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::IO(err)
}
}
impl From<oneshot::Canceled> for Error {
fn from(err: oneshot::Canceled) -> Error {
Error::Unexpected(format!("Oneshot was cancelled before use: {}", err))
}
}
impl<T: 'static + Send> From<mpsc::SendError<T>> for Error {
fn from(err: mpsc::SendError<T>) -> Error {
Error::Unexpected(format!("Cannot write to channel: {}", err))
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Internal(ref s) => s,
Error::IO(ref err) => err.description(),
Error::RESP(ref s, _) => s,
Error::Remote(ref s) => s,
Error::EndOfStream => "End of Stream",
Error::Unexpected(ref err) => err,
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::Internal(_) => None,
Error::IO(ref err) => Some(err),
Error::RESP(_, _) => None,
Error::Remote(_) => None,
Error::EndOfStream => None,
Error::Unexpected(_) => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::error::Error;
fmt::Display::fmt(self.description(), f)
}
}
|
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::str::FromStr;
use libosu::{
beatmap::Beatmap,
data::Mode,
events::{BackgroundEvent, BreakEvent, Event},
hitsounds::SampleSet,
math::Point,
timing::Millis,
};
fn load_beatmap(path: impl AsRef<Path>) -> Beatmap {
let mut file = File::open(path.as_ref()).expect("couldn't open file");
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("couldn't read file");
Beatmap::from_str(&contents).expect("couldn't parse")
}
#[test]
fn parse_taeyang_remote_control() {
let beatmap = load_beatmap("tests/files/774965.osu");
assert_eq!(beatmap.audio_filename, "control.mp3");
assert_eq!(beatmap.audio_leadin, Millis(1000));
assert_eq!(beatmap.preview_time, Millis(85495));
assert_eq!(beatmap.countdown, false);
assert_eq!(beatmap.sample_set, SampleSet::Normal);
assert_eq!(beatmap.stack_leniency, 0.8);
assert_eq!(beatmap.mode, Mode::Osu);
assert_eq!(beatmap.letterbox_in_breaks, false);
assert_eq!(beatmap.widescreen_storyboard, false);
assert_eq!(beatmap.title, "Remote Control");
assert_eq!(beatmap.title_unicode, "リモコン");
assert_eq!(beatmap.artist, "kradness&Reol");
assert_eq!(beatmap.artist_unicode, "kradness&れをる");
assert_eq!(beatmap.creator, "Taeyang");
assert_eq!(beatmap.difficulty_name, "Max Control!");
assert_eq!(beatmap.source, "");
assert_eq!(
beatmap.tags,
&[
"Jesus-P",
"じーざすP",
"Giga",
"Official",
"Rimokon",
"Wonderful*Opportunity",
"Kagamine",
"Rin",
"Len",
"Glider"
]
);
assert_eq!(beatmap.beatmap_id, 774965);
assert_eq!(beatmap.beatmap_set_id, 351630);
assert_eq!(
beatmap.events,
&[
Event::Background(BackgroundEvent {
filename: String::from("reol.jpg"),
offset: Point::new(0, 0)
}),
Event::Break(BreakEvent {
start_time: Millis(184604),
end_time: Millis(189653),
})
]
);
}
macro_rules! test_serde {
($($name:ident: $id:expr,)*) => {
$(
#[test]
fn $name() {
let mut file = File::open(format!("tests/files/{}.osu", $id)).expect("couldn't open file");
let mut contents = String::new();
file.read_to_string(&mut contents).expect("couldn't read file");
let beatmap = Beatmap::from_str(&contents).expect("couldn't parse");
let reexported = beatmap.to_string();
let beatmap2 = match Beatmap::from_str(&reexported) {
Ok(v) => v,
Err(err) => {
for (i, line) in reexported.lines().enumerate() {
let line_no = i as i32 + 1;
if (line_no - err.line as i32).abs() < 3 {
eprintln!("{}:\t{}", line_no, line);
}
}
panic!("error: {}", err);
}
};
assert_eq!(beatmap, beatmap2);
}
)*
};
}
test_serde! {
// test_parser_75: 75,
test_parser_129891: 129891,
test_parser_774965: 774965,
test_parser_804683: 804683,
test_parser_1595588: 1595588,
// https://github.com/iptq/libosu/issues/12
test_parser_1360: 1360,
test_parser_3516: 3516,
// https://github.com/iptq/libosu/issues/13
test_parser_169355: 169355,
}
|
use crate::components;
use crate::indices::EntityTime;
use serde::Serialize;
/// TableIds may be used as indices of tables
pub trait TableId:
'static + Ord + PartialOrd + Eq + PartialEq + Copy + Default + Send + std::fmt::Debug + Serialize
{
}
impl<T> TableId for T where
T: 'static
+ Ord
+ PartialOrd
+ Eq
+ PartialEq
+ Copy
+ Default
+ Send
+ std::fmt::Debug
+ Serialize
{
}
/// TableRows may be used as the row type of a table
pub trait TableRow: 'static + std::fmt::Debug {}
impl<T: 'static + std::fmt::Debug> TableRow for T {}
/// Components define both their shape (via their type) and the storage backend that shall be used to
/// store them.
pub trait Component<Id: TableId>: TableRow {
type Table: Table<Row = Self> + Default;
}
pub trait Table {
type Id: TableId;
type Row: TableRow;
// Id is Copy
fn delete(&mut self, id: Self::Id) -> Option<Self::Row>;
fn get(&self, id: Self::Id) -> Option<&Self::Row>;
fn name() -> &'static str {
use std::any::type_name;
type_name::<Self>()
}
}
pub trait LogTable {
fn get_logs_by_time(&self, time: u64) -> Vec<(EntityTime, components::LogEntry)>;
}
|
use core::fmt::Display;
use std::fmt;
#[allow(unused_must_use)]
#[derive(Debug, PartialEq)]
pub enum Error {
NotEnoughPinsLeft,
GameComplete,
}
#[derive(Debug, PartialEq, Clone)]
pub struct Frame {
roll_0: u16,
roll_1: u16,
strike: bool,
in_progress: bool,
is_frame_complete: bool,
score: u16
}
#[derive(Debug, PartialEq)]
pub struct BowlingGame {
running_frame: i32,
frames: Vec<Frame>
}
impl fmt::Display for BowlingGame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut res:fmt::Result = Ok(());
for (index, item) in self.frames.iter().enumerate() {
println!("Index : {} Roll = [{}, {}]; (Strike)->{} (In progress)->{} (Frame Comp.)->{} (Score)->{}",
index + 1, item.roll_0, item.roll_1, item.strike, item.in_progress, item.is_frame_complete, item.score);
}
res
}
}
impl BowlingGame {
pub fn new() -> Self {
let default_frame = Frame {
roll_0: 0 as u16,
roll_1: 0 as u16,
in_progress: false,
strike: false,
is_frame_complete: false,
score: 0 as u16
};
BowlingGame {
running_frame: 0,
frames: vec![default_frame; 10]
}
}
pub fn roll(&mut self, pins: u16) -> Result<(), Error> {
let running_frame = self.running_frame as usize;
let mut result: Result<(), Error> = Ok(());
if pins > 10 {
result = Err(Error::NotEnoughPinsLeft);
} else if running_frame >= 10 {
if running_frame == 10
&& self.frames[running_frame-1].strike
&& !self.frames[running_frame-1].is_frame_complete {
if self.frames[running_frame-1].in_progress {
self.frames[running_frame-1].roll_1 = pins;
if self.frames[running_frame-1].roll_1 + self.frames[running_frame-1].roll_0 > 10
&& self.frames[running_frame-1].roll_0 != 10 {
result = Err(Error::NotEnoughPinsLeft);
}
else {
self.frames[running_frame-1].is_frame_complete = true;
self.frames[running_frame-1].in_progress = false;
}
} else {
self.frames[running_frame-1].roll_0 = pins;
self.frames[running_frame-1].in_progress = true;
}
} else if running_frame == 10
&& !self.frames[running_frame-1].strike
&& !self.frames[running_frame-1].is_frame_complete
&& self.frames[running_frame-1].roll_0 + self.frames[running_frame-1].roll_1 == 10 {
self.frames[running_frame-1].strike = true;
self.frames[running_frame-1].in_progress = false;
self.frames[running_frame-1].roll_0 = pins;
self.frames[running_frame-1].is_frame_complete = true;
self.frames[running_frame-1].roll_1 = 0;
}
else {
// Check if the last frame has a spare which needs to be counted for one.
result = Err(Error::GameComplete);
}
} else if self.frames[running_frame].in_progress {
if pins + self.frames[running_frame].roll_0 > 10 {
result = Err(Error::NotEnoughPinsLeft);
} else if pins == 10 && self.frames[running_frame].roll_0 == 0 {
self.frames[running_frame].roll_1 = 10;
self.frames[running_frame].strike = false;
self.frames[running_frame].is_frame_complete = true;
self.frames[running_frame].in_progress = false;
} else {
self.frames[running_frame].roll_1 = pins;
if running_frame == 9
&& self.frames[running_frame].roll_0 + self.frames[running_frame].roll_1 == 10 {
self.frames[running_frame].in_progress = true;
self.frames[running_frame].is_frame_complete = false;
} else {
self.frames[running_frame].in_progress = false;
self.frames[running_frame].is_frame_complete = true;
}
self.running_frame += 1;
result = Ok(());
}
} else if pins == 10 {
// Strike at 10th element.
if self.running_frame == 9 {
self.frames[running_frame].is_frame_complete = false;
self.frames[running_frame].in_progress = false;
// Strike at elements 0 - 9
} else {
self.frames[running_frame].roll_1 = 10;
self.frames[running_frame].is_frame_complete = true;
self.frames[running_frame].in_progress = false;
}
self.frames[running_frame].strike = true;
self.running_frame += 1;
result = Ok(());
} else if !self.frames[running_frame].in_progress {
self.frames[running_frame].roll_0 = pins;
self.frames[running_frame].strike = false;
self.frames[running_frame].is_frame_complete = false;
self.frames[running_frame].in_progress = true;
}
result
}
pub fn score(&self) -> Option<u16> {
if self.running_frame < 10 || (self.running_frame == 10 && self.frames[9].is_frame_complete == false) {
None
}
else {
let mut temp = self.frames.clone();
for (index, item) in temp.iter_mut().enumerate() {
if item.strike == true {
// not 10th frame.
if index <= 8 {
if !self.frames[index+1].strike {
item.score = 10 + self.frames[index+1].roll_0 + self.frames[index+1].roll_1;
} else { // another strike. need roll_0 of the next frame.
if index + 2 < 10 {
if self.frames[index+2].strike {
item.score = 10 + 10 + 10;
} else {
item.score = 10 + 10 + self.frames[index+2].roll_0;
}
} else {
if self.frames[index+1].strike {
item.score = 10 + 10 + self.frames[index+1].roll_0;
} else {
item.score = 10 + self.frames[index+1].roll_0 + self.frames[index+1].roll_1;
}
}
}
} else {
if self.frames[index].strike {
// 9th index is the last strike.
item.score = 10 + item.roll_0 + item.roll_1
}
}
} else if item.roll_0 + item.roll_1 == 10 {
item.score = 10 + self.frames[index+1].roll_0;
} else {
item.score = item.roll_0 + item.roll_1;
}
}
let x = temp.iter().fold(0, |sum, x| sum + x.score);
Some(x)
}
}
}
|
use serenity::prelude::*;
use serenity::model::gateway::Ready;
use serenity::model::id::ChannelId;
pub struct Handler;
impl EventHandler for Handler
{
fn ready(&self, ctx: Context, _data_about_bot: Ready)
{
println!("Ready trigger fired!");
let channel_id: ChannelId = {
let json = std::fs::read_to_string("/home/toaster/fracking-toaster/.trigger").expect("Unable to read .trigger in startup!");
if json.is_empty() { return }
serde_json::from_str(&json).expect("Unable to serialize .trigger into a ChannelId!")
};
channel_id.say(&ctx.http, "I'm back online!").expect("Unable to report online status to startup channel!");
}
} |
use actix_web::HttpResponse;
use aes::Aes256;
// use block_cipher::{BlockCipher, NewBlockCipher};
use block_modes::block_padding::NoPadding;
use block_modes::{BlockMode, Cbc};
use byteorder::{BigEndian, ByteOrder};
// use openssl::symm::{Cipher, Crypter, Mode};
use ring::rand::SecureRandom;
use std::collections::HashMap;
use std::iter;
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use super::{base64, command, message};
type Aes256CbcNoPadding = Cbc<Aes256, NoPadding>;
// #[derive(Clone)]
struct WxWorkProjectCipherInfo {
pub cipher: Aes256CbcNoPadding,
pub key: Vec<u8>,
pub iv: Vec<u8>,
}
pub struct WxWorkProject {
name: Arc<String>,
pub token: String,
pub encoding_aes_key: String,
pub envs: Rc<serde_json::Value>,
pub cmds: Rc<command::WxWorkCommandList>,
pub events: Rc<command::WxWorkCommandList>,
cipher_info: Arc<Mutex<Box<WxWorkProjectCipherInfo>>>,
nonce: AtomicUsize,
}
unsafe impl Send for WxWorkProject {}
unsafe impl Sync for WxWorkProject {}
pub type WxWorkProjectPtr = Arc<WxWorkProject>;
pub type WxWorkProjectMap = HashMap<String, WxWorkProjectPtr>;
// fn get_block_size<T: BlockCipher + NewBlockCipher>() -> usize {
// T::BlockSize::to_usize()
// }
impl WxWorkProject {
pub fn parse(json: &serde_json::Value) -> WxWorkProjectMap {
let mut ret: HashMap<String, Arc<WxWorkProject>> = HashMap::new();
if let Some(arr) = json.as_array() {
for conf in arr {
let proj_res = WxWorkProject::new(conf);
if let Some(proj) = proj_res {
ret.insert((*proj.name()).clone(), Arc::new(proj));
}
}
}
ret
}
pub fn new(json: &serde_json::Value) -> Option<WxWorkProject> {
if !json.is_object() {
error!("project configure invalid: {}", json);
eprintln!("project configure invalid: {}", json);
return None;
}
let proj_name: String;
let proj_token: String;
let proj_aes_key: String;
let proj_cmds: command::WxWorkCommandList;
let proj_events: command::WxWorkCommandList;
let mut envs_obj = json!({});
{
if !json.is_object() {
error!("project must be a json object, but real is {}", json);
eprintln!("project must be a json object, but real is {}", json);
return None;
};
proj_name = if let Some(x) = command::read_string_from_json_object(json, "name") {
x
} else {
error!("project configure must has name field {}", json);
eprintln!("project configure must has name field {}", json);
return None;
};
proj_token = if let Some(x) = command::read_string_from_json_object(json, "token") {
x
} else {
error!(
"project \"{}\" configure must has token field {}",
proj_name, json
);
eprintln!(
"project \"{}\" configure must has token field {}",
proj_name, json
);
return None;
};
proj_aes_key =
if let Some(x) = command::read_string_from_json_object(json, "encodingAESKey") {
x
} else {
error!(
"project \"{}\" configure must has encodingAESKey field {}",
proj_name, json
);
eprintln!(
"project \"{}\" configure must has encodingAESKey field {}",
proj_name, json
);
return None;
};
let mut envs_var_count = 0;
if let Some(envs_kvs) = command::read_object_from_json_object(json, "env") {
for (k, v) in envs_kvs {
envs_obj[format!("WXWORK_ROBOT_PROJECT_{}", k)
.as_str()
.to_uppercase()] = if v.is_string() {
v.clone()
} else {
serde_json::Value::String(v.to_string())
};
envs_var_count += 1;
}
}
if let Some(kvs) = json.as_object() {
if let Some(cmds_json) = kvs.get("cmds") {
proj_cmds = command::WxWorkCommand::parse(cmds_json);
} else {
proj_cmds = Vec::new();
}
} else {
proj_cmds = Vec::new();
}
if let Some(kvs) = json.as_object() {
if let Some(cmds_json) = kvs.get("events") {
proj_events = command::WxWorkCommand::parse(cmds_json);
} else {
proj_events = Vec::new();
}
} else {
proj_events = Vec::new();
}
for cmd in proj_cmds.iter() {
info!(
"project \"{}\" load command \"{}\" success",
proj_name,
cmd.name()
);
}
for cmd in proj_events.iter() {
info!(
"project \"{}\" load event \"{}\" success",
proj_name,
cmd.name()
);
}
debug!("project \"{}\" with token(base64): \"{}\", aes key(base64): \"{}\" , env vars({}), load success.", proj_name, proj_token, proj_aes_key, envs_var_count);
}
envs_obj["WXWORK_ROBOT_PROJECT_NAME"] = serde_json::Value::String(proj_name.clone());
envs_obj["WXWORK_ROBOT_PROJECT_TOKEN"] = serde_json::Value::String(proj_token.clone());
envs_obj["WXWORK_ROBOT_PROJECT_ENCODING_AES_KEY"] =
serde_json::Value::String(proj_aes_key.clone());
let aes_key_bin = match base64::STANDARD_UTF7.decode(proj_aes_key.as_bytes()) {
Ok(x) => x,
Err(e) => {
error!(
"project \"{}\" configure encodingAESKey \"{}\" decode failed \"{}\"",
proj_name,
proj_aes_key,
e.to_string()
);
eprintln!(
"project \"{}\" configure encodingAESKey \"{}\" decode failed \"{}\"",
proj_name,
proj_aes_key,
e.to_string()
);
return None;
}
};
//let cipher_iv_len = <Aes256 as BlockCipher>::BlockSize::to_usize();
//let cipher_iv_len = U16::to_usize();
// According to https://en.wikipedia.org/wiki/Block_size_(cryptography)
// Block size of AES is always 128bits/16bytes
let cipher_iv_len: usize = 16;
let cipher_iv = if aes_key_bin.len() >= cipher_iv_len {
Vec::from(&aes_key_bin[0..cipher_iv_len])
} else {
Vec::new()
};
let cipher_ctx = match Aes256CbcNoPadding::new_var(&aes_key_bin, &cipher_iv) {
Ok(x) => x,
Err(e) => {
let err_msg = format!(
"project \"{}\" configure encodingAESKey \"{}\" failed, {:?}",
proj_name, proj_aes_key, e
);
error!("{}", err_msg);
eprintln!("{}", err_msg);
return None;
}
};
/*
let cipher_iv = if let Some(x) = cipher_ctx.iv_len() {
Vec::from(&aes_key_bin[0..x])
} else {
Vec::new()
};
*/
debug!(
"project \"{}\" load aes key: \"{}\", iv: \"{}\", block size: {}",
proj_name,
hex::encode(&aes_key_bin),
hex::encode(&cipher_iv),
cipher_iv_len
);
let cipher_info = WxWorkProjectCipherInfo {
cipher: cipher_ctx,
key: aes_key_bin,
iv: cipher_iv,
};
Some(WxWorkProject {
name: Arc::new(proj_name),
token: proj_token,
encoding_aes_key: proj_aes_key,
envs: Rc::new(envs_obj),
cmds: Rc::new(proj_cmds),
events: Rc::new(proj_events),
cipher_info: Arc::new(Mutex::new(Box::new(cipher_info))),
nonce: AtomicUsize::new(
if let Ok(x) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
(x.as_secs() as usize) << 16
} else {
1_usize << 16
},
),
})
}
pub fn name(&self) -> Arc<String> {
self.name.clone()
}
pub fn try_commands(
&self,
message: &str,
allow_hidden: bool,
) -> Option<(command::WxWorkCommandPtr, command::WxWorkCommandMatch)> {
WxWorkProject::try_capture_commands(&self.cmds, message, allow_hidden)
}
pub fn try_events(
&self,
message: &str,
allow_hidden: bool,
) -> Option<(command::WxWorkCommandPtr, command::WxWorkCommandMatch)> {
WxWorkProject::try_capture_commands(&self.events, message, allow_hidden)
}
pub fn try_capture_commands(
cmds: &[command::WxWorkCommandPtr],
message: &str,
allow_hidden: bool,
) -> Option<(command::WxWorkCommandPtr, command::WxWorkCommandMatch)> {
for cmd in cmds {
// empty message must equal
if cmd.name().is_empty() && !message.is_empty() {
continue;
}
if !allow_hidden {
// skip hidden command
if cmd.is_hidden() {
continue;
}
}
let mat_res = cmd.try_capture(message);
if mat_res.has_result() {
return Some((cmd.clone(), mat_res));
}
}
None
}
pub fn generate_template_vars(
&self,
cmd_match: &command::WxWorkCommandMatch,
) -> serde_json::Value {
let mut ret = self.envs.as_ref().clone();
ret = command::merge_envs(ret, cmd_match.ref_json());
ret
}
#[allow(unused)]
pub fn pkcs7_encode(&self, input: &[u8]) -> Vec<u8> {
let block_size: usize = 32;
let mut ret = Vec::new();
let text_length = input.len();
let padding_length = match block_size - text_length % block_size {
0 => block_size,
x => x,
};
let padding_char: u8 = padding_length as u8;
ret.reserve(text_length + padding_length);
ret.extend_from_slice(input);
ret.extend(iter::repeat(padding_char).take(padding_length));
ret
}
#[allow(unused)]
pub fn pkcs7_decode<'a>(&self, input: &'a [u8]) -> &'a [u8] {
let block_size: usize = 32;
if input.is_empty() {
return input;
}
let padding_char = input[input.len() - 1];
if padding_char < 1 || padding_char as usize > block_size {
return input;
}
&input[0..(input.len() - padding_char as usize)]
}
pub fn decrypt_msg_raw(&self, input: &[u8]) -> Result<Vec<u8>, String> {
// rand_msg=AES_Decrypt(aes_msg)
// 去掉rand_msg头部的16个随机字节和4个字节的msg_len,截取msg_len长度的部分即为msg,剩下的为尾部的receiveid
// 网络字节序
let decrypter;
// let block_size: usize;
match self.cipher_info.lock() {
Ok(c) => {
let ci = &*c;
decrypter = match Aes256CbcNoPadding::new_var(&ci.key, &ci.iv) {
Ok(x) => x,
Err(e) => {
let ret = format!(
"project \"{}\" try to create aes256 decrypter failed, {:?}",
self.name(),
e
);
error!("{}", ret);
return Err(ret);
}
};
// decrypter = ci.cipher.clone();
// block_size = ci.cipher.block_size();
}
Err(e) => {
let ret = format!(
"project \"{}\" try to lock cipher_info failed, {:?}",
self.name(),
e
);
error!("{}", ret);
return Err(ret);
}
}
match decrypter.decrypt_vec(&input) {
Ok(x) => Ok(x),
Err(e) => {
let ret = format!("project \"{}\" try to decrypt failed, {:?}", self.name(), e);
error!("{}", ret);
Err(ret)
}
}
/*
decrypter.pad(false);
let mut plaintext = vec![0; input.len() + block_size];
let mut plaintext_count = match decrypter.update(input, &mut plaintext) {
Ok(x) => x,
Err(e) => {
let ret = format!(
"project \"{}\" decrypt {} update failed\n{:?}",
self.name(),
hex::encode(input),
e
);
debug!("{}", ret);
return Err(ret);
}
};
plaintext_count += match decrypter.finalize(&mut plaintext[plaintext_count..]) {
Ok(x) => x,
Err(e) => {
let ret = format!(
"project \"{}\" decrypt {} finalize failed\n{:?}",
self.name(),
hex::encode(input),
e
);
debug!("{}", ret);
return Err(ret);
}
};
plaintext.truncate(plaintext_count);
Ok(plaintext)
*/
}
pub fn decrypt_msg_raw_base64(&self, input: &str) -> Result<Vec<u8>, String> {
// POST http://api.3dept.com/?msg_signature=ASDFQWEXZCVAQFASDFASDFSS×tamp=13500001234&nonce=123412323
// aes_msg=Base64_Decode(msg_encrypt)
let bin = match base64::STANDARD.decode(input.as_bytes()) {
Ok(x) => x,
Err(e) => {
let ret = format!(
"project \"{}\" decode base64 {} failed, {:?}",
self.name(),
input,
e.to_string()
);
error!("{}", ret);
return Err(ret);
}
};
match self.decrypt_msg_raw(&bin) {
Ok(x) => Ok(x),
Err(e) => Err(e),
}
}
pub fn decrypt_msg_raw_base64_content(
&self,
input: &str,
) -> Result<message::WxWorkMessageDec, String> {
let dec_bin = match self.decrypt_msg_raw_base64(input) {
Ok(x) => x,
Err(e) => {
return Err(e);
}
};
debug!(
"project \"{}\" try to decrypt base64: {}",
self.name(),
input
);
let dec_bin_unpadding = self.pkcs7_decode(&dec_bin);
if dec_bin_unpadding.len() <= 20 {
let err_msg = format!(
"project \"{}\" decode {} data length invalid",
self.name(),
hex::encode(&dec_bin_unpadding)
);
error!("{}", err_msg);
return Err(err_msg);
}
let msg_len = BigEndian::read_u32(&dec_bin_unpadding[16..20]) as usize;
if msg_len + 20 > dec_bin_unpadding.len() {
let err_msg = format!(
"project \"{}\" decode message length {} , but bin data {} has only length {}",
self.name(),
msg_len,
hex::encode(&dec_bin_unpadding),
dec_bin_unpadding.len()
);
error!("{}", err_msg);
return Err(err_msg);
}
let msg_content = match String::from_utf8(dec_bin_unpadding[20..(20 + msg_len)].to_vec()) {
Ok(x) => x,
Err(e) => {
let err_msg = format!(
"project \"{}\" decode message content {} failed, {:?}",
self.name(),
hex::encode(&dec_bin_unpadding[20..msg_len]),
e
);
error!("{}", err_msg);
return Err(err_msg);
}
};
let receiveid = if dec_bin_unpadding.len() > 20 + msg_len {
match String::from_utf8(dec_bin_unpadding[(20 + msg_len)..].to_vec()) {
Ok(x) => x,
Err(e) => {
let err_msg = format!(
"project \"{}\" decode message content {} failed, {:?}",
self.name(),
hex::encode(&dec_bin_unpadding[20..msg_len]),
e
);
error!("{}", err_msg);
String::default()
}
}
} else {
String::default()
};
debug!(
"project \"{}\" decode message from receiveid={} content {}",
self.name(),
receiveid,
msg_content
);
Ok(message::WxWorkMessageDec {
content: msg_content,
receiveid,
})
}
pub fn encrypt_msg_raw(&self, input: &[u8], random_str: &str) -> Result<Vec<u8>, String> {
// rand_msg=AES_Decrypt(aes_msg)
// 去掉rand_msg头部的16个随机字节和4个字节的msg_len,截取msg_len长度的部分即为msg,剩下的为尾部的receiveid
// 网络字节序,回包的receiveid直接为空即可
let mut input_len_buf = [0; 4];
BigEndian::write_u32(&mut input_len_buf, input.len() as u32);
let mut padded_plaintext: Vec<u8> = Vec::new();
padded_plaintext.reserve(64 + input.len());
padded_plaintext.extend_from_slice(random_str.as_bytes());
padded_plaintext.extend_from_slice(&input_len_buf);
padded_plaintext.extend_from_slice(input);
let padded_input = self.pkcs7_encode(&padded_plaintext);
let encrypter;
// let block_size: usize;
match self.cipher_info.lock() {
Ok(c) => {
let ci = &*c;
encrypter = match Aes256CbcNoPadding::new_var(&ci.key, &ci.iv) {
Ok(x) => x,
Err(e) => {
let ret = format!(
"project \"{}\" try to create aes256 encrypter failed, {:?}",
self.name(),
e
);
error!("{}", ret);
return Err(ret);
}
};
// encrypter = ci.cipher.clone();
/*
encrypter = match Crypter::new(ci.cipher, Mode::Encrypt, &ci.key, Some(&ci.iv)) {
Ok(x) => x,
Err(e) => {
let ret = format!(
"project \"{}\" create Crypter for encrypt {} with key={} iv={} failed\n{:?}",
self.name(),
hex::encode(input),
hex::encode(&ci.key),
hex::encode(&ci.iv),
e
);
debug!("{}", ret);
return Err(ret);
}
};
block_size = ci.cipher.block_size();
*/
}
Err(e) => {
let ret = format!(
"project \"{}\" try to lock cipher_info failed, {:?}",
self.name(),
e
);
error!("{}", ret);
return Err(ret);
}
}
let ret = encrypter.encrypt_vec(&padded_input);
Ok(ret)
/*
encrypter.pad(false);
let mut plaintext = vec![0; padded_input.len() + block_size];
let mut plaintext_count = match encrypter.update(&padded_input, &mut plaintext) {
Ok(x) => x,
Err(e) => {
let ret = format!(
"project \"{}\" encrypt {} update failed\n{:?}",
self.name(),
hex::encode(input),
e
);
debug!("{}", ret);
return Err(ret);
}
};
plaintext_count += match encrypter.finalize(&mut plaintext[plaintext_count..]) {
Ok(x) => x,
Err(e) => {
let ret = format!(
"project \"{}\" encrypt {} finalize failed\n{:?}",
self.name(),
hex::encode(input),
e
);
debug!("{}", ret);
return Err(ret);
}
};
plaintext.truncate(plaintext_count);
Ok(plaintext)
*/
}
pub fn encrypt_msg_raw_base64(&self, input: &[u8]) -> Result<String, String> {
// msg_encrypt = Base64_Encode(AES_Encrypt(rand_msg))
let random_str = self.alloc_random_str();
match self.encrypt_msg_raw(&input, &random_str) {
Ok(x) => match base64::STANDARD.encode(&x) {
Ok(v) => {
debug!(
"project \"{}\" use random string {} and encrypt \"{}\" to {}",
self.name(),
random_str,
match String::from_utf8(input.to_vec()) {
Ok(y) => y,
Err(_) => hex::encode(input),
},
v
);
Ok(v)
}
Err(e) => {
let ret = format!(
"project \"{}\" encrypt {} and encode to base64 failed, \n{:?}",
self.name(),
hex::encode(input),
e
);
debug!("{}", ret);
Err(ret)
}
},
Err(e) => Err(e),
}
}
pub fn make_msg_signature(&self, timestamp: &str, nonce: &str, msg_encrypt: &str) -> String {
// GET http://api.3dept.com/?msg_signature=ASDFQWEXZCVAQFASDFASDFSS×tamp=13500001234&nonce=123412323&echostr=ENCRYPT_STR
// dev_msg_signature=sha1(sort(token、timestamp、nonce、msg_encrypt))
// sort的含义是将参数值按照字母字典排序,然后从小到大拼接成一个字符串
// sha1处理结果要编码为可见字符,编码的方式是把每字节散列值打印为%02x(即16进制,C printf语法)格式,全部小写
let mut datas = [self.token.as_str(), timestamp, nonce, msg_encrypt];
datas.sort_unstable();
let cat_str = datas.concat();
let hash_res =
ring::digest::digest(&ring::digest::SHA1_FOR_LEGACY_USE_ONLY, cat_str.as_bytes());
// let hash_res = hash::hash(hash::MessageDigest::sha1(), cat_str.as_bytes());
// match hash_res {
// Ok(x) => hex::encode(x.as_ref()),
// Err(e) => format!("Sha1 for {} failed, {:?}", cat_str, e),
// }
hex::encode(&hash_res.as_ref())
}
pub fn check_msg_signature(
&self,
excepted_signature: &str,
timestamp: &str,
nonce: &str,
msg_encrypt: &str,
) -> bool {
let real_signature = self.make_msg_signature(×tamp, &nonce, &msg_encrypt);
debug!("project \"{}\" try to check msg signature: excepted_signature={}, timestamp={}, nonce={}, msg_encrypt={}, real_signature={}", self.name(), excepted_signature, timestamp, nonce, msg_encrypt, real_signature);
if real_signature.as_str() == excepted_signature {
true
} else {
error!(
"project \"{}\" check signature failed, except {}, reas is {}",
self.name(),
excepted_signature,
real_signature
);
false
}
}
fn alloc_nonce(&self) -> String {
let ret = self.nonce.fetch_add(1, Ordering::SeqCst);
let mut buf = [0; 8];
BigEndian::write_u64(&mut buf, ret as u64);
hex::encode(buf)
}
fn alloc_random_str(&self) -> String {
use ring::rand::SystemRandom;
let rng = SystemRandom::new();
let mut buf = [0; 8];
let _ = rng.fill(&mut buf);
hex::encode(buf)
}
pub fn make_xml_response(&self, msg_text: String) -> HttpResponse {
debug!(
"project \"{}\" start to encrypt message to base64\n{}",
self.name(),
msg_text
);
let msg_encrypt = match self.encrypt_msg_raw_base64(msg_text.as_bytes()) {
Ok(x) => x,
Err(e) => {
error!(
"project \"{}\" encrypt_msg_raw_base64 {} failed: {}",
self.name(),
msg_text,
e
);
return HttpResponse::Forbidden()
.content_type("application/xml")
.body(message::get_robot_response_access_deny_content(e.as_str()));
}
};
let nonce = self.alloc_nonce();
let timestamp = if let Ok(x) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
x.as_secs().to_string()
} else {
String::from("0")
};
let msg_signature =
self.make_msg_signature(timestamp.as_str(), nonce.as_str(), msg_encrypt.as_str());
match message::pack_message_response(msg_encrypt, msg_signature, timestamp, nonce) {
Ok(x) => HttpResponse::Ok().content_type("application/xml").body(x),
Err(e) => {
error!(
"project \"{}\" make_xml_response failed: {}",
self.name(),
e
);
HttpResponse::Forbidden()
.content_type("application/xml")
.body(message::get_robot_response_access_deny(e))
}
}
}
pub fn make_text_response(&self, msg: message::WxWorkMessageTextRsp) -> HttpResponse {
let rsp_xml = match message::pack_text_message(msg) {
Ok(x) => x,
Err(e) => {
error!(
"project \"{}\" make_text_response failed: {}",
self.name(),
e
);
return self.make_xml_response(e);
}
};
self.make_xml_response(rsp_xml)
}
pub fn make_markdown_response(&self, msg: message::WxWorkMessageMarkdownRsp) -> HttpResponse {
let rsp_xml = match message::pack_markdown_message(msg) {
Ok(x) => x,
Err(e) => {
error!(
"project \"{}\" make_markdown_response failed: {}",
self.name(),
e
);
return self.make_xml_response(e);
}
};
self.make_xml_response(rsp_xml)
}
pub fn make_error_response(&self, msg: String) -> HttpResponse {
self.make_markdown_response(message::WxWorkMessageMarkdownRsp { content: msg })
}
pub fn make_markdown_response_with_text(&self, msg: String) -> HttpResponse {
self.make_markdown_response(message::WxWorkMessageMarkdownRsp { content: msg })
}
pub fn make_image_response(&self, msg: message::WxWorkMessageImageRsp) -> HttpResponse {
let rsp_xml = match message::pack_image_message(msg) {
Ok(x) => x,
Err(e) => {
error!(
"project \"{}\" make_image_response failed: {}",
self.name(),
e
);
return self.make_xml_response(e);
}
};
self.make_xml_response(rsp_xml)
}
}
|
use crate::bgp::BgpSessionType::{EBgp, IBgpClient, IBgpPeer};
use crate::bgp::{BgpEvent, BgpRoute};
use crate::event::{Event, EventQueue};
use crate::router::*;
use crate::{AsId, Prefix};
use crate::{IgpNetwork, NetworkDevice};
use maplit::{hashmap, hashset};
#[test]
fn test_bgp_single() {
let mut r = Router::new("test", 0.into(), AsId(65001));
r.establish_bgp_session(100.into(), EBgp).unwrap();
r.establish_bgp_session(1.into(), IBgpPeer).unwrap();
r.establish_bgp_session(2.into(), IBgpPeer).unwrap();
r.establish_bgp_session(3.into(), IBgpPeer).unwrap();
r.establish_bgp_session(4.into(), IBgpClient).unwrap();
r.establish_bgp_session(5.into(), IBgpClient).unwrap();
r.establish_bgp_session(6.into(), IBgpClient).unwrap();
r.igp_forwarding_table = hashmap! {
100.into() => Some((100.into(), 0.0)),
1.into() => Some((1.into(), 1.0)),
2.into() => Some((2.into(), 1.0)),
3.into() => Some((2.into(), 4.0)),
4.into() => Some((4.into(), 2.0)),
5.into() => Some((4.into(), 6.0)),
6.into() => Some((1.into(), 13.0)),
10.into() => Some((1.into(), 6.0)),
11.into() => Some((1.into(), 15.0)),
};
let mut queue: EventQueue = EventQueue::new();
/////////////////////
// external update //
/////////////////////
r.handle_event(
Event::Bgp(
100.into(),
0.into(),
BgpEvent::Update(BgpRoute {
prefix: Prefix(200),
as_path: vec![AsId(1), AsId(2), AsId(3), AsId(4), AsId(5)],
next_hop: 100.into(),
local_pref: None,
med: None,
}),
),
&mut queue,
)
.unwrap();
// check that the router now has a route selected for 100 with the correct data
let entry = r.get_selected_bgp_route(Prefix(200)).unwrap();
assert_eq!(entry.from_type, EBgp);
assert_eq!(entry.route.next_hop, 100.into());
assert_eq!(entry.route.local_pref, Some(100));
assert_eq!(queue.len(), 6);
while let Some(job) = queue.pop_front() {
match job {
Event::Bgp(from, _, BgpEvent::Update(r)) => {
assert_eq!(from, 0.into());
assert_eq!(r.next_hop, 100.into());
}
_ => assert!(false),
}
}
// used for later
let original_entry = entry.clone();
/////////////////////
// internal update //
/////////////////////
// update from route reflector
r.handle_event(
Event::Bgp(
1.into(),
0.into(),
BgpEvent::Update(BgpRoute {
prefix: Prefix(201),
as_path: vec![AsId(1), AsId(2), AsId(3)],
next_hop: 11.into(),
local_pref: Some(50),
med: None,
}),
),
&mut queue,
)
.unwrap();
// check that the router now has a route selected for 100 with the correct data
let entry = r.get_selected_bgp_route(Prefix(201)).unwrap();
assert_eq!(entry.from_type, IBgpPeer);
assert_eq!(entry.route.next_hop, 11.into());
assert_eq!(entry.route.local_pref, Some(50));
assert_eq!(queue.len(), 4);
while let Some(job) = queue.pop_front() {
match job {
Event::Bgp(from, to, BgpEvent::Update(r)) => {
assert_eq!(from, 0.into());
assert!(hashset![4, 5, 6, 100].contains(&(to.index() as usize)));
if to == 100.into() {
assert_eq!(r.next_hop, 0.into());
} else {
assert_eq!(r.next_hop, 11.into());
}
}
_ => assert!(false),
}
}
//////////////////
// worse update //
//////////////////
// update from route reflector
r.handle_event(
Event::Bgp(
2.into(),
0.into(),
BgpEvent::Update(BgpRoute {
prefix: Prefix(200),
as_path: vec![AsId(1), AsId(2), AsId(3), AsId(4), AsId(5)],
next_hop: 10.into(),
local_pref: None,
med: None,
}),
),
&mut queue,
)
.unwrap();
// check that the router now has a route selected for 100 with the correct data
let entry = r.get_selected_bgp_route(Prefix(200)).unwrap();
assert_eq!(entry.from_type, EBgp);
assert_eq!(entry.route.next_hop, 100.into());
assert_eq!(queue.len(), 0);
///////////////////
// better update //
///////////////////
// update from route reflector
r.handle_event(
Event::Bgp(
5.into(),
0.into(),
BgpEvent::Update(BgpRoute {
prefix: Prefix(200),
as_path: vec![
AsId(1),
AsId(2),
AsId(3),
AsId(4),
AsId(5),
AsId(6),
AsId(7),
AsId(8),
AsId(9),
AsId(10),
],
next_hop: 5.into(),
local_pref: Some(150),
med: None,
}),
),
&mut queue,
)
.unwrap();
// check that the router now has a route selected for 100 with the correct data
let entry = r.get_selected_bgp_route(Prefix(200)).unwrap().clone();
assert_eq!(entry.from_type, IBgpClient);
assert_eq!(entry.route.next_hop, 5.into());
assert_eq!(entry.route.local_pref, Some(150));
assert_eq!(queue.len(), 7);
while let Some(job) = queue.pop_front() {
match job {
Event::Bgp(from, to, BgpEvent::Update(r)) => {
assert_eq!(from, 0.into());
assert!(hashset![1, 2, 3, 4, 6, 100].contains(&(to.index() as usize)));
if to == 100.into() {
assert_eq!(r.next_hop, 0.into());
assert_eq!(r.local_pref, None);
} else {
assert_eq!(r.next_hop, 5.into());
assert_eq!(r.local_pref, Some(150));
}
}
Event::Bgp(from, to, BgpEvent::Withdraw(prefix)) => {
assert_eq!(from, 0.into());
assert_eq!(to, 5.into());
assert_eq!(prefix, Prefix(200));
}
}
}
///////////////////////
// retract bad route //
///////////////////////
r.handle_event(
Event::Bgp(2.into(), 0.into(), BgpEvent::Withdraw(Prefix(200))),
&mut queue,
)
.unwrap();
// check that the router now has a route selected for 100 with the correct data
let new_entry = r.get_selected_bgp_route(Prefix(200)).unwrap();
assert_eq!(new_entry, entry);
assert_eq!(queue.len(), 0);
////////////////////////
// retract good route //
////////////////////////
r.handle_event(
Event::Bgp(5.into(), 0.into(), BgpEvent::Withdraw(Prefix(200))),
&mut queue,
)
.unwrap();
// check that the router now has a route selected for 100 with the correct data
//eprintln!("{:#?}", r);
let new_entry = r.get_selected_bgp_route(Prefix(200)).unwrap();
assert_eq!(new_entry, original_entry);
assert_eq!(queue.len(), 7);
while let Some(job) = queue.pop_front() {
match job {
Event::Bgp(from, to, BgpEvent::Update(r)) => {
assert_eq!(from, 0.into());
assert!(hashset![1, 2, 3, 4, 5, 6].contains(&(to.index() as usize)));
assert_eq!(r.next_hop, 100.into());
assert_eq!(r.local_pref, Some(100));
}
Event::Bgp(from, to, BgpEvent::Withdraw(prefix)) => {
assert_eq!(from, 0.into());
assert_eq!(to, 100.into());
assert_eq!(prefix, Prefix(200));
}
}
}
////////////////////////
// retract last route //
////////////////////////
r.handle_event(
Event::Bgp(100.into(), 0.into(), BgpEvent::Withdraw(Prefix(200))),
&mut queue,
)
.unwrap();
// check that the router now has a route selected for 100 with the correct data
assert!(r.get_selected_bgp_route(Prefix(200)).is_none());
assert_eq!(queue.len(), 6);
while let Some(job) = queue.pop_front() {
match job {
Event::Bgp(from, to, BgpEvent::Withdraw(Prefix(200))) => {
assert_eq!(from, 0.into());
assert!(hashset![1, 2, 3, 4, 5, 6].contains(&(to.index() as usize)));
}
_ => unreachable!(),
}
}
}
#[test]
fn test_fw_table_simple() {
let mut net: IgpNetwork = IgpNetwork::new();
let mut a = Router::new("A", net.add_node(()), AsId(65001));
let mut b = Router::new("B", net.add_node(()), AsId(65001));
let mut c = Router::new("C", net.add_node(()), AsId(65001));
let d = Router::new("D", net.add_node(()), AsId(65001));
let e = Router::new("E", net.add_node(()), AsId(65001));
net.add_edge(a.router_id(), b.router_id(), 1.0);
net.add_edge(b.router_id(), c.router_id(), 1.0);
net.add_edge(c.router_id(), d.router_id(), 1.0);
net.add_edge(d.router_id(), e.router_id(), 1.0);
net.add_edge(e.router_id(), d.router_id(), 1.0);
net.add_edge(d.router_id(), c.router_id(), 1.0);
net.add_edge(c.router_id(), b.router_id(), 1.0);
net.add_edge(b.router_id(), a.router_id(), 1.0);
/*
* all weights = 1
* c ----- c
* | |
* | |
* b d
* | |
* | |
* a e
*/
a.write_igp_forwarding_table(&net).unwrap();
let expected_forwarding_table = hashmap! {
a.router_id() => Some((a.router_id(), 0.0)),
b.router_id() => Some((b.router_id(), 1.0)),
c.router_id() => Some((b.router_id(), 2.0)),
d.router_id() => Some((b.router_id(), 3.0)),
e.router_id() => Some((b.router_id(), 4.0)),
};
let exp = &expected_forwarding_table;
let acq = &a.igp_forwarding_table;
for target in vec![&a, &b, &c, &d, &e] {
assert_eq!(exp.get(&target.router_id()), acq.get(&target.router_id()));
}
b.write_igp_forwarding_table(&net).unwrap();
let expected_forwarding_table = hashmap! {
a.router_id() => Some((a.router_id(), 1.0)),
b.router_id() => Some((b.router_id(), 0.0)),
c.router_id() => Some((c.router_id(), 1.0)),
d.router_id() => Some((c.router_id(), 2.0)),
e.router_id() => Some((c.router_id(), 3.0)),
};
let exp = &expected_forwarding_table;
let acq = &b.igp_forwarding_table;
for target in vec![&a, &b, &c, &d, &e] {
assert_eq!(exp.get(&target.router_id()), acq.get(&target.router_id()));
}
c.write_igp_forwarding_table(&net).unwrap();
let expected_forwarding_table = hashmap! {
a.router_id() => Some((b.router_id(), 2.0)),
b.router_id() => Some((b.router_id(), 1.0)),
c.router_id() => Some((c.router_id(), 0.0)),
d.router_id() => Some((d.router_id(), 1.0)),
e.router_id() => Some((d.router_id(), 2.0)),
};
let exp = &expected_forwarding_table;
let acq = &c.igp_forwarding_table;
for target in vec![&a, &b, &c, &d, &e] {
assert_eq!(exp.get(&target.router_id()), acq.get(&target.router_id()));
}
}
#[test]
fn test_igp_fw_table_complex() {
let mut net: IgpNetwork = IgpNetwork::new();
let mut a = Router::new("A", net.add_node(()), AsId(65001));
let b = Router::new("B", net.add_node(()), AsId(65001));
let mut c = Router::new("C", net.add_node(()), AsId(65001));
let d = Router::new("D", net.add_node(()), AsId(65001));
let e = Router::new("E", net.add_node(()), AsId(65001));
let f = Router::new("F", net.add_node(()), AsId(65001));
let g = Router::new("G", net.add_node(()), AsId(65001));
let h = Router::new("H", net.add_node(()), AsId(65001));
net.add_edge(a.router_id(), b.router_id(), 3.0);
net.add_edge(b.router_id(), a.router_id(), 3.0);
net.add_edge(a.router_id(), e.router_id(), 1.0);
net.add_edge(e.router_id(), a.router_id(), 1.0);
net.add_edge(b.router_id(), c.router_id(), 8.0);
net.add_edge(c.router_id(), b.router_id(), 8.0);
net.add_edge(b.router_id(), f.router_id(), 2.0);
net.add_edge(f.router_id(), b.router_id(), 2.0);
net.add_edge(c.router_id(), d.router_id(), 8.0);
net.add_edge(d.router_id(), c.router_id(), 8.0);
net.add_edge(c.router_id(), f.router_id(), 1.0);
net.add_edge(f.router_id(), c.router_id(), 1.0);
net.add_edge(c.router_id(), g.router_id(), 1.0);
net.add_edge(g.router_id(), c.router_id(), 1.0);
net.add_edge(d.router_id(), h.router_id(), 1.0);
net.add_edge(h.router_id(), d.router_id(), 1.0);
net.add_edge(e.router_id(), f.router_id(), 1.0);
net.add_edge(f.router_id(), e.router_id(), 1.0);
net.add_edge(f.router_id(), g.router_id(), 8.0);
net.add_edge(g.router_id(), f.router_id(), 8.0);
net.add_edge(g.router_id(), h.router_id(), 1.0);
net.add_edge(h.router_id(), g.router_id(), 1.0);
/*
* 3 8 8
* a ---- b ---- c ---- d
* | | / | |
* |1 2| -- |1 |1
* | | / 1 | |
* e ---- f ---- g ---- h
* 1 8 1
*/
a.write_igp_forwarding_table(&net).unwrap();
let expected_forwarding_table = hashmap! {
a.router_id() => Some((a.router_id(), 0.0)),
b.router_id() => Some((b.router_id(), 3.0)),
c.router_id() => Some((e.router_id(), 3.0)),
d.router_id() => Some((e.router_id(), 6.0)),
e.router_id() => Some((e.router_id(), 1.0)),
f.router_id() => Some((e.router_id(), 2.0)),
g.router_id() => Some((e.router_id(), 4.0)),
h.router_id() => Some((e.router_id(), 5.0)),
};
let exp = &expected_forwarding_table;
let acq = &a.igp_forwarding_table;
for target in vec![&a, &b, &c, &d, &e, &f, &g, &h] {
assert_eq!(exp.get(&target.router_id()), acq.get(&target.router_id()));
}
c.write_igp_forwarding_table(&net).unwrap();
let expected_forwarding_table = hashmap! {
a.router_id() => Some((f.router_id(), 3.0)),
b.router_id() => Some((f.router_id(), 3.0)),
c.router_id() => Some((c.router_id(), 0.0)),
d.router_id() => Some((g.router_id(), 3.0)),
e.router_id() => Some((f.router_id(), 2.0)),
f.router_id() => Some((f.router_id(), 1.0)),
g.router_id() => Some((g.router_id(), 1.0)),
h.router_id() => Some((g.router_id(), 2.0)),
};
let exp = &expected_forwarding_table;
let acq = &c.igp_forwarding_table;
for target in vec![&a, &b, &c, &d, &e, &f, &g, &h] {
assert_eq!(exp.get(&target.router_id()), acq.get(&target.router_id()));
}
}
|
use super::{Read, Result, Write};
use crate::{alloc::Allocator, containers::Array};
impl Read for &[u8]
{
#[inline]
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
{
let count = buf.len().min(self.len());
let (to_copy, remaining) = self.split_at(count);
buf[..count].copy_from_slice(to_copy);
*self = remaining;
Ok(count)
}
}
impl<A: Allocator> Write for &mut Array<u8, A>
{
fn write(&mut self, buf: &[u8]) -> Result<usize>
{
(*self).write(buf)
}
fn flush(&mut self) -> Result<()>
{
(*self).flush()
}
}
impl<A: Allocator> Write for Array<u8, A>
{
fn write(&mut self, buf: &[u8]) -> Result<usize>
{
let old_len = self.len();
self.resize(self.len() + buf.len(), 0);
(&mut self[old_len..]).copy_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> Result<()>
{
Ok(())
}
}
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn read_u8_slice()
{
let mut data: &[u8] = &[1, 2, 3, 4, 5];
let output = &mut [0, 0];
assert_eq!(data.read(output), Ok(2));
assert_eq!(output[0], 1);
assert_eq!(output[1], 2);
assert_eq!(data.read(output), Ok(2));
assert_eq!(output[0], 3);
assert_eq!(output[1], 4);
assert_eq!(data.read(output), Ok(1));
assert_eq!(output[0], 5);
assert_eq!(data.read(output), Ok(0));
}
#[test]
fn write_u8_array()
{
let mut array = Array::<u8>::new();
array.write_all(&[1, 2, 3, 4, 5, 6]).unwrap();
assert_eq!(&array[..], &[1, 2, 3, 4, 5, 6]);
}
}
|
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
mod libs;
use rocket_cors;
use rocket::http::Method;
use rocket_cors::{AllowedHeaders, AllowedOrigins, Error};
// use async_std::task::block_on;
use futures::executor::block_on;
use libs::{database_client::{DatabaseClient, DatabaseBase}, routes};
fn main() -> Result<(), Error> {
let mut database = DatabaseClient::new();
block_on(database.connect()).expect("The database connection fails");
let allowed_origins = AllowedOrigins::all();
let cors = rocket_cors::CorsOptions {
allowed_origins,
allowed_methods: vec![Method::Get, Method::Post, Method::Put].into_iter().map(From::from).collect(),
allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
allow_credentials: false,
..Default::default()
}.to_cors()?;
rocket::ignite()
.manage(database)
.mount("/", routes::initialize_routes())
.attach(cors)
.launch();
Ok(())
}
|
// use canrun::{both, pair, var, Can, Equals, Goal, State};
// extern crate env_logger;
// #[test]
// fn does_not_overflow() {
// let _ = env_logger::init();
// let x = var();
// let infinite_xs: Goal<usize> = x.equals(pair(x.can(), Can::Nil));
// // An overflow is not triggered if infinite_xs is the second argument
// let bad_goal = both(infinite_xs, x.equals(Can::Val(1)));
// let results = bad_goal.run(State::new()).nth(0);
// // The goal should be invalidated early and not return a state
// assert!(results.is_none());
// }
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Creator {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
pub properties: CreatorProperties,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccount {
#[serde(flatten)]
pub tracked_resource: TrackedResource,
pub sku: Sku,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<Kind>,
#[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")]
pub system_data: Option<SystemData>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MapsAccountProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccountUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<Kind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MapsAccountProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreatorUpdateParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CreatorProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccounts {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<MapsAccount>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreatorList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Creator>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Kind {
Gen1,
Gen2,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
pub name: sku::Name,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
}
pub mod sku {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Name {
S0,
S1,
G2,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsKeySpecification {
#[serde(rename = "keyType")]
pub key_type: maps_key_specification::KeyType,
}
pub mod maps_key_specification {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum KeyType {
#[serde(rename = "primary")]
Primary,
#[serde(rename = "secondary")]
Secondary,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccountKeys {
#[serde(rename = "primaryKeyLastUpdated", default, skip_serializing_if = "Option::is_none")]
pub primary_key_last_updated: Option<String>,
#[serde(rename = "primaryKey", default, skip_serializing_if = "Option::is_none")]
pub primary_key: Option<String>,
#[serde(rename = "secondaryKey", default, skip_serializing_if = "Option::is_none")]
pub secondary_key: Option<String>,
#[serde(rename = "secondaryKeyLastUpdated", default, skip_serializing_if = "Option::is_none")]
pub secondary_key_last_updated: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsOperations {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<OperationDetail>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDetail {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")]
pub is_data_action: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplay>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<OperationProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplay {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationProperties {
#[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")]
pub service_specification: Option<ServiceSpecification>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServiceSpecification {
#[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")]
pub metric_specifications: Vec<MetricSpecification>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricSpecification {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")]
pub display_description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dimensions: Vec<Dimension>,
#[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")]
pub aggregation_type: Option<String>,
#[serde(rename = "fillGapWithZero", default, skip_serializing_if = "Option::is_none")]
pub fill_gap_with_zero: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(rename = "resourceIdDimensionNameOverride", default, skip_serializing_if = "Option::is_none")]
pub resource_id_dimension_name_override: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Dimension {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "internalName", default, skip_serializing_if = "Option::is_none")]
pub internal_name: Option<String>,
#[serde(rename = "internalMetricName", default, skip_serializing_if = "Option::is_none")]
pub internal_metric_name: Option<String>,
#[serde(rename = "sourceMdmNamespace", default, skip_serializing_if = "Option::is_none")]
pub source_mdm_namespace: Option<String>,
#[serde(rename = "toBeExportedToShoebox", default, skip_serializing_if = "Option::is_none")]
pub to_be_exported_to_shoebox: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MapsAccountProperties {
#[serde(rename = "uniqueId", default, skip_serializing_if = "Option::is_none")]
pub unique_id: Option<String>,
#[serde(rename = "disableLocalAuth", default, skip_serializing_if = "Option::is_none")]
pub disable_local_auth: Option<bool>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreatorProperties {
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "storageUnits")]
pub storage_units: i32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorDetail>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorDetail {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<ErrorDetail>,
#[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")]
pub additional_info: Vec<ErrorAdditionalInfo>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorAdditionalInfo {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrackedResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
pub location: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SystemData {
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")]
pub created_by_type: Option<system_data::CreatedByType>,
#[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by_type: Option<system_data::LastModifiedByType>,
#[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")]
pub last_modified_at: Option<String>,
}
pub mod system_data {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CreatedByType {
User,
Application,
ManagedIdentity,
Key,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LastModifiedByType {
User,
Application,
ManagedIdentity,
Key,
}
}
|
use crate::prelude::*;
use num::Integer;
pub fn pt1(input: Vec<Disc>) -> Result<u64> {
let mut lcm = 1;
let mut start_time = 0;
for (idx, disc) in input.into_iter().enumerate() {
let current = (idx as u64 + 1 + disc.current + start_time) % disc.size;
let remainder = (disc.size - current) % disc.size;
// `start_time` must advance `remainder`, but is only allowed to increment
// in multiples of `lcm` (otherwise previous discs would no longer be valid).
let mut increment = remainder;
while increment % lcm != 0 {
increment += disc.size;
}
start_time += increment;
lcm = lcm.lcm(&disc.size);
}
Ok(start_time)
}
pub fn pt2(mut input: Vec<Disc>) -> Result<u64> {
input.push(Disc {
size: 11,
current: 0,
});
pt1(input)
}
pub fn parse(s: &str) -> IResult<&str, Vec<Disc>> {
use parsers::*;
fold_many1(
tuple((
preceded(tag("Disc #"), usize_str),
delimited(
tag(" has "),
u64_str,
tag(" positions; at time=0, it is at position "),
),
terminated(u64_str, pair(char('.'), opt(line_ending))),
)),
|| Vec::new(),
|mut v, (idx, size, current)| {
v.push(Disc { size, current });
assert_eq!(idx, v.len());
v
},
)(s)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Disc {
size: u64,
current: u64,
}
#[test]
fn day15() -> Result<()> {
test_part!(parse, pt1, "\
Disc #1 has 5 positions; at time=0, it is at position 4.
Disc #2 has 2 positions; at time=0, it is at position 1." => 5);
Ok(())
}
|
/// IssueTemplate represents an issue template for a repository
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct IssueTemplate {
pub about: Option<String>,
pub content: Option<String>,
pub file_name: Option<String>,
pub labels: Option<Vec<String>>,
pub name: Option<String>,
pub title: Option<String>,
}
impl IssueTemplate {
/// Create a builder for this object.
#[inline]
pub fn builder() -> IssueTemplateBuilder {
IssueTemplateBuilder {
body: Default::default(),
}
}
#[inline]
pub fn repo_get_issue_templates() -> IssueTemplateGetBuilder<crate::generics::MissingOwner, crate::generics::MissingRepo> {
IssueTemplateGetBuilder {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
}
}
}
impl Into<IssueTemplate> for IssueTemplateBuilder {
fn into(self) -> IssueTemplate {
self.body
}
}
/// Builder for [`IssueTemplate`](./struct.IssueTemplate.html) object.
#[derive(Debug, Clone)]
pub struct IssueTemplateBuilder {
body: self::IssueTemplate,
}
impl IssueTemplateBuilder {
#[inline]
pub fn about(mut self, value: impl Into<String>) -> Self {
self.body.about = Some(value.into());
self
}
#[inline]
pub fn content(mut self, value: impl Into<String>) -> Self {
self.body.content = Some(value.into());
self
}
#[inline]
pub fn file_name(mut self, value: impl Into<String>) -> Self {
self.body.file_name = Some(value.into());
self
}
#[inline]
pub fn labels(mut self, value: impl Iterator<Item = impl Into<String>>) -> Self {
self.body.labels = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
#[inline]
pub fn name(mut self, value: impl Into<String>) -> Self {
self.body.name = Some(value.into());
self
}
#[inline]
pub fn title(mut self, value: impl Into<String>) -> Self {
self.body.title = Some(value.into());
self
}
}
/// Builder created by [`IssueTemplate::repo_get_issue_templates`](./struct.IssueTemplate.html#method.repo_get_issue_templates) method for a `GET` operation associated with `IssueTemplate`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct IssueTemplateGetBuilder<Owner, Repo> {
inner: IssueTemplateGetBuilderContainer,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
}
#[derive(Debug, Default, Clone)]
struct IssueTemplateGetBuilderContainer {
param_owner: Option<String>,
param_repo: Option<String>,
}
impl<Owner, Repo> IssueTemplateGetBuilder<Owner, Repo> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> IssueTemplateGetBuilder<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>) -> IssueTemplateGetBuilder<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 IssueTemplateGetBuilder<crate::generics::OwnerExists, crate::generics::RepoExists> {
type Output = Vec<IssueTemplate>;
const METHOD: http::Method = http::Method::GET;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/issue_templates", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?")).into()
}
}
|
extern crate aufindlib;
extern crate clap;
extern crate dirs;
extern crate rustyline;
use clap::{Arg, App, SubCommand};
use rustyline::Editor;
use std::path::Path;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const HISTORY_FILE: &'static str = ".aufind_history";
const ARG_CASE_SENSITIVE: &'static str = "CASE_SENSITIVE";
const ARG_PATTERN: &'static str = "PATTERN";
const ARG_INCLUDE_DIRS: &'static str = "INCLUDE_DIRS";
const ARG_INCLUDE_FILES: &'static str = "INCLUDE_FILES";
const ARG_HIGHLIGHT_OUTPUT: &'static str = "HIGHLIGHT_OUTPUT";
const TRUE_STR: &'static str = "true";
const FALSE_STR: &'static str = "false";
const STRINGS_CONSIDERED_FALSE: [&'static str; 4] = ["false", "0", "", "no"];
fn to_bool(val: &str) -> bool {
let lower = String::from(val).to_lowercase();
let mut result = true;
for pattern in STRINGS_CONSIDERED_FALSE.iter() {
if &lower == pattern {
result = false
}
}
result
}
fn from_bool(val: bool) -> &'static str {
if val {
TRUE_STR
} else {
FALSE_STR
}
}
fn query_worker(args: &aufindlib::SearchArgs) {
let mut rl = Editor::<()>::new();
let history_file = Path::new(&dirs::home_dir()
.expect("Cannot get location of home dir")).join(HISTORY_FILE);
if rl.load_history(&history_file).is_err() {
println!("Note: no previous history found");
}
let read_line = rl.readline("?> ");
match read_line {
Ok(line) => {
aufindlib::search(&args.with_pattern(&line), &mut |x| println!("{}", x));
rl.add_history_entry(line.as_ref());
rl.save_history(&history_file).expect("Failed to store history");
},
Err(_) => {
println!("Cancelled, exiting");
}
}
}
fn args_from_matches<'a>(matches: &clap::ArgMatches) -> aufindlib::SearchArgs<'a> {
let mut args = aufindlib::SearchArgs::default();
args.case_sensitive = to_bool(matches.value_of(ARG_CASE_SENSITIVE).expect("Defaulted option should always present"));
args.include_dirs = to_bool(matches.value_of(ARG_INCLUDE_DIRS).expect("Defaulted option should always present"));
args.include_files = to_bool(matches.value_of(ARG_INCLUDE_FILES).expect("Defaulted option should always present"));
args.highlight = to_bool(matches.value_of(ARG_HIGHLIGHT_OUTPUT).expect("Defaulted option should always present"));
args
}
fn main() {
let default_args = aufindlib::SearchArgs::default();
let arg_case_sensitive = Arg::with_name(ARG_CASE_SENSITIVE)
.help("Toggle case sensitivity")
.required(false)
.takes_value(true)
.default_value(from_bool(default_args.case_sensitive))
.short("c")
.long("case-sensitive");
let arg_include_dirs = Arg::with_name(ARG_INCLUDE_DIRS)
.help("Include directories in search results")
.required(false)
.takes_value(true)
.default_value(from_bool(default_args.include_dirs))
.short("d")
.long("include-dirs");
let arg_include_files = Arg::with_name(ARG_INCLUDE_FILES)
.help("Include files in search results")
.required(false)
.takes_value(true)
.default_value(from_bool(default_args.include_files))
.short("f")
.long("include-files");
let arg_highlight_output = Arg::with_name(ARG_HIGHLIGHT_OUTPUT)
.help("Highlight matches in output")
.required(false)
.takes_value(true)
.default_value(from_bool(default_args.highlight))
.short("h")
.long("highlight-output");
let matches = App::new("aufind")
.version(VERSION)
.author("Alexander Prokopchuk <ya@tomatl.org>")
.about("Simple file search utility")
.subcommand(SubCommand::with_name("find")
.about("parse from CLI")
.arg(arg_case_sensitive.clone())
.arg(arg_include_dirs.clone())
.arg(arg_include_files.clone())
.arg(arg_highlight_output.clone())
.arg(Arg::with_name(ARG_PATTERN)
.help("Pattern to match")
.required(false)
.takes_value(true)
.index(1)))
.subcommand(SubCommand::with_name("query")
.about("read from stdout")
.arg(arg_case_sensitive.clone())
.arg(arg_include_dirs.clone())
.arg(arg_include_files.clone())
.arg(arg_highlight_output.clone()))
.get_matches();
if let Some(matches) = matches.subcommand_matches("find") {
let default_pattern = default_args.construct_pattern();
let args = args_from_matches(&matches)
.with_pattern(matches.value_of(ARG_PATTERN).unwrap_or(&default_pattern));
aufindlib::search(&args, &mut |x| println!("{}", x));
} else if let Some(matches) = matches.subcommand_matches("query") {
let args = args_from_matches(&matches);
query_worker(&args);
}
}
|
use serde::ser::Serialize;
use serde::de::DeserializeOwned;
use serde_json::value::Value;
use serde_json;
use super::types::{PunterId, SiteId};
use super::map::{River, Map};
use std::collections::BTreeMap;
#[derive(PartialEq, Debug)]
pub enum Req {
Handshake { name: String, },
Ready { punter: PunterId, futures: Option<Vec<Future>>, },
Move(Move),
}
#[derive(PartialEq, Debug)]
pub enum Rep {
Handshake { name: String, },
Timeout(f64),
Setup(Setup),
Move { moves: Vec<Move>, },
Stop {
moves: Vec<Move>,
scores: Vec<Score>,
},
}
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct Future {
pub source: SiteId,
pub target: SiteId,
}
#[derive(PartialEq, Debug, Deserialize)]
pub struct Setup {
pub punter: PunterId,
pub punters: usize,
pub map: Map,
pub settings: Settings,
}
#[derive(PartialEq, Default, Debug, Deserialize)]
pub struct Settings {
pub futures: bool,
pub splurges: bool,
pub options: bool,
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum Move {
Claim { punter: PunterId, source: SiteId, target: SiteId, },
Pass { punter: PunterId, },
Splurge { punter: PunterId, route: Vec<SiteId>, },
Option { punter: PunterId, source: SiteId, target: SiteId, },
}
#[derive(Debug, PartialEq, Deserialize)]
pub struct Score {
pub punter: PunterId,
pub score: isize,
}
#[derive(Debug)]
pub enum Error {
Json(serde_json::Error),
UnexpectedJson,
}
#[derive(Debug, Deserialize)]
#[allow(non_camel_case_types)]
enum ServerMove {
claim { punter: PunterId, source: SiteId, target: SiteId, },
pass { punter: PunterId, },
splurge { punter: PunterId, route: Vec<SiteId>, },
option { punter: PunterId, source: SiteId, target: SiteId, },
}
#[derive(Debug, Deserialize)]
struct ServerMoves {
moves: Vec<ServerMove>,
}
#[derive(Debug, Deserialize)]
struct ServerStop {
moves: Vec<ServerMove>,
scores: Vec<Score>,
}
#[derive(Debug, Deserialize)]
struct ServerSite {
id: SiteId,
}
#[derive(Debug, Deserialize)]
struct ServerMap {
sites: Vec<ServerSite>,
rivers: Vec<River>,
mines: Vec<SiteId>,
}
impl Rep {
pub fn from_json<S>(s: &str) -> Result<(Rep, Option<S>), Error> where S: DeserializeOwned {
match serde_json::from_str::<Value>(s).map_err(Error::Json)? {
Value::Object(mut map) => {
let maybe_state = if let Some(value) = map.remove("state") {
if map.contains_key("move") || map.contains_key("stop") {
Some(serde_json::from_value::<S>(value).map_err(Error::Json)?)
} else {
None
}
} else {
None
};
if map.contains_key("move") {
let move_node = map.remove("move").unwrap();
let smove = serde_json::from_value::<ServerMoves>(move_node).map_err(Error::Json)?;
Ok((Rep::Move {
moves: smove.moves.into_iter().map(|m| {
match m {
ServerMove::claim { punter, source, target, } =>
Move::Claim { punter: punter, source: source, target: target, },
ServerMove::pass { punter, } =>
Move::Pass { punter: punter, },
ServerMove::splurge { punter, route, } =>
Move::Splurge { punter: punter, route: route, },
ServerMove::option { punter, source, target, } =>
Move::Option { punter: punter, source: source, target: target, },
}
}).collect(),
}, maybe_state))
} else if map.contains_key("stop") {
let stop_node = map.remove("stop").unwrap();
let stop = serde_json::from_value::<ServerStop>(stop_node).map_err(Error::Json)?;
Ok((Rep::Stop {
moves: stop.moves.into_iter().map(|m| {
match m {
ServerMove::claim { punter, source, target, } =>
Move::Claim { punter: punter, source: source, target: target, },
ServerMove::pass { punter, } =>
Move::Pass { punter: punter },
ServerMove::splurge { punter, route, } =>
Move::Splurge { punter: punter, route: route, },
ServerMove::option { punter, source, target, } =>
Move::Option { punter: punter, source: source, target: target, },
}
}).collect(),
scores: stop.scores,
}, maybe_state))
} else if map.contains_key("punter") && map.contains_key("punters") && map.contains_key("map") {
let smap = serde_json::from_value::<ServerMap>(map.remove("map").unwrap()).map_err(Error::Json)?;
Ok((Rep::Setup(Setup {
punter: serde_json::from_value::<PunterId>(map.remove("punter").unwrap()).map_err(Error::Json)?,
punters: serde_json::from_value::<usize>(map.remove("punters").unwrap()).map_err(Error::Json)?,
map: Map {
sites: smap.sites.into_iter().map(|s| s.id).collect(),
rivers: smap.rivers,
mines: smap.mines,
},
settings: if let Some(Value::Object(mut settings_obj)) = map.remove("settings") {
Settings {
futures: match settings_obj.remove("futures") {
Some(Value::Bool(true)) => true,
_ => false,
},
splurges: match settings_obj.remove("splurges") {
Some(Value::Bool(true)) => true,
_ => false,
},
options: match settings_obj.remove("options") {
Some(Value::Bool(true)) => true,
_ => false,
},
}
} else {
Default::default()
},
}), None))
} else if map.contains_key("timeout") {
Ok((Rep::Timeout(serde_json::from_value::<f64>(map.remove("timeout").unwrap()).map_err(Error::Json)?), None))
} else if map.contains_key("you") {
Ok((Rep::Handshake {
name: serde_json::from_value::<String>(map.remove("you").unwrap()).map_err(Error::Json)?,
}, None))
} else {
Err(Error::UnexpectedJson)
}
},
_ => {
Err(Error::UnexpectedJson)
}
}
}
}
impl Req {
pub fn to_json<S>(self, maybe_state: Option<S>) -> Result<String, Error> where S: Serialize {
let mut res = BTreeMap::new();
match self {
Req::Handshake { name } => {
res.insert("me".to_string(), serde_json::to_value(name).map_err(Error::Json)?);
},
Req::Ready { punter, futures, } => {
res.insert("ready".to_string(), serde_json::to_value(punter).map_err(Error::Json)?);
if let Some(futs) = futures {
let fut_values = futs.into_iter()
.map(|fut| {
serde_json::to_value(
vec![("source".to_string(), serde_json::to_value(fut.source).map_err(Error::Json)?),
("target".to_string(), serde_json::to_value(fut.target).map_err(Error::Json)?)]
.into_iter()
.collect::<BTreeMap<String, Value>>()).map_err(Error::Json)
})
.collect::<Result<Vec<_>, _>>()?;
res.insert("futures".to_string(), Value::Array(fut_values));
}
if let Some(state) = maybe_state {
res.insert("state".to_string(), serde_json::to_value(state).map_err(Error::Json)?);
}
},
Req::Move(mv) => {
match mv {
Move::Claim { punter, source, target, } => {
let m = vec![
("punter".to_string(), serde_json::to_value(punter).map_err(Error::Json)?),
("source".to_string(), serde_json::to_value(source).map_err(Error::Json)?),
("target".to_string(), serde_json::to_value(target).map_err(Error::Json)?),
].into_iter().collect::<BTreeMap<String, Value>>();
res.insert("claim".to_string(), serde_json::to_value(m).map_err(Error::Json)?);
},
Move::Pass { punter } => {
let m = vec![
("punter".to_string(), serde_json::to_value(punter).map_err(Error::Json)?),
].into_iter().collect::<BTreeMap<String,Value>>();
res.insert("pass".to_string(), serde_json::to_value(m).map_err(Error::Json)?);
},
Move::Splurge { punter, route, } => {
let m = vec![
("punter".to_string(), serde_json::to_value(punter).map_err(Error::Json)?),
("route".to_string(), serde_json::to_value(route).map_err(Error::Json)?),
].into_iter().collect::<BTreeMap<String, Value>>();
res.insert("splurge".to_string(), serde_json::to_value(m).map_err(Error::Json)?);
},
Move::Option { punter, source, target, } => {
let m = vec![
("punter".to_string(), serde_json::to_value(punter).map_err(Error::Json)?),
("source".to_string(), serde_json::to_value(source).map_err(Error::Json)?),
("target".to_string(), serde_json::to_value(target).map_err(Error::Json)?),
].into_iter().collect::<BTreeMap<String, Value>>();
res.insert("option".to_string(), serde_json::to_value(m).map_err(Error::Json)?);
},
}
if let Some(state) = maybe_state {
res.insert("state".to_string(), serde_json::to_value(state).map_err(Error::Json)?);
}
}
}
Ok(serde_json::to_string(&res).map_err(Error::Json)?)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn proto_handshake() {
let object = Rep::from_json::<()>("{\"you\": \"test_name\"}").unwrap().0;
let result = Rep::Handshake { name: "test_name".to_string() };
assert_eq!(object,result);
}
#[test]
fn proto_move_1() {
let object = Rep::from_json::<()>("{\"move\":{\"moves\":[{\"claim\":{\"punter\":0,\"source\":0,\"target\":1}},{\"claim\":{\"punter\":1,\"source\":1,\"target\":2}}]}}").unwrap().0;
let result = Rep::Move {
moves: vec![
Move::Claim { punter: 0, source: 0, target: 1, },
Move::Claim { punter: 1, source: 1, target: 2, },
]
};
assert_eq!(object,result);
}
#[test]
fn proto_move_2() {
let object = Rep::from_json::<()>("{\"move\":{\"moves\":[{\"pass\":{\"punter\":0}},{\"pass\":{\"punter\":1}}]}}").unwrap().0;
let result = Rep::Move {
moves: vec![
Move::Pass { punter: 0 },
Move::Pass { punter: 1 },
]
};
assert_eq!(object,result);
}
#[test]
fn proto_move_3() {
let object = Rep::from_json::<()>("{\"move\":{\"moves\":[{\"splurge\":{\"punter\":0,\"route\":[0,1]}},{\"claim\":{\"punter\":1,\"source\":1,\"target\":2}}]}}").unwrap().0;
let result = Rep::Move {
moves: vec![
Move::Splurge { punter: 0, route: vec![0, 1], },
Move::Claim { punter: 1, source: 1, target: 2, },
]
};
assert_eq!(object,result);
}
#[test]
fn proto_move_4() {
let object = Rep::from_json::<()>("{\"move\":{\"moves\":[{\"option\":{\"punter\":0,\"source\":0,\"target\":1}},{\"option\":{\"punter\":1,\"source\":1,\"target\":2}}]}}").unwrap().0;
let result = Rep::Move {
moves: vec![
Move::Option { punter: 0, source: 0, target: 1, },
Move::Option { punter: 1, source: 1, target: 2, },
]
};
assert_eq!(object,result);
}
#[test]
fn proto_stop() {
let object = Rep::from_json::<()>("{\"stop\":{\"moves\":[{\"option\":{\"punter\":0,\"source\":5,\"target\":7}},{\"claim\":{\"punter\":1,\"source\":7,\"target\":1}}], \"scores\":[{\"punter\":0,\"score\":-6},{\"punter\":1,\"score\":6}]}}").unwrap().0;
let result = Rep::Stop {
moves: vec![
Move::Option { punter: 0, source: 5, target: 7, },
Move::Claim { punter: 1, source: 7, target: 1, },
],
scores: vec![
Score { punter: 0, score: -6 },
Score { punter: 1, score: 6 },
],
};
assert_eq!(object,result);
}
#[test]
fn proto_setup() {
let object = Rep::from_json::<()>("{\"punter\":0, \"punters\":2,
\"map\":{\"sites\":[{\"id\":4},{\"id\":1},{\"id\":3},{\"id\":6},{\"id\":5},{\"id\":0},{\"id\":7},{\"id\":2}], \"rivers\":[{\"source\":3,\"target\":4},{\"source\":0,\"target\":1},{\"source\":2,\"target\":3}, {\"source\":1,\"target\":3},{\"source\":5,\"target\":6},{\"source\":4,\"target\":5}, {\"source\":3,\"target\":5},{\"source\":6,\"target\":7},{\"source\":5,\"target\":7},{\"source\":1,\"target\":7},{\"source\":0,\"target\":7},{\"source\":1,\"target\":2}], \"mines\":[1,5]}}").unwrap().0;
let result = Rep::Setup(Setup {
punter: 0,
punters: 2,
map: Map {
sites: vec![4, 1, 3, 6, 5, 0, 7, 2],
rivers: vec![
River::new(3, 4),
River::new(0, 1),
River::new(2, 3),
River::new(1, 3),
River::new(5, 6),
River::new(4, 5),
River::new(3, 5),
River::new(6, 7),
River::new(5, 7),
River::new(1, 7),
River::new(0, 7),
River::new(1, 2),
].into_iter().collect(),
mines: vec![1,5].into_iter().collect(),
},
settings: Default::default(),
});
assert_eq!(object,result);
}
#[test]
fn proto_setup_settings() {
let object = Rep::from_json::<()>("{\"punter\":0, \"punters\":2,
\"map\":{\"sites\":[{\"id\":4},{\"id\":1},{\"id\":3},{\"id\":6},{\"id\":5},{\"id\":0},{\"id\":7},{\"id\":2}], \"rivers\":[{\"source\":3,\"target\":4},{\"source\":0,\"target\":1},{\"source\":2,\"target\":3}, {\"source\":1,\"target\":3},{\"source\":5,\"target\":6},{\"source\":4,\"target\":5}, {\"source\":3,\"target\":5},{\"source\":6,\"target\":7},{\"source\":5,\"target\":7},{\"source\":1,\"target\":7},{\"source\":0,\"target\":7},{\"source\":1,\"target\":2}], \"mines\":[1,5]},\"settings\":{\"futures\":true,\"splurges\":true,\"options\":true}}").unwrap().0;
let result = Rep::Setup(Setup {
punter: 0,
punters: 2,
map: Map {
sites: vec![4, 1, 3, 6, 5, 0, 7, 2],
rivers: vec![
River::new(3, 4),
River::new(0, 1),
River::new(2, 3),
River::new(1, 3),
River::new(5, 6),
River::new(4, 5),
River::new(3, 5),
River::new(6, 7),
River::new(5, 7),
River::new(1, 7),
River::new(0, 7),
River::new(1, 2),
].into_iter().collect(),
mines: vec![1,5].into_iter().collect(),
},
settings: Settings {
futures: true,
splurges: true,
options: true,
},
});
assert_eq!(object,result);
}
#[test]
fn proto_timeout() {
let object = Rep::from_json::<()>("{\"timeout\": 10.0}").unwrap().0;
let result = Rep::Timeout(10.0);
assert_eq!(object,result);
}
#[test]
fn proto_out_handshake() {
let object = Req::Handshake { name: "test_name".to_string() };
let result = "{\"me\":\"test_name\"}";
assert_eq!(object.to_json::<()>(None).unwrap(),result.to_string());
}
#[test]
fn proto_out_ready() {
let object = Req::Ready { punter: 1, futures: None, };
let result = "{\"ready\":1}";
assert_eq!(object.to_json::<()>(None).unwrap(),result.to_string());
}
#[test]
fn proto_out_ready_futs() {
let object = Req::Ready { punter: 1, futures: Some(vec![Future { source: 0, target: 1, }]), };
let result = "{\"futures\":[{\"source\":0,\"target\":1}],\"ready\":1}";
assert_eq!(object.to_json::<()>(None).unwrap(),result.to_string());
}
#[test]
fn proto_out_move_1() {
let object = Req::Move(Move::Claim { punter: 2, source: 8, target: 1 });
let result = "{\"claim\":{\"punter\":2,\"source\":8,\"target\":1}}";
assert_eq!(object.to_json::<()>(None).unwrap(),result.to_string());
}
#[test]
fn proto_out_move_2() {
let object = Req::Move(Move::Pass { punter: 0 });
let result = "{\"pass\":{\"punter\":0}}";
assert_eq!(object.to_json::<()>(None).unwrap(),result.to_string());
}
#[test]
fn proto_out_move_3() {
let object = Req::Move(Move::Option { punter: 2, source: 8, target: 1 });
let result = "{\"option\":{\"punter\":2,\"source\":8,\"target\":1}}";
assert_eq!(object.to_json::<()>(None).unwrap(),result.to_string());
}
}
|
//! This example demonstrates how to roll your own event loop,
//! if for some reason you want to do that instead of using the `EventHandler`
//! trait to do that for you.
//!
//! This is exactly how `ggez::event::run()` works, it really is not
//! doing anything magical. But, if you want a bit more power over
//! the control flow of your game, this is how you get it.
//!
//! It is functionally identical to the `super_simple.rs` example apart from that.
use ggez::event;
use ggez::event::winit_event::{Event, KeyboardInput, WindowEvent};
use ggez::graphics::{self, Color, DrawMode};
use ggez::GameResult;
use winit::event_loop::ControlFlow;
pub fn main() -> GameResult {
let cb = ggez::ContextBuilder::new("eventloop", "ggez");
let (mut ctx, events_loop) = cb.build()?;
let mut position: f32 = 1.0;
// Handle events. Refer to `winit` docs for more information.
events_loop.run(move |mut event, _window_target, control_flow| {
if !ctx.continuing {
*control_flow = ControlFlow::Exit;
return;
}
*control_flow = ControlFlow::Poll;
let ctx = &mut ctx;
// This tells `ggez` to update it's internal states, should the event require that.
// These include cursor position, view updating on resize, etc.
event::process_event(ctx, &mut event);
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => event::quit(ctx),
WindowEvent::KeyboardInput {
input:
KeyboardInput {
virtual_keycode: Some(keycode),
..
},
..
} => {
if let event::KeyCode::Escape = keycode {
*control_flow = winit::event_loop::ControlFlow::Exit
}
}
// `CloseRequested` and `KeyboardInput` events won't appear here.
x => println!("Other window event fired: {:?}", x),
},
Event::MainEventsCleared => {
// Tell the timer stuff a frame has happened.
// Without this the FPS timer functions and such won't work.
ctx.timer_context.tick();
// Update
position += 1.0;
// Draw
graphics::clear(ctx, [0.1, 0.2, 0.3, 1.0].into());
let circle = graphics::Mesh::new_circle(
ctx,
DrawMode::fill(),
glam::Vec2::new(0.0, 0.0),
100.0,
2.0,
Color::WHITE,
)
.unwrap();
graphics::draw(ctx, &circle, (glam::Vec2::new(position, 380.0),)).unwrap();
graphics::present(ctx).unwrap();
// reset the mouse delta for the next frame
// necessary because it's calculated cumulatively each cycle
ctx.mouse_context.reset_delta();
ggez::timer::yield_now();
}
x => println!("Device event fired: {:?}", x),
}
});
}
|
/// Tarit for converting generated i32 to target test type.
pub trait FromI32
{
fn from_i32( value: &i32 ) -> Self;
}
/// We use floats
impl FromI32 for f32
{
fn from_i32( value: &i32 ) -> f32
{
return value.clone() as f32;
}
}
/// We use floats
impl FromI32 for i32
{
fn from_i32( value: &i32 ) -> i32
{
return value.clone();
}
}
|
use std::env;
use std::collections::HashMap;
fn fibm(mem: &mut HashMap<i32, i32>, n: i32) -> i32 {
if n < 2 {
n
} else {
{
let opt = mem.get(&n);
if opt.is_some() {
return *opt.unwrap()
}
}
let res: i32 = (fibm(mem, n - 1) + fibm(mem, n - 2)) % 100000007;
mem.insert(n, res);
res
}
}
fn main() {
let mut mem = HashMap::<i32, i32>::new();
let args: Vec<_> = env::args().collect();
for arg in &args[1..] {
let n: i32 = arg.parse::<i32>().unwrap();
println!("fib({}) = {}", n, fibm(&mut mem, n));
}
} |
use std::collections::HashMap;
use std::collections::HashSet;
fn recover_secret(triplets: Vec<[char; 3]>) -> String {
type Graph = HashMap<char, HashSet<char>>;
let mut graph = triplets
.iter()
.fold(HashMap::new(), |mut acc: Graph, trip| {
trip.iter().fold(None, |prev, &x| {
let cur = acc.entry(x).or_insert(HashSet::new());
match prev {
Some(val) => cur.insert(val),
None => false
};
Some(x)
});
acc
});
println!("{:#?}", graph);
let mut secret = String::new();
while graph.len() != 0 {
let (&head, _) = graph.iter().find(|&(_, s)| s.len() == 0).unwrap();
secret.push(head);
graph.remove(&head);
for (_, s) in graph.iter_mut() { s.remove(&head); }
}
secret
}
#[test]
fn test_recover_secret() {
assert_eq!(
recover_secret(vec![['a', 'b', 'c'], ['b', 'c', 'd']]),
"abcd"
);
assert_eq!(
recover_secret(vec![['b', 'c', 'd'], ['c', 'd', 'e']]),
"bcde"
);
}
#[test]
fn example_test() {
assert_eq!(
recover_secret(vec![
['t', 'u', 'p'],
['w', 'h', 'i'],
['t', 's', 'u'],
['a', 't', 's'],
['h', 'a', 'p'],
['t', 'i', 's'],
['w', 'h', 's'],
]),
"whatisup"
);
}
|
use std::sync::atomic::{AtomicUsize, Ordering};
use std::mem::size_of;
use std::fmt;
use super::Counter;
const PADDING_LEN: usize = 64 - 2 * size_of::<AtomicUsize>();
pub struct AtomicCounter {
counter: AtomicUsize,
last: AtomicUsize,
/// To prevent false sharing
_padding: [u8; PADDING_LEN],
}
const LSB: usize = 1;
fn make(value: usize) -> Option<Counter> {
if value & LSB == 0 {
Some(Counter(value))
} else {
None
}
}
impl AtomicCounter {
/// Create new `AtomicCounter` from given counter.
pub fn new(value: Counter) -> Self {
AtomicCounter {
counter: value.0.into(),
// Initially invalid counter
last: 1.into(),
_padding: [0; PADDING_LEN],
}
}
/// Fetch internal counter. If closed, returns `Err(Counter)` with last counter observed.
pub fn fetch(&self) -> Result<Counter, Counter> {
make(self.counter.load(Ordering::Acquire)).ok_or_else(|| loop {
if let Some(last) = make(self.last.load(Ordering::Acquire)) {
break last;
}
})
}
/// Increase internal counter by 1. Returns previous counter or `None` if closed.
pub fn incr(&self) -> Option<Counter> {
// It actually increase `0b10` as its LSB is reserved for close detection.
make(self.counter.fetch_add(0b10, Ordering::Release))
}
/// Conditionally change internal counter with given ordering.
///
/// If internal counter is equal to `cond`, change it to `value` and returns `Ok(())`.
/// If not, doesn't touch it and returns previous counter or `None` if closed.
pub fn comp_swap(
&self, cond: Counter, value: Counter, ord: Ordering
) -> Result<(), Option<Counter>> {
let res = self.counter.compare_and_swap(cond.0, value.0, ord);
if res == cond.0 {
Ok(())
} else {
Err(make(res))
}
}
/// Close internal counter.
///
/// Once closed, every operations of this `AtomicCounter` should fail.
pub fn close(&self) {
let mut value = self.counter.load(Ordering::Acquire);
loop {
// already closed
if value & LSB != 0 {
return;
}
let prev = self.counter.compare_and_swap(value, LSB, Ordering::Release);
if prev == value {
break;
} else {
value = prev;
}
}
// store last observed value
self.last.store(value, Ordering::Release);
}
}
impl From<Counter> for AtomicCounter {
fn from(v: Counter) -> Self {
AtomicCounter::new(v)
}
}
impl From<usize> for AtomicCounter {
fn from(v: usize) -> Self {
AtomicCounter::new(v.into())
}
}
impl Default for AtomicCounter {
fn default() -> Self {
AtomicCounter::new(Counter::default())
}
}
impl fmt::Debug for AtomicCounter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.fetch() {
Ok(count) => write!(f, "AtomicCounter({})", count.0 >> 1),
Err(last) => write!(f, "AtomicCounter(Closed, {})", last.0 >> 1),
}
}
}
|
use std;
use std::fmt;
use std::cell::RefCell;
use std::rc::Rc;
use hashbrown::HashMap;
use crate::ast::*;
use crate::object;
use crate::object::{Object, Environment, Function, Builtin, Array, MonkeyHash};
use crate::token::Token;
use crate::parser;
pub type EvalResult = Result<Rc<Object>, EvalError>;
#[derive(Debug)]
pub struct EvalError {
pub message: String,
}
impl fmt::Display for EvalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}", self.message)
}
}
impl std::error::Error for EvalError {
fn description(&self) -> &str {
&self.message
}
}
pub fn eval(node: &Node, env: Rc<RefCell<Environment>>) -> EvalResult {
match node {
Node::Program(prog) => eval_program(&prog, env),
Node::Statement(stmt) => eval_statement(&stmt, env),
Node::Expression(exp) => eval_expression(&exp, env),
}
}
fn eval_expression(exp: &Expression, env: Rc<RefCell<Environment>>) -> EvalResult {
match exp {
Expression::Integer(int) => Ok(Rc::new(Object::Int(*int))),
Expression::Boolean(b) => Ok(Rc::new(Object::Bool(*b))),
Expression::String(s) => Ok(Rc::new(Object::String(s.clone()))),
Expression::Prefix(pre) => {
let right = eval_expression(&pre.right, env)?;
eval_prefix_expression(&pre.operator, right)
},
Expression::Infix(infix) => {
let left = eval_expression(&infix.left, Rc::clone(&env))?;
let right = eval_expression(&infix.right, env)?;
eval_infix_expression(&infix.operator, left, right)
},
Expression::If(ifexp) => {
let evaluated = eval_expression(&ifexp.condition, Rc::clone(&env))?;
match is_truthy(&evaluated) {
true => eval_block(&ifexp.consequence, env),
false => {
match &ifexp.alternative {
Some(alt) => eval_block(&alt, env),
None => Ok(Rc::new(Object::Null)),
}
}
}
},
Expression::Identifier(ident) => {
eval_identifier(ident, env)
},
Expression::Function(f) => {
let func = Function{parameters: f.parameters.clone(), body: f.body.clone(), env: Rc::clone(&env)};
Ok(Rc::new(Object::Function(Rc::new(func))))
},
Expression::Call(exp) => {
let function = eval_expression(&exp.function, Rc::clone(&env))?;
let args = eval_expressions(&exp.arguments, env)?;
apply_function(&function, &args)
},
Expression::Array(a) => {
let elements = eval_expressions(&a.elements, Rc::clone(&env))?;
Ok(Rc::new(Object::Array(Rc::new(Array{elements}))))
},
Expression::Index(i) => {
let left = eval_expression(&i.left, Rc::clone(&env))?;
let index = eval_expression(&i.index, env)?;
eval_index_expression(left, index)
},
Expression::Hash(h) => {
eval_hash_literal(&h, Rc::clone(&env))
},
}
}
fn eval_hash_literal(h: &HashLiteral, env: Rc<RefCell<Environment>>) -> EvalResult {
let mut pairs = HashMap::new();
for (key_exp, val_exp) in &h.pairs {
let key = eval_expression(key_exp, Rc::clone(&env))?;
let value = eval_expression(val_exp, Rc::clone(&env))?;
pairs.insert(key, value);
}
Ok(Rc::new(Object::Hash(Rc::new(MonkeyHash{pairs}))))
}
fn eval_index_expression(left: Rc<Object>, index: Rc<Object>) -> EvalResult {
match (&*left, &*index) {
(Object::Array(a), Object::Int(i)) => {
match a.elements.get(*i as usize) {
Some(el) => Ok(Rc::clone(el)),
None => Ok(Rc::new(Object::Null))
}
},
(Object::Hash(h), _object) => {
match &*index {
Object::String(_) | Object::Int(_) | Object::Bool(_) => {
match h.pairs.get(&*index) {
Some(obj) => Ok(Rc::clone(obj)),
None => Ok(Rc::new(Object::Null))
}
},
_ => Err(EvalError{message: format!("unusable as hash key: {}", index)})
}
}
_ => Err(EvalError{message: format!("index operator not supported {}", index)})
}
}
fn eval_identifier(ident: &str, env: Rc<RefCell<Environment>>) -> EvalResult {
match env.borrow().get(ident) {
Some(obj) => {
Ok(obj.clone())
},
None => {
match Builtin::lookup(ident) {
Some(obj) => Ok(Rc::new(obj)),
None => Err(EvalError{message: format!("identifier not found: {}", ident)}),
}
}
}
}
fn apply_function(func: &Object, args: &Vec<Rc<Object>>) -> EvalResult {
match func {
Object::Function(f) => {
let extended_env = extend_function_env(f, args);
let evaluated = eval_block(&f.body, extended_env)?;
Ok(unwrap_return_value(evaluated))
},
Object::Builtin(b) => {
match b.apply(args) {
Ok(obj) => Ok(obj),
Err(err) => Err(EvalError{message: err}),
}
},
f => Err(EvalError{message: format!("{:?} is not a function", f)})
}
}
fn extend_function_env(func: &Function, args: &Vec<Rc<Object>>) -> Rc<RefCell<Environment>> {
let env = Rc::new(RefCell::new(Environment::new_enclosed(Rc::clone(&func.env))));
let mut args_iter = args.into_iter();
for param in &func.parameters {
let arg = args_iter.next().unwrap();
env.borrow_mut().set(param.name.clone(), Rc::clone(arg))
}
env
}
fn unwrap_return_value(obj: Rc<Object>) -> Rc<Object> {
if let Object::Return(ret) = &*obj {
return Rc::clone(&ret.value)
}
obj
}
fn eval_expressions(exps: &Vec<Expression>, env: Rc<RefCell<Environment>>) -> Result<Vec<Rc<Object>>, EvalError> {
let mut objs = Vec::with_capacity(exps.len());
for e in exps {
let res = eval_expression(&e, Rc::clone(&env))?;
objs.push(res);
}
Ok(objs)
}
fn is_truthy(obj: &Object) -> bool {
match obj {
Object::Null => false,
Object::Bool(false) => false,
_ => true,
}
}
fn eval_infix_expression(operator: &Token, left: Rc<Object>, right: Rc<Object>) -> EvalResult {
match (&*left, &*right) {
(Object::Int(l), Object::Int(r)) => eval_integer_infix_expression(operator, *l, *r),
(Object::Bool(l), Object::Bool(r)) => eval_bool_infix_expression(operator, *l, *r),
(Object::String(l), Object::String(r)) => eval_string_infix_expression(operator, l.clone(), &*r),
_ => Err(EvalError{message: format!("type mismatch: {:?} {} {:?}", left, operator, right)}),
}
}
fn eval_string_infix_expression(operator: &Token, left: String, right: &str) -> EvalResult {
match operator {
Token::Plus => Ok(Rc::new(Object::String(left + right))),
_ => Err(EvalError{message: format!("unknown operator {} {} {}", left, operator, right)}),
}
}
fn eval_bool_infix_expression(operator: &Token, left: bool, right: bool) -> EvalResult {
match operator {
Token::Eq => Ok(Rc::new(Object::Bool(left == right))),
Token::Neq => Ok(Rc::new(Object::Bool(left != right))),
_ => Err(EvalError{message: format!("unknown operator: {} {} {}", left, operator, right)})
}
}
fn eval_integer_infix_expression(operator: &Token, left: i64, right: i64) -> EvalResult {
match operator {
Token::Plus => Ok(Rc::new(Object::Int(left + right))),
Token::Minus => Ok(Rc::new(Object::Int(left - right))),
Token::Asterisk => Ok(Rc::new(Object::Int(left * right))),
Token::Slash => Ok(Rc::new(Object::Int(left / right))),
Token::Lt => Ok(Rc::new(Object::Bool(left < right))),
Token::Gt => Ok(Rc::new(Object::Bool(left > right))),
Token::Eq => Ok(Rc::new(Object::Bool(left == right))),
Token::Neq => Ok(Rc::new(Object::Bool(left != right))),
_ => Err(EvalError{message: format!("unknown operator {}", operator)}),
}
}
fn eval_block(block: &BlockStatement, env: Rc<RefCell<Environment>>) -> EvalResult {
let mut result = Rc::new(Object::Null);
for stmt in &block.statements {
let res = eval_statement(stmt, Rc::clone(&env))?;
match *res {
Object::Return(_) => return Ok(res),
_ => result = res,
}
}
Ok(result)
}
fn eval_statement(stmt: &Statement, env: Rc<RefCell<Environment>>) -> EvalResult {
match stmt {
Statement::Expression(exp) => eval_expression(&exp.expression, env),
Statement::Return(ret) => {
let value = eval_expression(&ret.value, env)?;
Ok(Rc::new(Object::Return(Rc::new(object::Return{value}))))
},
Statement::Let(stmt) => {
let exp = eval_expression(&stmt.value, Rc::clone(&env))?;
let obj = Rc::clone(&exp);
env.borrow_mut().set(stmt.name.clone(), obj);
Ok(exp)
}
}
}
fn eval_program(prog: &Program, env: Rc<RefCell<Environment>>) -> EvalResult {
let mut result = Rc::new(Object::Null);
for stmt in &prog.statements {
let res = eval_statement(stmt, Rc::clone(&env))?;
let v = Rc::clone(&res);
match &*v {
Object::Return(r) => return Ok(Rc::clone(&r.value)),
_ => result = res,
}
}
Ok(result)
}
fn eval_prefix_expression(operator: &Token, right: Rc<Object>) -> EvalResult {
match *operator {
Token::Bang => eval_bang_operator_expression(right),
Token::Minus => eval_minus_prefix_operator_expression(right),
_ => Err(EvalError{message:format!("unknown prefix operator {}", operator)}),
}
}
fn eval_bang_operator_expression(right: Rc<Object>) -> EvalResult {
Ok(Rc::new(match *right {
Object::Bool(true) => Object::Bool(false),
Object::Bool(false) => Object::Bool(true),
Object::Null => Object::Bool(true),
_ => Object::Bool(false),
}))
}
fn eval_minus_prefix_operator_expression(right: Rc<Object>) -> EvalResult {
match *right {
Object::Int(val) => {
Ok(Rc::new(Object::Int(-val)))
},
_ => Err(EvalError{message: format!("unknown operator: -{:?}", right)}),
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::object::Object;
#[test]
fn eval_integer_expression() {
struct Test<'a> {
input: &'a str,
expected: i64,
}
let tests = vec![
Test{input: "5", expected: 5},
Test{input: "10", expected: 10},
Test{input: "-5", expected: -5},
Test{input: "-10", expected: -10},
Test{input: "5 + 5 + 5 + 5 - 10", expected: 10},
Test{input: "2 * 2 * 2 * 2 * 2", expected: 32},
Test{input: "-50 + 100 + -50", expected: 0},
Test{input: "5 * 2 + 10", expected: 20},
Test{input: "5 + 2 * 10", expected: 25},
Test{input: "20 + 2 * -10", expected: 0},
Test{input: "50 / 2 * 2 + 10", expected: 60},
Test{input: "2 * (5 + 10)", expected: 30},
Test{input: "3 * 3 * 3 + 10", expected: 37},
Test{input: "3 * (3 * 3) + 10", expected: 37},
Test{input: "(5 + 10 * 2 + 15 / 3) * 2 + -10", expected: 50},
];
for t in tests {
let evaluated = test_eval(t.input);
test_integer_object(&evaluated, t.expected);
}
}
#[test]
fn eval_boolean_expression() {
struct Test<'a> {
input: &'a str,
expected: bool,
}
let tests = vec![
Test{input: "true", expected: true},
Test{input: "false", expected: false},
Test{input: "1 < 2", expected: true},
Test{input: "1 > 2", expected: false},
Test{input: "1 < 1", expected: false},
Test{input: "1 > 1", expected: false},
Test{input: "1 == 1", expected: true},
Test{input: "1 != 1", expected: false},
Test{input: "1 == 2", expected: false},
Test{input: "1 != 2", expected: true},
Test{input: "true == true", expected: true},
Test{input: "false == false", expected: true},
Test{input: "true == false", expected: false},
Test{input: "true != false", expected: true},
Test{input: "false != true", expected: true},
Test{input: "(1 < 2) == true", expected: true},
Test{input: "(1 < 2) == false", expected: false},
Test{input: "(1 > 2) == true", expected: false},
Test{input: "(1 > 2) == false", expected: true},
];
for t in tests {
let evaluated = test_eval(t.input);
test_boolean_object(&evaluated, t.expected);
}
}
#[test]
fn bang_operator() {
struct Test<'a> {
input: &'a str,
expected: bool,
}
let tests = vec![
Test{input: "!true", expected: false},
Test{input: "!false", expected: true},
Test{input: "!5", expected: false},
Test{input: "!!true", expected: true},
Test{input: "!!false", expected: false},
Test{input: "!!5", expected: true},
];
for t in tests {
let evaluated = test_eval(t.input);
test_boolean_object(&evaluated, t.expected);
}
}
#[test]
fn if_else_expressions() {
struct Test<'a> {
input: &'a str,
expected: Object,
}
let tests = vec![
Test{input: "if (true) { 10 }", expected: Object::Int(10)},
Test{input: "if (false) { 10 }", expected: Object::Null},
Test{input: "if (1) { 10 }", expected: Object::Int(10)},
Test{input: "if (1 < 2) { 10 }", expected: Object::Int(10)},
Test{input: "if (1 > 2) { 10 }", expected: Object::Null},
Test{input: "if (1 > 2) { 10 } else { 20 }", expected: Object::Int(20)},
Test{input: "if (1 < 2) { 10 } else { 20 }", expected: Object::Int(10)},
];
for t in tests {
let evaluated = &*test_eval(t.input);
match t.expected {
Object::Int(i) => test_integer_object(&evaluated, i),
_ => test_null_object(&evaluated),
}
}
}
#[test]
fn return_statements() {
struct Test<'a> {
input: &'a str,
expected: i64,
}
let tests = vec![
Test{input: "return 10;", expected: 10},
Test{input: "return 10; 9;", expected: 10},
Test{input: "return 2 * 5; 9;", expected: 10},
Test{input: "9; return 2 * 5; 9;", expected: 10},
Test{input: "if (10 > 1) {
if (10 > 1) {
return 10;
}
return 1;
}", expected: 10},
];
for t in tests {
let evaluated = test_eval(t.input);
test_integer_object(&evaluated, t.expected)
}
}
#[test]
fn error_handling() {
struct Test<'a> {
input: &'a str,
expected: &'a str,
}
let tests = vec![
Test{input: "5 + true;", expected: "type mismatch: Int(5) + Bool(true)"},
Test{input: "5 + true; 5;", expected: "type mismatch: Int(5) + Bool(true)"},
Test{input: "-true", expected: "unknown operator: -Bool(true)"},
Test{input: "true + false", expected: "unknown operator: true + false"},
Test{input: "5; true + false; 5", expected: "unknown operator: true + false"},
Test{input: "if (10 > 1) { true + false; }", expected: "unknown operator: true + false"},
Test{input: "if (10 > 1) {
if (10 > 1) {
return true + false;
}
return 1;
}", expected: "unknown operator: true + false"},
Test{input: "foobar", expected: "identifier not found: foobar"},
Test{input: r#" {"name": "Monkey"}[fn(x) { x }]; "#, expected: "unusable as hash key: fn(x) {\nx\n}"},
];
for t in tests {
let env = Rc::new(RefCell::new(Environment::new()));
match parser::parse(t.input) {
Ok(node) => {
match eval(&node, env) {
Err(e) => assert_eq!(e.message, t.expected),
n => panic!("expected error {} but got {:?}", t.expected, n)
}
},
Err(e) => panic!("error {:?} on input {}", e, t.input),
}
}
}
#[test]
fn let_statements() {
struct Test<'a> {
input: &'a str,
expected: i64,
}
let tests = vec![
Test{input: "let a = 5; a;", expected: 5},
Test{input: "let a = 5 * 5; a;", expected: 25},
Test{input: "let a = 5; let b = a; b;", expected: 5},
Test{input: "let a = 5; let b = a; let c = a + b + 5; c;", expected: 15},
];
for t in tests {
let evaluated = test_eval(t.input);
test_integer_object(&evaluated, t.expected)
}
}
#[test]
fn function_object() {
let input = "fn(x) { x + 2; };";
let evaluated = &*test_eval(input);
match evaluated {
Object::Function(f) => {
assert_eq!(f.parameters.len(), 1);
assert_eq!(f.parameters.first().unwrap().name, "x");
assert_eq!(f.body.to_string(), "(x + 2)");
},
_ => panic!("expected function object but got {:?}", evaluated)
}
}
#[test]
fn function_application() {
struct Test<'a> {
input: &'a str,
expected: i64,
}
let tests = vec![
Test{input: "let identity = fn(x) { x; }; identity(5);", expected: 5},
Test{input: "let identity = fn(x) { return x; }; identity(5);", expected: 5},
Test{input: "let double = fn(x) { x * 2; }; double(5);", expected: 10},
Test{input: "let add = fn(x, y) { x + y; }; add(5, 5);", expected: 10},
Test{input: "let add = fn(x, y) { x + y; }; add(5 + 5, add(5, 5));", expected: 20},
Test{input: "fn(x) { x; }(5)", expected: 5},
];
for t in tests {
test_integer_object(&test_eval(t.input), t.expected)
}
}
#[test]
fn closures() {
let input = "let newAdder = fn(x) {
fn(y) { x + y };
};
let addTwo = newAdder(2);
addTwo(2);";
test_integer_object(&test_eval(input), 4)
}
#[test]
fn string_literal() {
let input = r#""Hello World!"#;
match &*test_eval(input) {
Object::String(s) => assert_eq!(s, "Hello World!"),
obj => panic!(format!("expected string but got {:?}", obj))
}
}
#[test]
fn string_concatenation() {
let input = r#""Hello" + " " + "World!""#;
match &*test_eval(input) {
Object::String(s) => assert_eq!(s, "Hello World!"),
obj => panic!(format!("expected string but got {:?}", obj))
}
}
#[test]
fn builtin_functions() {
struct Test<'a> {
input: &'a str,
expected: Object,
}
let tests = vec![
Test{input: r#"len("")"#, expected: Object::Int(0)},
Test{input: r#"len("four")"#, expected: Object::Int(4)},
Test{input: r#"len("hello world")"#, expected: Object::Int(11)},
Test{input: "len([1, 2, 3])", expected: Object::Int(3)},
Test{input: "len([])", expected: Object::Int(0)},
Test{input: "first([1, 2, 3])", expected: Object::Int(1)},
Test{input: "first([])", expected: Object::Null},
Test{input: "last([1, 2, 3])", expected: Object::Int(3)},
Test{input: "last([])", expected: Object::Null},
Test{input: "rest([1, 2, 3])", expected: Object::Array(Rc::new(Array{elements: vec![Rc::new(Object::Int(2)), Rc::new(Object::Int(3))]}))},
Test{input: "rest([])", expected: Object::Array(Rc::new(Array{elements: vec![]}))},
Test{input: "push([], 1)", expected: Object::Array(Rc::new(Array{elements: vec![Rc::new(Object::Int(1))]}))},
];
for t in tests {
let obj = test_eval(t.input);
match (&t.expected, &*obj) {
(Object::Int(exp), Object::Int(got)) => assert_eq!(*exp, *got, "on input {} expected {} but got {}", t.input, exp, got),
(Object::Null, Object::Null) => {},
(Object::Array(ex), Object::Array(got)) => {
assert_eq!(ex.elements.len(), got.elements.len());
let mut got_iter = (&got.elements).into_iter();
for obj in &ex.elements {
let got_obj = Rc::clone(got_iter.next().unwrap());
match (&*Rc::clone(obj), &*got_obj) {
(Object::Int(exi), Object::Int(goti)) => assert_eq!(*exi, *goti),
_ => panic!("{:?} not same type as {:?}", got_obj, obj)
}
}
}
_ => panic!("on input {} expected {:?} but got {:?}", t.input, t.expected, obj)
}
}
}
#[test]
fn builtin_errors() {
struct Test<'a> {
input: &'a str,
expected: &'a str,
}
let tests = vec![
Test{input: r#"len(1)"#, expected: "object Int(1) not supported as an argument for len"},
Test{input: r#"len("one", "two")"#, expected: "len takes only 1 array or string argument"},
Test{input: r#"first(1)"#, expected: "object Int(1) not supported as an argument for first"},
];
for t in tests {
let env = Rc::new(RefCell::new(Environment::new()));
match parser::parse(t.input) {
Ok(node) => {
match eval(&node, env) {
Ok(obj) => panic!("expected error on input {} but got {:?}", t.input, obj),
Err(err) => assert_eq!(t.expected, err.message, "on input {} expected error {} but got {}", t.input, t.expected, err.message)
}
},
Err(e) => panic!("error {:?} on input {}", e, t.input),
}
}
}
#[test]
fn array_literals() {
let input = "[1, 2 * 2, 3 + 3]";
let obj = test_eval(input);
match &*obj {
Object::Array(a) => {
test_integer_object(a.elements.get(0).unwrap(), 1);
test_integer_object(a.elements.get(1).unwrap(), 4);
test_integer_object(a.elements.get(2).unwrap(), 6);
},
_ => panic!("expected array but got {:?}", obj)
}
}
#[test]
fn array_index_expressions() {
struct Test<'a> {
input: &'a str,
expected: i64,
}
let tests = vec![
Test{input: "[1, 2, 3][0]", expected: 1},
Test{input: "[1, 2, 3][1]", expected: 2},
Test{input: "[1, 2, 3][2]", expected: 3},
Test{input: "let i = 0; [1][i];", expected: 1},
Test{input: "[1, 2, 3][1 + 1];", expected: 3},
Test{input: "let myArray = [1, 2, 3]; myArray[2];", expected: 3},
Test{input: "let myArray = [1, 2, 3]; myArray[0] + myArray[1] + myArray[2];", expected: 6},
Test{input: "let myArray = [1, 2, 3]; let i = myArray[0]; myArray[i]", expected: 2},
];
for t in tests {
let obj = test_eval(t.input);
match &*obj {
Object::Int(i) => assert_eq!(*i, t.expected),
_ => panic!("expected int obj but got {:?}", obj)
}
}
}
#[test]
fn invalid_array_index() {
let inputs = vec![
"[1, 2, 3][3]",
"[1, 2, 3][-1]",
];
for input in inputs {
let obj = test_eval(input);
match &*obj {
Object::Null => {},
_ => panic!("expected null object, but got {:?}", obj)
}
}
}
#[test]
fn hash_literal() {
let input = r#"let two = "two";
{
"one": 10 - 9,
two: 1 + 1,
"thr" + "ee": 6 / 2,
4: 4,
true: 5,
false: 6
}
"#;
let obj = test_eval(input);
match &*obj {
Object::Hash(h) => {
assert_eq!(h.pairs.len(), 6);
for (key, value) in &h.pairs {
match (&*Rc::clone(key), &*Rc::clone(value)) {
(Object::String(k), Object::Int(val)) => {
match k.as_str() {
"one" => assert_eq!(*val, 1),
"two" => assert_eq!(*val, 2),
"three" => assert_eq!(*val, 3),
_ => panic!("unexpected string key {}", k)
}
},
(Object::Bool(b), Object::Int(val)) => {
if *b {
assert_eq!(*val, 5)
} else {
assert_eq!(*val, 6)
}
},
(Object::Int(k), Object::Int(val)) => assert_eq!(k, val),
_ => panic!("unexpected key value pair {:?} {:?}", key, value)
}
}
},
_ => panic!("expected hash object, but got {:?}", obj)
}
}
#[test]
fn hash_index_expressions() {
struct Test<'a> {
input: &'a str,
expected: Object,
}
let tests = vec![
Test{input: r#" {"foo":5}["foo"] "#, expected: Object::Int(5)},
Test{input: r#" {"foo":5}["bar"] "#, expected: Object::Null},
Test{input: r#" let key = "foo"; {"foo":5}[key] "#, expected: Object::Int(5)},
Test{input: r#" {}["foo"] "#, expected: Object::Null},
Test{input: r#" {5: 5}[5] "#, expected: Object::Int(5)},
Test{input: r#" {true: 5}[true] "#, expected: Object::Int(5)},
Test{input: r#" {false: 5}[false] "#, expected: Object::Int(5)},
];
for t in tests {
let obj = test_eval(t.input);
match (&t.expected, &*obj) {
(Object::Int(exp), Object::Int(got)) => assert_eq!(*exp, *got, "on input {} expected {} but got {}", t.input, exp, got),
(Object::Null, Object::Null) => {},
_ => panic!("on input {} expected {:?} but got {:?}", t.input, t.expected, obj)
}
}
}
fn test_eval(input: &str) -> Rc<Object> {
let env = Rc::new(RefCell::new(Environment::new()));
match parser::parse(input) {
Ok(node) => {
eval(&node, env).expect(input)
},
Err(e) => panic!("error {:?} on input {}", e, input),
}
}
fn test_integer_object(obj: &Object, expected: i64) {
match obj {
Object::Int(i) => assert_eq!(i, &expected),
_ => panic!("expected integer object, but got {:?}", obj),
}
}
fn test_boolean_object(obj: &Object, expected: bool) {
match obj {
Object::Bool(b) => assert_eq!(b, &expected),
_ => panic!("expected boolean object, but got {:?}", obj),
}
}
fn test_null_object(obj: &Object) {
match obj {
Object::Null => {},
_ => panic!("expected null but got {:?}", obj),
}
}
} |
#[doc = "Register `SYSCFG_ITLINE9` reader"]
pub type R = crate::R<SYSCFG_ITLINE9_SPEC>;
#[doc = "Field `DMA1_CH1` reader - DMA1 channel 1interrupt request pending"]
pub type DMA1_CH1_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - DMA1 channel 1interrupt request pending"]
#[inline(always)]
pub fn dma1_ch1(&self) -> DMA1_CH1_R {
DMA1_CH1_R::new((self.bits & 1) != 0)
}
}
#[doc = "SYSCFG interrupt line 9 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`syscfg_itline9::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SYSCFG_ITLINE9_SPEC;
impl crate::RegisterSpec for SYSCFG_ITLINE9_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`syscfg_itline9::R`](R) reader structure"]
impl crate::Readable for SYSCFG_ITLINE9_SPEC {}
#[doc = "`reset()` method sets SYSCFG_ITLINE9 to value 0"]
impl crate::Resettable for SYSCFG_ITLINE9_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//! Partial unmarshall and traversal. (requires `partial` feature)
//!
//!
//! ## Appliactions
//! Parital reading **is** for:
//! - Reading large tycho encoded files.
//!
//! Parital reading **is not** for:
//! - Reading from streams/sockets.
//!
//! Tycho Parital reading is designed for reading from large files where proccessing is limited
//! such as in a database or data store, where the contents do not need to be serialized.
//!
//! ## Quick Example
//! ```
//! use tycho::partial::{PartialReader, PartialElement};
//!
//! // Create a partial reader from a vec with example bytes.
//! let mut reader = PartialReader::from_vec(vec![
//! /* ... */
//! # 5, 35, 102, 111, 111, 0, 1, 4, 1, 10, 98, 97, 114, 0, 1, 4, 2, 0, 20, 98, 97, 122, 0, 1, 2, 11, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100
//! ]);
//!
//! // Get the root element from
//! let root = reader.element().unwrap();
//!
//! // check if the root element is a structure
//! if let PartialElement::Struct(mut s) = root {
//!
//! // iterate over fields with reader.
//! for (key, value) in s.iter(&mut reader) {
//! println!("{:?}: {:?}", key, value);
//! }
//! }
//!
//! ```
//!
//! ## Getting Started
//!
//! ### Reader
//! Parital reading requires a `ParitalReader` to be created.
//! The partial reader has an internal pointer and handles state management.
//!
//! A `ParitalReader` can wrap any type that implements `Read` and `Seek`
//! and thier respective async counterparts.
//!
//! `ParitalReader` then implements its own `Read` trait that handles the pointer when read.
//!
//! ```
//! // From a Vec<u8>
//! use tycho::partial::PartialReader;
//!
//! let mut reader = PartialReader::from_vec(Vec::<u8>::new());
//! ```
//!
//! ```
//! // From a cursor
//! use std::io::Cursor;
//! use tycho::partial::PartialReader;
//!
//! let cursor = Cursor::new(Vec::<u8>::new());
//! let mut reader = PartialReader::from(cursor);
//! ```
//! ```no_run
//! // From a file
//! use std::io::{Cursor, BufReader};
//! use tycho::partial::PartialReader;
//! use std::fs::File;
//!
//! let file = File::open("path/to/file").unwrap();
//! let buf = BufReader::new(file);
//! let mut reader = PartialReader::from(buf);
//! ```
//!
//! ### Pointers
//! Pointers map to a set of bytes within a reader.
//! They contain a `position` and `size`,
//! with position representing the start loaction and size the data length.
//!
//! Pointers are given out within a ParitalElement and wrapped within a container type.
//! While the user may not interact with a pointer directly it may help with understanding how
//! tycho paritally parses bytes.
//!
//! ### Element
//! ParitalElements contain a proccessed value or a unproccess container with its respective pointer.
//!
//! Within this libary there are four types of partial element:
//! - Proccessed (Unit, Value)
//! - Pointing (Option, Variant)
//! - Container (Struct, List, Map, Array)
//! - Compression (Compression)
//!
//! Proccessed values can be accesed by pattern matching the `ParitalElement` enum,
//! which will return a normaal value.
//!
//! Pointing elements return a box with another partial element which can be pattern matched
//! and handled accordingly.
//!
//! Container elements allow you to iterate over thier children one at a time.
//! See below for more infomation
//!
//! Compression elements allow you to get the bytes or another partial element upon request.
//!
//! ### Containers
//! All container types (Struct, List, Map, Array) share a `PartialContainer` which takes a generic.
//!
//! The PartialContainer type has another `head` pointer to keep track of the current item.
//!
//! **Further documentation soon*
#[cfg(feature = "async_tokio")]
pub use async_::reader::PartialAsyncReader;
pub use element::PartialElement;
pub use reader::{PartialPointer, PartialReader};
//pub use types::{PartialArray, PartialList, PartialMap, PartialStruct};
//pub mod types;
pub mod container;
pub(crate) mod reader;
pub(crate) mod element;
pub mod types;
//pub(crate) mod test;
#[cfg(feature = "async_tokio")]
pub(crate) mod async_;
|
use crate::{
grammar::{name_ref, patterns, separated_list, types, ParseError},
parser::{CompletedMarker, Parser},
syntax::{SyntaxKind::*, TokenSet},
};
pub const EXPR_FIRST: TokenSet = token_set![IF_KW, L_BRACKET, L_ANGLE, MATCH_KW, L_PAREN, IDENT];
pub fn expression(p: &mut Parser) -> Option<CompletedMarker> {
let prec_marker = match p.current() {
IF_KW => Some(if_expr(p)),
L_CURLY => Some(block_expr(p)),
L_ANGLE => Some(struct_expr(p)),
MATCH_KW => Some(match_expr(p)),
L_PAREN => Some(tuple_expr(p)),
IDENT => Some(var_expr(p)),
_ => literal(p),
};
if let Some(mut prec_marker) = prec_marker {
loop {
prec_marker = match p.current() {
L_PAREN => call_expr(p, prec_marker),
COLON => ascription_expr(p, prec_marker),
PERIOD => field_expr(p, prec_marker),
_ => break None,
};
}
} else {
p.err_and_bump("Expected an expression".into());
None
}
}
pub fn tuple_expr(p: &mut Parser) -> CompletedMarker {
assert!(p.at(L_PAREN));
separated_list(p, TUPLE_EXPR, Some([L_PAREN, R_PAREN]), COMMA, &expression)
}
pub fn struct_expr(p: &mut Parser) -> CompletedMarker {
assert!(p.at(L_ANGLE));
separated_list(
p,
STRUCT_EXPR,
Some([L_ANGLE, R_ANGLE]),
COMMA,
struct_field,
)
}
pub fn struct_field(p: &mut Parser) {
let m = p.start();
name_ref(p);
p.expect(COLON);
expression(p);
m.complete(p, STRUCT_EXPR_FIELD);
}
pub fn var_expr(p: &mut Parser) -> CompletedMarker {
assert!(p.at(IDENT));
let m = p.start();
name_ref(p);
m.complete(p, VAR_EXPR)
}
pub fn if_expr(p: &mut Parser) -> CompletedMarker {
assert!(p.at(IF_KW));
let m = p.start();
p.bump(); // eat the keyword
expression(p);
if p.at(L_CURLY) {
block_expr(p);
} else {
p.error(ParseError::expect(L_CURLY, p.current()));
}
if p.eat(ELSE_KW) {
if p.at(IF_KW) {
if_expr(p);
} else if p.at(L_CURLY) {
block_expr(p);
} else {
p.error("Expected block or else-if".into())
}
}
m.complete(p, IF_EXPR)
}
pub fn match_expr(p: &mut Parser) -> CompletedMarker {
assert!(p.at(MATCH_KW));
let m = p.start();
p.bump();
expression(p);
separated_list(
p,
MATCH_EXPR_ARM_LIST,
Some([L_CURLY, R_CURLY]),
COMMA,
match_arm,
);
m.complete(p, MATCH_EXPR)
}
pub fn match_arm(p: &mut Parser) {
let m = p.start();
patterns::pattern(p);
p.expect(THICK_ARROW);
expression(p);
m.complete(p, MATCH_EXPR_ARM);
}
pub fn call_expr(p: &mut Parser, prec: CompletedMarker) -> CompletedMarker {
assert!(p.at(L_PAREN));
let m = prec.precede(p);
separated_list(
p,
CALL_EXPR_ARG_LIST,
Some([L_PAREN, R_PAREN]),
COMMA,
expression,
);
m.complete(p, CALL_EXPR)
}
pub fn field_expr(p: &mut Parser, prec: CompletedMarker) -> CompletedMarker {
assert!(p.at(PERIOD));
let m = prec.precede(p);
p.bump();
if p.at(IDENT) {
name_ref(p)
} else if p.at(INT_NUM) {
p.bump()
} else {
p.error("expected field name or number".into())
}
m.complete(p, FIELD_EXPR)
}
pub fn ascription_expr(p: &mut Parser, prec: CompletedMarker) -> CompletedMarker {
assert!(p.at(COLON));
let m = prec.precede(p);
p.bump();
types::typ(p);
m.complete(p, ASCRIPTION_EXPR)
}
pub fn block_expr(p: &mut Parser) -> CompletedMarker {
assert!(p.at(L_CURLY));
let block = p.start();
p.bump(); // eat l curly
while !p.at(EOF) && !p.at(R_CURLY) {
match p.current() {
SEMI => p.bump(),
LET_KW => let_stmnt(p),
_ => {
if let Some(prec) = expression(p) {
if p.at(SEMI) {
let m = prec.precede(p);
p.bump();
m.complete(p, EXPR_STMNT);
} else if !(p.at(EOF) || p.at(R_CURLY)) {
p.error("Statement terminated without semicolon".into())
} else {
break;
}
}
},
}
}
p.expect(R_CURLY);
block.complete(p, BLOCK_EXPR)
}
pub const STMNT_FIRST: TokenSet = token_set![LET_KW].union(EXPR_FIRST);
pub fn let_stmnt(p: &mut Parser) {
assert!(p.at(LET_KW));
let m = p.start();
// let statement
p.bump();
patterns::pattern(p);
p.expect(EQ);
expression(p);
p.expect(SEMI);
m.complete(p, LET_STMNT);
}
pub(crate) const LITERAL_FIRST: TokenSet =
token_set![TRUE_KW, FALSE_KW, INT_NUM, FLOAT_NUM, SYMBOL];
pub(crate) fn literal(p: &mut Parser) -> Option<CompletedMarker> {
if !p.at_ts(LITERAL_FIRST) {
return None;
}
let m = p.start();
p.bump();
Some(m.complete(p, LITERAL))
}
|
use euclid::Point2D;
use euclid::Vector2D;
pub mod debug;
pub mod nurbs;
#[derive(Clone, Copy, Debug)]
pub struct ModelSpace;
#[derive(Clone, Copy, Debug)]
pub struct CanvasSpace;
#[derive(Clone, Copy, Debug)]
pub struct ScreenSpace;
#[derive(Clone, Copy, Debug)]
pub struct PixelSpace;
#[derive(Clone, Debug)]
pub struct Line<S> {
pub start: Point2D<f32, S>,
pub end: Point2D<f32, S>,
}
impl<S> Line<S> {
pub fn new(start_x: f32, start_y: f32, end_x: f32, end_y: f32) -> Line<S> {
Line {
start: Point2D::new(start_x, start_y),
end: Point2D::new(end_x, end_y),
}
}
pub fn from_tuple((start, end): (Point2D<f32, S>, Point2D<f32, S>)) -> Option<Line<S>> {
if start.x.is_nan() || start.y.is_nan() || end.x.is_nan() || end.y.is_nan() {
None
} else {
Some(Line { start, end })
}
}
}
#[derive(Clone, Debug)]
pub struct Ray<S> {
pub origin: Point2D<f32, S>,
pub direction: Vector2D<f32, S>,
}
impl<S> Ray<S> {
pub fn intersect_line(&self, line: &Line<S>) -> Option<f32> {
let v1 = self.origin - line.start;
let s = line.end - line.start;
let v3 = Vector2D::new(-self.direction.y, self.direction.x);
let dot = s.dot(v3);
if dot.abs() < 0.000001 {
return None;
}
let t1 = s.cross(v1) / dot;
let t2 = v1.dot(v3) / dot;
if t1 >= 0.0 && (t2 >= 0.0 && t2 <= 1.0) {
return Some(t1);
}
None
}
pub fn intersect_lines(&self, lines: impl Iterator<Item = Line<S>>) -> Option<f32> {
lines
.filter_map(|l| self.intersect_line(&l))
.min_by(|a, b| a.partial_cmp(b).unwrap())
}
pub fn at(&self, t: f32) -> Point2D<f32, S> {
self.origin + self.direction * t
}
}
|
mod handlers;
use std::{
collections::{HashSet, HashMap},
};
use threadpool::ThreadPool;
use crossbeam_channel::{Sender, Receiver};
use languageserver_types::Url;
use libanalysis::{World, WorldState, FileId};
use serde_json::to_value;
use {
req, dispatch,
Task, Result, PathMap,
io::{Io, RawMsg, RawRequest, RawNotification},
vfs::{FileEvent, FileEventKind},
conv::TryConvWith,
main_loop::handlers::{
handle_syntax_tree,
handle_extend_selection,
publish_diagnostics,
publish_decorations,
handle_document_symbol,
handle_code_action,
handle_execute_command,
handle_workspace_symbol,
handle_goto_definition,
handle_find_matching_brace,
},
};
pub(super) fn main_loop(
io: &mut Io,
world: &mut WorldState,
pool: &mut ThreadPool,
task_sender: Sender<Task>,
task_receiver: Receiver<Task>,
fs_events_receiver: Receiver<Vec<FileEvent>>,
) -> Result<()> {
info!("server initialized, serving requests");
let mut next_request_id = 0;
let mut pending_requests: HashSet<u64> = HashSet::new();
let mut path_map = PathMap::new();
let mut mem_map: HashMap<FileId, Option<String>> = HashMap::new();
let mut fs_events_receiver = Some(&fs_events_receiver);
loop {
enum Event {
Msg(RawMsg),
Task(Task),
Fs(Vec<FileEvent>),
ReceiverDead,
FsWatcherDead,
}
let event = select! {
recv(io.receiver(), msg) => match msg {
Some(msg) => Event::Msg(msg),
None => Event::ReceiverDead,
},
recv(task_receiver, task) => Event::Task(task.unwrap()),
recv(fs_events_receiver, events) => match events {
Some(events) => Event::Fs(events),
None => Event::FsWatcherDead,
}
};
match event {
Event::ReceiverDead => {
io.cleanup_receiver()?;
unreachable!();
}
Event::FsWatcherDead => {
fs_events_receiver = None;
}
Event::Task(task) => {
match task {
Task::Request(mut request) => {
request.id = next_request_id;
pending_requests.insert(next_request_id);
next_request_id += 1;
io.send(RawMsg::Request(request));
}
Task::Respond(response) =>
io.send(RawMsg::Response(response)),
Task::Notify(n) =>
io.send(RawMsg::Notification(n)),
Task::Die(error) =>
return Err(error),
}
continue;
}
Event::Fs(events) => {
trace!("fs change, {} events", events.len());
let changes = events.into_iter()
.map(|event| {
let text = match event.kind {
FileEventKind::Add(text) => Some(text),
FileEventKind::Remove => None,
};
(event.path, text)
})
.map(|(path, text)| {
(path_map.get_or_insert(path), text)
})
.filter_map(|(id, text)| {
if mem_map.contains_key(&id) {
mem_map.insert(id, text);
None
} else {
Some((id, text))
}
});
world.change_files(changes);
}
Event::Msg(msg) => {
match msg {
RawMsg::Request(req) => {
if !on_request(io, world, &path_map, pool, &task_sender, req)? {
return Ok(());
}
}
RawMsg::Notification(not) => {
on_notification(io, world, &mut path_map, pool, &task_sender, not, &mut mem_map)?
}
RawMsg::Response(resp) => {
if !pending_requests.remove(&resp.id) {
error!("unexpected response: {:?}", resp)
}
}
}
}
};
}
}
fn on_request(
io: &mut Io,
world: &WorldState,
path_map: &PathMap,
pool: &ThreadPool,
sender: &Sender<Task>,
req: RawRequest,
) -> Result<bool> {
let mut req = Some(req);
handle_request_on_threadpool::<req::SyntaxTree>(
&mut req, pool, path_map, world, sender, handle_syntax_tree,
)?;
handle_request_on_threadpool::<req::ExtendSelection>(
&mut req, pool, path_map, world, sender, handle_extend_selection,
)?;
handle_request_on_threadpool::<req::FindMatchingBrace>(
&mut req, pool, path_map, world, sender, handle_find_matching_brace,
)?;
handle_request_on_threadpool::<req::DocumentSymbolRequest>(
&mut req, pool, path_map, world, sender, handle_document_symbol,
)?;
handle_request_on_threadpool::<req::CodeActionRequest>(
&mut req, pool, path_map, world, sender, handle_code_action,
)?;
handle_request_on_threadpool::<req::WorkspaceSymbol>(
&mut req, pool, path_map, world, sender, handle_workspace_symbol,
)?;
handle_request_on_threadpool::<req::GotoDefinition>(
&mut req, pool, path_map, world, sender, handle_goto_definition,
)?;
dispatch::handle_request::<req::ExecuteCommand, _>(&mut req, |params, resp| {
io.send(RawMsg::Response(resp.into_response(Ok(None))?));
let world = world.snapshot();
let path_map = path_map.clone();
let sender = sender.clone();
pool.execute(move || {
let (edit, cursor) = match handle_execute_command(world, path_map, params) {
Ok(res) => res,
Err(e) => return sender.send(Task::Die(e)),
};
match to_value(edit) {
Err(e) => return sender.send(Task::Die(e.into())),
Ok(params) => {
let request = RawRequest {
id: 0,
method: <req::ApplyWorkspaceEdit as req::ClientRequest>::METHOD.to_string(),
params,
};
sender.send(Task::Request(request))
}
}
if let Some(cursor) = cursor {
let request = RawRequest {
id: 0,
method: <req::MoveCursor as req::ClientRequest>::METHOD.to_string(),
params: to_value(cursor).unwrap(),
};
sender.send(Task::Request(request))
}
});
Ok(())
})?;
let mut shutdown = false;
dispatch::handle_request::<req::Shutdown, _>(&mut req, |(), resp| {
let resp = resp.into_response(Ok(()))?;
io.send(RawMsg::Response(resp));
shutdown = true;
Ok(())
})?;
if shutdown {
info!("lifecycle: initiating shutdown");
return Ok(false);
}
if let Some(req) = req {
error!("unknown method: {:?}", req);
io.send(RawMsg::Response(dispatch::unknown_method(req.id)?));
}
Ok(true)
}
fn on_notification(
io: &mut Io,
world: &mut WorldState,
path_map: &mut PathMap,
pool: &ThreadPool,
sender: &Sender<Task>,
not: RawNotification,
mem_map: &mut HashMap<FileId, Option<String>>,
) -> Result<()> {
let mut not = Some(not);
dispatch::handle_notification::<req::DidOpenTextDocument, _>(&mut not, |params| {
let uri = params.text_document.uri;
let path = uri.to_file_path()
.map_err(|()| format_err!("invalid uri: {}", uri))?;
let file_id = path_map.get_or_insert(path);
mem_map.insert(file_id, None);
world.change_file(file_id, Some(params.text_document.text));
update_file_notifications_on_threadpool(
pool, world.snapshot(), path_map.clone(), sender.clone(), uri,
);
Ok(())
})?;
dispatch::handle_notification::<req::DidChangeTextDocument, _>(&mut not, |mut params| {
let file_id = params.text_document.try_conv_with(path_map)?;
let text = params.content_changes.pop()
.ok_or_else(|| format_err!("empty changes"))?
.text;
world.change_file(file_id, Some(text));
update_file_notifications_on_threadpool(
pool, world.snapshot(), path_map.clone(), sender.clone(), params.text_document.uri,
);
Ok(())
})?;
dispatch::handle_notification::<req::DidCloseTextDocument, _>(&mut not, |params| {
let file_id = params.text_document.try_conv_with(path_map)?;
let text = match mem_map.remove(&file_id) {
Some(text) => text,
None => bail!("unmatched close notification"),
};
world.change_file(file_id, text);
let not = req::PublishDiagnosticsParams {
uri: params.text_document.uri,
diagnostics: Vec::new(),
};
let not = dispatch::send_notification::<req::PublishDiagnostics>(not);
io.send(RawMsg::Notification(not));
Ok(())
})?;
if let Some(not) = not {
error!("unhandled notification: {:?}", not);
}
Ok(())
}
fn handle_request_on_threadpool<R: req::ClientRequest>(
req: &mut Option<RawRequest>,
pool: &ThreadPool,
path_map: &PathMap,
world: &WorldState,
sender: &Sender<Task>,
f: fn(World, PathMap, R::Params) -> Result<R::Result>,
) -> Result<()>
{
dispatch::handle_request::<R, _>(req, |params, resp| {
let world = world.snapshot();
let path_map = path_map.clone();
let sender = sender.clone();
pool.execute(move || {
let res = f(world, path_map, params);
let task = match resp.into_response(res) {
Ok(resp) => Task::Respond(resp),
Err(e) => Task::Die(e),
};
sender.send(task);
});
Ok(())
})
}
fn update_file_notifications_on_threadpool(
pool: &ThreadPool,
world: World,
path_map: PathMap,
sender: Sender<Task>,
uri: Url,
) {
pool.execute(move || {
match publish_diagnostics(world.clone(), path_map.clone(), uri.clone()) {
Err(e) => {
error!("failed to compute diagnostics: {:?}", e)
}
Ok(params) => {
let not = dispatch::send_notification::<req::PublishDiagnostics>(params);
sender.send(Task::Notify(not));
}
}
match publish_decorations(world, path_map.clone(), uri) {
Err(e) => {
error!("failed to compute decorations: {:?}", e)
}
Ok(params) => {
let not = dispatch::send_notification::<req::PublishDecorations>(params);
sender.send(Task::Notify(not))
}
}
});
}
|
use crate::{
backend::SchemaBuilder, foreign_key::*, index::*, prepare::*, types::*, ColumnDef,
SchemaStatementBuilder,
};
/// Create a table
///
/// # Examples
///
/// ```
/// use sea_query::{*, tests_cfg::*};
///
/// let table = Table::create()
/// .table(Char::Table)
/// .if_not_exists()
/// .col(ColumnDef::new(Char::Id).integer().not_null().auto_increment().primary_key())
/// .col(ColumnDef::new(Char::FontSize).integer().not_null())
/// .col(ColumnDef::new(Char::Character).string().not_null())
/// .col(ColumnDef::new(Char::SizeW).integer().not_null())
/// .col(ColumnDef::new(Char::SizeH).integer().not_null())
/// .col(ColumnDef::new(Char::FontId).integer().default(Value::Null))
/// .foreign_key(
/// ForeignKey::create()
/// .name("FK_2e303c3a712662f1fc2a4d0aad6")
/// .from(Char::Table, Char::FontId)
/// .to(Font::Table, Font::Id)
/// .on_delete(ForeignKeyAction::Cascade)
/// .on_update(ForeignKeyAction::Cascade)
/// )
/// .to_owned();
///
/// assert_eq!(
/// table.to_string(MysqlQueryBuilder),
/// vec![
/// r#"CREATE TABLE IF NOT EXISTS `character` ("#,
/// r#"`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,"#,
/// r#"`font_size` int NOT NULL,"#,
/// r#"`character` varchar(255) NOT NULL,"#,
/// r#"`size_w` int NOT NULL,"#,
/// r#"`size_h` int NOT NULL,"#,
/// r#"`font_id` int DEFAULT NULL,"#,
/// r#"CONSTRAINT `FK_2e303c3a712662f1fc2a4d0aad6`"#,
/// r#"FOREIGN KEY (`font_id`) REFERENCES `font` (`id`)"#,
/// r#"ON DELETE CASCADE ON UPDATE CASCADE"#,
/// r#")"#,
/// ].join(" ")
/// );
/// assert_eq!(
/// table.to_string(PostgresQueryBuilder),
/// vec![
/// r#"CREATE TABLE IF NOT EXISTS "character" ("#,
/// r#""id" serial NOT NULL PRIMARY KEY,"#,
/// r#""font_size" integer NOT NULL,"#,
/// r#""character" varchar NOT NULL,"#,
/// r#""size_w" integer NOT NULL,"#,
/// r#""size_h" integer NOT NULL,"#,
/// r#""font_id" integer DEFAULT NULL,"#,
/// r#"CONSTRAINT "FK_2e303c3a712662f1fc2a4d0aad6""#,
/// r#"FOREIGN KEY ("font_id") REFERENCES "font" ("id")"#,
/// r#"ON DELETE CASCADE ON UPDATE CASCADE"#,
/// r#")"#,
/// ].join(" ")
/// );
/// assert_eq!(
/// table.to_string(SqliteQueryBuilder),
/// vec![
/// r#"CREATE TABLE IF NOT EXISTS `character` ("#,
/// r#"`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,"#,
/// r#"`font_size` integer NOT NULL,"#,
/// r#"`character` text NOT NULL,"#,
/// r#"`size_w` integer NOT NULL,"#,
/// r#"`size_h` integer NOT NULL,"#,
/// r#"`font_id` integer DEFAULT NULL,"#,
/// r#"FOREIGN KEY (`font_id`) REFERENCES `font` (`id`) ON DELETE CASCADE ON UPDATE CASCADE"#,
/// r#")"#,
/// ].join(" ")
/// );
/// ```
#[derive(Debug, Clone)]
pub struct TableCreateStatement {
pub(crate) table: Option<DynIden>,
pub(crate) columns: Vec<ColumnDef>,
pub(crate) options: Vec<TableOpt>,
pub(crate) partitions: Vec<TablePartition>,
pub(crate) indexes: Vec<IndexCreateStatement>,
pub(crate) foreign_keys: Vec<ForeignKeyCreateStatement>,
pub(crate) if_not_exists: bool,
}
/// All available table options
#[derive(Debug, Clone)]
pub enum TableOpt {
Engine(String),
Collate(String),
CharacterSet(String),
}
/// All available table partition options
#[derive(Debug, Clone)]
pub enum TablePartition {}
impl Default for TableCreateStatement {
fn default() -> Self {
Self::new()
}
}
impl TableCreateStatement {
/// Construct create table statement
pub fn new() -> Self {
Self {
table: None,
columns: Vec::new(),
options: Vec::new(),
partitions: Vec::new(),
indexes: Vec::new(),
foreign_keys: Vec::new(),
if_not_exists: false,
}
}
#[deprecated(
since = "0.9.6",
note = "Please use the [`TableCreateStatement::if_not_exists`]"
)]
pub fn create_if_not_exists(&mut self) -> &mut Self {
self.if_not_exists = true;
self
}
/// Create table if table not exists
pub fn if_not_exists(&mut self) -> &mut Self {
self.if_not_exists = true;
self
}
/// Set table name
pub fn table<T: 'static>(&mut self, table: T) -> &mut Self
where
T: Iden,
{
self.table = Some(SeaRc::new(table));
self
}
/// Add a new table column
pub fn col(&mut self, column: ColumnDef) -> &mut Self {
let mut column = column;
column.table = self.table.clone();
self.columns.push(column);
self
}
/// Add an index. MySQL only.
///
/// # Examples
///
/// ```
/// use sea_query::{*, tests_cfg::*};
///
/// assert_eq!(
/// Table::create()
/// .table(Glyph::Table)
/// .col(ColumnDef::new(Glyph::Id).integer().not_null())
/// .index(
/// Index::create()
/// .unique()
/// .name("idx-glyph-id")
/// .col(Glyph::Id)
/// )
/// .to_string(MysqlQueryBuilder),
/// vec![
/// "CREATE TABLE `glyph` (",
/// "`id` int NOT NULL,",
/// "UNIQUE KEY `idx-glyph-id` (`id`)",
/// ")",
/// ].join(" ")
/// );
/// ```
pub fn index(&mut self, index: IndexCreateStatement) -> &mut Self {
self.indexes.push(index);
self
}
/// Add an primary key.
///
/// # Examples
///
/// ```
/// use sea_query::{*, tests_cfg::*};
///
/// let mut statement = Table::create();
/// statement
/// .table(Glyph::Table)
/// .col(ColumnDef::new(Glyph::Id).integer().not_null())
/// .col(ColumnDef::new(Glyph::Image).string().not_null())
/// .primary_key(
/// Index::create()
/// .col(Glyph::Id)
/// .col(Glyph::Image)
/// );
/// assert_eq!(statement.to_string(MysqlQueryBuilder),
/// vec![
/// "CREATE TABLE `glyph` (",
/// "`id` int NOT NULL,",
/// "`image` varchar(255) NOT NULL,",
/// "PRIMARY KEY (`id`, `image`)",
/// ")",
/// ].join(" ")
/// );
/// assert_eq!(statement.to_string(PostgresQueryBuilder),
/// vec![
/// "CREATE TABLE \"glyph\" (",
/// "\"id\" integer NOT NULL,",
/// "\"image\" varchar NOT NULL,",
/// "PRIMARY KEY (\"id\", \"image\")",
/// ")",
/// ].join(" ")
/// );
/// assert_eq!(statement.to_string(SqliteQueryBuilder),
/// vec![
/// "CREATE TABLE `glyph` (",
/// "`id` integer NOT NULL,",
/// "`image` text NOT NULL,",
/// "PRIMARY KEY (`id`, `image`)",
/// ")",
/// ].join(" ")
/// );
/// ```
pub fn primary_key(&mut self, index: IndexCreateStatement) -> &mut Self {
let mut index = index;
index.primary = true;
self.indexes.push(index);
self
}
/// Add a foreign key
pub fn foreign_key(&mut self, foreign_key: ForeignKeyCreateStatement) -> &mut Self {
self.foreign_keys.push(foreign_key);
self
}
/// Set database engine. MySQL only.
pub fn engine(&mut self, string: &str) -> &mut Self {
self.opt(TableOpt::Engine(string.into()));
self
}
/// Set database collate. MySQL only.
pub fn collate(&mut self, string: &str) -> &mut Self {
self.opt(TableOpt::Collate(string.into()));
self
}
/// Set database character set. MySQL only.
pub fn character_set(&mut self, string: &str) -> &mut Self {
self.opt(TableOpt::CharacterSet(string.into()));
self
}
fn opt(&mut self, option: TableOpt) -> &mut Self {
self.options.push(option);
self
}
#[allow(dead_code)]
fn partition(&mut self, partition: TablePartition) -> &mut Self {
self.partitions.push(partition);
self
}
pub fn get_table_name(&self) -> Option<String> {
self.table.as_ref().map(|table| table.to_string())
}
pub fn get_columns(&self) -> &Vec<ColumnDef> {
self.columns.as_ref()
}
pub fn get_foreign_key_create_stmts(&self) -> &Vec<ForeignKeyCreateStatement> {
self.foreign_keys.as_ref()
}
pub fn get_indexes(&self) -> &Vec<IndexCreateStatement> {
self.indexes.as_ref()
}
}
impl SchemaStatementBuilder for TableCreateStatement {
fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String {
let mut sql = SqlWriter::new();
schema_builder.prepare_table_create_statement(self, &mut sql);
sql.result()
}
fn build_any(&self, schema_builder: &dyn SchemaBuilder) -> String {
let mut sql = SqlWriter::new();
schema_builder.prepare_table_create_statement(self, &mut sql);
sql.result()
}
}
|
use std::cmp;
use std::collections::{BinaryHeap, HashMap};
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use may_queue::mpsc::Queue;
use may_queue::mpsc_list_v1::Entry;
use may_queue::mpsc_list_v1::Queue as TimeoutQueue;
use parking_lot::{Mutex, RwLock};
use crate::sync::AtomicOption;
const NANOS_PER_MILLI: u64 = 1_000_000;
const NANOS_PER_SEC: u64 = 1_000_000_000;
const HASH_CAP: usize = 1024;
#[inline]
fn dur_to_ns(dur: Duration) -> u64 {
// Note that a duration is a (u64, u32) (seconds, nanoseconds) pair
dur.as_secs()
.saturating_mul(NANOS_PER_SEC)
.saturating_add(u64::from(dur.subsec_nanos()))
}
#[inline]
pub const fn ns_to_dur(ns: u64) -> Duration {
Duration::new(ns / NANOS_PER_SEC, (ns % NANOS_PER_SEC) as u32)
}
#[allow(dead_code)]
#[inline]
pub const fn ns_to_ms(ns: u64) -> u64 {
(ns + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI
}
#[inline]
fn get_instant() -> &'static Instant {
// TODO: wait for MaybeUninit::zero stable https://github.com/rust-lang/rust/issues/91850
// use std::mem::MaybeUninit;
// static START_TIME: MaybeUninit<Instant> = MaybeUninit::zeroed();
// unsafe {&*START_TIME.as_ptr() }
lazy_static::lazy_static! {
static ref START_TIME: Instant = Instant::now();
}
&START_TIME
}
// get the current wall clock in ns
#[inline]
pub fn now() -> u64 {
// we need a Monotonic Clock here
get_instant().elapsed().as_nanos() as u64
}
// timeout event data
pub struct TimeoutData<T> {
time: u64, // the wall clock in ns that the timer expires
pub data: T, // the data associate with the timeout event
}
// timeout handler which can be removed/cancelled
pub type TimeoutHandle<T> = Entry<TimeoutData<T>>;
struct TimeoutQueueWrapper<T> {
inner: TimeoutQueue<TimeoutData<T>>,
in_use: AtomicUsize,
}
impl<T> TimeoutQueueWrapper<T> {
fn new() -> Self {
TimeoutQueueWrapper {
inner: TimeoutQueue::new(),
in_use: AtomicUsize::new(0),
}
}
}
type IntervalList<T> = Arc<TimeoutQueueWrapper<T>>;
// this is the data type that used by the binary heap to get the latest timer
struct IntervalEntry<T> {
time: u64, // the head timeout value in the list, should be latest
list: IntervalList<T>, // point to the interval list
interval: u64,
}
impl<T> IntervalEntry<T> {
// trigger the timeout event with the supplying function
// return next expire time
pub fn pop_timeout<F>(&self, now: u64, f: &F) -> Option<u64>
where
F: Fn(T),
{
let p = |v: &TimeoutData<T>| v.time <= now;
while let Some(timeout) = self.list.inner.pop_if(&p) {
f(timeout.data);
}
unsafe { self.list.inner.peek() }.map(|t| t.time)
}
}
impl<T> PartialEq for IntervalEntry<T> {
fn eq(&self, other: &Self) -> bool {
self.time == other.time
}
}
impl<T> Eq for IntervalEntry<T> {}
impl<T> PartialOrd for IntervalEntry<T> {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<T> cmp::Ord for IntervalEntry<T> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
other.time.cmp(&self.time)
}
}
// the timeout list data structure
pub struct TimeOutList<T> {
// interval based hash map, protected by rw lock
interval_map: RwLock<HashMap<u64, IntervalList<T>>>,
// a priority queue, each element is the head of a mpsc queue
timer_bh: Mutex<BinaryHeap<IntervalEntry<T>>>,
}
impl<T> TimeOutList<T> {
pub fn new() -> Self {
TimeOutList {
interval_map: RwLock::new(HashMap::with_capacity(HASH_CAP)),
timer_bh: Mutex::new(BinaryHeap::new()),
}
}
fn install_timer_bh(&self, entry: IntervalEntry<T>) {
if entry.list.in_use.fetch_add(1, Ordering::AcqRel) == 0 {
self.timer_bh.lock().push(entry);
}
}
// add a timeout event to the list
// this can be called in any thread
// return true if we need to recall next expire
pub fn add_timer(&self, dur: Duration, data: T) -> (TimeoutHandle<T>, bool) {
let interval = dur_to_ns(dur);
let time = now() + interval; // TODO: deal with overflow?
//println!("add timer = {:?}", time);
let timeout = TimeoutData { time, data };
let interval_list = {
// use the read lock protect
let interval_map_r = self.interval_map.read();
(*interval_map_r).get(&interval).cloned()
// drop the read lock here
};
if let Some(interval_list) = interval_list {
let (handle, is_head) = interval_list.inner.push(timeout);
if is_head {
// install the interval list to the binary heap
self.install_timer_bh(IntervalEntry {
time,
interval,
list: interval_list,
});
}
return (handle, is_head);
}
// if the interval list is not there, get the write locker to install the list
// use the write lock protect
let mut interval_map_w = self.interval_map.write();
// recheck the interval list in case other thread may install it
if let Some(interval_list) = (*interval_map_w).get(&interval) {
let (handle, is_head) = interval_list.inner.push(timeout);
if is_head {
// this rarely happens
self.install_timer_bh(IntervalEntry {
time,
interval,
list: interval_list.clone(),
});
}
return (handle, is_head);
}
let interval_list = Arc::new(TimeoutQueueWrapper::<T>::new());
let ret = interval_list.inner.push(timeout).0;
(*interval_map_w).insert(interval, interval_list.clone());
// drop the write lock here
mem::drop(interval_map_w);
// install the new interval list to the binary heap
self.install_timer_bh(IntervalEntry {
time,
interval,
list: interval_list,
});
(ret, true)
}
// schedule in the timer thread
// this will remove all the expired timeout event
// and call the supplied function with registered data
// return the time in ns for the next expiration
pub fn schedule_timer<F: Fn(T)>(&self, now: u64, f: &F) -> Option<u64> {
loop {
// first peek the BH to see if there is any timeout event
let mut entry = {
let mut timer_bh = self.timer_bh.lock();
let top_entry = timer_bh.peek();
match top_entry {
// the latest timeout event not happened yet
Some(entry) => {
if entry.time > now {
return Some(entry.time - now);
} else {
// find out one entry
}
}
None => return None,
}
let entry = timer_bh.pop().unwrap();
entry.list.in_use.store(0, Ordering::Release);
entry
};
// consume all the timeout event
// the binary heap can be modified here
// during running the timeout handler
match entry.pop_timeout(now, f) {
Some(time) => {
if entry.list.in_use.fetch_add(1, Ordering::AcqRel) == 0 {
// re-push the entry
entry.time = time;
self.timer_bh.lock().push(entry);
}
}
None => {
// if the interval list is empty, need to delete it
let mut interval_map_w = self.interval_map.write();
// recheck if the interval list is empty, other thread may append data to it
if entry.list.inner.is_empty() {
// if the len of the hash map is big enough just leave the queue there
if (*interval_map_w).len() > HASH_CAP {
// the list is really empty now, we can safely remove it
(*interval_map_w).remove(&entry.interval);
}
} else if entry.list.in_use.fetch_add(1, Ordering::AcqRel) == 0 {
// release the w lock first, we don't need it any more
mem::drop(interval_map_w);
// the list is push some data by other thread
entry.time = unsafe { entry.list.inner.peek() }.unwrap().time;
self.timer_bh.lock().push(entry);
}
}
}
}
}
}
pub struct TimerThread<T> {
timer_list: TimeOutList<T>,
// collect the remove request
remove_list: Queue<TimeoutHandle<T>>,
// the timer thread wakeup handler
wakeup: AtomicOption<thread::Thread>,
}
impl<T> TimerThread<T> {
pub fn new() -> Self {
TimerThread {
timer_list: TimeOutList::new(),
remove_list: Queue::new(),
wakeup: AtomicOption::none(),
}
}
pub fn add_timer(&self, dur: Duration, data: T) -> TimeoutHandle<T> {
let (h, is_recal) = self.timer_list.add_timer(dur, data);
// wake up the timer thread if it's a new queue
if is_recal {
if let Some(t) = self.wakeup.take() {
t.unpark();
}
}
h
}
pub fn del_timer(&self, handle: TimeoutHandle<T>) {
self.remove_list.push(handle);
if let Some(t) = self.wakeup.take() {
t.unpark();
}
}
// the timer thread function
pub fn run<F: Fn(T)>(&self, f: &F) {
let current_thread = thread::current();
loop {
while let Some(h) = self.remove_list.pop() {
h.remove();
}
// we must register the thread handle first
// or there will be no signal to wakeup the timer thread
unsafe { self.wakeup.unsync_store(current_thread.clone()) };
if !self.remove_list.is_empty() {
if let Some(t) = self.wakeup.take() {
t.unpark();
}
}
match self.timer_list.schedule_timer(now(), f) {
Some(time) => thread::park_timeout(ns_to_dur(time)),
None => thread::park(),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
#[test]
fn test_timeout_list() {
let timer = Arc::new(TimerThread::<usize>::new());
let t = timer.clone();
let f = |data: usize| {
println!("timeout data:{data:?}");
};
thread::spawn(move || t.run(&f));
let t1 = timer.clone();
thread::spawn(move || {
t1.add_timer(Duration::from_millis(1000), 50);
t1.add_timer(Duration::from_millis(1000), 60);
t1.add_timer(Duration::from_millis(1400), 70);
});
thread::sleep(Duration::from_millis(10));
timer.add_timer(Duration::from_millis(1000), 10);
timer.add_timer(Duration::from_millis(500), 40);
timer.add_timer(Duration::from_millis(1200), 20);
thread::sleep(Duration::from_millis(100));
timer.add_timer(Duration::from_millis(1000), 30);
thread::sleep(Duration::from_millis(1500));
}
}
|
/*
* YNAB API Endpoints
*
* Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudget.com
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct ScheduledTransactionDetail {
#[serde(rename = "id")]
pub id: String,
/// The first date for which the Scheduled Transaction was scheduled.
#[serde(rename = "date_first")]
pub date_first: String,
/// The next date for which the Scheduled Transaction is scheduled.
#[serde(rename = "date_next")]
pub date_next: String,
#[serde(rename = "frequency")]
pub frequency: Frequency,
/// The scheduled transaction amount in milliunits format
#[serde(rename = "amount")]
pub amount: i64,
#[serde(rename = "memo", skip_serializing_if = "Option::is_none")]
pub memo: Option<String>,
/// The scheduled transaction flag
#[serde(rename = "flag_color", skip_serializing_if = "Option::is_none")]
pub flag_color: Option<FlagColor>,
#[serde(rename = "account_id")]
pub account_id: String,
#[serde(rename = "payee_id", skip_serializing_if = "Option::is_none")]
pub payee_id: Option<String>,
#[serde(rename = "category_id", skip_serializing_if = "Option::is_none")]
pub category_id: Option<String>,
/// If a transfer, the account_id which the scheduled transaction transfers to
#[serde(rename = "transfer_account_id", skip_serializing_if = "Option::is_none")]
pub transfer_account_id: Option<String>,
/// Whether or not the scheduled transaction has been deleted. Deleted scheduled transactions will only be included in delta requests.
#[serde(rename = "deleted")]
pub deleted: bool,
#[serde(rename = "account_name")]
pub account_name: String,
#[serde(rename = "payee_name", skip_serializing_if = "Option::is_none")]
pub payee_name: Option<String>,
#[serde(rename = "category_name", skip_serializing_if = "Option::is_none")]
pub category_name: Option<String>,
/// If a split scheduled transaction, the subtransactions.
#[serde(rename = "subtransactions")]
pub subtransactions: Vec<crate::models::ScheduledSubTransaction>,
}
impl ScheduledTransactionDetail {
pub fn new(id: String, date_first: String, date_next: String, frequency: Frequency, amount: i64, account_id: String, deleted: bool, account_name: String, subtransactions: Vec<crate::models::ScheduledSubTransaction>) -> ScheduledTransactionDetail {
ScheduledTransactionDetail {
id,
date_first,
date_next,
frequency,
amount,
memo: None,
flag_color: None,
account_id,
payee_id: None,
category_id: None,
transfer_account_id: None,
deleted,
account_name,
payee_name: None,
category_name: None,
subtransactions,
}
}
}
///
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum Frequency {
#[serde(rename = "never")]
Never,
#[serde(rename = "daily")]
Daily,
#[serde(rename = "weekly")]
Weekly,
#[serde(rename = "everyOtherWeek")]
EveryOtherWeek,
#[serde(rename = "twiceAMonth")]
TwiceAMonth,
#[serde(rename = "every4Weeks")]
Every4Weeks,
#[serde(rename = "monthly")]
Monthly,
#[serde(rename = "everyOtherMonth")]
EveryOtherMonth,
#[serde(rename = "every3Months")]
Every3Months,
#[serde(rename = "every4Months")]
Every4Months,
#[serde(rename = "twiceAYear")]
TwiceAYear,
#[serde(rename = "yearly")]
Yearly,
#[serde(rename = "everyOtherYear")]
EveryOtherYear,
}
/// The scheduled transaction flag
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum FlagColor {
#[serde(rename = "red")]
Red,
#[serde(rename = "orange")]
Orange,
#[serde(rename = "yellow")]
Yellow,
#[serde(rename = "green")]
Green,
#[serde(rename = "blue")]
Blue,
#[serde(rename = "purple")]
Purple,
}
|
use crate::aoc_utils::read_input;
pub fn run(input_filename: &str) {
let input = read_input(input_filename);
let mapped: Vec<Vec<char>> = input.lines().map(|l| l.chars().collect()).collect();
part1(&mapped);
part2(&mapped);
}
const TREE: char = '#';
fn count_trees_on_slope(mapped: &Vec<Vec<char>>, step_x: usize, step_y: usize) -> u128 {
let mut start_x = 0;
let mut start_y = 0;
let mut tree_count = 0;
let map_max_x = mapped[start_y].len();
while start_y < mapped.len() {
if mapped[start_y][start_x] == TREE {
tree_count += 1;
}
start_x += step_x;
start_y += step_y;
if start_x >= map_max_x {
start_x -= map_max_x;
}
}
return tree_count;
}
fn part1(mapped: &Vec<Vec<char>>) {
println!("Part1: {}", count_trees_on_slope(&mapped, 3, 1))
}
const TO_CHECK: [(usize, usize); 5] = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)];
fn part2(mapped: &Vec<Vec<char>>) {
let mut tree_count: u128 = 1; // Since we're multiplying we start on one
TO_CHECK.iter().for_each(|(step_x, step_y)| {
tree_count *= count_trees_on_slope(&mapped, *step_x, *step_y);
});
println!("Part2: {}", tree_count)
}
|
use std::collections::HashMap;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Provide a space-separated list of integers.");
return;
}
let mut list: Vec<i32> = args[1..]
.iter()
.map(|x| x.trim().parse().expect("Integers only"))
.collect();
list.sort();
let len = list.len();
let mean = list.iter().fold(0, |acc, x| acc + x) as f64 / (len as f64);
let median = if len % 2 == 0 {
(list[len / 2 - 1] + list[len / 2]) as f64 / 2.0
} else {
list[len / 2] as f64
};
let mut map = HashMap::new();
for x in list {
let count = map.entry(x).or_insert(0);
*count += 1;
}
let max = *map.values().max().unwrap();
let mode = map.iter().find(|(_, &val)| val == max).unwrap().0;
println!("Mean: {:.3}\nMedian: {}\nMode: {}", mean, median, mode);
}
|
pub use auth::Auth;
mod auth;
|
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2016 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT.
#[repr(C)]
pub struct ibv_device_attr_ex
{
pub orig_attr: ibv_device_attr,
pub comp_mask: u32,
pub odp_caps: ibv_odp_caps,
pub completion_timestamp_mask: u64,
pub hca_core_clock: u64,
pub device_cap_flags_ex: u64,
pub tso_caps: ibv_tso_caps,
pub rss_caps: ibv_rss_caps,
pub max_wq_type_rq: u32,
pub packet_pacing_caps: ibv_packet_pacing_caps,
pub raw_packet_caps: u32,
pub tm_caps: ibv_tm_caps,
pub cq_mod_caps: ibv_cq_moderation_caps,
}
impl Default for ibv_device_attr_ex
{
#[inline(always)]
fn default() -> Self
{
unsafe { zeroed() }
}
}
impl Debug for ibv_device_attr_ex
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter) -> Result
{
write!(f, "ibv_device_attr_ex {{ orig_attr: {:?}, odp_caps: {:?}, tso_caps: {:?}, rss_caps: {:?}, packet_pacing_caps: {:?}, tm_caps: {:?}, cq_mod_caps: {:?} }}", self.orig_attr, self.odp_caps, self.tso_caps, self.rss_caps, self.packet_pacing_caps, self.tm_caps, self.cq_mod_caps)
}
}
|
use std::fs;
use regex::Regex;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bag {
color_code: String,
count: usize,
}
impl Bag {
pub fn new(color_code: String, count: usize) -> Bag {
Bag{ color_code, count }
}
pub fn parse(text: &str) -> Option<Bag> {
// Split out bag info (ex: "1 dotted black bag")
lazy_static! {
static ref BAG: Regex = Regex::new(r"^(\d+) (\w+ \w+) bags?\.?$").unwrap();
}
if !BAG.is_match(&text) {
return None;
}
let caps = BAG.captures(text).unwrap();
let count = caps.get(1).unwrap().as_str().parse::<usize>().unwrap();
let color_code = caps.get(2).unwrap().as_str().to_string();
Some(Bag{ color_code, count })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rule {
outer: Bag,
inner: Vec<Bag>,
}
impl Rule {
pub fn new(outer: Bag, inner: Vec<Bag>) -> Rule {
Rule { outer, inner }
}
pub fn parse(line: &str) -> Rule {
let p: Vec<&str> = line.split(" contain ").collect();
assert_eq!(p.len(), 2);
Rule {
outer: Bag::parse(&format!("1 {}", p[0])).unwrap(), // Workaround to add a '1' count to the outer bag
inner: p[1].split(", ")
.map(|t| Bag::parse(t))
.filter(|x| x.is_some())
.map(|x| x.unwrap())
.collect()
}
}
}
pub fn day7(args: &[String]) -> i32 {
println!("Day 7");
if args.len() != 1 {
println!("Missing input file");
return -1;
}
let filename = &args[0];
println!("In file {}", filename);
let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file");
let rules: Vec<Rule> = contents.lines().map(|l| Rule::parse(l)).collect();
println!("Rules {:?}", rules.len());
// Part 1
println!("Part 1: {}", part1("shiny gold", &rules));
// Part 2
println!("Part 2: {}", part2("shiny gold", &rules));
0
}
pub fn part1(color_code: &str, rules: &Vec<Rule>) -> usize {
let result: Vec<(String, bool)> =
rules.iter()
.map(|r| (r.outer.color_code.to_string(), contains_bag(color_code, &r, &rules)))
.collect();
// count the bags that can contain (excluding itself, the reson for the -1)
result.iter().filter(|(_c, r)| *r).count() - 1
}
pub fn contains_bag(color_code: &str, current: &Rule, rules: &Vec<Rule>) -> bool {
if color_code == ¤t.outer.color_code {
return true;
}
for i in ¤t.inner {
// find the bag rule
for r in rules {
if r.outer.color_code == i.color_code {
// recursively traverse tree
if contains_bag(&color_code, r, rules) {
return true;
}
}
}
}
false
}
pub fn part2(color_code: &str, rules: &Vec<Rule>) -> usize {
let r = rules.iter().find(|r| color_code == &r.outer.color_code);
if r.is_some() {
// count the bags (excluding itself, the reson for the -1)
return inner_bag_count(r.unwrap(), rules) - 1;
}
0
}
pub fn inner_bag_count(current: &Rule, rules: &Vec<Rule>) -> usize {
let mut bag_count = 1;
for i in ¤t.inner {
// find the bag rule
for r in rules {
if r.outer.color_code == i.color_code {
// recursively traverse tree
bag_count += i.count * inner_bag_count(r, rules);
}
}
}
bag_count
} |
use colored::*;
use std::env;
use std::process::Command;
use anyhow::{Context, Result};
use clap::ArgMatches;
use crate::cli::cfg::get_cfg;
use crate::cli::error::CliError;
use crate::cli::settings::get_settings;
use crate::cli::terminal::message::success;
use super::sync::{sync_workflow, SyncSettings};
pub fn env_edit(app: &ArgMatches) -> Result<()> {
let mut cfg = get_cfg()?;
cfg.sync_local_to_global()?;
let cfg = cfg;
let settings = get_settings(app, &cfg);
let env_name = settings.env()?;
let editor = app.value_of("editor");
let sync_settings = SyncSettings::new(app);
let setup = cfg.current_setup(settings.setup()?)?;
let env_file = setup.env_file(env_name)?;
let command = |editor: &str| Command::new(editor).arg(&env_file).status();
let exist_code = if let Some(editor) = editor {
command(editor)?
} else if let Ok(editor) = env::var("EDITOR") {
command(editor.as_str())?
} else {
open::that(&env_file)?
};
if exist_code.code().is_none() || exist_code.code().unwrap() > 0 {
return Err(CliError::OpenEditorFail.into());
}
let env = setup
.env(env_name)
.context(format!("fail to check env file `{}`", env_name.bold()))?;
success(format!("`{}` edited", env_name.bold()).as_str());
let envs = setup.envs().into_iter().filter_map(|r| r.ok()).collect();
sync_workflow(env, envs, sync_settings)?;
Ok(())
}
|
use anyhow::Context;
use rusqlite::Transaction;
pub(crate) fn migrate(transaction: &Transaction<'_>) -> anyhow::Result<()> {
// We need to check if this db needs fixing at all
let update_is_not_required = {
let mut stmt = transaction
.prepare("SELECT sql FROM sqlite_schema where tbl_name = 'starknet_events'")
.context("Preparing statement")?;
let mut rows = stmt.query([]).context("Executing query")?;
// Unwrap is safe because the schema for this table obviously contains more than
// zero SQL statements, as can be seen in revision 7 migration.
// The first statement of the schema for this table is the creation of the table
// which could be missing the crucial action, which is ON DELETE CASCADE.
rows.next()?
.unwrap()
.get_ref_unwrap("sql")
.as_str()?
.contains("ON DELETE CASCADE")
};
if update_is_not_required {
return Ok(());
}
// When altering a table in a way that requires recreating it through copying and deletion
// it is [recommended](https://www.sqlite.org/lang_altertable.html) to:
// 1. create the new table with some temporary name
// 2. copy the data from the old table
// 3. drop the old table
// 4. rename the new table
// Instead of the opposite:
// 1. rename the old table
// 2. create the new table with the final name
// 3. copy the data from the old table
// 4. drop the old table
//
// Important notes:
// 1. Triggers and indexes are dropped with the old `starknet_events` table,
// so they need to be recreated
// 2. The virtual table `starknet_events_keys` remains unchanged but:
// - we need to make sure that the new `starknet_events` table
// [keeps the same rowids](https://www.sqlite.org/fts5.html#external_content_tables)
// as its older version
// - otherwise `starknet_events_keys` could refer invalid rowids
// - rendering future event queries unreliable
transaction
.execute_batch(
r"
CREATE TABLE starknet_events_v2 (
block_number INTEGER NOT NULL,
idx INTEGER NOT NULL,
transaction_hash BLOB NOT NULL,
from_address BLOB NOT NULL,
-- Keys are represented as base64 encoded strings separated by space
keys TEXT,
data BLOB,
FOREIGN KEY(block_number) REFERENCES starknet_blocks(number)
ON DELETE CASCADE
);
-- Copy rowids to be sure that starknet_events_keys still references valid rows
INSERT INTO starknet_events_v2 (
rowid,
block_number,
idx,
transaction_hash,
from_address,
keys,
data)
SELECT starknet_events.rowid,
starknet_events.block_number,
starknet_events.idx,
starknet_events.transaction_hash,
starknet_events.from_address,
starknet_events.keys,
starknet_events.data
FROM starknet_events;
DROP TABLE starknet_events;
ALTER TABLE starknet_events_v2 RENAME TO starknet_events;
-- Event filters can specify ranges of blocks
CREATE INDEX starknet_events_block_number ON starknet_events(block_number);
-- Event filter can specify a contract address
CREATE INDEX starknet_events_from_address ON starknet_events(from_address);
CREATE TRIGGER starknet_events_ai
AFTER INSERT ON starknet_events
BEGIN
INSERT INTO starknet_events_keys(rowid, keys)
VALUES (
new.rowid,
new.keys
);
END;
CREATE TRIGGER starknet_events_ad
AFTER DELETE ON starknet_events
BEGIN
INSERT INTO starknet_events_keys(starknet_events_keys, rowid, keys)
VALUES (
'delete',
old.rowid,
old.keys
);
END;
CREATE TRIGGER starknet_events_au
AFTER UPDATE ON starknet_events
BEGIN
INSERT INTO starknet_events_keys(starknet_events_keys, rowid, keys)
VALUES (
'delete',
old.rowid,
old.keys
);
INSERT INTO starknet_events_keys(rowid, keys)
VALUES (
new.rowid,
new.keys
);
END;",
)
.context("Recreating the starknet_events table, related triggers and indexes")?;
Ok(())
}
|
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct BenchGroup {
pub group_name: String,
pub ids: Vec<BenchID>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BenchID {
pub id: String,
pub entries: Vec<BenchEntry>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BenchEntry {
pub val: f32,
pub times: Vec<u64>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EvalGroup {
pub group_name: String,
pub ids: Vec<EvalID>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EvalID {
pub id: String,
pub entries: Vec<EvalEntry>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EvalEntry {
pub x: f32,
pub y: u32,
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Object {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseInstanceCollection {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DatabaseInstance>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseInstance {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DatabaseInstanceProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseInstanceProperties {
#[serde(rename = "discoveryData", default, skip_serializing_if = "Vec::is_empty")]
pub discovery_data: Vec<DatabaseInstanceDiscoveryDetails>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<serde_json::Value>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseInstanceDiscoveryDetails {
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
#[serde(rename = "instanceId", default, skip_serializing_if = "Option::is_none")]
pub instance_id: Option<String>,
#[serde(rename = "enqueueTime", default, skip_serializing_if = "Option::is_none")]
pub enqueue_time: Option<String>,
#[serde(rename = "solutionName", default, skip_serializing_if = "Option::is_none")]
pub solution_name: Option<String>,
#[serde(rename = "instanceName", default, skip_serializing_if = "Option::is_none")]
pub instance_name: Option<String>,
#[serde(rename = "instanceVersion", default, skip_serializing_if = "Option::is_none")]
pub instance_version: Option<String>,
#[serde(rename = "instanceType", default, skip_serializing_if = "Option::is_none")]
pub instance_type: Option<String>,
#[serde(rename = "hostName", default, skip_serializing_if = "Option::is_none")]
pub host_name: Option<String>,
#[serde(rename = "ipAddress", default, skip_serializing_if = "Option::is_none")]
pub ip_address: Option<String>,
#[serde(rename = "portNumber", default, skip_serializing_if = "Option::is_none")]
pub port_number: Option<i32>,
#[serde(rename = "extendedInfo", default, skip_serializing_if = "Option::is_none")]
pub extended_info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseInstanceSummary {
#[serde(rename = "databasesAssessedCount", default, skip_serializing_if = "Option::is_none")]
pub databases_assessed_count: Option<i32>,
#[serde(rename = "migrationReadyCount", default, skip_serializing_if = "Option::is_none")]
pub migration_ready_count: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseCollection {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Database>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Database {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DatabaseProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseProperties {
#[serde(rename = "assessmentData", default, skip_serializing_if = "Vec::is_empty")]
pub assessment_data: Vec<DatabaseAssessmentDetails>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseAssessmentDetails {
#[serde(rename = "assessmentId", default, skip_serializing_if = "Option::is_none")]
pub assessment_id: Option<String>,
#[serde(rename = "migrationBlockersCount", default, skip_serializing_if = "Option::is_none")]
pub migration_blockers_count: Option<i32>,
#[serde(rename = "breakingChangesCount", default, skip_serializing_if = "Option::is_none")]
pub breaking_changes_count: Option<i32>,
#[serde(rename = "isReadyForMigration", default, skip_serializing_if = "Option::is_none")]
pub is_ready_for_migration: Option<bool>,
#[serde(rename = "assessmentTargetType", default, skip_serializing_if = "Option::is_none")]
pub assessment_target_type: Option<String>,
#[serde(rename = "lastAssessedTime", default, skip_serializing_if = "Option::is_none")]
pub last_assessed_time: Option<String>,
#[serde(rename = "compatibilityLevel", default, skip_serializing_if = "Option::is_none")]
pub compatibility_level: Option<String>,
#[serde(rename = "databaseSizeInMB", default, skip_serializing_if = "Option::is_none")]
pub database_size_in_mb: Option<String>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
#[serde(rename = "enqueueTime", default, skip_serializing_if = "Option::is_none")]
pub enqueue_time: Option<String>,
#[serde(rename = "solutionName", default, skip_serializing_if = "Option::is_none")]
pub solution_name: Option<String>,
#[serde(rename = "instanceId", default, skip_serializing_if = "Option::is_none")]
pub instance_id: Option<String>,
#[serde(rename = "databaseName", default, skip_serializing_if = "Option::is_none")]
pub database_name: Option<String>,
#[serde(rename = "extendedInfo", default, skip_serializing_if = "Option::is_none")]
pub extended_info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EventCollection {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<MigrateEvent>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MigrateEvent {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MigrateEventProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MigrateEventProperties {
#[serde(rename = "instanceType", default, skip_serializing_if = "Option::is_none")]
pub instance_type: Option<String>,
#[serde(rename = "errorCode", default, skip_serializing_if = "Option::is_none")]
pub error_code: Option<String>,
#[serde(rename = "errorMessage", default, skip_serializing_if = "Option::is_none")]
pub error_message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recommendation: Option<String>,
#[serde(rename = "possibleCauses", default, skip_serializing_if = "Option::is_none")]
pub possible_causes: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub solution: Option<String>,
#[serde(rename = "clientRequestId", default, skip_serializing_if = "Option::is_none")]
pub client_request_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ODataQueryOptions1 {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<FilterQueryOption>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ODataQueryContext {
#[serde(rename = "defaultQuerySettings", default, skip_serializing_if = "Option::is_none")]
pub default_query_settings: Option<DefaultQuerySettings>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<IEdmModel>,
#[serde(rename = "elementType", default, skip_serializing_if = "Option::is_none")]
pub element_type: Option<IEdmType>,
#[serde(rename = "navigationSource", default, skip_serializing_if = "Option::is_none")]
pub navigation_source: Option<IEdmNavigationSource>,
#[serde(rename = "elementClrType", default, skip_serializing_if = "Option::is_none")]
pub element_clr_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<ODataPath>,
#[serde(rename = "requestContainer", default, skip_serializing_if = "Option::is_none")]
pub request_container: Option<IServiceProvider>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ODataRawQueryOptions {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FilterQueryOption {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context: Option<ODataQueryContext>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub validator: Option<FilterQueryValidator>,
#[serde(rename = "filterClause", default, skip_serializing_if = "Option::is_none")]
pub filter_clause: Option<FilterClause>,
#[serde(rename = "rawValue", default, skip_serializing_if = "Option::is_none")]
pub raw_value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ODataQueryValidator {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DefaultQuerySettings {
#[serde(rename = "enableExpand", default, skip_serializing_if = "Option::is_none")]
pub enable_expand: Option<bool>,
#[serde(rename = "enableSelect", default, skip_serializing_if = "Option::is_none")]
pub enable_select: Option<bool>,
#[serde(rename = "enableCount", default, skip_serializing_if = "Option::is_none")]
pub enable_count: Option<bool>,
#[serde(rename = "enableOrderBy", default, skip_serializing_if = "Option::is_none")]
pub enable_order_by: Option<bool>,
#[serde(rename = "enableFilter", default, skip_serializing_if = "Option::is_none")]
pub enable_filter: Option<bool>,
#[serde(rename = "maxTop", default, skip_serializing_if = "Option::is_none")]
pub max_top: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmModel {
#[serde(rename = "schemaElements", default, skip_serializing_if = "Vec::is_empty")]
pub schema_elements: Vec<IEdmSchemaElement>,
#[serde(rename = "vocabularyAnnotations", default, skip_serializing_if = "Vec::is_empty")]
pub vocabulary_annotations: Vec<IEdmVocabularyAnnotation>,
#[serde(rename = "referencedModels", default, skip_serializing_if = "Vec::is_empty")]
pub referenced_models: Vec<IEdmModel>,
#[serde(rename = "declaredNamespaces", default, skip_serializing_if = "Vec::is_empty")]
pub declared_namespaces: Vec<String>,
#[serde(rename = "directValueAnnotationsManager", default, skip_serializing_if = "Option::is_none")]
pub direct_value_annotations_manager: Option<IEdmDirectValueAnnotationsManager>,
#[serde(rename = "entityContainer", default, skip_serializing_if = "Option::is_none")]
pub entity_container: Option<IEdmEntityContainer>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmType {
#[serde(rename = "typeKind", default, skip_serializing_if = "Option::is_none")]
pub type_kind: Option<i_edm_type::TypeKind>,
}
pub mod i_edm_type {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TypeKind {
None,
Primitive,
Entity,
Complex,
Collection,
EntityReference,
Enum,
TypeDefinition,
Untyped,
Path,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmNavigationSource {
#[serde(rename = "navigationPropertyBindings", default, skip_serializing_if = "Vec::is_empty")]
pub navigation_property_bindings: Vec<IEdmNavigationPropertyBinding>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<IEdmPathExpression>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<IEdmType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ODataPath {
#[serde(rename = "edmType", default, skip_serializing_if = "Option::is_none")]
pub edm_type: Option<IEdmType>,
#[serde(rename = "navigationSource", default, skip_serializing_if = "Option::is_none")]
pub navigation_source: Option<IEdmNavigationSource>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub segments: Vec<ODataPathSegment>,
#[serde(rename = "pathTemplate", default, skip_serializing_if = "Option::is_none")]
pub path_template: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub path: Vec<ODataPathSegment>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IServiceProvider {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SelectExpandQueryValidator {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SelectExpandClause {
#[serde(rename = "selectedItems", default, skip_serializing_if = "Vec::is_empty")]
pub selected_items: Vec<SelectItem>,
#[serde(rename = "allSelected", default, skip_serializing_if = "Option::is_none")]
pub all_selected: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ApplyClause {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub transformations: Vec<TransformationNode>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FilterQueryValidator {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FilterClause {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expression: Option<SingleValueNode>,
#[serde(rename = "rangeVariable", default, skip_serializing_if = "Option::is_none")]
pub range_variable: Option<RangeVariable>,
#[serde(rename = "itemType", default, skip_serializing_if = "Option::is_none")]
pub item_type: Option<IEdmTypeReference>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmSchemaElement {
#[serde(rename = "schemaElementKind", default, skip_serializing_if = "Option::is_none")]
pub schema_element_kind: Option<i_edm_schema_element::SchemaElementKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
pub mod i_edm_schema_element {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SchemaElementKind {
None,
TypeDefinition,
Term,
Action,
EntityContainer,
Function,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmVocabularyAnnotation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub qualifier: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub term: Option<IEdmTerm>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<IEdmVocabularyAnnotatable>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<IEdmExpression>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmDirectValueAnnotationsManager {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmEntityContainer {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub elements: Vec<IEdmEntityContainerElement>,
#[serde(rename = "schemaElementKind", default, skip_serializing_if = "Option::is_none")]
pub schema_element_kind: Option<i_edm_entity_container::SchemaElementKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
pub mod i_edm_entity_container {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SchemaElementKind {
None,
TypeDefinition,
Term,
Action,
EntityContainer,
Function,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmNavigationPropertyBinding {
#[serde(rename = "navigationProperty", default, skip_serializing_if = "Option::is_none")]
pub navigation_property: Option<IEdmNavigationProperty>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<IEdmNavigationSource>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<IEdmPathExpression>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmPathExpression {
#[serde(rename = "pathSegments", default, skip_serializing_if = "Vec::is_empty")]
pub path_segments: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(rename = "expressionKind", default, skip_serializing_if = "Option::is_none")]
pub expression_kind: Option<i_edm_path_expression::ExpressionKind>,
}
pub mod i_edm_path_expression {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ExpressionKind {
None,
BinaryConstant,
BooleanConstant,
DateTimeOffsetConstant,
DecimalConstant,
FloatingConstant,
GuidConstant,
IntegerConstant,
StringConstant,
DurationConstant,
Null,
Record,
Collection,
Path,
If,
Cast,
IsType,
FunctionApplication,
LabeledExpressionReference,
Labeled,
PropertyPath,
NavigationPropertyPath,
DateConstant,
TimeOfDayConstant,
EnumMember,
AnnotationPath,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ODataPathSegment {
#[serde(rename = "edmType", default, skip_serializing_if = "Option::is_none")]
pub edm_type: Option<IEdmType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identifier: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SelectItem {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TransformationNode {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<transformation_node::Kind>,
}
pub mod transformation_node {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Kind {
Aggregate,
GroupBy,
Filter,
Compute,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SingleValueNode {
#[serde(rename = "typeReference", default, skip_serializing_if = "Option::is_none")]
pub type_reference: Option<IEdmTypeReference>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<single_value_node::Kind>,
}
pub mod single_value_node {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Kind {
None,
Constant,
Convert,
NonResourceRangeVariableReference,
BinaryOperator,
UnaryOperator,
SingleValuePropertyAccess,
CollectionPropertyAccess,
SingleValueFunctionCall,
Any,
CollectionNavigationNode,
SingleNavigationNode,
SingleValueOpenPropertyAccess,
SingleResourceCast,
All,
CollectionResourceCast,
ResourceRangeVariableReference,
SingleResourceFunctionCall,
CollectionFunctionCall,
CollectionResourceFunctionCall,
NamedFunctionParameter,
ParameterAlias,
EntitySet,
KeyLookup,
SearchTerm,
CollectionOpenPropertyAccess,
CollectionComplexNode,
SingleComplexNode,
Count,
SingleValueCast,
CollectionPropertyNode,
AggregatedCollectionPropertyNode,
In,
CollectionConstant,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RangeVariable {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "typeReference", default, skip_serializing_if = "Option::is_none")]
pub type_reference: Option<IEdmTypeReference>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmTypeReference {
#[serde(rename = "isNullable", default, skip_serializing_if = "Option::is_none")]
pub is_nullable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub definition: Option<IEdmType>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmTerm {
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<IEdmTypeReference>,
#[serde(rename = "appliesTo", default, skip_serializing_if = "Option::is_none")]
pub applies_to: Option<String>,
#[serde(rename = "defaultValue", default, skip_serializing_if = "Option::is_none")]
pub default_value: Option<String>,
#[serde(rename = "schemaElementKind", default, skip_serializing_if = "Option::is_none")]
pub schema_element_kind: Option<i_edm_term::SchemaElementKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
pub mod i_edm_term {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SchemaElementKind {
None,
TypeDefinition,
Term,
Action,
EntityContainer,
Function,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmVocabularyAnnotatable {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmExpression {
#[serde(rename = "expressionKind", default, skip_serializing_if = "Option::is_none")]
pub expression_kind: Option<i_edm_expression::ExpressionKind>,
}
pub mod i_edm_expression {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ExpressionKind {
None,
BinaryConstant,
BooleanConstant,
DateTimeOffsetConstant,
DecimalConstant,
FloatingConstant,
GuidConstant,
IntegerConstant,
StringConstant,
DurationConstant,
Null,
Record,
Collection,
Path,
If,
Cast,
IsType,
FunctionApplication,
LabeledExpressionReference,
Labeled,
PropertyPath,
NavigationPropertyPath,
DateConstant,
TimeOfDayConstant,
EnumMember,
AnnotationPath,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmEntityContainerElement {
#[serde(rename = "containerElementKind", default, skip_serializing_if = "Option::is_none")]
pub container_element_kind: Option<i_edm_entity_container_element::ContainerElementKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub container: Option<IEdmEntityContainer>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
pub mod i_edm_entity_container_element {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ContainerElementKind {
None,
EntitySet,
ActionImport,
FunctionImport,
Singleton,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmNavigationProperty {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partner: Box<Option<IEdmNavigationProperty>>,
#[serde(rename = "onDelete", default, skip_serializing_if = "Option::is_none")]
pub on_delete: Option<i_edm_navigation_property::OnDelete>,
#[serde(rename = "containsTarget", default, skip_serializing_if = "Option::is_none")]
pub contains_target: Option<bool>,
#[serde(rename = "referentialConstraint", default, skip_serializing_if = "Option::is_none")]
pub referential_constraint: Option<IEdmReferentialConstraint>,
#[serde(rename = "propertyKind", default, skip_serializing_if = "Option::is_none")]
pub property_kind: Option<i_edm_navigation_property::PropertyKind>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<IEdmTypeReference>,
#[serde(rename = "declaringType", default, skip_serializing_if = "Option::is_none")]
pub declaring_type: Option<IEdmStructuredType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
pub mod i_edm_navigation_property {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum OnDelete {
None,
Cascade,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PropertyKind {
None,
Structural,
Navigation,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmReferentialConstraint {
#[serde(rename = "propertyPairs", default, skip_serializing_if = "Vec::is_empty")]
pub property_pairs: Vec<EdmReferentialConstraintPropertyPair>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmStructuredType {
#[serde(rename = "isAbstract", default, skip_serializing_if = "Option::is_none")]
pub is_abstract: Option<bool>,
#[serde(rename = "isOpen", default, skip_serializing_if = "Option::is_none")]
pub is_open: Option<bool>,
#[serde(rename = "baseType", default, skip_serializing_if = "Option::is_none")]
pub base_type: Box<Option<IEdmStructuredType>>,
#[serde(rename = "declaredProperties", default, skip_serializing_if = "Vec::is_empty")]
pub declared_properties: Vec<IEdmProperty>,
#[serde(rename = "typeKind", default, skip_serializing_if = "Option::is_none")]
pub type_kind: Option<i_edm_structured_type::TypeKind>,
}
pub mod i_edm_structured_type {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TypeKind {
None,
Primitive,
Entity,
Complex,
Collection,
EntityReference,
Enum,
TypeDefinition,
Untyped,
Path,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EdmReferentialConstraintPropertyPair {
#[serde(rename = "dependentProperty", default, skip_serializing_if = "Option::is_none")]
pub dependent_property: Option<IEdmStructuralProperty>,
#[serde(rename = "principalProperty", default, skip_serializing_if = "Option::is_none")]
pub principal_property: Option<IEdmStructuralProperty>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmProperty {
#[serde(rename = "propertyKind", default, skip_serializing_if = "Option::is_none")]
pub property_kind: Option<i_edm_property::PropertyKind>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<IEdmTypeReference>,
#[serde(rename = "declaringType", default, skip_serializing_if = "Option::is_none")]
pub declaring_type: Option<IEdmStructuredType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
pub mod i_edm_property {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PropertyKind {
None,
Structural,
Navigation,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct IEdmStructuralProperty {
#[serde(rename = "defaultValueString", default, skip_serializing_if = "Option::is_none")]
pub default_value_string: Option<String>,
#[serde(rename = "propertyKind", default, skip_serializing_if = "Option::is_none")]
pub property_kind: Option<i_edm_structural_property::PropertyKind>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<IEdmTypeReference>,
#[serde(rename = "declaringType", default, skip_serializing_if = "Option::is_none")]
pub declaring_type: Option<IEdmStructuredType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
pub mod i_edm_structural_property {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PropertyKind {
None,
Structural,
Navigation,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MachineCollection {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Machine>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Machine {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MachineProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MachineProperties {
#[serde(rename = "discoveryData", default, skip_serializing_if = "Vec::is_empty")]
pub discovery_data: Vec<DiscoveryDetails>,
#[serde(rename = "assessmentData", default, skip_serializing_if = "Vec::is_empty")]
pub assessment_data: Vec<AssessmentDetails>,
#[serde(rename = "migrationData", default, skip_serializing_if = "Vec::is_empty")]
pub migration_data: Vec<MigrationDetails>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DiscoveryDetails {
#[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")]
pub os_type: Option<String>,
#[serde(rename = "osName", default, skip_serializing_if = "Option::is_none")]
pub os_name: Option<String>,
#[serde(rename = "osVersion", default, skip_serializing_if = "Option::is_none")]
pub os_version: Option<String>,
#[serde(rename = "enqueueTime", default, skip_serializing_if = "Option::is_none")]
pub enqueue_time: Option<String>,
#[serde(rename = "solutionName", default, skip_serializing_if = "Option::is_none")]
pub solution_name: Option<String>,
#[serde(rename = "machineId", default, skip_serializing_if = "Option::is_none")]
pub machine_id: Option<String>,
#[serde(rename = "machineManagerId", default, skip_serializing_if = "Option::is_none")]
pub machine_manager_id: Option<String>,
#[serde(rename = "fabricType", default, skip_serializing_if = "Option::is_none")]
pub fabric_type: Option<String>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
#[serde(rename = "machineName", default, skip_serializing_if = "Option::is_none")]
pub machine_name: Option<String>,
#[serde(rename = "ipAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub ip_addresses: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fqdn: Option<String>,
#[serde(rename = "biosId", default, skip_serializing_if = "Option::is_none")]
pub bios_id: Option<String>,
#[serde(rename = "macAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub mac_addresses: Vec<String>,
#[serde(rename = "extendedInfo", default, skip_serializing_if = "Option::is_none")]
pub extended_info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AssessmentDetails {
#[serde(rename = "assessmentId", default, skip_serializing_if = "Option::is_none")]
pub assessment_id: Option<String>,
#[serde(rename = "targetVMSize", default, skip_serializing_if = "Option::is_none")]
pub target_vm_size: Option<String>,
#[serde(rename = "targetVMLocation", default, skip_serializing_if = "Option::is_none")]
pub target_vm_location: Option<String>,
#[serde(rename = "targetStorageType", default, skip_serializing_if = "Option::is_none")]
pub target_storage_type: Option<serde_json::Value>,
#[serde(rename = "enqueueTime", default, skip_serializing_if = "Option::is_none")]
pub enqueue_time: Option<String>,
#[serde(rename = "solutionName", default, skip_serializing_if = "Option::is_none")]
pub solution_name: Option<String>,
#[serde(rename = "machineId", default, skip_serializing_if = "Option::is_none")]
pub machine_id: Option<String>,
#[serde(rename = "machineManagerId", default, skip_serializing_if = "Option::is_none")]
pub machine_manager_id: Option<String>,
#[serde(rename = "fabricType", default, skip_serializing_if = "Option::is_none")]
pub fabric_type: Option<String>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
#[serde(rename = "machineName", default, skip_serializing_if = "Option::is_none")]
pub machine_name: Option<String>,
#[serde(rename = "ipAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub ip_addresses: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fqdn: Option<String>,
#[serde(rename = "biosId", default, skip_serializing_if = "Option::is_none")]
pub bios_id: Option<String>,
#[serde(rename = "macAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub mac_addresses: Vec<String>,
#[serde(rename = "extendedInfo", default, skip_serializing_if = "Option::is_none")]
pub extended_info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MigrationDetails {
#[serde(rename = "migrationPhase", default, skip_serializing_if = "Option::is_none")]
pub migration_phase: Option<String>,
#[serde(rename = "migrationTested", default, skip_serializing_if = "Option::is_none")]
pub migration_tested: Option<bool>,
#[serde(rename = "replicationProgressPercentage", default, skip_serializing_if = "Option::is_none")]
pub replication_progress_percentage: Option<i32>,
#[serde(rename = "targetVMArmId", default, skip_serializing_if = "Option::is_none")]
pub target_vm_arm_id: Option<String>,
#[serde(rename = "enqueueTime", default, skip_serializing_if = "Option::is_none")]
pub enqueue_time: Option<String>,
#[serde(rename = "solutionName", default, skip_serializing_if = "Option::is_none")]
pub solution_name: Option<String>,
#[serde(rename = "machineId", default, skip_serializing_if = "Option::is_none")]
pub machine_id: Option<String>,
#[serde(rename = "machineManagerId", default, skip_serializing_if = "Option::is_none")]
pub machine_manager_id: Option<String>,
#[serde(rename = "fabricType", default, skip_serializing_if = "Option::is_none")]
pub fabric_type: Option<String>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
#[serde(rename = "machineName", default, skip_serializing_if = "Option::is_none")]
pub machine_name: Option<String>,
#[serde(rename = "ipAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub ip_addresses: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fqdn: Option<String>,
#[serde(rename = "biosId", default, skip_serializing_if = "Option::is_none")]
pub bios_id: Option<String>,
#[serde(rename = "macAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub mac_addresses: Vec<String>,
#[serde(rename = "extendedInfo", default, skip_serializing_if = "Option::is_none")]
pub extended_info: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MigrateProject {
#[serde(rename = "eTag", default, skip_serializing_if = "Option::is_none")]
pub e_tag: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<MigrateProjectProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<migrate_project::Tags>,
}
pub mod migrate_project {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tags {
#[serde(rename = "additionalProperties", default, skip_serializing_if = "Option::is_none")]
pub additional_properties: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MigrateProjectProperties {
#[serde(rename = "registeredTools", default, skip_serializing_if = "Vec::is_empty")]
pub registered_tools: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<serde_json::Value>,
#[serde(rename = "lastSummaryRefreshedTime", default, skip_serializing_if = "Option::is_none")]
pub last_summary_refreshed_time: Option<String>,
#[serde(rename = "refreshSummaryState", default, skip_serializing_if = "Option::is_none")]
pub refresh_summary_state: Option<migrate_project_properties::RefreshSummaryState>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<migrate_project_properties::ProvisioningState>,
}
pub mod migrate_project_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RefreshSummaryState {
Started,
InProgress,
Completed,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Accepted,
Creating,
Deleting,
Failed,
Moving,
Succeeded,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProjectSummary {
#[serde(rename = "instanceType", default, skip_serializing_if = "Option::is_none")]
pub instance_type: Option<String>,
#[serde(rename = "refreshSummaryState", default, skip_serializing_if = "Option::is_none")]
pub refresh_summary_state: Option<project_summary::RefreshSummaryState>,
#[serde(rename = "lastSummaryRefreshedTime", default, skip_serializing_if = "Option::is_none")]
pub last_summary_refreshed_time: Option<String>,
#[serde(rename = "extendedSummary", default, skip_serializing_if = "Option::is_none")]
pub extended_summary: Option<serde_json::Value>,
}
pub mod project_summary {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RefreshSummaryState {
Started,
InProgress,
Completed,
Failed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegisterToolInput {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool: Option<register_tool_input::Tool>,
}
pub mod register_tool_input {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Tool {
ServerDiscovery,
ServerAssessment,
ServerMigration,
Cloudamize,
Turbonomic,
Zerto,
CorentTech,
ServerAssessmentV1,
#[serde(rename = "ServerMigration_Replication")]
ServerMigrationReplication,
Carbonite,
DataMigrationAssistant,
DatabaseMigrationService,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RegistrationResult {
#[serde(rename = "isRegistered", default, skip_serializing_if = "Option::is_none")]
pub is_registered: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RefreshSummaryResult {
#[serde(rename = "isRefreshed", default, skip_serializing_if = "Option::is_none")]
pub is_refreshed: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RefreshSummaryInput {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub goal: Option<refresh_summary_input::Goal>,
}
pub mod refresh_summary_input {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Goal {
Servers,
Databases,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Solution {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<SolutionProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SolutionProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool: Option<solution_properties::Tool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub purpose: Option<solution_properties::Purpose>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub goal: Option<solution_properties::Goal>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<solution_properties::Status>,
#[serde(rename = "cleanupState", default, skip_serializing_if = "Option::is_none")]
pub cleanup_state: Option<solution_properties::CleanupState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<SolutionSummary>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<SolutionDetails>,
}
pub mod solution_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Tool {
ServerDiscovery,
ServerAssessment,
ServerMigration,
Cloudamize,
Turbonomic,
Zerto,
CorentTech,
ServerAssessmentV1,
#[serde(rename = "ServerMigration_Replication")]
ServerMigrationReplication,
Carbonite,
DataMigrationAssistant,
DatabaseMigrationService,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Purpose {
Discovery,
Assessment,
Migration,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Goal {
Servers,
Databases,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
Inactive,
Active,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CleanupState {
None,
Started,
InProgress,
Completed,
Failed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SolutionSummary {
#[serde(rename = "instanceType", default, skip_serializing_if = "Option::is_none")]
pub instance_type: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SolutionDetails {
#[serde(rename = "groupCount", default, skip_serializing_if = "Option::is_none")]
pub group_count: Option<i32>,
#[serde(rename = "assessmentCount", default, skip_serializing_if = "Option::is_none")]
pub assessment_count: Option<i32>,
#[serde(rename = "extendedDetails", default, skip_serializing_if = "Option::is_none")]
pub extended_details: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SolutionsCollection {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Solution>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SolutionConfig {
#[serde(rename = "publisherSasUri", default, skip_serializing_if = "Option::is_none")]
pub publisher_sas_uri: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServersProjectSummary {
#[serde(flatten)]
pub project_summary: ProjectSummary,
#[serde(rename = "discoveredCount", default, skip_serializing_if = "Option::is_none")]
pub discovered_count: Option<i32>,
#[serde(rename = "assessedCount", default, skip_serializing_if = "Option::is_none")]
pub assessed_count: Option<i32>,
#[serde(rename = "replicatingCount", default, skip_serializing_if = "Option::is_none")]
pub replicating_count: Option<i32>,
#[serde(rename = "testMigratedCount", default, skip_serializing_if = "Option::is_none")]
pub test_migrated_count: Option<i32>,
#[serde(rename = "migratedCount", default, skip_serializing_if = "Option::is_none")]
pub migrated_count: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseProjectSummary {
#[serde(flatten)]
pub project_summary: ProjectSummary,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServersSolutionSummary {
#[serde(flatten)]
pub solution_summary: SolutionSummary,
#[serde(rename = "discoveredCount", default, skip_serializing_if = "Option::is_none")]
pub discovered_count: Option<i32>,
#[serde(rename = "assessedCount", default, skip_serializing_if = "Option::is_none")]
pub assessed_count: Option<i32>,
#[serde(rename = "replicatingCount", default, skip_serializing_if = "Option::is_none")]
pub replicating_count: Option<i32>,
#[serde(rename = "testMigratedCount", default, skip_serializing_if = "Option::is_none")]
pub test_migrated_count: Option<i32>,
#[serde(rename = "migratedCount", default, skip_serializing_if = "Option::is_none")]
pub migrated_count: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabasesSolutionSummary {
#[serde(flatten)]
pub solution_summary: SolutionSummary,
#[serde(rename = "databasesAssessedCount", default, skip_serializing_if = "Option::is_none")]
pub databases_assessed_count: Option<i32>,
#[serde(rename = "databaseInstancesAssessedCount", default, skip_serializing_if = "Option::is_none")]
pub database_instances_assessed_count: Option<i32>,
#[serde(rename = "migrationReadyCount", default, skip_serializing_if = "Option::is_none")]
pub migration_ready_count: Option<i32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MachineMigrateEventProperties {
#[serde(flatten)]
pub migrate_event_properties: MigrateEventProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub machine: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatabaseMigrateEventProperties {
#[serde(flatten)]
pub migrate_event_properties: MigrateEventProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub database: Option<String>,
#[serde(rename = "databaseInstanceId", default, skip_serializing_if = "Option::is_none")]
pub database_instance_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationResultList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<OperationDisplay>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationDisplay {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
|
use bevy::prelude::*;
mod actors;
fn main() {
App::build()
.add_plugins(DefaultPlugins)
.add_startup_system(setup.system())
.add_startup_system(actors::background::setup_background.system())
.add_startup_system(actors::player::setup_player.system())
.add_startup_system(actors::mote::setup_mote_system.system())
.add_system(actors::player::update_manabars.system())
.add_system(actors::player::update_camera.system())
.add_system(actors::background::bg_position_system.system())
.add_system(actors::player::player_update.system())
.add_system(actors::mote::mote_system.system())
.add_event::<actors::mote::SpawnMoteEvent>()
.run();
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
let texture_handle = asset_server.load("sprites/background.png");
commands.spawn_bundle(SpriteBundle {
material: materials.add(texture_handle.into()),
..Default::default()
});
commands.spawn_bundle(OrthographicCameraBundle::new_2d())
.insert(actors::player::MainCam{
position: Vec3::new(0.,0.,0.)
});
} |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Coprocessor access control register"]
pub cpacr: CPACR,
}
#[doc = "CPACR (rw) register accessor: Coprocessor access control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpacr::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 [`cpacr::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 [`cpacr`]
module"]
pub type CPACR = crate::Reg<cpacr::CPACR_SPEC>;
#[doc = "Coprocessor access control register"]
pub mod cpacr;
|
/*
* 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
*/
/// MetricSearchResponse : Object containing the list of metrics matching the search query.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricSearchResponse {
#[serde(rename = "results", skip_serializing_if = "Option::is_none")]
pub results: Option<Box<crate::models::MetricSearchResponseResults>>,
}
impl MetricSearchResponse {
/// Object containing the list of metrics matching the search query.
pub fn new() -> MetricSearchResponse {
MetricSearchResponse {
results: None,
}
}
}
|
use alloc::vec::Vec;
use util::Hash;
use crate::consts::STABLE;
macro_rules! init_state {
($self:expr, $block:expr, $( $i:expr ), +) => {
$(
$self.state[$i + 32] = $block[$i] ^ $self.state[$i];
)*
};
}
macro_rules! round {
($self:expr, $t:expr, $($i:expr), +) => {
$(
// このループを展開するとむしろ遅くなる
// 多分ループ回数が大きすぎるのが問題(16 * 48 = 768回)
for k in 0..48 {
$self.state[k] ^= STABLE[$t as usize];
$t = $self.state[k] as usize;
}
$t = ($t + $i) % 256;
)*
};
}
macro_rules! checksum_j {
($self:expr, $message:expr, $checksum:expr, $c:expr, $l:expr, $i:expr, $( $j:expr ), +) => {
$(
$c = $message[16 * $i + $j];
$checksum[$j] ^= STABLE[($c ^ $l) as usize];
$l = $checksum[$j];
)*
};
}
macro_rules! checksnum_i {
($self:expr, $block:expr, $checksum:expr, $c:expr, $l:expr, $( $i:expr ), +) => {
$(
$c = $block[$i];
$checksum[$i] ^= STABLE[($c ^ $l) as usize];
$l = $checksum[$i];
)*
};
}
pub struct Md2 {
state: [u8; 48],
}
impl Md2 {
pub fn new() -> Self {
Self::default()
}
#[allow(unused_assignments)]
fn compress(&mut self, block: &[u8]) {
self.state[16..32].copy_from_slice(block);
init_state!(self, block, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
let mut t = 0;
round!(self, t, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17);
}
#[allow(unused_assignments)]
fn compress_checksum(&mut self, message: &[u8], padded_block: &[u8; 16]) {
let mut checksum = [0u8; 16];
let mut c;
let mut l = 0;
for i in 0..(message.len() / 16) {
checksum_j!(
self, message, checksum, c, l, i, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15
);
}
checksnum_i!(
self,
padded_block,
checksum,
c,
l,
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
);
self.compress(&checksum);
}
}
impl Default for Md2 {
fn default() -> Self {
Self { state: [0; 48] }
}
}
impl Hash for Md2 {
fn hash_to_bytes(&mut self, message: &[u8]) -> Vec<u8> {
let len = message.len();
if len == 0 {
// First block is filled with 16 (padding bytes)
self.compress(&[16; 16]);
self.compress_checksum(&[], &[16; 16]);
} else if len >= 16 {
message
.chunks_exact(16)
.for_each(|block| self.compress(block));
}
if len != 0 {
let paddlen = len % 16;
let mut block = [(16 - paddlen) as u8; 16]; // padding
let offset = len - paddlen;
block[..paddlen].clone_from_slice(&message[offset..len]);
self.compress(&block);
self.compress_checksum(message, &block);
}
self.state[0..16].to_vec()
}
}
|
use std::f64;
use std::collections::HashMap;
use ast::{Ast, ConstKind, FuncKind, OpKind};
use ast::AstVal::*;
use ast::FuncKind::*;
use ast::OpKind::*;
use ast::ConstKind::*;
use lexer::lex_equation;
use parser::parse_tokens;
use errors::{CalcrResult, CalcrError};
pub struct Interpreter {
vars: HashMap<String, f64>,
last_result: f64,
}
impl Interpreter {
pub fn new() -> Interpreter {
Interpreter {
vars: HashMap::new(),
last_result: 0.0,
}
}
pub fn eval_expression(&mut self, expr: &String) -> CalcrResult<Option<f64>> {
let toks = try!(lex_equation(expr));
let ast = try!(parse_tokens(toks));
let result = self.eval_expr(&ast);
// if we got an actual number as the result, then store it for later use
if let Ok(Some(ref res)) = result {
self.last_result = *res;
}
result
}
fn eval_expr(&mut self, ast: &Ast) -> CalcrResult<Option<f64>> {
if ast.val == Op(Assign) {
let (lhs, rhs) = try!(ast.get_binary_branches());
if let Name(ref name) = lhs.val {
let val = try!(self.eval_eq(rhs));
self.vars.insert(name.clone(), val);
Ok(None)
} else {
Err(CalcrError {
desc: "Interal error - expected Assign to have Name in left branch"
.to_string(),
span: None,
})
}
} else {
self.eval_eq(ast).map(|val| Some(val))
}
}
fn eval_eq(&mut self, ast: &Ast) -> CalcrResult<f64> {
match ast.val {
Func(ref f) => self.eval_func(f, ast),
Op(ref o) => self.eval_op(o, ast),
Const(ref c) => self.eval_const(c),
Num(ref n) => Ok(*n),
LastResult => Ok(self.last_result),
Name(ref name) => {
if let Some(val) = self.vars.get(name) {
Ok(*val)
} else {
Err(CalcrError {
desc: format!("Invalid function or constant: {}", name),
span: Some(ast.get_total_span()),
})
}
}
}
}
fn eval_func(&mut self, f: &FuncKind, ast: &Ast) -> CalcrResult<f64> {
let child = try!(ast.get_unary_branch());
let arg = try!(self.eval_eq(child));
match *f {
Sin => Ok(arg.sin()),
Cos => Ok(arg.cos()),
Tan => Ok(arg.tan()),
Asin => Ok(arg.asin()),
Acos => Ok(arg.acos()),
Atan => Ok(arg.atan()),
Abs => Ok(arg.abs()),
Exp => Ok(arg.exp()),
Sqrt => {
if arg < 0.0 {
Err(CalcrError {
desc: "Cannot take the square root of a negative number".to_string(),
span: Some(child.get_total_span()),
})
} else {
Ok(arg.sqrt())
}
},
Ln => {
if arg <= 0.0 {
Err(CalcrError {
desc: "Cannot take the logarithm of a non-positive number".to_string(),
span: Some(child.get_total_span()),
})
} else {
Ok(arg.ln())
}
},
Log => {
if arg <= 0.0 {
Err(CalcrError {
desc: "Cannot take the logarithm of a non-positive number".to_string(),
span: Some(child.get_total_span()),
})
} else {
Ok(arg.log10())
}
},
}
}
fn eval_op(&mut self, op: &OpKind, ast: &Ast) -> CalcrResult<f64> {
match ast.branches.len() {
2 => {
let (lhs, rhs) = ast.get_binary_branches().unwrap();
let (lhs, rhs) = (try!(self.eval_eq(lhs)), try!(self.eval_eq(rhs)));
match *op {
Plus => Ok(lhs + rhs),
Minus => Ok(lhs - rhs),
Mult => Ok(lhs * rhs),
Div => Ok(lhs / rhs),
Pow => Ok(lhs.powf(rhs)),
_ => Err(CalcrError {
desc: "Internal error - expected AstOp to have binary branch".to_string(),
span: None,
})
}
},
1 => {
let child = ast.get_unary_branch().unwrap();
let val = try!(self.eval_eq(child));
match *op {
Neg => Ok(-val),
Fact => self.evalf_fact(val, child),
_ => Err(CalcrError {
desc: "Internal error - expected AstOp to have unary branch".to_string(),
span: None,
})
}
},
_ => Err(CalcrError {
desc: "Internal error - AstOp nodes must have 1 or 2 branches".to_string(),
span: None,
})
}
}
fn eval_const(&mut self, c: &ConstKind) -> CalcrResult<f64> {
Ok(match *c {
Pi => f64::consts::PI,
E => (1.0f64).exp(),
Phi => 1.6180339887498948482,
})
}
fn evalf_fact(&mut self, mut num: f64, child: &Ast) -> CalcrResult<f64> {
if num.fract() == 0.0 && num >= 0.0 {
let mut out = 1.0;
while num > 0.0 {
out *= num;
num -= 1.0;
}
Ok(out)
} else {
Err(CalcrError {
desc: "The factorial function only accepts positive whole numbers".to_string(),
span: Some(child.get_total_span()),
})
}
}
} |
fn main(){
//signed int i8, i16, i32, i64, i128, for negatives to positives intervals
//unsigned switch i to u, only positive
let x128: u128 = 0xFAFBFCFD_FEF1F2F3_F4F5F6F7_F8F9FAFB;
let x64 : i64 = 123456;
//32 bit and 64 bit floating point numbers
let x = 2.0; //f64 is the default
let y : f32 = 3.0;//f32
println!("The value of x128, x, y is: {} {} {}", x128, x, y) ;
let c = 'z';//plicas para char
let thumb = '👍';
let is_job_done : bool = false;
println!("Some chars : {} {}", c, thumb);
} |
use async_trait::async_trait;
use hyper::{Body, Request, Response};
use web3::{transports, Web3};
mod hyper_helpers;
mod input_checker;
mod router;
#[async_trait]
pub trait RouterTrait {
async fn route(&self, req: Request<Body>) -> Result<Response<Body>, hyper::Error>;
}
#[derive(Clone)]
pub struct Router {
pub web3: Web3<transports::Http>,
}
#[async_trait]
impl RouterTrait for Router {
async fn route(&self, req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
router::route_request(self.web3.clone(), req).await
}
}
|
#[doc = "Register `CR` reader"]
pub type R = crate::R<CR_SPEC>;
#[doc = "Register `CR` writer"]
pub type W = crate::W<CR_SPEC>;
#[doc = "Field `JCEN` reader - JPEG Core Enable"]
pub type JCEN_R = crate::BitReader;
#[doc = "Field `JCEN` writer - JPEG Core Enable"]
pub type JCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IFTIE` reader - Input FIFO Threshold Interrupt Enable"]
pub type IFTIE_R = crate::BitReader;
#[doc = "Field `IFTIE` writer - Input FIFO Threshold Interrupt Enable"]
pub type IFTIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IFNFIE` reader - Input FIFO Not Full Interrupt Enable"]
pub type IFNFIE_R = crate::BitReader;
#[doc = "Field `IFNFIE` writer - Input FIFO Not Full Interrupt Enable"]
pub type IFNFIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OFTIE` reader - Output FIFO Threshold Interrupt Enable"]
pub type OFTIE_R = crate::BitReader;
#[doc = "Field `OFTIE` writer - Output FIFO Threshold Interrupt Enable"]
pub type OFTIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OFNEIE` reader - Output FIFO Not Empty Interrupt Enable"]
pub type OFNEIE_R = crate::BitReader;
#[doc = "Field `OFNEIE` writer - Output FIFO Not Empty Interrupt Enable"]
pub type OFNEIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `EOCIE` reader - End of Conversion Interrupt Enable"]
pub type EOCIE_R = crate::BitReader;
#[doc = "Field `EOCIE` writer - End of Conversion Interrupt Enable"]
pub type EOCIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HPDIE` reader - Header Parsing Done Interrupt Enable"]
pub type HPDIE_R = crate::BitReader;
#[doc = "Field `HPDIE` writer - Header Parsing Done Interrupt Enable"]
pub type HPDIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IDMAEN` reader - Input DMA Enable"]
pub type IDMAEN_R = crate::BitReader;
#[doc = "Field `IDMAEN` writer - Input DMA Enable"]
pub type IDMAEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ODMAEN` reader - Output DMA Enable"]
pub type ODMAEN_R = crate::BitReader;
#[doc = "Field `ODMAEN` writer - Output DMA Enable"]
pub type ODMAEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IFF` reader - Input FIFO Flush"]
pub type IFF_R = crate::BitReader;
#[doc = "Field `OFF` reader - Output FIFO Flush"]
pub type OFF_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - JPEG Core Enable"]
#[inline(always)]
pub fn jcen(&self) -> JCEN_R {
JCEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Input FIFO Threshold Interrupt Enable"]
#[inline(always)]
pub fn iftie(&self) -> IFTIE_R {
IFTIE_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Input FIFO Not Full Interrupt Enable"]
#[inline(always)]
pub fn ifnfie(&self) -> IFNFIE_R {
IFNFIE_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Output FIFO Threshold Interrupt Enable"]
#[inline(always)]
pub fn oftie(&self) -> OFTIE_R {
OFTIE_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Output FIFO Not Empty Interrupt Enable"]
#[inline(always)]
pub fn ofneie(&self) -> OFNEIE_R {
OFNEIE_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - End of Conversion Interrupt Enable"]
#[inline(always)]
pub fn eocie(&self) -> EOCIE_R {
EOCIE_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Header Parsing Done Interrupt Enable"]
#[inline(always)]
pub fn hpdie(&self) -> HPDIE_R {
HPDIE_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 11 - Input DMA Enable"]
#[inline(always)]
pub fn idmaen(&self) -> IDMAEN_R {
IDMAEN_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - Output DMA Enable"]
#[inline(always)]
pub fn odmaen(&self) -> ODMAEN_R {
ODMAEN_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - Input FIFO Flush"]
#[inline(always)]
pub fn iff(&self) -> IFF_R {
IFF_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - Output FIFO Flush"]
#[inline(always)]
pub fn off(&self) -> OFF_R {
OFF_R::new(((self.bits >> 14) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - JPEG Core Enable"]
#[inline(always)]
#[must_use]
pub fn jcen(&mut self) -> JCEN_W<CR_SPEC, 0> {
JCEN_W::new(self)
}
#[doc = "Bit 1 - Input FIFO Threshold Interrupt Enable"]
#[inline(always)]
#[must_use]
pub fn iftie(&mut self) -> IFTIE_W<CR_SPEC, 1> {
IFTIE_W::new(self)
}
#[doc = "Bit 2 - Input FIFO Not Full Interrupt Enable"]
#[inline(always)]
#[must_use]
pub fn ifnfie(&mut self) -> IFNFIE_W<CR_SPEC, 2> {
IFNFIE_W::new(self)
}
#[doc = "Bit 3 - Output FIFO Threshold Interrupt Enable"]
#[inline(always)]
#[must_use]
pub fn oftie(&mut self) -> OFTIE_W<CR_SPEC, 3> {
OFTIE_W::new(self)
}
#[doc = "Bit 4 - Output FIFO Not Empty Interrupt Enable"]
#[inline(always)]
#[must_use]
pub fn ofneie(&mut self) -> OFNEIE_W<CR_SPEC, 4> {
OFNEIE_W::new(self)
}
#[doc = "Bit 5 - End of Conversion Interrupt Enable"]
#[inline(always)]
#[must_use]
pub fn eocie(&mut self) -> EOCIE_W<CR_SPEC, 5> {
EOCIE_W::new(self)
}
#[doc = "Bit 6 - Header Parsing Done Interrupt Enable"]
#[inline(always)]
#[must_use]
pub fn hpdie(&mut self) -> HPDIE_W<CR_SPEC, 6> {
HPDIE_W::new(self)
}
#[doc = "Bit 11 - Input DMA Enable"]
#[inline(always)]
#[must_use]
pub fn idmaen(&mut self) -> IDMAEN_W<CR_SPEC, 11> {
IDMAEN_W::new(self)
}
#[doc = "Bit 12 - Output DMA Enable"]
#[inline(always)]
#[must_use]
pub fn odmaen(&mut self) -> ODMAEN_W<CR_SPEC, 12> {
ODMAEN_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 = "JPEG control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::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 [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CR_SPEC;
impl crate::RegisterSpec for CR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`cr::R`](R) reader structure"]
impl crate::Readable for CR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"]
impl crate::Writable for CR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CR to value 0"]
impl crate::Resettable for CR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::cell::RefCell;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::rc::Rc;
use crate::cartridge::{Cartridge, MirrorMode};
use crate::ppu::{self, PpuInterface};
use crate::savable::Savable;
/// First address of the ROM memory space
const ROM_START: u16 = 0x0000;
/// Last address of the ROM memory space
const ROM_END: u16 = 0x1FFF;
/// Size of one nametable
const NTA_SIZE: u16 = 0x400;
/// Size of the VRAM (Doubled to handle some games which use 4screen mapping)
const VRAM_SIZE: usize = 0x800 * 2;
/// First address of the VRAM memory space
const VRAM_START: u16 = 0x2000;
/// Last address of the VRAM memory space
const VRAM_END: u16 = 0x3EFF;
/// Size of the palette RAM
const PALETTE_RAM_SIZE: usize = 0x20;
/// First address of the palette RAM memory space
const PALETTE_START: u16 = 0x3F00;
/// Last address of the palette RAM memory space
const PALETTE_END: u16 = 0x3FFF;
/// Memory bus of the Ppu
pub struct PpuBus {
cartridge: Rc<RefCell<Cartridge>>,
pal_ram: [u8; PALETTE_RAM_SIZE],
vram: [u8; VRAM_SIZE],
}
impl PpuInterface for PpuBus {}
impl Savable for PpuBus {
fn save(&self, output: &mut BufWriter<File>) -> bincode::Result<()> {
for i in 0..PALETTE_RAM_SIZE {
bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.pal_ram[i])?;
}
for i in 0..VRAM_SIZE {
bincode::serialize_into::<&mut BufWriter<File>, _>(output, &self.vram[i])?;
}
Ok(())
}
fn load(&mut self, input: &mut BufReader<File>) -> bincode::Result<()> {
for i in 0..PALETTE_RAM_SIZE {
self.pal_ram[i] = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?;
}
for i in 0..VRAM_SIZE {
self.vram[i] = bincode::deserialize_from::<&mut BufReader<File>, _>(input)?;
}
Ok(())
}
}
impl ppu::Interface for PpuBus {
fn read(&self, addr: u16) -> u8 {
// The ppu bus only maps from 0x0000 to 0x3FFF;
let addr = addr & 0x3FFF;
match addr {
// ROM memory space: read from CHR ROM on the cartridge
ROM_START..=ROM_END => self.cartridge.borrow_mut().read_chr(addr),
// VRAM memory space: read from VRAM
VRAM_START..=VRAM_END => {
// Mirror the address first
let index = self.mirrored_vaddr(addr) as usize;
self.vram[index]
}
// Palette RAM memory space:
PALETTE_START..=PALETTE_END => {
let mut index = addr;
// This check is because
// 0x3F10 == 0x3F00
// 0x3F14 == 0x3F04
// 0x3F18 == 0x3F08
// 0x3F1C == 0x3F0C
if index % 4 == 0 {
index &= 0x0F;
}
// Palette mirrors every 0x20 (32)
index &= 0x1F;
self.pal_ram[index as usize]
}
_ => unreachable!("Reached impossible match arm. (Ppu bus addr) {:#04X}", addr),
}
}
fn write(&mut self, addr: u16, data: u8) {
// The ppu bus only maps from 0x0000 to 0x3FFF;
let addr = addr & 0x3FFF;
match addr {
// ROM memory space: read from CHR ROM on the cartridge
ROM_START..=ROM_END => self.cartridge.borrow_mut().write_chr(addr, data),
// VRAM memory space: read from VRAM
VRAM_START..=VRAM_END => {
// Mirror the address first
let index = self.mirrored_vaddr(addr) as usize;
self.vram[index] = data;
}
// Palette RAM memory space:
PALETTE_START..=PALETTE_END => {
let mut index = addr;
// This check is because
// 0x3F10 == 0x3F00
// 0x3F14 == 0x3F04
// 0x3F18 == 0x3F08
// 0x3F1C == 0x3F0C
if index % 4 == 0 {
index &= 0x0F;
}
// Palette mirrors every 0x20 (32)
index &= 0x1F;
self.pal_ram[index as usize] = data;
}
_ => unreachable!("Reached impossible match arm. (Ppu bus addr) {:#04X}", addr),
}
}
// Signals a new scanline was rendered to the cartridge
fn inc_scanline(&mut self) {
self.cartridge.borrow_mut().inc_scanline()
}
}
impl PpuBus {
pub fn new(cartridge: Rc<RefCell<Cartridge>>) -> Self {
Self {
cartridge,
pal_ram: [0; PALETTE_RAM_SIZE],
vram: [0; VRAM_SIZE],
}
}
/// Returns the address mirrored based on the current mirroring mode
fn mirrored_vaddr(&self, addr: u16) -> u16 {
// Mask because 0x2000 - 0x2FFF mirrors 0x3000 - 0x3EFF
let addr = addr & 0x2FFF;
// Substract the memory map offset to have real memory index
let index = addr - VRAM_START;
// Calculate which nametable we are in
let nta = index / NTA_SIZE;
match self.cartridge.borrow().mirror_mode() {
// |---------|---------| |---------|---------|
// | | | | | |
// | 0 - A | 1 - B | | 0 | 1 | The hardware has space for only 2 nametables
// | | | | | |
// |---------|---------| |---------|---------|
// | | |
// | 2 - A | 3 - B |
// | | |
// |---------|---------|
// Here 2 mirrors 0 and 3 mirrors 1
// I simply substract the size of the first two nametables if we are in 2 or 3.
// Otherwise I return the index because nametables 0 and 1 are already mapped correctly
MirrorMode::Vertical => match nta {
2 | 3 => index - (NTA_SIZE * 2),
_ => index,
},
// |---------|---------| |---------|---------|
// | | | | | |
// | 0 - A | 1 - A | | 0 | 1 | The hardware has space for only 2 nametables
// | | | | | |
// |---------|---------| |---------|---------|
// | | |
// | 2 - B | 3 - B |
// | | |
// |---------|---------|
// Here 1 mirrors 0 and 3 mirrors 2.
// I want to map nametable 0 to hardware nametable 0 and nametable 2 to hardware nametable 1.
// Nametable 0 is already mapped
// Because nametable 1 mirrors 0, I can simply substract the nametable size.
// Then I want to map nametable 2 to hardware nametable 1, so I also can substract the size.
// Finally for nametable 3, because it is a mirror of nametable 2, it should map onto hardware nametable 1.
// So I substract twice the size of a nametable
MirrorMode::Horizontal => match nta {
1 | 2 => index - NTA_SIZE,
3 => index - (NTA_SIZE * 2),
_ => index,
},
// |---------|---------| |---------|---------|
// | | | | | |
// | 0 - A | 1 - A | | 0 | 1 | The hardware has space for only 2 nametables
// | | | | | |
// |---------|---------| |---------|---------|
// | | |
// | 2 - A | 3 - A |
// | | |
// |---------|---------|
// This setting maps everthing to hardware nametable 0
MirrorMode::OneScreenLo => index & 0x3FF,
// |---------|---------| |---------|---------|
// | | | | | |
// | 0 - A | 1 - A | | 0 | 1 | The hardware has space for only 2 nametables
// | | | | | |
// |---------|---------| |---------|---------|
// | | |
// | 2 - A | 3 - A |
// | | |
// |---------|---------|
// This setting maps everthing to hardware nametable 1.
// I simply add the size after masking the address
MirrorMode::OneScreenHi => (index & 0x3FF) + NTA_SIZE,
// |---------|---------| |---------|---------|
// | | | | | |
// | 0 - A | 1 - B | | 0 | 1 | The hardware has space for only 2 nametables
// | | | | | |
// |---------|---------| |---------|---------|
// | | | | | |
// | 2 - C | 3 - D | | 2 | 3 | The extra nametables were on the cartridge PCB
// | | | | | |
// |---------|---------| |---------|---------|
// Real hardware would use memory on the cartridge but, I simply
// allocated a Vec of twice the size of VRAM and use the index directly
MirrorMode::FourScreen => index,
}
}
}
|
extern crate portmidi;
extern crate rosc;
use types::*;
use dsp::{FilterType, Waveform};
macro_rules! feq {
($lhs:expr, $rhs:expr) => {
($lhs - $rhs).abs() < 1.0E-7
};
}
#[derive(Debug, Clone)]
pub enum ControlEvent {
Unsupported,
NoteOn {
key: u8,
velocity: Float,
},
NoteOff {
key: u8,
velocity: Float,
},
ADSR {
id: String,
attack: Time,
decay: Time,
sustain: Float,
release: Time,
},
Waveform {
id: String,
waveform: Waveform,
},
Volume(Vec<Float>),
Pan(Vec<Float>),
Phase {
id: String,
phase: Float,
},
Transpose {
id: String,
transpose: i32,
},
Detune {
id: String,
detune: i32,
},
FM {
id: String,
levels: Vec<Float>,
},
Filter {
filter_type: Option<FilterType>,
freq: Option<Float>,
q: Option<Float>,
},
}
pub trait Controllable {
fn handle(&mut self, msg: &ControlEvent);
}
|
type Tree = ();
type Forest = Vec<Vec<Option<Tree>>>;
fn input_line_to_row(input: Vec<&str>) -> Vec<Option<Tree>> {
input
.iter()
.filter(|i| *i == &"." || *i == &"#")
.map(|i| match i.as_ref() {
"#" => Some(()),
_ => None,
})
.collect()
}
fn input_lines_to_forest(input: &Vec<String>) -> Forest {
input
.iter()
.map(|i| input_line_to_row(i.split("").collect()))
.collect()
}
// Core logic used for both part 1 and 2
fn get_num_trees(input: &Vec<String>, (x_slope, y_slope): (usize, usize)) -> usize {
let forest: Forest = input_lines_to_forest(input);
// How wide is our forest?
let forest_width: usize = forest[0].len();
// We can't rely on our current row index to solely determine the x position
// in a particular iteration, because if we've skipped a row (early return)
// we shouldn't again walk forward `x_slope` number of characters
// Said another way, with a slope of (1, 2), after including/counting (0, 0),
// our next spot should be (1, 2), not (2, 2) (0+1+1 after three iterations)
let mut current_x_pos = 0;
let sum_trees = forest.iter().enumerate().fold(0, |sum, (i, row)| {
// We should conditionally check rows based on whether we've
// sufficiently moved far enough down the Y axis
if i % y_slope != 0 {
return sum;
}
// Use modulus to wrap back around to the beginning of the row
// (this effectively "repeats" our input map horizontally)
let wrapping_x_position = current_x_pos % forest_width;
// Increment x_pos now that we've found the next position to check.
current_x_pos += x_slope;
match row[wrapping_x_position] {
Some(_) => sum + 1,
None => sum,
}
});
sum_trees
}
pub fn get_answers(input: Vec<String>) -> (usize, usize) {
let answer_one = get_num_trees(&input, (3, 1));
let answer_two = vec![(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
.iter()
.map(|coords| {
let a = get_num_trees(&input, *coords);
println!("Coords {:?} return {}", coords, a);
a
})
.fold(1, |product, num| product * num);
(answer_one, answer_two)
}
|
use nu::{
serve_plugin, CallInfo, Plugin, Primitive, ReturnSuccess, ReturnValue, ShellError, Signature,
Tagged, TaggedItem, Value,
};
struct Sum {
total: Option<Tagged<Value>>,
}
impl Sum {
fn new() -> Sum {
Sum { total: None }
}
fn sum(&mut self, value: Tagged<Value>) -> Result<(), ShellError> {
match value.item() {
Value::Primitive(Primitive::Nothing) => Ok(()),
Value::Primitive(Primitive::Int(i)) => {
match &self.total {
Some(Tagged {
item: Value::Primitive(Primitive::Int(j)),
tag,
}) => {
//TODO: handle overflow
self.total = Some(Value::int(i + j).tagged(*tag));
Ok(())
}
None => {
self.total = Some(value.clone());
Ok(())
}
_ => Err(ShellError::string(format!(
"Could not sum non-integer or unrelated types"
))),
}
}
Value::Primitive(Primitive::Bytes(b)) => {
match self.total {
Some(Tagged {
item: Value::Primitive(Primitive::Bytes(j)),
tag,
}) => {
//TODO: handle overflow
self.total = Some(Value::bytes(b + j).tagged(tag));
Ok(())
}
None => {
self.total = Some(value);
Ok(())
}
_ => Err(ShellError::string(format!(
"Could not sum non-integer or unrelated types"
))),
}
}
x => Err(ShellError::string(format!(
"Unrecognized type in stream: {:?}",
x
))),
}
}
}
impl Plugin for Sum {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("sum")
.desc("Sum a column of values.")
.filter())
}
fn begin_filter(&mut self, _: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![])
}
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
self.sum(input)?;
Ok(vec![])
}
fn end_filter(&mut self) -> Result<Vec<ReturnValue>, ShellError> {
match self.total {
None => Ok(vec![]),
Some(ref v) => Ok(vec![ReturnSuccess::value(v.clone())]),
}
}
}
fn main() {
serve_plugin(&mut Sum::new());
}
|
use crate::error::{from_protobuf_error, NiaServerError, NiaServerResult};
use crate::protocol::Serializable;
use protobuf::Message;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ActionKeyRelease {
key_code: i32,
}
impl ActionKeyRelease {
pub fn new(key_code: i32) -> ActionKeyRelease {
ActionKeyRelease { key_code }
}
pub fn get_key_code(&self) -> i32 {
self.key_code
}
}
impl Serializable<ActionKeyRelease, nia_protocol_rust::ActionKeyRelease>
for ActionKeyRelease
{
fn to_pb(&self) -> nia_protocol_rust::ActionKeyRelease {
let mut action_key_release_pb =
nia_protocol_rust::ActionKeyRelease::new();
action_key_release_pb.set_key_code(self.get_key_code());
action_key_release_pb
}
fn from_pb(
object_pb: nia_protocol_rust::ActionKeyRelease,
) -> NiaServerResult<ActionKeyRelease> {
let action_key_release =
ActionKeyRelease::new(object_pb.get_key_code());
Ok(action_key_release)
}
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[test]
fn serializable_and_deserializable() {
let expected = 123;
let action_key_release = ActionKeyRelease::new(expected);
let bytes = action_key_release.to_bytes().unwrap();
let action_key_release = ActionKeyRelease::from_bytes(bytes).unwrap();
let result = action_key_release.key_code;
assert_eq!(expected, result)
}
}
|
#[macro_use]
extern crate may;
fn partition<T: PartialOrd + Send>(v: &mut [T]) -> usize {
let pivot = v.len() - 1;
let mut i = 0;
for j in 0..pivot {
if v[j] <= v[pivot] {
v.swap(i, j);
i += 1;
}
}
v.swap(i, pivot);
i
}
pub fn quick_sort<T: PartialOrd + Send>(v: &mut [T]) {
// for each coroutine the min size of each job
if v.len() <= 0x1000 {
return v.sort_by(|a, b| a.partial_cmp(b).unwrap());
}
let mid = partition(v);
let (lo, hi) = v.split_at_mut(mid);
join!(quick_sort(lo), quick_sort(hi));
}
#[cfg(test)]
mod tests {
use super::*;
fn is_sorted<T: Send + Ord>(v: &[T]) -> bool {
(1..v.len()).all(|i| v[i - 1] <= v[i])
}
#[test]
fn it_works() {
let mut v = vec![8, 2, 9, 6, 5, 0, 1, 4, 3, 7];
quick_sort(&mut v);
assert_eq!(is_sorted(&v), true);
}
}
|
#[cfg(debug_assertions)]
use crate::base::db::colored;
use crate::base::db::red;
#[cfg(debug_assertions)]
use diesel::query_builder::QueryBuilder;
use diesel::{connection::TransactionManager, prelude::*};
fn _connection_pool(
mut db_url: String,
) -> r2d2::Pool<r2d2_diesel::ConnectionManager<RealmConnection>> {
if crate::base::is_test() {
// add search_path=test (%3D is = sign)
if db_url.contains('?') {
db_url += "&options=-c search_path%3Dtest"
} else {
db_url += "?options=-c search_path%3Dtest"
}
};
let manager = r2d2_diesel::ConnectionManager::<RealmConnection>::new(db_url);
r2d2::Pool::builder()
.max_size(10)
.build(manager)
.expect("Failed to create DIESEL_POOL.")
}
lazy_static! {
pub static ref DIESEL_POOLS: antidote::RwLock<
std::collections::HashMap<
String,
r2d2::Pool<r2d2_diesel::ConnectionManager<RealmConnection>>,
>,
> = antidote::RwLock::new(std::collections::HashMap::new());
}
pub fn connection() -> r2d2::PooledConnection<r2d2_diesel::ConnectionManager<RealmConnection>> {
connection_with_url(std::env::var("DATABASE_URL").expect("DATABASE_URL not set"))
}
pub fn connection_with_url(
db_url: String,
) -> r2d2::PooledConnection<r2d2_diesel::ConnectionManager<RealmConnection>> {
{
if let Some(pool) = DIESEL_POOLS.read().get(&db_url) {
return pool.get().unwrap();
}
}
match DIESEL_POOLS.write().entry(db_url.clone()) {
std::collections::hash_map::Entry::Vacant(e) => {
let conn_pool = _connection_pool(db_url);
let conn = conn_pool.get().unwrap();
e.insert(conn_pool);
conn
}
std::collections::hash_map::Entry::Occupied(e) => e.get().get().unwrap(),
}
}
pub fn db_test<F>(run: F)
where
F: FnOnce(&RealmConnection) -> Result<(), failure::Error>,
{
let conn = connection();
conn.test_transaction::<_, failure::Error, _>(|| {
let r = run(&conn).map_err(|e| {
eprintln!("failed: {:?}", &e);
e
});
rollback_if_required(&conn);
r
})
}
#[cfg(debug_assertions)]
pub struct DebugConnection {
pub conn: diesel::PgConnection,
}
#[cfg(debug_assertions)]
pub type RealmConnection = DebugConnection;
#[cfg(not(debug_assertions))]
pub type RealmConnection = diesel::PgConnection;
fn rollback(conn: &RealmConnection) {
if let Err(e) = conn.transaction_manager().rollback_transaction(conn) {
red("connection_not_clean_and_cleanup_failed", e);
};
}
pub fn rollback_if_required(conn: &RealmConnection) {
if let Err(e) = diesel::sql_query("SELECT 1").execute(conn) {
red("connection_not_clean", e);
rollback(conn);
} else {
let t: &dyn diesel::connection::TransactionManager<RealmConnection> =
conn.transaction_manager();
let depth = t.get_transaction_depth();
if depth != 0 {
red("connection_not_clean", depth);
rollback(conn);
}
}
}
#[cfg(debug_assertions)]
impl diesel::connection::SimpleConnection for DebugConnection {
fn batch_execute(&self, query: &str) -> QueryResult<()> {
self.conn.batch_execute(query)
}
}
#[cfg(debug_assertions)]
impl DebugConnection {
fn new(url: &str) -> ConnectionResult<Self> {
Ok(DebugConnection {
conn: diesel::PgConnection::establish(url)?,
})
}
}
#[cfg(debug_assertions)]
impl diesel::connection::Connection for DebugConnection {
type Backend = diesel::pg::Pg;
type TransactionManager = diesel::connection::AnsiTransactionManager;
fn establish(url: &str) -> ConnectionResult<Self> {
let start = std::time::Instant::now();
let r = DebugConnection::new(url);
eprintln!("EstablishConnection in {}", crate::base::elapsed(start));
r
}
fn execute(&self, query: &str) -> QueryResult<usize> {
let start = std::time::Instant::now();
let r = self.conn.execute(query);
eprintln!(
"ExecuteQuery: {} in {}.",
colored(query),
crate::base::elapsed(start)
);
r
}
fn query_by_index<T, U>(&self, source: T) -> QueryResult<Vec<U>>
where
T: diesel::query_builder::AsQuery,
T::Query:
diesel::query_builder::QueryFragment<diesel::pg::Pg> + diesel::query_builder::QueryId,
diesel::pg::Pg: diesel::sql_types::HasSqlType<T::SqlType>,
U: diesel::deserialize::Queryable<T::SqlType, diesel::pg::Pg>,
{
let start = std::time::Instant::now();
let query = source.as_query();
let debug_query = diesel::debug_query(&query).to_string();
let r = self.conn.query_by_index(query);
eprintln!(
"QueryByIndex: {} in {}.",
colored(debug_query.as_str()),
crate::base::elapsed(start)
);
r
}
fn query_by_name<T, U>(&self, source: &T) -> QueryResult<Vec<U>>
where
T: diesel::query_builder::QueryFragment<diesel::pg::Pg> + diesel::query_builder::QueryId,
U: diesel::deserialize::QueryableByName<diesel::pg::Pg>,
{
let start = std::time::Instant::now();
let query = {
let mut qb = diesel::pg::PgQueryBuilder::default();
source.to_sql(&mut qb)?;
qb.finish()
};
let r = self.conn.query_by_name(source);
eprintln!(
"QueryByName: {} in {}",
colored(query.as_str()),
crate::base::elapsed(start)
);
r
}
fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize>
where
T: diesel::query_builder::QueryFragment<diesel::pg::Pg> + diesel::query_builder::QueryId,
{
let start = std::time::Instant::now();
let query = {
let mut qb = diesel::pg::PgQueryBuilder::default();
source.to_sql(&mut qb)?;
qb.finish()
};
let r = self.conn.execute_returning_count(source);
eprintln!(
"ExecuteReturningCount: {} in {}",
colored(query.as_str()),
crate::base::elapsed(start)
);
r
}
fn transaction_manager(&self) -> &Self::TransactionManager {
self.conn.transaction_manager()
}
}
#[cfg(test)]
mod tests {
use super::RealmConnection;
use crate::diesel::RunQueryDsl;
use diesel::{self, sql_query};
// cargo test --package amitu_base base::db::tests::print_test -- --nocapture --exact
#[test]
fn print_test() {
fn exec(conn: &RealmConnection) {
let _ = sql_query("SELECT 1").execute(conn);
}
let conn = super::connection();
exec(&conn);
}
}
|
use rand::{thread_rng, Rng};
use rand::distributions::{Alphanumeric};
pub fn encode(key: &str, s: &str) -> Option<String> {
let mut res: Option<String> = None;
let mut output: String = String::new();
let key_char: Vec<char> = key.chars().collect();
let lowercase_numeric_check = key.chars().filter(|ch| !ch.is_alphabetic() || !ch.is_lowercase()).count() == 0 && key.len() != 0;
if lowercase_numeric_check {
let key_char_distance: Vec<u8> = key_char.iter().map(|ch| {
*ch as u8 - 'a' as u8
}).collect();
for (index, chr) in s.chars().enumerate() {
let index_key_distance = index % key_char_distance.len();
let mut char_transformed = chr as u8 + key_char_distance[index_key_distance];
char_transformed = match char_transformed {
x if x > 'z' as u8 => 'a' as u8 + (x - 'z' as u8 - 1),
rest => rest
};
output.push(char_transformed as char);
}
res = Some(output);
}
res
}
pub fn decode(key: &str, s: &str) -> Option<String> {
let mut res: Option<String> = None;
let mut output: String = String::new();
let key_char: Vec<char> = key.chars().collect();
let lowercase_numeric_check = key.chars().filter(|ch| !ch.is_alphabetic() || !ch.is_lowercase())
.count() == 0 && key.len() != 0;
if lowercase_numeric_check {
let key_char_distance: Vec<u8> = key_char.iter().map(|ch| {
*ch as u8 - 'a' as u8
}).collect();
for (index, chr) in s.chars().enumerate() {
let index_key_distance = index % key_char_distance.len();
let mut char_transformed = chr as u8 - key_char_distance[index_key_distance];
char_transformed = match char_transformed {
x if x < 'a' as u8 => 'z' as u8 - ('a' as u8 - x - 1),
rest => rest
};
output.push(char_transformed as char);
}
res = Some(output);
}
res
}
pub fn encode_random(s: &str) -> (String, String) {
let rng = thread_rng();
let random_string: String = rng.sample_iter(Alphanumeric)
.filter(|ch| ch.is_alphanumeric() && ch.is_lowercase())
.take(100)
.collect();
let rs = random_string.clone();
(random_string, encode(&rs, s).unwrap())
}
|
#![no_main]
#![no_std]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::{entry, exception};
#[exception]
#[entry] //~ ERROR this attribute is not allowed on an exception handler
fn SVCall() -> ! {
loop {}
}
|
struct test {
var: i8
}
fn main() {
let test = test {
var: 1
};
println!("Hello world: {}", test);
} |
pub const HBAR: f32 = 1.0;
pub const M: f32 = 1.0;
pub const DX: f32 = 0.1;
pub const DT: f32 = 0.001;
pub const WIDTH: usize = 500;
pub const HEIGHT: usize = 500;
pub const NUM_FRAMES: usize = 500;
pub const SLIT_HEIGHT: isize = -1;
pub const SLIT_1_START: isize = 100;
pub const SLIT_1_END: isize = 100;
pub const SLIT_2_START: isize = 100;
pub const SLIT_2_END: isize = 100;
pub const DISPATCH_LAYOUT : [u32 ; 3] = [128, 128, 1];
pub const SHADER_LAYOUT : [usize ; 3] = [32, 32, 1];
|
use std::error;
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
use std::vec::Vec;
fn get_lines(filename: &str) -> Result<std::io::Lines<io::BufReader<std::fs::File>>> {
let path = Path::new(&filename);
let file = File::open(path)?;
Ok(io::BufReader::new(file).lines())
}
#[derive(Debug)]
struct Password {
pwd: std::string::String,
low: i32,
high: i32,
c: char,
}
// Change the alias to `Box<error::Error>`.
type Result<T> = std::result::Result<T, Box<dyn error::Error>>;
fn parse_password(line: &str) -> Result<Password> {
// 1-9 a: abcdefg
let mut iter = line.split_whitespace();
let range: Vec<_> = iter
.next()
.ok_or("failed to parse range")?
.to_string()
.split('-')
.map(|s| s.parse::<i32>())
.collect();
let (low, high) = (range[0].clone()?, range[1].clone()?);
let mid = iter.next().ok_or("failed to parse mid")?;
let pwd = iter.next().ok_or("failed to parse pwd")?;
Ok(Password {
low,
high,
c: mid.chars().nth(0).ok_or("mid is empty")?,
pwd: pwd.to_string(),
})
}
fn valid_count(line: &str) -> Result<bool> {
let p = parse_password(line)?;
let count = p.pwd.chars().filter(|x| x == &p.c).count() as i32;
Ok(p.low <= count && count <= p.high)
}
type BoolFn = fn(&str) -> Result<bool>;
fn num_valid(lines: std::io::Lines<io::BufReader<std::fs::File>>, is_valid: BoolFn) -> Result<i32> {
let results: Result<Vec<Bool>> = lines.map(|line| is_valid(&line?)).collect();
results + 123;
Ok(results?.iter().filter(|x| **x).count() as i32)
}
fn valid_position(line: &str) -> Result<bool> {
let p = parse_password(line)?;
let x = p.pwd.as_bytes()[(p.low - 1) as usize] as char;
let y = p.pwd.as_bytes()[(p.high - 1) as usize] as char;
Ok(1 == (((p.c == x) as i32) + ((p.c == y) as i32)))
}
fn run_test(filename: &str, is_valid: BoolFn) -> Result<()> {
let example_lines = get_lines(filename)?;
println!("{}", num_valid(example_lines, is_valid)?);
Ok(())
}
fn main() {
for (filename, is_valid) in vec![
("example.input", valid_count as BoolFn),
("problem.input", valid_count as BoolFn),
("problem.input", valid_position as BoolFn),
] {
if let Err(e) = run_test(filename, is_valid) {
println!("{:?}", e);
}
}
}
|
use crate::models::{
Address, CollectionMethod, Order, Payment, PaymentStripe, PostDeliveryOption, Postage, User,
};
use juniper::ID;
#[juniper::object(description = "Contact Details of the person making the purchase")]
impl User {
/// Contact name
fn name(&self) -> &str { &self.name }
/// Contact email
fn email(&self) -> &str { &self.email }
}
#[juniper::object(
description = "The root order. This holds all details on an order including contact, address and postage information"
)]
impl Order {
fn id(&self) -> &ID { &self.id }
/// Contact details
fn user(&self) -> User { self.user.clone() }
/// delivery address
fn address(&self) -> Option<Address> { self.address.clone() }
/// postage details
fn postage(&self) -> Option<Postage> { self.postage.clone() }
/// quantity of scarves to be delivered
fn quantity(&self) -> i32 { self.quantity }
/// is the item Picked up or delivered
fn method(&self) -> CollectionMethod { self.method }
fn payment(&self) -> Option<Payment> { self.payment.clone() }
}
#[juniper::object(description = "Delivery Address")]
impl Address {
fn apartment(&self) -> Option<String> { self.apartment.clone() }
fn street(&self) -> &str { &self.street }
fn town(&self) -> &str { &self.town }
fn state(&self) -> &str { &self.state }
fn post_code(&self) -> i32 { self.post_code }
}
#[juniper::object(description = "The type of postage the user has selected, and the price")]
impl Postage {
fn code(&self) -> &str { &self.code }
}
#[juniper::object(description = "A post delivery option from Australia Post")]
impl PostDeliveryOption {
/// The name of the delivery option
fn name(&self) -> &str { &self.name }
/// The price of the deliver option as stated by the API
fn price(&self) -> f64 { self.price }
fn code(&self) -> &str { &self.code }
}
#[juniper::object]
#[derive(Clone, Debug)]
impl Payment {
fn stripe(&self) -> Option<PaymentStripe> { self.stripe.clone() }
}
#[juniper::object]
#[derive(Clone, Debug)]
impl PaymentStripe {
fn client_secret(&self) -> Option<String> { self.client_secret.clone() }
}
|
use swf_tree as ast;
use nom::IResult;
use nom::{le_i16 as parse_le_i16, le_u8 as parse_u8, le_u16 as parse_le_u16, le_u32 as parse_le_u32};
use parsers::basic_data_types::{
parse_rect,
parse_be_f16,
parse_s_rgb8,
parse_straight_s_rgba8,
parse_i32_bits,
parse_u32_bits,
};
use parsers::shapes::parse_glyph;
use ordered_float::OrderedFloat;
// TODO: Check with `nom`, it creates warnings: unused variable: `e`
#[allow(unused_variables)]
pub fn parse_grid_fitting_bits(input: (&[u8], usize)) -> IResult<(&[u8], usize), ast::text::GridFitting> {
switch!(
input,
apply!(parse_u32_bits, 3),
0 => value!(ast::text::GridFitting::None) |
1 => value!(ast::text::GridFitting::Pixel) |
2 => value!(ast::text::GridFitting::SubPixel)
// TODO(demurgos): Throw error
)
}
// TODO(demurgos): Fill an issue with `nom` to solve the `unused variable e` warning
#[allow(unused_variables)]
pub fn parse_csm_table_hint_bits(input: (&[u8], usize)) -> IResult<(&[u8], usize), ast::text::CsmTableHint> {
switch!(
input,
apply!(parse_u32_bits, 2),
0 => value!(ast::text::CsmTableHint::Thin) |
1 => value!(ast::text::CsmTableHint::Medium) |
2 => value!(ast::text::CsmTableHint::Thick)
// TODO(demurgos): Throw error
)
}
// TODO: Check with `nom`, it creates warnings: unused variable: `e`
#[allow(unused_variables)]
pub fn parse_text_renderer_bits(input: (&[u8], usize)) -> IResult<(&[u8], usize), ast::text::TextRenderer> {
switch!(
input,
apply!(parse_u32_bits, 2),
0 => value!(ast::text::TextRenderer::Normal) |
1 => value!(ast::text::TextRenderer::Advanced)
// TODO(demurgos): Throw error
)
}
pub fn parse_font_alignment_zone(input: &[u8]) -> IResult<&[u8], ast::text::FontAlignmentZone> {
do_parse!(
input,
data: length_count!(parse_u8, parse_font_alignment_zone_data) >>
flags: parse_u8 >>
(ast::text::FontAlignmentZone {
data: data,
has_x: (flags & (1 << 0)) != 0,
has_y: (flags & (1 << 1)) != 0
})
)
}
pub fn parse_font_alignment_zone_data(input: &[u8]) -> IResult<&[u8], ast::text::FontAlignmentZoneData> {
do_parse!(
input,
origin: parse_be_f16 >>
size: parse_be_f16 >>
// TODO(demurgos): What happens if we get a NaN?
(ast::text::FontAlignmentZoneData {
origin: OrderedFloat::<f32>(origin),
size: OrderedFloat::<f32>(size),
})
)
}
pub fn parse_text_record_string(input: &[u8], has_alpha: bool, index_bits: usize, advance_bits: usize) -> IResult<&[u8], Vec<ast::text::TextRecord>> {
let mut result: Vec<ast::text::TextRecord> = Vec::new();
let mut current_input: &[u8] = input;
while current_input.len() > 0 {
// A null byte indicates the end of the string of actions
if current_input[0] == 0 {
current_input = ¤t_input[1..];
return IResult::Done(current_input, result);
}
match parse_text_record(current_input, has_alpha, index_bits, advance_bits) {
IResult::Done(next_input, text_record) => {
current_input = next_input;
result.push(text_record);
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(_) => return IResult::Incomplete(::nom::Needed::Unknown),
};
}
IResult::Incomplete(::nom::Needed::Unknown)
}
// TODO: Check with `nom`, it creates warnings: unused variable: `e`
#[allow(unused_variables)]
pub fn parse_text_record(input: &[u8], has_alpha: bool, index_bits: usize, advance_bits: usize) -> IResult<&[u8], ast::text::TextRecord> {
do_parse!(
input,
flags: parse_u8 >>
has_font: value!((flags & (1 << 3)) != 0) >>
has_color: value!((flags & (1 << 2)) != 0) >>
has_offset_x: value!((flags & (1 << 1)) != 0) >>
has_offset_y: value!((flags & (1 << 0)) != 0) >>
font_id: cond!(has_font, parse_le_u16) >>
color: cond!(has_color, switch!(value!(has_alpha),
true => call!(parse_straight_s_rgba8) |
false => map!(parse_s_rgb8, |c| ast::StraightSRgba8 {r: c.r, g: c.g, b: c.b, a: 255})
)) >>
offset_x: cond!(has_offset_x, parse_le_i16) >>
offset_y: cond!(has_offset_y, parse_le_i16) >>
font_size: cond!(has_font, parse_le_u16) >>
entry_count: parse_u8 >>
entries: bits!(length_count!(
value!(entry_count),
apply!(parse_glyph_entry, index_bits, advance_bits)
)) >>
(ast::text::TextRecord {
font_id: font_id,
color: color,
offset_x: offset_x.unwrap_or_default(),
offset_y: offset_y.unwrap_or_default(),
font_size: font_size,
entries: entries,
})
)
}
pub fn parse_glyph_entry(input: (&[u8], usize), index_bits: usize, advance_bits: usize) -> IResult<(&[u8], usize), ast::text::GlyphEntry> {
do_parse!(
input,
index: map!(apply!(parse_u32_bits, index_bits), |x| x as usize) >>
advance: apply!(parse_i32_bits, advance_bits) >>
(ast::text::GlyphEntry {
index: index,
advance: advance,
})
)
}
pub fn parse_offset_glyphs(input: &[u8], glyph_count: usize, use_wide_offsets: bool) -> IResult<&[u8], Vec<ast::Glyph>> {
let parsed_offsets = if use_wide_offsets {
pair!(
input,
length_count!(value!(glyph_count), map!(parse_le_u32, |x| x as usize)),
map!(parse_le_u32, |x| x as usize)
)
} else {
pair!(
input,
length_count!(value!(glyph_count), map!(parse_le_u16, |x| x as usize)),
map!(parse_le_u16, |x| x as usize)
)
};
let (offsets, end_offset) = match parsed_offsets {
IResult::Done(_, o) => o,
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
let mut glyphs: Vec<ast::Glyph> = Vec::with_capacity(glyph_count);
for i in 0..glyph_count {
let start_offset = offsets[i];
let end_offset = if i + 1 < glyph_count { offsets[i + 1] } else { end_offset };
match parse_glyph(&input[start_offset..end_offset]) {
IResult::Done(_, o) => glyphs.push(o),
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
}
value!(&input[end_offset..], glyphs)
}
pub fn parse_kerning_record(input: &[u8]) -> IResult<&[u8], ast::text::KerningRecord> {
do_parse!(
input,
left: parse_le_u16 >>
right: parse_le_u16 >>
adjustment: parse_le_i16 >>
(ast::text::KerningRecord {
left: left,
right: right,
adjustment: adjustment,
})
)
}
pub fn parse_font_layout(input: &[u8], glyph_count: usize) -> IResult<&[u8], ast::text::FontLayout> {
do_parse!(input,
ascent: parse_le_u16 >>
descent: parse_le_u16 >>
leading: parse_le_u16 >>
advances: length_count!(value!(glyph_count), parse_le_u16) >>
bounds: length_count!(value!(glyph_count), parse_rect) >>
kerning: length_count!(parse_le_u16, parse_kerning_record) >>
(ast::text::FontLayout {
ascent: ascent,
descent: descent,
leading: leading,
advances,
bounds,
kerning,
})
)
}
#[allow(unused_variables)]
pub fn parse_text_alignment(input: &[u8]) -> IResult<&[u8], ast::text::TextAlignment> {
switch!(
input,
parse_u8,
0 => value!(ast::text::TextAlignment::Left) |
1 => value!(ast::text::TextAlignment::Right) |
2 => value!(ast::text::TextAlignment::Center) |
3 => value!(ast::text::TextAlignment::Justify)
// TODO(demurgos): Throw error
)
}
|
$NetBSD: patch-src_bootstrap_compile.rs,v 1.12 2023/05/03 22:39:09 he Exp $
On Darwin, do not use @rpath for internal libraries.
--- src/bootstrap/compile.rs.orig 2022-12-12 16:02:12.000000000 +0000
+++ src/bootstrap/compile.rs
@@ -488,7 +488,7 @@ fn copy_sanitizers(
|| target == "x86_64-apple-ios"
{
// Update the library’s install name to reflect that it has been renamed.
- apple_darwin_update_library_name(&dst, &format!("@rpath/{}", &runtime.name));
+ apple_darwin_update_library_name(&dst, &format!("@PREFIX@/lib/{}", &runtime.name));
// Upon renaming the install name, the code signature of the file will invalidate,
// so we will sign it again.
apple_darwin_sign_file(&dst);
|
// SPDX-License-Identifier: MIT
extern crate clap;
use crate::{files, runner};
use clap::{
crate_authors, crate_description, crate_name, crate_version, App, AppSettings, Arg, SubCommand,
};
const SUBCMD_RUN: &str = "run";
const SUBCMD_RUN_PART: &str = "PART";
const SUBCMD_RUN_INPUT: &str = "INPUT";
const SUBCMD_WRITE: &str = "write";
const SUBCMD_WRITE_PART: &str = "PART";
const SUBCMD_WRITE_INPUT: &str = "INPUT";
const SUBCMD_TEST: &str = "test";
const SUBCMD_TEST_PART: &str = "PART";
const SUBCMD_TEST_INPUT: &str = "INPUT";
const SUBCMD_TEST_DIFF: &str = "diff";
pub enum TestType {
All,
Specific { input: String },
}
pub enum Action {
Run {
part: String,
input: String,
},
Write {
part: String,
input: String,
},
Test {
part: String,
test_type: TestType,
show_diff: bool,
},
NoOp,
}
impl Action {
pub fn parse_args() -> Action {
let matches = App::new(crate_name!())
.about(crate_description!())
.version(crate_version!())
.author(crate_authors!())
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
SubCommand::with_name(SUBCMD_RUN)
.about("execute part with input")
.arg(
Arg::with_name(SUBCMD_RUN_PART)
.help("which part to execute")
.required(true)
.index(1),
)
.arg(
Arg::with_name(SUBCMD_RUN_INPUT)
.help("which input to feed in")
.index(2),
),
)
.subcommand(
SubCommand::with_name(SUBCMD_WRITE)
.about("write output after running part with input")
.arg(
Arg::with_name(SUBCMD_WRITE_PART)
.help("which part to execute")
.required(true)
.index(1),
)
.arg(
Arg::with_name(SUBCMD_WRITE_INPUT)
.help("which input to feed in")
.index(2),
),
)
.subcommand(
SubCommand::with_name(SUBCMD_TEST)
.about("test each input for part")
.arg(
Arg::with_name(SUBCMD_TEST_PART)
.help("which part to test")
.required(true)
.index(1),
)
.arg(
Arg::with_name(SUBCMD_TEST_INPUT)
.help("which particular test input to run")
.index(2),
)
.arg(
Arg::with_name(SUBCMD_TEST_DIFF)
.help("show diff")
.short("d")
.long(SUBCMD_TEST_DIFF),
),
)
.get_matches();
if let Some(matches) = matches.subcommand_matches(SUBCMD_RUN) {
let part = matches.value_of(SUBCMD_RUN_PART).unwrap().to_string();
let input = matches
.value_of(SUBCMD_RUN_INPUT)
.unwrap_or(&part)
.to_string();
Action::Run { part, input }
} else if let Some(matches) = matches.subcommand_matches(SUBCMD_WRITE) {
let part = matches.value_of(SUBCMD_WRITE_PART).unwrap().to_string();
let input = matches
.value_of(SUBCMD_WRITE_INPUT)
.unwrap_or(&part)
.to_string();
Action::Write { part, input }
} else if let Some(matches) = matches.subcommand_matches(SUBCMD_TEST) {
let part = matches.value_of(SUBCMD_TEST_PART).unwrap().to_string();
let test_type = match matches.value_of(SUBCMD_TEST_INPUT) {
Some(input) => TestType::Specific {
input: input.to_string(),
},
None => TestType::All,
};
let show_diff = matches.is_present(SUBCMD_TEST_DIFF);
Action::Test {
part,
test_type,
show_diff,
}
} else {
Action::NoOp
}
}
pub fn execute(self) {
match self {
Action::Run { part, input } => {
let prog_filename = files::get_prog_filename(&part);
let input_filename = files::get_input_filename(&input);
let output = runner::run_python_prog(&prog_filename, &input_filename)
.unwrap_or_else(|err| panic!("{}", err));
print!("{}", output);
}
Action::Write { part, input } => {
let prog_filename = files::get_prog_filename(&part);
let input_filename = files::get_input_filename(&input);
let output_filename = files::get_output_filename(&input);
let output = runner::run_python_prog(&prog_filename, &input_filename)
.unwrap_or_else(|err| panic!("{}", err));
runner::write_output(&output_filename, &output)
.unwrap_or_else(|err| panic!("{}", err));
}
Action::Test {
part,
test_type,
show_diff,
} => {
let prog_filename = files::get_prog_filename(&part);
let test_cases = match test_type {
TestType::Specific { input } => vec![runner::TestCase {
input_filename: files::get_input_filename(&input),
expected_output_filename: files::get_output_filename(&input),
}],
TestType::All => {
let test_prefix = files::get_test_prefix(&part);
let test_files = files::get_all_input_filenames_with_prefix(&test_prefix)
.unwrap_or_else(|err| panic!("{}", err));
let mut test_files: Vec<runner::TestCase> = test_files
.iter()
.map(|f| runner::TestCase {
input_filename: f.to_string(),
expected_output_filename: files::get_output_filename(
&files::remove_ext(f, files::INPUT_EXT),
),
})
.collect();
// if live input and output are available,
// then let's add them too (this is optional)
let live_input = files::get_input_filename(&part);
let live_output = files::get_output_filename(&part);
if files::file_exists(&live_input) && files::file_exists(&live_output) {
test_files.push(runner::TestCase {
input_filename: live_input,
expected_output_filename: live_output,
});
}
test_files
}
};
let (mut success, mut failure, mut error) = (0, 0, 0);
let test_results: Vec<(runner::TestCase, runner::TestResult)> = test_cases
.into_iter()
.map(|tc| {
let result = runner::run_test(&prog_filename, &tc);
match result {
runner::TestResult::Success => success += 1,
runner::TestResult::Failure { .. } => failure += 1,
_ => error += 1,
}
(tc, result)
})
.collect();
if show_diff {
for (tc, tres) in &test_results {
if let runner::TestResult::Failure { .. } = tres {
println!("{}", runner::get_diff(&tc, &tres));
println!();
}
}
}
for (tc, tres) in test_results {
println!("{}", runner::get_test_result_string(&tc, &tres));
}
println!();
println!("{} success, {} failure, {} error", success, failure, error);
if failure == 0 && error == 0 {
println!("All test cases passed.");
} else {
println!("FAILED some test cases.");
}
}
Action::NoOp => (),
}
}
}
|
/// CreatePullRequestOption options when creating a pull request
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CreatePullRequestOption {
pub assignee: Option<String>,
pub assignees: Option<Vec<String>>,
pub base: Option<String>,
pub body: Option<String>,
pub due_date: Option<String>,
pub head: Option<String>,
pub labels: Option<Vec<i64>>,
pub milestone: Option<i64>,
pub title: Option<String>,
}
impl CreatePullRequestOption {
/// Create a builder for this object.
#[inline]
pub fn builder() -> CreatePullRequestOptionBuilder {
CreatePullRequestOptionBuilder {
body: Default::default(),
}
}
#[inline]
pub fn repo_create_pull_request() -> CreatePullRequestOptionPostBuilder<crate::generics::MissingOwner, crate::generics::MissingRepo> {
CreatePullRequestOptionPostBuilder {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
}
}
}
impl Into<CreatePullRequestOption> for CreatePullRequestOptionBuilder {
fn into(self) -> CreatePullRequestOption {
self.body
}
}
impl Into<CreatePullRequestOption> for CreatePullRequestOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists> {
fn into(self) -> CreatePullRequestOption {
self.inner.body
}
}
/// Builder for [`CreatePullRequestOption`](./struct.CreatePullRequestOption.html) object.
#[derive(Debug, Clone)]
pub struct CreatePullRequestOptionBuilder {
body: self::CreatePullRequestOption,
}
impl CreatePullRequestOptionBuilder {
#[inline]
pub fn assignee(mut self, value: impl Into<String>) -> Self {
self.body.assignee = Some(value.into());
self
}
#[inline]
pub fn assignees(mut self, value: impl Iterator<Item = impl Into<String>>) -> Self {
self.body.assignees = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
#[inline]
pub fn base(mut self, value: impl Into<String>) -> Self {
self.body.base = Some(value.into());
self
}
#[inline]
pub fn body(mut self, value: impl Into<String>) -> Self {
self.body.body = Some(value.into());
self
}
#[inline]
pub fn due_date(mut self, value: impl Into<String>) -> Self {
self.body.due_date = Some(value.into());
self
}
#[inline]
pub fn head(mut self, value: impl Into<String>) -> Self {
self.body.head = Some(value.into());
self
}
#[inline]
pub fn labels(mut self, value: impl Iterator<Item = impl Into<i64>>) -> Self {
self.body.labels = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
#[inline]
pub fn milestone(mut self, value: impl Into<i64>) -> Self {
self.body.milestone = Some(value.into());
self
}
#[inline]
pub fn title(mut self, value: impl Into<String>) -> Self {
self.body.title = Some(value.into());
self
}
}
/// Builder created by [`CreatePullRequestOption::repo_create_pull_request`](./struct.CreatePullRequestOption.html#method.repo_create_pull_request) method for a `POST` operation associated with `CreatePullRequestOption`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct CreatePullRequestOptionPostBuilder<Owner, Repo> {
inner: CreatePullRequestOptionPostBuilderContainer,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
}
#[derive(Debug, Default, Clone)]
struct CreatePullRequestOptionPostBuilderContainer {
body: self::CreatePullRequestOption,
param_owner: Option<String>,
param_repo: Option<String>,
}
impl<Owner, Repo> CreatePullRequestOptionPostBuilder<Owner, Repo> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> CreatePullRequestOptionPostBuilder<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>) -> CreatePullRequestOptionPostBuilder<Owner, crate::generics::RepoExists> {
self.inner.param_repo = Some(value.into());
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn assignee(mut self, value: impl Into<String>) -> Self {
self.inner.body.assignee = Some(value.into());
self
}
#[inline]
pub fn assignees(mut self, value: impl Iterator<Item = impl Into<String>>) -> Self {
self.inner.body.assignees = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
#[inline]
pub fn base(mut self, value: impl Into<String>) -> Self {
self.inner.body.base = Some(value.into());
self
}
#[inline]
pub fn body(mut self, value: impl Into<String>) -> Self {
self.inner.body.body = Some(value.into());
self
}
#[inline]
pub fn due_date(mut self, value: impl Into<String>) -> Self {
self.inner.body.due_date = Some(value.into());
self
}
#[inline]
pub fn head(mut self, value: impl Into<String>) -> Self {
self.inner.body.head = Some(value.into());
self
}
#[inline]
pub fn labels(mut self, value: impl Iterator<Item = impl Into<i64>>) -> Self {
self.inner.body.labels = Some(value.map(|value| value.into()).collect::<Vec<_>>().into());
self
}
#[inline]
pub fn milestone(mut self, value: impl Into<i64>) -> Self {
self.inner.body.milestone = Some(value.into());
self
}
#[inline]
pub fn title(mut self, value: impl Into<String>) -> Self {
self.inner.body.title = Some(value.into());
self
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreatePullRequestOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists> {
type Output = crate::pull_request::PullRequest;
const METHOD: http::Method = http::Method::POST;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/pulls", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?")).into()
}
fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> {
use crate::client::Request;
Ok(req
.json(&self.inner.body))
}
}
impl crate::client::ResponseWrapper<crate::pull_request::PullRequest, CreatePullRequestOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists>> {
#[inline]
pub fn message(&self) -> Option<String> {
self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
#[inline]
pub fn url(&self) -> Option<String> {
self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
}
|
use super::{DataClass, DataIdDefinition};
use ::std::marker::PhantomData;
pub type DataIdSimpleType = (i8, i8);
pub(crate) static DATAID_DEFINITION : DataIdDefinition<DataIdSimpleType,DataIdType> =
DataIdDefinition {
data_id: 48,
class: DataClass::RemoteBoilerParameters,
read: true,
write: false,
check: None,
phantom_simple: PhantomData {},
phantom_complex: PhantomData {}
};
dataidtypedef!(upper_bound: i8, lower_bound: i8); |
use core::ops::AddAssign;
use super::vec2::*;
use super::vec3::*;
use std::ops::{Add, Div, Mul, Sub, Neg};
#[derive(Clone, Copy, Debug)]
pub struct Vec4 {
pub value: [f64; 4],
}
impl std::fmt::Display for Vec4 {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(fmt, "{},{},{},{}", self.value[0],self.value[1],self.value[2],self.value[3])
}
}
impl Vec4 {
pub const ORIGIN: Vec4 = Vec4 {
value: [0.0, 0.0, 0.0, 1.0],
};
pub fn new(x: f64, y: f64, z: f64, w: f64) -> Vec4 {
Vec4 {
value: [x, y, z, w],
}
}
pub fn normalize(mut self) -> Self {
let length = self.length();
for n in 0..3 {
self.value[n] = self.value[n] / length
}
self.value[3] = 1.0;
return self;
}
pub fn x(&self) -> f64 {
self.value[0]
}
pub fn y(&self) -> f64 {
self.value[1]
}
pub fn z(&self) -> f64 {
self.value[2]
}
pub fn w(&self) -> f64 {
self.value[3]
}
pub fn xyz(&self) -> Vec3 {
Vec3::new(self.value[0], self.value[1],self.value[2]) / self.value[3]
}
}
impl Vec4 {
pub fn xy<'a>(&'a self) -> Vec2 {
Vec2::new(self.x(), self.y())
}
pub fn length(&self) -> f64 {
(self.x() * self.x() + self.y() * self.y() + self.z() * self.z()).sqrt() / self.w()
}
pub fn cross(v1: Vec4, v2: Vec4) -> Vec4 {
// (a b c) X (d e f)
// (bf-ce, cd-af, ae-bd)
let inv_div = 1.0 / (v1.w() * v2.w());
Vec4::new(
(v1.y() * v2.z() - v1.z() * v2.y()) * inv_div,
(v1.z() * v2.x() - v1.x() * v2.z()) * inv_div,
(v1.x() * v2.y() - v1.y() * v2.x()) * inv_div,
1.0,
)
}
pub fn dot(v1: &Vec4, v2: &Vec4) -> f64 {
let inv_div = 1.0 / (v1.w() * v2.w());
(v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z()) * inv_div
}
}
impl Add for Vec4 {
type Output = Vec4;
fn add(self, other: Self) -> Vec4 {
let mut clone = self.clone();
clone.value[0] = clone.x() / clone.w() + other.x() / other.w();
clone.value[1] = clone.y() / clone.w() + other.y() / other.w();
clone.value[2] = clone.z() / clone.w() + other.z() / other.w();
clone.value[3] = 1.0;
clone
}
}
impl AddAssign<Self> for Vec4 {
fn add_assign(&mut self, other: Self) {
if other.value[3] == 0.0 {
self.value = other.value;
return;
}
let factor = self.value[3] / other.value[3];
self.value[0] += other.value[0] * factor;
self.value[1] += other.value[1] * factor;
self.value[2] += other.value[2] * factor;
self.value[3] = 1.0;
}
}
impl Neg for Vec4 {
type Output = Vec4;
fn neg(mut self) -> Vec4 {
self.value[3] = - self.value[3];
self
}
}
impl Sub for Vec4 {
type Output = Vec4;
fn sub(self, other: Self) -> Vec4 {
let mut clone = self.clone();
clone.value[0] = clone.x() / clone.w() - other.x() / other.w();
clone.value[1] = clone.y() / clone.w() - other.y() / other.w();
clone.value[2] = clone.z() / clone.w() - other.z() / other.w();
clone.value[3] = 1.0;
clone
}
}
impl Div<f64> for Vec4 {
type Output = Vec4;
fn div(self, other: f64) -> Vec4 {
let mut clone = self.clone();
clone.value[3] *= other;
clone
}
}
impl Mul<f64> for Vec4 {
type Output = Vec4;
fn mul(self, other: f64) -> Vec4 {
let mut clone = self.clone();
clone.value[3] /= other;
clone
}
}
impl Mul<Self> for Vec4 {
type Output = f64;
fn mul(self, other: Self) -> f64 {
let mut res = 0.0;
for i in 0..3 {
res += self.value[i] * other.value[i];
}
res / self.value[3] / other.value[3]
}
} |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//! An implementation of a 62-bit STARK-friendly prime field with modulus 2^62 - 111 * 2^39 + 1.
//!
//! All operations in this field are implemented using Montgomery arithmetic. It supports very
//! fast modular arithmetic including branchless multiplication and addition. Base elements are
//! stored in the Montgomery form using `u64` as the backing type.
use super::{
traits::{FieldElement, StarkField},
QuadExtensionA,
};
use core::{
convert::{TryFrom, TryInto},
fmt::{Debug, Display, Formatter},
mem,
ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
slice,
};
use utils::{
collections::Vec, string::ToString, AsBytes, ByteReader, ByteWriter, Deserializable,
DeserializationError, Serializable,
};
#[cfg(feature = "std")]
use core::ops::Range;
#[cfg(feature = "std")]
use rand::{distributions::Uniform, prelude::*};
#[cfg(test)]
mod tests;
// CONSTANTS
// ================================================================================================
/// Field modulus = 2^62 - 111 * 2^39 + 1
const M: u64 = 4611624995532046337;
/// 2^128 mod M; this is used for conversion of elements into Montgomery representation.
const R2: u64 = 630444561284293700;
/// 2^192 mod M; this is used during element inversion.
const R3: u64 = 732984146687909319;
/// -M^{-1} mod 2^64; this is used during element multiplication.
const U: u128 = 4611624995532046335;
/// Number of bytes needed to represent field element
const ELEMENT_BYTES: usize = core::mem::size_of::<u64>();
// 2^39 root of unity
const G: u64 = 4421547261963328785;
#[cfg(feature = "std")]
const RANGE: Range<u64> = Range { start: 0, end: M };
// FIELD ELEMENT
// ================================================================================================
/// Represents base field element in the field.
///
/// Internal values are stored in Montgomery representation and can be in the range [0; 2M). The
/// backing type is `u64`.
#[derive(Copy, Clone, Debug, Default)]
pub struct BaseElement(u64);
impl BaseElement {
/// Creates a new field element from the provided `value`; the value is converted into
/// Montgomery representation.
pub const fn new(value: u64) -> BaseElement {
// multiply the value with R2 to convert to Montgomery representation; this is OK because
// given the value of R2, the product of R2 and `value` is guaranteed to be in the range
// [0, 4M^2 - 4M + 1)
let z = mul(value, R2);
BaseElement(z)
}
}
impl FieldElement for BaseElement {
type PositiveInteger = u64;
type BaseField = Self;
const ZERO: Self = BaseElement::new(0);
const ONE: Self = BaseElement::new(1);
const ELEMENT_BYTES: usize = ELEMENT_BYTES;
const IS_MALLEABLE: bool = true;
fn exp(self, power: Self::PositiveInteger) -> Self {
let mut b = self;
if power == 0 {
return Self::ONE;
} else if b == Self::ZERO {
return Self::ZERO;
}
let mut r = if power & 1 == 1 { b } else { Self::ONE };
for i in 1..64 - power.leading_zeros() {
b = b.square();
if (power >> i) & 1 == 1 {
r *= b;
}
}
r
}
fn inv(self) -> Self {
BaseElement(inv(self.0))
}
fn conjugate(&self) -> Self {
BaseElement(self.0)
}
#[cfg(feature = "std")]
fn rand() -> Self {
let range = Uniform::from(RANGE);
let mut g = thread_rng();
BaseElement::new(g.sample(range))
}
fn from_random_bytes(bytes: &[u8]) -> Option<Self> {
Self::try_from(bytes).ok()
}
fn elements_into_bytes(elements: Vec<Self>) -> Vec<u8> {
let mut v = core::mem::ManuallyDrop::new(elements);
let p = v.as_mut_ptr();
let len = v.len() * Self::ELEMENT_BYTES;
let cap = v.capacity() * Self::ELEMENT_BYTES;
unsafe { Vec::from_raw_parts(p as *mut u8, len, cap) }
}
fn elements_as_bytes(elements: &[Self]) -> &[u8] {
// TODO: take endianness into account
let p = elements.as_ptr();
let len = elements.len() * Self::ELEMENT_BYTES;
unsafe { slice::from_raw_parts(p as *const u8, len) }
}
unsafe fn bytes_as_elements(bytes: &[u8]) -> Result<&[Self], DeserializationError> {
if bytes.len() % Self::ELEMENT_BYTES != 0 {
return Err(DeserializationError::InvalidValue(format!(
"number of bytes ({}) does not divide into whole number of field elements",
bytes.len(),
)));
}
let p = bytes.as_ptr();
let len = bytes.len() / Self::ELEMENT_BYTES;
if (p as usize) % mem::align_of::<u64>() != 0 {
return Err(DeserializationError::InvalidValue(
"slice memory alignment is not valid for this field element type".to_string(),
));
}
Ok(slice::from_raw_parts(p as *const Self, len))
}
fn zeroed_vector(n: usize) -> Vec<Self> {
// this uses a specialized vector initialization code which requests zero-filled memory
// from the OS; unfortunately, this works only for built-in types and we can't use
// Self::ZERO here as much less efficient initialization procedure will be invoked.
// We also use u64 to make sure the memory is aligned correctly for our element size.
let result = vec![0u64; n];
// translate a zero-filled vector of u64s into a vector of base field elements
let mut v = core::mem::ManuallyDrop::new(result);
let p = v.as_mut_ptr();
let len = v.len();
let cap = v.capacity();
unsafe { Vec::from_raw_parts(p as *mut Self, len, cap) }
}
#[cfg(feature = "std")]
fn prng_vector(seed: [u8; 32], n: usize) -> Vec<Self> {
let range = Uniform::from(RANGE);
let g = StdRng::from_seed(seed);
g.sample_iter(range).take(n).map(BaseElement::new).collect()
}
#[inline(always)]
fn normalize(&mut self) {
self.0 = normalize(self.0)
}
}
impl StarkField for BaseElement {
type QuadExtension = QuadExtensionA<Self>;
/// sage: MODULUS = 2^62 - 111 * 2^39 + 1 \
/// sage: GF(MODULUS).is_prime_field() \
/// True \
/// sage: GF(MODULUS).order() \
/// 4611624995532046337
const MODULUS: Self::PositiveInteger = M;
const MODULUS_BITS: u32 = 64;
/// sage: GF(MODULUS).primitive_element() \
/// 3
const GENERATOR: Self = BaseElement::new(3);
/// sage: is_odd((MODULUS - 1) / 2^39) \
/// True
const TWO_ADICITY: u32 = 39;
/// sage: k = (MODULUS - 1) / 2^39 \
/// sage: GF(MODULUS).primitive_element()^k \
/// 4421547261963328785
const TWO_ADIC_ROOT_OF_UNITY: Self = BaseElement::new(G);
fn get_modulus_le_bytes() -> Vec<u8> {
Self::MODULUS.to_le_bytes().to_vec()
}
fn as_int(&self) -> Self::PositiveInteger {
// convert from Montgomery representation by multiplying by 1
let result = mul(self.0, 1);
// since the result of multiplication can be in [0, 2M), we need to normalize it
normalize(result)
}
}
impl Display for BaseElement {
fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
write!(f, "{}", self.as_int())
}
}
// EQUALITY CHECKS
// ================================================================================================
impl PartialEq for BaseElement {
fn eq(&self, other: &Self) -> bool {
// since either of the elements can be in [0, 2M) range, we normalize them first to be
// in [0, M) range and then compare them.
normalize(self.0) == normalize(other.0)
}
}
impl Eq for BaseElement {}
// OVERLOADED OPERATORS
// ================================================================================================
impl Add for BaseElement {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Self(add(self.0, rhs.0))
}
}
impl AddAssign for BaseElement {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs
}
}
impl Sub for BaseElement {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self(sub(self.0, rhs.0))
}
}
impl SubAssign for BaseElement {
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs;
}
}
impl Mul for BaseElement {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
Self(mul(self.0, rhs.0))
}
}
impl MulAssign for BaseElement {
fn mul_assign(&mut self, rhs: Self) {
*self = *self * rhs
}
}
impl Div for BaseElement {
type Output = Self;
fn div(self, rhs: Self) -> Self {
Self(mul(self.0, inv(rhs.0)))
}
}
impl DivAssign for BaseElement {
fn div_assign(&mut self, rhs: Self) {
*self = *self / rhs
}
}
impl Neg for BaseElement {
type Output = Self;
fn neg(self) -> Self {
Self(sub(0, self.0))
}
}
// TYPE CONVERSIONS
// ================================================================================================
impl From<u128> for BaseElement {
/// Converts a 128-bit value into a filed element. If the value is greater than or equal to
/// the field modulus, modular reduction is silently preformed.
fn from(value: u128) -> Self {
// make sure the value is < 4M^2 - 4M + 1; this is overly conservative and a single
// subtraction of (M * 2^65) should be enough, but this needs to be proven
const M4: u128 = (2 * M as u128).pow(2) - 4 * (M as u128) + 1;
const Q: u128 = (2 * M as u128).pow(2) - 4 * (M as u128);
let mut v = value;
while v >= M4 {
v -= Q;
}
// apply similar reduction as during multiplication; as output we get z = v * R^{-1} mod M,
// so we need to Montgomery-multiply it be R^3 to get z = v * R mod M
let q = (((v as u64) as u128) * U) as u64;
let z = v + (q as u128) * (M as u128);
let z = mul((z >> 64) as u64, R3);
BaseElement(z)
}
}
impl From<u64> for BaseElement {
/// Converts a 64-bit value into a filed element. If the value is greater than or equal to
/// the field modulus, modular reduction is silently preformed.
fn from(value: u64) -> Self {
BaseElement::new(value)
}
}
impl From<u32> for BaseElement {
/// Converts a 32-bit value into a filed element.
fn from(value: u32) -> Self {
BaseElement::new(value as u64)
}
}
impl From<u16> for BaseElement {
/// Converts a 16-bit value into a filed element.
fn from(value: u16) -> Self {
BaseElement::new(value as u64)
}
}
impl From<u8> for BaseElement {
/// Converts an 8-bit value into a filed element.
fn from(value: u8) -> Self {
BaseElement::new(value as u64)
}
}
impl From<[u8; 8]> for BaseElement {
/// Converts the value encoded in an array of 8 bytes into a field element. The bytes are
/// assumed to encode the element in the canonical representation in little-endian byte order.
/// If the value is greater than or equal to the field modulus, modular reduction is silently
/// preformed.
fn from(bytes: [u8; 8]) -> Self {
let value = u64::from_le_bytes(bytes);
BaseElement::new(value)
}
}
impl<'a> TryFrom<&'a [u8]> for BaseElement {
type Error = DeserializationError;
/// Converts a slice of bytes into a field element; returns error if the value encoded in bytes
/// is not a valid field element. The bytes are assumed to encode the element in the canonical
/// representation in little-endian byte order.
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
if bytes.len() < ELEMENT_BYTES {
return Err(DeserializationError::InvalidValue(format!(
"not enough bytes for a full field element; expected {} bytes, but was {} bytes",
ELEMENT_BYTES,
bytes.len(),
)));
}
if bytes.len() > ELEMENT_BYTES {
return Err(DeserializationError::InvalidValue(format!(
"too many bytes for a field element; expected {} bytes, but was {} bytes",
ELEMENT_BYTES,
bytes.len(),
)));
}
let value = bytes
.try_into()
.map(u64::from_le_bytes)
.map_err(|error| DeserializationError::UnknownError(format!("{}", error)))?;
if value >= M {
return Err(DeserializationError::InvalidValue(format!(
"invalid field element: value {} is greater than or equal to the field modulus",
value
)));
}
Ok(BaseElement::new(value))
}
}
impl AsBytes for BaseElement {
fn as_bytes(&self) -> &[u8] {
// TODO: take endianness into account
let self_ptr: *const BaseElement = self;
unsafe { slice::from_raw_parts(self_ptr as *const u8, ELEMENT_BYTES) }
}
}
// SERIALIZATION / DESERIALIZATION
// ------------------------------------------------------------------------------------------------
impl Serializable for BaseElement {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
// convert from Montgomery representation into canonical representation
target.write_u8_slice(&self.as_int().to_le_bytes());
}
}
impl Deserializable for BaseElement {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let value = source.read_u64()?;
if value >= M {
return Err(DeserializationError::InvalidValue(format!(
"invalid field element: value {} is greater than or equal to the field modulus",
value
)));
}
Ok(BaseElement::new(value))
}
}
// FINITE FIELD ARITHMETIC
// ================================================================================================
/// Computes (a + b) reduced by M such that the output is in [0, 2M) range; a and b are assumed to
/// be in [0, 2M).
#[inline(always)]
fn add(a: u64, b: u64) -> u64 {
let z = a + b;
let q = (z >> 62) * M;
z - q
}
/// Computes (a - b) reduced by M such that the output is in [0, 2M) range; a and b are assumed to
/// be in [0, 2M).
#[inline(always)]
fn sub(a: u64, b: u64) -> u64 {
if a < b {
2 * M - b + a
} else {
a - b
}
}
/// Computes (a * b) reduced by M such that the output is in [0, 2M) range; a and b are assumed to
/// be in [0, 2M).
#[inline(always)]
const fn mul(a: u64, b: u64) -> u64 {
let z = (a as u128) * (b as u128);
let q = (((z as u64) as u128) * U) as u64;
let z = z + (q as u128) * (M as u128);
(z >> 64) as u64
}
/// Computes y such that (x * y) % M = 1 except for when when x = 0; in such a case, 0 is returned;
/// x is assumed to in [0, 2M) range, and the output will also be in [0, 2M) range.
#[inline(always)]
#[allow(clippy::many_single_char_names)]
fn inv(x: u64) -> u64 {
if x == 0 {
return 0;
};
let mut a: u128 = 0;
let mut u: u128 = if x & 1 == 1 {
x as u128
} else {
(x as u128) + (M as u128)
};
let mut v: u128 = M as u128;
let mut d = (M as u128) - 1;
while v != 1 {
while v < u {
u -= v;
d += a;
while u & 1 == 0 {
if d & 1 == 1 {
d += M as u128;
}
u >>= 1;
d >>= 1;
}
}
v -= u;
a += d;
while v & 1 == 0 {
if a & 1 == 1 {
a += M as u128;
}
v >>= 1;
a >>= 1;
}
}
while a > (M as u128) {
a -= M as u128;
}
mul(a as u64, R3)
}
// HELPER FUNCTIONS
// ================================================================================================
/// Reduces any value in [0, 2M) range to [0, M) range
#[inline(always)]
fn normalize(value: u64) -> u64 {
if value >= M {
value - M
} else {
value
}
}
|
#[macro_use]
extern crate criterion;
use criterion::{AxisScale, BenchmarkId, Criterion, PlotConfiguration};
use rand::prelude::*;
use std::ops::Range;
fn kitchen_sink(kvs: &[(Range<i32>, bool)]) {
use segmap::SegmentMap;
let mut range_map: SegmentMap<i32, bool> = SegmentMap::new();
// Remove every second range.
let mut remove = false;
for (range, value) in kvs {
if remove {
range_map.clear_range(range.clone());
} else {
range_map.set(range.clone(), *value);
}
remove = !remove;
}
}
fn old_kitchen_sink(kvs: &[(Range<i32>, bool)]) {
use rangemap::RangeMap;
let mut range_map: RangeMap<i32, bool> = RangeMap::new();
// Remove every second range.
let mut remove = false;
for (range, value) in kvs {
if remove {
range_map.remove(range.clone());
} else {
range_map.insert(range.clone(), *value);
}
remove = !remove;
}
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("kitchen sink", |b| {
let mut rng = thread_rng();
let kvs: Vec<(Range<i32>, bool)> = (0..1000)
.map(|_| {
let start = rng.gen_range(0..1000);
let end = start + rng.gen_range(1..100);
let value: bool = random();
(start..end, value)
})
.collect();
b.iter(|| kitchen_sink(&kvs))
});
let mut group = c.benchmark_group("comparison");
let mut rng = thread_rng();
group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic));
group.sample_size(100);
group.measurement_time(std::time::Duration::from_secs(60));
for elems in (1..=6u32).map(|exp| 10i32.pow(exp)) {
let kvs: Vec<(Range<i32>, bool)> = (0..elems)
.map(|_| {
let start = rng.gen_range(0..1000);
let end = start + rng.gen_range(1..100);
let value: bool = random();
(start..end, value)
})
.collect();
group.bench_with_input(BenchmarkId::new("Published", elems), &kvs, |b, kvs| {
b.iter(|| old_kitchen_sink(kvs))
});
group.bench_with_input(BenchmarkId::new("Forked", elems), &kvs, |b, kvs| {
b.iter(|| kitchen_sink(kvs))
});
}
group.finish()
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
/*!
* Sylphrena AI core program - https://github.com/ShardAi
* Version - 1.0.0.0
*
* Copyright (c) 2017 Eirik Skjeggestad Dale
*/
extern crate daemonize;
mod core;
use std::{thread, time, env};
use std::fs::File;
use daemonize::Daemonize;
use core::syl_core::Sylcore;
fn main() {
println!("---=== Sylphrena-core started ===---");
for argument in env::args() {
if argument == "-help" || argument == "-h" {
println!("List of available arguments:");
println!("-h See the available arguments");
println!("-d Start this application as daemon");
}
else if argument == "-d" {
let stdout = File::create("/tmp/sylphrena-core.out").unwrap();
let stderr = File::create("/tmp/sylphrena-core.err").unwrap();
let daemonize = Daemonize::new()
.pid_file("/tmp/sylphrena-core.pid") // Every method except `new` and `start`
.chown_pid_file(true) // is optional, see `Daemonize` documentation
.working_directory("/tmp") // for default behaviour.
.user("root")
.group("daemon") // Group name
.group(2) // or group id.
.umask(0o777) // Set umask, `0o027` by default.
.stdout(stdout) // Redirect stdout to `/tmp/sylphrena-core.out`.
.stderr(stderr) // Redirect stderr to `/tmp/sylphrena-core.err`.
.privileged_action(|| "Executed before drop privileges");
match daemonize.start() {
Ok(_) => println!("Success, sylphrena-core daemonized"),
Err(e) => eprintln!("Error, {}", e),
}
}
}
let mut core = Sylcore::new("syl-core");
core.start_server();
let mut counter = 0;
loop {
counter += 1;
println!("One more step in the loop, count: {0}", counter);
thread::sleep(time::Duration::from_millis(10000)); // set to 60000 when actually done with main method.
}
}
|
// Copyright (C) 2020 Stephane Raux. Distributed under the MIT license.
use std::{
io,
time::Duration,
};
use winapi::{
shared::ntdef::LARGE_INTEGER,
um::profileapi::{QueryPerformanceCounter, QueryPerformanceFrequency},
};
#[derive(Debug)]
pub struct Clock {
freq: u64,
last_elapsed: Duration,
}
impl Clock {
pub fn new() -> Self {
let mut freq = LARGE_INTEGER::default();
let status = unsafe {
QueryPerformanceFrequency(&mut freq)
};
if status == 0 {
let error = io::Error::last_os_error();
panic!("QueryPerformanceFrequency failed (it is documented as infallible since \
Windows XP): {}", error);
}
Self {
freq: unsafe { *freq.QuadPart() as u64 },
last_elapsed: Default::default(),
}
}
pub fn elapsed(&mut self) -> Duration {
let mut counter = LARGE_INTEGER::default();
let status = unsafe {
QueryPerformanceCounter(&mut counter)
};
if status == 0 {
let error = io::Error::last_os_error();
panic!("QueryPerformanceCounter failed (it is documented as infallible since \
Windows XP): {}", error);
}
let counter = unsafe { *counter.QuadPart() as u64 };
let seconds = counter / self.freq;
let nanoseconds = (counter % self.freq) as u128 * 1_000_000_000 / self.freq as u128;
let nanoseconds = nanoseconds as u32;
let d = Duration::new(seconds, nanoseconds);
if self.last_elapsed < d {
self.last_elapsed = d;
}
self.last_elapsed
}
}
|
pub mod lexer;
pub mod token;
pub use self::token::Token;
pub use self::lexer::Lexer;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.