text stringlengths 8 4.13M |
|---|
// -*- rust -*-
iter two() -> int { put 0; put 1; }
fn main() {
let a: [mutable int] = [mutable -1, -1, -1, -1];
let p: int = 0;
for each i: int in two() {
for each j: int in two() { a[p] = 10 * i + j; p += 1; }
}
assert (a[0] == 0);
assert (a[1] == 1);
assert (a[2] == 10);
assert (a[3] == 11);
}
|
use actix::prelude::*;
/// Notify game of a disconnected participant
#[derive(Message)]
#[rtype(result = "()")]
pub struct Disconnected {
pub name: String,
pub participant_type: String,
}
/// Notify game of an unresponsive participant (not responding to pings)
#[derive(Message)]
#[rtype(result = "()")]
pub struct Unresponsive {
pub name: String,
pub participant_type: String,
}
/// Notify game of a responding participant who was previously unresponsive
#[derive(Message)]
#[rtype(result = "()")]
pub struct Responsive {
pub name: String,
pub participant_type: String,
}
|
use super::*;
use log::info;
// TODO: probably move out proc gen
#[derive(Default)]
pub struct GamePlaySystem;
impl<'a> System<'a> for GamePlaySystem {
type SystemData = (
(
Entities<'a>,
WriteStorage<'a, Isometry>,
WriteStorage<'a, Blast>,
WriteStorage<'a, MultyLazer>,
WriteStorage<'a, ShotGun>,
WriteStorage<'a, Lifetime>,
WriteStorage<'a, AsteroidMarker>,
ReadStorage<'a, CharacterMarker>,
ReadStorage<'a, ShipMarker>,
WriteStorage<'a, Polygon>,
WriteStorage<'a, Shield>,
WriteStorage<'a, Lifes>,
WriteStorage<'a, DamageFlash>,
ReadStorage<'a, ShipStats>,
ReadStorage<'a, Coin>,
ReadStorage<'a, Exp>,
ReadStorage<'a, Health>,
ReadStorage<'a, SideBulletCollectable>,
ReadStorage<'a, SideBulletAbility>,
ReadStorage<'a, DoubleCoinsCollectable>,
ReadStorage<'a, DoubleExpCollectable>,
ReadStorage<'a, CollectableMarker>,
ReadStorage<'a, DoubleCoinsAbility>,
ReadStorage<'a, DoubleExpAbility>,
ReadStorage<'a, AtlasImage>,
ReadStorage<'a, Size>,
),
ReadStorage<'a, ReflectBulletCollectable>,
ReadStorage<'a, ReflectBulletAbility>,
ReadExpect<'a, red::Viewport>,
ReadStorage<'a, Projectile>,
ReadExpect<'a, PreloadedImages>,
Write<'a, EventChannel<InsertEvent>>,
Write<'a, Progress>,
Write<'a, SpawnedUpgrades>,
Read<'a, AvaliableUpgrades>,
ReadExpect<'a, Description>,
Write<'a, CurrentWave>,
Read<'a, Waves>,
Write<'a, EventChannel<Sound>>,
ReadExpect<'a, PreloadedSounds>,
Write<'a, AppState>,
WriteExpect<'a, MacroGame>,
WriteExpect<'a, GlobalParams>,
ReadExpect<'a, Arc<Mutex<EventChannel<InsertEvent>>>>,
Read<'a, LazyUpdate>,
Write<'a, UpgradesStats>,
);
fn run(&mut self, data: Self::SystemData) {
let (
(
entities,
mut isometries,
blasts,
mut multiple_lazers,
mut shotguns,
mut lifetimes,
asteroid_markers,
character_markers,
ships,
polygons,
mut shields,
mut lifes,
mut flashes,
ships_stats,
coins,
exps,
healths,
side_bullet_collectables,
side_bullet_ability,
double_coins_collectable,
double_exp_collectable,
collectables,
double_coins_abilities,
double_exp_abilities,
atlas_images,
sizes,
),
reflect_bullet_collectable,
reflect_bullet_ability,
viewport,
projectiles,
preloaded_images,
mut insert_channel,
mut progress,
mut spawned_upgrades,
avaliable_upgrades,
description,
mut current_wave,
waves,
mut sounds_channel,
preloaded_sounds,
mut app_state,
mut macro_game,
mut global_params,
asteroids_channel,
lazy_update,
mut upgrade_stats,
) = data;
let dims = viewport.dimensions();
let (w, h) = (dims.0 as f32, dims.1 as f32);
info!("asteroids: gameplay started");
for flash in (&mut flashes).join() {
flash.0 /= 1.2f32;
}
if let Some((shield, life, ship_stats, _character)) =
(&mut shields, &mut lifes, &ships_stats, &character_markers)
.join()
.next()
{
shield.0 =
(shield.0 + ship_stats.shield_regen).min(ship_stats.max_shield);
life.0 =
(life.0 + ship_stats.health_regen).min(ship_stats.max_health);
} else {
return;
};
if progress.experience >= progress.current_max_experience() {
progress.level_up();
let mut rng = thread_rng();
let up_id = rng.gen_range(0, avaliable_upgrades.len());
let mut second_id = rng.gen_range(0, avaliable_upgrades.len());
while second_id == up_id {
second_id = rng.gen_range(0, avaliable_upgrades.len());
}
spawned_upgrades.push([up_id, second_id]);
// *app_state = AppState::Play(PlayState::Upgrade);
}
let (char_entity, char_isometry, _char) =
(&entities, &isometries, &character_markers)
.join()
.next()
.unwrap();
let char_isometry = char_isometry.clone(); // to avoid borrow
let pos3d = char_isometry.0.translation.vector;
let character_position = Point2::new(pos3d.x, pos3d.y);
{
// player trace
let mut transparent_basic = preloaded_images.glow;
transparent_basic.transparency = 0.1;
let trace = entities.create();
lazy_update
.insert(trace, Size(sizes.get(char_entity).unwrap().0 * 1.3)); // hack
lazy_update.insert(trace, transparent_basic);
lazy_update.insert(trace, char_isometry);
lazy_update
.insert(trace, Lifetime::new(Duration::from_millis(300)));
for (entity, iso, projectile, bullet_image, size) in
(&entities, &isometries, &projectiles, &atlas_images, &sizes)
.join()
{
let mut transparent_bullet = bullet_image.clone();
transparent_bullet.transparency = 0.1;
let trace = entities.create();
lazy_update.insert(trace, *size);
lazy_update.insert(trace, transparent_bullet);
lazy_update.insert(trace, iso.clone());
lazy_update
.insert(trace, Lifetime::new(Duration::from_millis(300)));
}
}
for (entity, lifetime) in (&entities, &mut lifetimes).join() {
if lifetime.delete() {
if double_coins_abilities.get(entity).is_some() {
upgrade_stats.coins_mult /= 2;
entities.delete(entity).unwrap();
}
if double_exp_abilities.get(entity).is_some() {
upgrade_stats.exp_mult /= 2;
entities.delete(entity).unwrap();
}
if side_bullet_ability.get(entity).is_some() {
if let Some(gun) = shotguns.get_mut(char_entity) {
// it's hack to avoid overflow
// posibble if we forgot to delete upgrade from previous game
if gun.side_projectiles_number > 0 {
gun.side_projectiles_number -= 1;
}
}
if let Some(multy_lazer) =
multiple_lazers.get_mut(char_entity)
{
multy_lazer.minus_side_lazers();
}
}
if let Some(reflect_ability) =
reflect_bullet_ability.get(entity)
{
if reflect_bullet_ability.count() == 1 {
if let Some(gun) = shotguns.get_mut(char_entity) {
if gun.reflection.is_some() {
gun.reflection = None
}
}
// if let Some(ref mut reflection) = gun.reflection {
// reflection.lifetime += Duration::from_millis(200);
// }
}
}
if let Some(blast) = blasts.get(entity) {
let owner =
if let Some(projectile) = projectiles.get(entity) {
projectile.owner
} else {
entity
};
let position =
isometries.get(entity).unwrap().0.translation.vector;
blast_explode(
Point2::new(position.x, position.y),
&mut insert_channel,
&mut sounds_channel,
&preloaded_sounds,
&preloaded_images,
blast.blast_radius,
);
// process_blast_damage
let blast_position =
isometries.get(entity).unwrap().0.translation.vector;
for (entity, life, isometry) in
(&entities, &mut lifes, &isometries).join()
{
let position = isometry.0.translation.vector;
let is_character = entity == char_entity;
let is_asteroid =
asteroid_markers.get(entity).is_some();
let affected = is_character && owner != char_entity
|| entity != char_entity
&& (owner == char_entity || is_asteroid);
if affected
&& (blast_position - position).norm()
< blast.blast_radius
{
if is_character {
global_params.damaged(DAMAGED_RED);
}
if process_damage(
life,
shields.get_mut(entity),
blast.blast_damage,
) {
if is_asteroid {
let asteroid = entity;
let polygon = polygons.get(entity).unwrap();
asteroid_explode(
Point2::new(position.x, position.y),
&mut insert_channel,
&mut sounds_channel,
&preloaded_sounds,
&preloaded_images,
polygon.max_r,
);
let iso =
isometries.get(asteroid).unwrap().0;
let poly =
polygons.get(asteroid).unwrap().clone();
let channel_arc =
(*asteroids_channel).clone();
thread::spawn(move || {
spawn_asteroids(
iso,
poly,
channel_arc,
None,
);
});
}
if is_character {
to_menu(
&mut app_state,
&mut progress,
&mut macro_game.score_table,
);
}
// delete character
entities.delete(entity).unwrap();
// dbg!("dead");
}
}
}
}
entities.delete(entity).unwrap()
}
}
for (entity, iso, _collectable) in
(&entities, &mut isometries, &collectables).join()
{
let collectable_position = iso.0.translation.vector;
if (pos3d - collectable_position).norm() < MAGNETO_RADIUS {
let vel = 0.3 * (pos3d - collectable_position).normalize();
iso.0.translation.vector += vel;
}
if (pos3d - collectable_position).norm() < COLLECT_RADIUS {
let mut rng = thread_rng();
if let Some(coin) = coins.get(entity) {
let coin_id = rng.gen_range(1, 3);
let coins_add = upgrade_stats.coins_mult * coin.0;
add_text(
&entities,
TextComponent {
text: format!("+{}", coins_add).to_string(),
color: (1.0, 1.0, 0.7, 1.0),
},
&lazy_update,
Point2::new(
collectable_position.x,
collectable_position.y,
),
Some(Lifetime::new(Duration::from_secs(1))),
);
let coin_sound = if coin_id == 0 {
preloaded_sounds.coin
} else {
preloaded_sounds.coin2
};
sounds_channel.single_write(Sound(
coin_sound,
Point2::new(
collectable_position.x,
collectable_position.y,
),
));
progress.add_coins(coins_add);
progress.add_score(coins_add);
macro_game.coins += coins_add;
}
if let Some(exp) = exps.get(entity) {
sounds_channel.single_write(Sound(
preloaded_sounds.exp,
Point2::new(
collectable_position.x,
collectable_position.y,
),
));
let add_exp = upgrade_stats.exp_mult * exp.0;
progress.add_score(3 * add_exp);
add_text(
&entities,
TextComponent {
text: format!("+{}", add_exp).to_string(),
color: (0.6, 3.0, 1.0, 1.0),
},
&lazy_update,
Point2::new(
collectable_position.x,
collectable_position.y,
),
Some(Lifetime::new(Duration::from_secs(1))),
);
progress.add_exp(add_exp);
}
if let Some(health) = healths.get(entity) {
lifes.get_mut(char_entity).unwrap().0 += health.0;
}
if side_bullet_collectables.get(entity).is_some() {
insert_channel.single_write(InsertEvent::SideBulletAbility);
add_text(
&entities,
TextComponent {
text: "Triple bullets".to_string(),
color: (1.0, 1.0, 1.0, 1.0),
},
&lazy_update,
Point2::new(
collectable_position.x,
collectable_position.y,
),
Some(Lifetime::new(Duration::from_secs(1))),
);
if let Some(gun) = shotguns.get_mut(char_entity) {
gun.side_projectiles_number += 1;
}
if let Some(multy_lazer) =
multiple_lazers.get_mut(char_entity)
{
multy_lazer.plus_side_lazers();
}
}
if double_coins_collectable.get(entity).is_some() {
add_text(
&entities,
TextComponent {
text: "Double coins".to_string(),
color: (1.0, 1.0, 1.0, 1.0),
},
&lazy_update,
Point2::new(
collectable_position.x,
collectable_position.y,
),
Some(Lifetime::new(Duration::from_secs(1))),
);
insert_channel.single_write(InsertEvent::DoubleCoinsAbility)
}
if reflect_bullet_collectable.get(entity).is_some() {
add_text(
&entities,
TextComponent {
text: "Reflectable".to_string(),
color: (1.0, 1.0, 1.0, 1.0),
},
&lazy_update,
Point2::new(
collectable_position.x,
collectable_position.y,
),
Some(Lifetime::new(Duration::from_secs(1))),
);
insert_channel
.single_write(InsertEvent::ReflectBulletAbility)
}
if double_exp_collectable.get(entity).is_some() {
add_text(
&entities,
TextComponent {
text: "Double experience".to_string(),
color: (1.0, 1.0, 1.0, 1.0),
},
&lazy_update,
Point2::new(
collectable_position.x,
collectable_position.y,
),
Some(Lifetime::new(Duration::from_secs(1))),
);
insert_channel.single_write(InsertEvent::DoubleExpAbility)
}
entities.delete(entity).unwrap();
}
}
let cnt = ships.count();
let wave = &waves.0[current_wave.id];
let (add_cnt, const_spawn) = if cnt == 1 {
current_wave.iteration += 1;
(wave.ships_number - cnt + 1, true)
} else {
(0, false)
};
if current_wave.iteration > wave.iterations {
current_wave.iteration = 0;
current_wave.id = (waves.0.len() - 1).min(current_wave.id + 1);
add_screen_text(
&entities,
TextComponent {
text: format!("Wave {}", current_wave.id).to_string(),
color: (1.0, 1.0, 0.7, 1.0),
},
&lazy_update,
Point2::new(w / 2.0, h / 2.0),
Some(Lifetime::new(Duration::from_secs(1))),
);
}
let mut rng = thread_rng();
fn ships2insert(spawn_pos: Point2, enemy: EnemyKind) -> InsertEvent {
InsertEvent::Ship {
iso: Point3::new(spawn_pos.x, spawn_pos.y, 0f32),
light_shape: Geometry::Circle { radius: 1f32 },
spin: 0f32,
kind: enemy.ai_kind,
gun_kind: enemy.gun_kind,
ship_stats: enemy.ship_stats,
size: enemy.size,
image: enemy.image,
snake: enemy.snake,
rift: enemy.rift,
}
};
for _ in 0..add_cnt {
if wave.distribution.len() > 0 {
let spawn_pos = spawn_position(
character_position,
PLAYER_AREA,
ACTIVE_AREA,
);
// TODO move from loop
let ships = &description.enemies;
let ship_id = wave
.distribution
.choose_weighted(&mut rng, |item| item.1)
.unwrap()
.0;
insert_channel.single_write(ships2insert(
spawn_pos,
ships[ship_id].clone(),
));
}
}
if const_spawn {
for kind in wave.const_distribution.iter() {
// dbg!(kind);
for _ in 0..kind.1 {
let spawn_pos = spawn_position(
character_position,
PLAYER_AREA,
ACTIVE_AREA,
);
let ships = &description.enemies;
let ship_id = kind.0;
insert_channel.single_write(ships2insert(
spawn_pos,
ships[ship_id].clone(),
));
}
}
}
info!("asteroids: gameplay ended");
}
}
|
mod errors;
mod fork;
mod wg_config;
use futures::stream::TryStreamExt;
use ipnetwork::Ipv4Network;
use nix::fcntl::{open, OFlag};
use nix::mount::{mount, umount, MsFlags};
use nix::sched::{setns, unshare, CloneFlags};
use nix::sys::signal::{kill, SIGKILL};
use nix::sys::stat::Mode;
use nix::sys::wait::waitpid;
use nix::unistd::{close, dup2, getpid, mkdir, pipe, unlink};
use nix::unistd::{execvp, fork, ForkResult};
use regex::Regex;
use std::convert::TryInto;
use std::ffi::CString;
use std::io::Stdout;
use std::io::Write;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::path::Path;
use std::process::{Command, Stdio};
use std::thread::sleep;
use wireguard_uapi::{RouteSocket, WgSocket};
use wg_config::WireguardConfig;
use fork::fork_fn;
use nftnl::{nft_expr, nftnl_sys::libc, Batch, Chain, FinalizedBatch, ProtoFamily, Rule, Table};
use sysctl::Sysctl;
/// Network namespace file descriptor is created at /proc/{pid}/ns/net
/// To keep alive, we create a file at /var/run/netns/{name}
/// then bind mount the namespace file descriptor to /var/run/netns/{name}
/// To destroy, unmount /var/run/netns/{name} and delete the created file there
#[derive(Debug)]
pub struct RawNetworkNamespace {
name: String,
pid: i32,
}
// TODO: Implement exec, destroy (do not force on Drop here, that can be done in application if
// desired), veth brige networking
impl RawNetworkNamespace {
pub fn new(name: &str) -> Self {
// Namespace must be created as root (or setuid)
// TODO: Check if possible with capabilities
let child = fork_fn(
|| {
let nsdir = "/var/run/netns";
unshare(CloneFlags::CLONE_NEWNET).expect("Failed to unshare network namespace");
mkdir(nsdir, Mode::empty()).ok();
let ns_namepath = format!("{}/{}", nsdir, name);
let ns_rawpath = "/proc/self/ns/net";
let mut oflag: OFlag = OFlag::empty();
oflag.insert(OFlag::O_RDONLY);
oflag.insert(OFlag::O_EXCL);
oflag.insert(OFlag::O_CREAT);
close(
open(ns_namepath.as_str(), oflag, Mode::empty())
.expect("Failed to create (open) network namespace name file"),
)
.expect("Failed to create (close) network namespace name file");
mount::<str, str, str, str>(
Some(ns_rawpath),
ns_namepath.as_str(),
None,
MsFlags::MS_BIND,
None,
)
.expect("Mount error");
std::process::exit(0);
},
true,
);
Self {
name: name.to_string(),
pid: child.as_raw(),
}
}
pub fn destroy(self) {
let nsdir = "/var/run/netns";
let ns_namepath = format!("{}/{}", nsdir, self.name);
umount(ns_namepath.as_str()).expect("Unmount failed");
unlink(ns_namepath.as_str()).expect("Unmount failed");
}
// TODO: Allow return value from Closure if blocking?
// TODO: Can we do better than spawning a new process for every operation?
// Consider maintaining one process inside namespace with inter-process communication
// But need to handle possibility of many network namespaces
pub fn run_in_namespace(&self, fun: impl FnOnce(), blocking: bool) -> nix::unistd::Pid {
fork_fn(
|| {
let nsdir = "/var/run/netns";
let ns_namepath = format!("{}/{}", nsdir, self.name);
let mut oflag: OFlag = OFlag::empty();
oflag.insert(OFlag::O_RDONLY);
oflag.insert(OFlag::O_EXCL);
let fd = open(ns_namepath.as_str(), oflag, Mode::empty()).expect("Open failed");
setns(fd, CloneFlags::CLONE_NEWNET).expect("setns failed");
close(fd).expect("close failed");
fun();
},
blocking,
)
}
// TODO: Add blocking version, implement std::process::Command interface? + IPC?
pub fn exec_no_block(&self, command: &[&str], silent: bool) -> nix::unistd::Pid {
// let stdout = std::io::stdout();
// let raw_fd: RawFd = stdout.as_raw_fd();
// TODO: current directory, user + group ID
self.run_in_namespace(
|| {
if silent {
// Redirect stdout to /dev/null
let stdout = std::io::stdout();
let stderr = std::io::stderr();
let raw_fd_stdout: RawFd = stdout.as_raw_fd();
let fd_null = open("/dev/null", OFlag::O_WRONLY, Mode::empty())
.expect("Failed to open /dev/null");
let raw_fd_stderr: RawFd = stderr.as_raw_fd();
dup2(fd_null, raw_fd_stdout).expect("Failed to overwrite stdout");
dup2(fd_null, raw_fd_stderr).expect("Failed to overwrite stderr");
close(fd_null).expect("Failed to close /dev/null fd");
}
let args_c: Result<Vec<CString>, _> =
command.iter().map(|&x| CString::new(x)).collect();
let args_c = args_c.expect("Failed to convert args to CString");
execvp(args_c.first().expect("No command"), args_c.as_slice())
.expect("Failed to exec command");
},
false,
)
}
/// Create loopback and set up
/// Equivalent of:
/// ip netns exec netns ip addr add 127.0.0.1/8 dev lo
/// ip netns exec netns ip link set lo up
pub fn add_loopback(&mut self) {
self.run_in_namespace(
|| {
let rt = tokio::runtime::Runtime::new().expect("Failed to construct Tokio runtime");
rt.block_on(async {
let (connection, handle, _) = rtnetlink::new_connection().unwrap();
rt.spawn(connection);
let mut links = handle
.link()
.get()
.set_name_filter("lo".to_string())
.execute();
let ip = ipnetwork::IpNetwork::new(
std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1)),
8,
)
.expect("Failed to construct IP");
if let Some(link) = links.try_next().await.expect("Failed to get link") {
handle
.address()
.add(link.header.index, ip.ip(), ip.prefix())
.execute()
.await
.expect("Failed to add address");
handle
.link()
.set(link.header.index)
.up()
.execute()
.await
.expect("Failed to set link up");
}
});
std::process::exit(0);
},
false,
);
}
pub fn add_veth_bridge(
&mut self,
src_name: &str,
dest_name: &str,
src_ip: &ipnetwork::IpNetwork,
dest_ip: &ipnetwork::IpNetwork,
) {
// TODO: Refactor this to get device indices only once!
// On host - dest veth
let rt = tokio::runtime::Runtime::new().expect("Failed to construct Tokio runtime");
rt.block_on(async {
let (connection, handle, _) = rtnetlink::new_connection().unwrap();
rt.spawn(connection);
handle
.link()
.add()
.veth(dest_name.to_string(), src_name.to_string())
.execute()
.await
.expect("Failed to create veth link");
let mut links = handle
.link()
.get()
.set_name_filter(dest_name.to_string())
.execute();
if let Some(link) = links.try_next().await.expect("Failed to get dest link") {
handle
.address()
.add(link.header.index, dest_ip.ip(), dest_ip.prefix())
.execute()
.await
.expect("Failed to add dest address");
handle
.link()
.set(link.header.index)
.up()
.execute()
.await
.expect("Failed to set link up");
}
// Move src to namespace
let mut links = handle
.link()
.get()
.set_name_filter(src_name.to_string())
.execute();
let fd_netns = open(
format!("/var/run/netns/{}", self.name).as_str(),
OFlag::O_RDONLY,
Mode::empty(),
)
.expect("Failed to open netns fd");
if let Some(link) = links.try_next().await.expect("Failed to get src link") {
println!("pid: {:?}", self.pid);
handle
.link()
.set(link.header.index)
.setns_by_fd(fd_netns)
.execute()
.await
.expect("Failed to move and set src link up");
}
close(fd_netns).expect("Failed to close netns fd");
});
// In netns - src veth
self.run_in_namespace(
|| {
let rt = tokio::runtime::Runtime::new().expect("Failed to construct Tokio runtime");
rt.block_on(async {
let (connection, handle, _) = rtnetlink::new_connection().unwrap();
rt.spawn(connection);
let mut links = handle
.link()
.get()
.set_name_filter(src_name.to_string())
.execute();
if let Some(link) = links.try_next().await.expect("Failed to get src link") {
handle
.address()
.add(link.header.index, src_ip.ip(), src_ip.prefix())
.execute()
.await
.expect("Failed to add src address");
// May be unnecessary since we set up when moving in to this namespace
handle
.link()
.set(link.header.index)
.up()
.execute()
.await
.expect("Failed to set link up");
// Route default gateway - ip netns exec piavpn ip route add default via 10.200.200.1 dev vpn1
let route = handle.route();
let dest_ipv4 = if let std::net::IpAddr::V4(ip) = dest_ip.ip() {
ip
} else {
panic!("Bad ipv4 IP for veth gateway");
};
route
.add()
.output_interface(link.header.index)
.v4()
.gateway(dest_ipv4)
.protocol(0)
.execute()
.await
.expect("Failed to add veth route");
}
});
std::process::exit(0);
},
false,
);
}
pub fn add_wireguard_device(&self, name: &str) {
self.run_in_namespace(|| add_wireguard_device(name), true);
}
pub fn set_wireguard_device(&self, name: &str, config: &WireguardConfig) {
self.run_in_namespace(|| set_wireguard_device(name, config), true);
}
/// Equivalent of:
/// ip -6 address add {address} dev {name}
/// ip -4 address add {address} dev {name}
/// ip link set mtu 1420 up dev {name}
pub fn wg_dev_up(&self, name: &str, config: &WireguardConfig) {
self.run_in_namespace(
|| {
let rt = tokio::runtime::Runtime::new().expect("Failed to construct Tokio runtime");
rt.block_on(async {
let (connection, handle, _) = rtnetlink::new_connection().unwrap();
rt.spawn(connection);
let mut links = handle
.link()
.get()
.set_name_filter(name.to_string())
.execute();
if let Some(link) = links.try_next().await.expect("Failed to get link") {
for address in config.interface.address.iter() {
// TODO: device is not specified here?
handle
.address()
.add(link.header.index, address.addr(), 32)
.execute()
.await
.expect("Failed to add address");
// TODO: custom MTU
handle
.link()
.set(link.header.index)
.mtu(1420)
.up()
.execute()
.await
.expect("Failed to set link up");
}
// ip -4 route add 0.0.0.0/0 dev {if_name} table {fwmark}
let route = handle.route();
route
.add()
// TODO: This gets a cryptic error when this is input_interface and no
// error from the rtnetlink crate!
// Would it be possible to improve this API to catch bad requests
// at build time?
.output_interface(link.header.index)
.v4()
.table(111)
.destination_prefix(Ipv4Addr::new(0, 0, 0, 0), 0)
.execute()
.await
.expect("Failed to add Wireguard route");
}
//TODO:
// "ip", "-4", "rule", "add", "not", "fwmark", fwmark, "table", fwmark
// https://github.com/svinota/pyroute2/issues/756
// Also need NLAs? :(
// "ip","-4","rule","add","table","main","suppress_prefixlength","0",
// Probably not needed inside netns: but can try to implement with attributes
// https://stackoverflow.com/questions/65178004/what-does-ip-4-rule-add-table-main-suppress-prefixlength-0-meaning
// Added as attribute
// addattr32(&req.n, sizeof(req), FRA_SUPPRESS_PREFIXLEN, pl);
// append to request NLAs directly?
// https://docs.rs/netlink-packet-route/0.7.1/netlink_packet_route/rtnl/route/nlas/enum.Nla.html
});
std::process::exit(0);
},
false,
);
}
}
pub fn host_add_masquerade_nft(
table_name: &str,
chain_name: &str,
interface_name: &str,
ip_mask: ipnetwork::IpNetwork,
) {
// TODO: Finish this and add Error types
// Get interface index with rtnetlink instead?
let mut batch = Batch::new();
// Add table: nft add table inet vopono_nat
let table = Table::new(&CString::new(table_name).unwrap(), ProtoFamily::Inet);
batch.add(&table, nftnl::MsgType::Add);
// Add postrouting chain: nft add chain inet vopono_nat postrouting { type nat hook postrouting priority 100 ; }
// // TODO update this to set nat type etc.
let mut out_chain = Chain::new(&CString::new(chain_name).unwrap(), &table);
out_chain.set_hook(nftnl::Hook::PostRouting, 100);
out_chain.set_type(nftnl::ChainType::Nat);
// out_chain.set_policy(nftnl::Policy::Accept);
batch.add(&out_chain, nftnl::MsgType::Add);
// Add masquerade rule: nft add rule inet vopono_nat postrouting oifname &interface.name ip saddr &ip_mask counter masquerade
let mut allow_loopback_in_rule = Rule::new(&out_chain);
// TODO: Get index from rtnetlink?
// let lo_iface_index = iface_index(interface_name).expect("TODO ERROR");
let ipnet = ip_mask;
allow_loopback_in_rule.add_expr(&nft_expr!(meta oifname));
allow_loopback_in_rule.add_expr(&nft_expr!(
cmp == nftnl::expr::InterfaceName::Exact(
CString::new(interface_name).expect("Bad interface name to CString conversion")
)
));
allow_loopback_in_rule.add_expr(&nft_expr!(meta nfproto));
allow_loopback_in_rule.add_expr(&nft_expr!(cmp == libc::NFPROTO_IPV4 as u8));
allow_loopback_in_rule.add_expr(&nft_expr!(payload ipv4 saddr));
allow_loopback_in_rule.add_expr(&nft_expr!(bitwise mask ipnet.mask(), xor 0));
allow_loopback_in_rule.add_expr(&nft_expr!(cmp == ipnet.ip()));
allow_loopback_in_rule.add_expr(&nft_expr!(counter));
allow_loopback_in_rule.add_expr(&nft_expr!(masquerade));
batch.add(&allow_loopback_in_rule, nftnl::MsgType::Add);
let finalized_batch = batch.finalize();
// TODO: Error handling
send_and_process(&finalized_batch);
}
fn send_and_process(batch: &FinalizedBatch) {
// Create a netlink socket to netfilter.
let socket = mnl::Socket::new(mnl::Bus::Netfilter).expect("TODO ERROR");
// Send all the bytes in the batch.
socket.send_all(batch).expect("TODO ERROR");
// Try to parse the messages coming back from netfilter. This part is still very unclear.
let portid = socket.portid();
let mut buffer = vec![0; nftnl::nft_nlmsg_maxsize() as usize];
let very_unclear_what_this_is_for = 2;
while let Some(message) = socket_recv(&socket, &mut buffer[..]).expect("TODO ERROR") {
match mnl::cb_run(message, very_unclear_what_this_is_for, portid).expect("TODO ERROR") {
mnl::CbResult::Stop => {
break;
}
mnl::CbResult::Ok => (),
}
}
// Ok(())
}
// TODO - replace this with rtnetlink calls?
fn iface_index(name: &str) -> Result<libc::c_uint, std::io::Error> {
let c_name = CString::new(name)?;
let index = unsafe { libc::if_nametoindex(c_name.as_ptr()) };
if index == 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(index)
}
}
fn socket_recv<'a>(
socket: &mnl::Socket,
buf: &'a mut [u8],
) -> Result<Option<&'a [u8]>, Box<dyn std::error::Error>> {
let ret = socket.recv(buf)?;
if ret > 0 {
Ok(Some(&buf[..ret]))
} else {
Ok(None)
}
}
pub fn host_enable_ipv4_forwarding() {
// sysctl -q net.ipv4.ip_forward=1
let ctl = sysctl::Ctl::new("net.ipv4.ip_forward").expect("TODO ERROR sysctl");
let org = ctl.value().unwrap();
println!("original sysctl val: {}", org);
let _set = ctl
.set_value(sysctl::CtlValue::String("1".to_string()))
.expect("TODO ERROR sysctl");
}
/// Equivalent of: ip link add {name} type wireguard
pub fn add_wireguard_device(name: &str) {
wireguard_uapi::RouteSocket::connect()
.expect("failed to connect route socket")
.add_device(name)
.expect("Failed to add wg device")
}
pub fn read_wg_config(config_file: &Path) -> WireguardConfig {
let config_string = std::fs::read_to_string(&config_file).unwrap();
// TODO: Avoid hacky regex for valid toml
let re = Regex::new(r"(?P<key>[^\s]+) = (?P<value>[^\s]+)").unwrap();
let mut config_string = re
.replace_all(&config_string, "$key = \"$value\"")
.to_string();
config_string.push('\n');
toml::from_str(&config_string).unwrap()
}
// TODO: Change wireguard_uapi api to use &mut here for chaining?
// TODO: Change API to make AllowedIP take ownership
// TODO: Change API to accept Vec instead of only 32-bit array for keys
/// Equivalent of: wg setconf {name} {config_file}
pub fn set_wireguard_device(name: &str, config: &WireguardConfig) {
let mut dev = wireguard_uapi::linux::set::Device::from_ifname(name);
let private_key_vec = base64::decode(config.interface.private_key.clone()).unwrap();
let mut privkey: [u8; 32] = [0; 32];
for i in 0..privkey.len() {
privkey[i] = private_key_vec[i];
}
let mut dev = dev.private_key(&privkey);
// TODO: Are we assuming only one peer here?
let mut dev = dev.flags(vec![wireguard_uapi::linux::set::WgDeviceF::ReplacePeers]);
let mut dev = dev.listen_port(0);
// TODO: is it okay to set this here?
let mut dev = dev.fwmark(111);
let public_key_vec = base64::decode(config.peer.public_key.clone()).unwrap();
let mut pubkey: [u8; 32] = [0; 32];
for i in 0..pubkey.len() {
pubkey[i] = public_key_vec[i];
}
let mut peer = wireguard_uapi::linux::set::Peer::from_public_key(&pubkey);
let mut peer = peer.flags(vec![wireguard_uapi::linux::set::WgPeerF::ReplaceAllowedIps]);
let mut peer = peer.endpoint(&config.peer.endpoint);
let addrs: Vec<IpAddr> = config.peer.allowed_ips.iter().map(|x| x.addr()).collect();
let allowed_ips = addrs
.iter()
.map(|x| {
let mut ip = wireguard_uapi::linux::set::AllowedIp::from_ipaddr(&x);
ip.cidr_mask = Some(0);
ip
})
.collect::<Vec<_>>();
let mut peer = peer.allowed_ips(allowed_ips);
let mut dev = dev.peers(vec![peer]);
let mut socket = wireguard_uapi::WgSocket::connect().unwrap();
socket.set_device(dev).unwrap();
}
#[cfg(test)]
mod tests {
// Tests must be run with superuser privileges :(
// sudo -E cargo test
use super::*;
#[test]
fn create_netns() {
println!("test pid: {:?}", getpid().as_raw());
let netns = RawNetworkNamespace::new("testns");
println!("{:?}", netns);
let out = std::process::Command::new("ip")
.args(&["netns", "list"])
.output()
.unwrap();
assert!(String::from_utf8(out.stdout).unwrap().contains("testns"));
netns.destroy();
let out = std::process::Command::new("ip")
.args(&["netns", "list"])
.output()
.unwrap();
assert!(!(String::from_utf8(out.stdout).unwrap().contains("testns")));
}
#[test]
fn exec_netns() {
println!("test pid: {:?}", getpid().as_raw());
let netns = RawNetworkNamespace::new("execns");
println!("{:?}", netns);
let handle = netns.exec_no_block(&["ping", "-c", "1", "8.8.8.8"], false);
std::thread::sleep(std::time::Duration::from_secs(2));
kill(handle, SIGKILL).expect("kill failed");
netns.destroy();
}
#[test]
fn add_loopback() {
let mut netns = RawNetworkNamespace::new("testlo");
netns.add_loopback();
// TODO: Make this blocking
std::thread::sleep(std::time::Duration::from_secs(5));
let handle = netns.exec_no_block(&["ip", "addr"], false);
std::thread::sleep(std::time::Duration::from_secs(2));
kill(handle, SIGKILL).expect("kill failed");
netns.destroy();
}
}
|
// #[macro_use] extern crate rocket;
#[derive(Debug)]
pub struct VersionHelper {
content: String,
}
impl VersionHelper {
pub async fn print_elapsed() {
use rocket::tokio::time::{sleep, Duration, Instant};
let start = Instant::now();
// let zz: () = start; // yields: found struct `std::time::Instant`
sleep(Duration::from_secs(1)).await; // original line 2
let elapsed: Duration = start.elapsed();
// let zz: () = elapsed; // yields: found struct `Duration`
println!( "elapsed time, `{:?}`", elapsed );
}
}
|
use serde_derive::{Deserialize, Serialize};
use clipboard::{ClipboardContext, ClipboardProvider};
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let mut view = web_view::builder()
.title("Emote Picker")
.user_data(())
.invoke_handler(|_wv, arg| {
handle_view_cmd(arg)
.map_err(|e| web_view::Error::custom(e.to_string()))
})
.content(web_view::Content::Html(include_str!("main.html")))
.size(400, 300)
.build()?;
view.send_message(ViewMessage::Init)?;
let entries = get_emoji_info()?;
let handle = view.handle();
std::thread::spawn(move || {
let msg = ViewMessage::Update { entries: &entries };
let json = serde_json::to_string(&msg).unwrap();
let json = format!("on_message({})", json);
handle.dispatch(move |vw| {
vw.eval(&json)
.map_err(|e| web_view::Error::custom(e.to_string()))
}).unwrap();
});
view.run()?;
Ok(())
}
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ViewCommand {
Debug { text: String },
CopyToClipboard { text: String },
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ViewMessage<'e> {
Init,
Update {
entries: &'e [EmoteEntry],
}
}
#[derive(Debug, Deserialize, Serialize)]
struct EmoteEntry {
text: String,
name: String,
group: String,
tags: Vec<String>,
}
fn get_emoji_info() -> Result<Vec<EmoteEntry>, Box<dyn Error>> {
let mut emote_list_path = dirs::config_dir()
.expect("Couldn't get config dir");
emote_list_path.push("emote-picker/emotes.json");
let emote_list = std::fs::read_to_string(emote_list_path)
.unwrap_or("[]".into());
serde_json::from_str(&emote_list)
.map_err(Into::into)
}
trait WebViewExt {
fn send_message(&mut self, msg: ViewMessage) -> Result<(), Box<dyn Error>>;
}
impl<T> WebViewExt for web_view::WebView<'_, T> {
fn send_message(&mut self, msg: ViewMessage) -> Result<(), Box<dyn Error>> {
let json = serde_json::to_string(&msg)?;
self.eval(&format!("on_message({})", json))?;
Ok(())
}
}
fn handle_view_cmd(arg: &str) -> Result<(), Box<dyn Error>> {
let msg: ViewCommand = serde_json::from_str(arg)?;
match msg {
ViewCommand::Debug{text} => {
println!("[dbg] {}", text);
}
ViewCommand::CopyToClipboard{text} => {
println!("copy {}", text);
let mut clip = ClipboardContext::new()?;
clip.set_contents(text)?;
}
}
Ok(())
}
|
type Con = Box<Connective>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Connective {
Var(String),
Predicate(String, Vec<String>),
Not(Con),
And(Con, Con),
Or(Con, Con),
Implicate(Con, Con),
Biimplicate(Con, Con),
ForAll(String, Con),
Exists(String, Con),
// All(Vec<Connective>),
// Consequence(Con, Con),
}
|
//! Provides the bubble sort feature
/// Triggers one step of the bubble sort
pub fn iterate_over_bubble_sort(
array: &mut [u8],
index: &mut usize,
swapped: &mut bool,
) {
if array[*index - 1] > array[*index] {
array.swap(
*index - 1,
*index,
);
*swapped = true;
}
*index += 1;
}
|
#![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 AvailableOperation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<AvailableOperationDisplay>,
#[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 name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<available_operation::Origin>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<AvailableOperationDisplayPropertyServiceSpecification>,
}
pub mod available_operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Origin {
#[serde(rename = "user")]
User,
#[serde(rename = "system")]
System,
#[serde(rename = "user,system")]
UserSystem,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AvailableOperationDisplay {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AvailableOperationDisplayPropertyServiceSpecification {
#[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")]
pub service_specification: Option<AvailableOperationDisplayPropertyServiceSpecificationMetricsList>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AvailableOperationDisplayPropertyServiceSpecificationMetricsItem {
#[serde(rename = "aggregationType")]
pub aggregation_type: available_operation_display_property_service_specification_metrics_item::AggregationType,
#[serde(rename = "displayDescription")]
pub display_description: String,
#[serde(rename = "displayName")]
pub display_name: String,
pub name: String,
pub unit: String,
}
pub mod available_operation_display_property_service_specification_metrics_item {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AggregationType {
Average,
Total,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AvailableOperationDisplayPropertyServiceSpecificationMetricsList {
#[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")]
pub metric_specifications: Vec<AvailableOperationDisplayPropertyServiceSpecificationMetricsItem>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AvailableOperationsListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<AvailableOperation>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsrpError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<CsrpErrorBody>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CsrpErrorBody {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<CsrpErrorBody>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationHostName {
#[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<customization_host_name::Type>,
}
pub mod customization_host_name {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "USER_DEFINED")]
UserDefined,
#[serde(rename = "PREFIX_BASED")]
PrefixBased,
#[serde(rename = "FIXED")]
Fixed,
#[serde(rename = "VIRTUAL_MACHINE_NAME")]
VirtualMachineName,
#[serde(rename = "CUSTOM_NAME")]
CustomName,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationIpAddress {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub argument: Option<String>,
#[serde(rename = "ipAddress", default, skip_serializing_if = "Option::is_none")]
pub ip_address: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<customization_ip_address::Type>,
}
pub mod customization_ip_address {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "CUSTOM")]
Custom,
#[serde(rename = "DHCP_IP")]
DhcpIp,
#[serde(rename = "FIXED_IP")]
FixedIp,
#[serde(rename = "USER_DEFINED")]
UserDefined,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationIpSettings {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub gateway: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ip: Option<CustomizationIpAddress>,
#[serde(rename = "subnetMask", default, skip_serializing_if = "Option::is_none")]
pub subnet_mask: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationIdentity {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<String>,
#[serde(rename = "hostName", default, skip_serializing_if = "Option::is_none")]
pub host_name: Option<CustomizationHostName>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<customization_identity::Type>,
#[serde(rename = "userData", default, skip_serializing_if = "Option::is_none")]
pub user_data: Option<customization_identity::UserData>,
}
pub mod customization_identity {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "WINDOWS_TEXT")]
WindowsText,
#[serde(rename = "WINDOWS")]
Windows,
#[serde(rename = "LINUX")]
Linux,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UserData {
#[serde(rename = "isPasswordPredefined", default, skip_serializing_if = "Option::is_none")]
pub is_password_predefined: Option<bool>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationNicSetting {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub adapter: Option<CustomizationIpSettings>,
#[serde(rename = "macAddress", default, skip_serializing_if = "Option::is_none")]
pub mac_address: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationPoliciesListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<CustomizationPolicy>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationPolicy {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<CustomizationPolicyProperties>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationPolicyProperties {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "privateCloudId", default, skip_serializing_if = "Option::is_none")]
pub private_cloud_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub specification: Option<CustomizationSpecification>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<customization_policy_properties::Type>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
pub mod customization_policy_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "LINUX")]
Linux,
#[serde(rename = "WINDOWS")]
Windows,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomizationSpecification {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<CustomizationIdentity>,
#[serde(rename = "nicSettings", default, skip_serializing_if = "Vec::is_empty")]
pub nic_settings: Vec<CustomizationNicSetting>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DedicatedCloudNode {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DedicatedCloudNodeProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sku: Option<Sku>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DedicatedCloudNodeListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DedicatedCloudNode>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DedicatedCloudNodeProperties {
#[serde(rename = "availabilityZoneId")]
pub availability_zone_id: String,
#[serde(rename = "availabilityZoneName", default, skip_serializing_if = "Option::is_none")]
pub availability_zone_name: Option<String>,
#[serde(rename = "cloudRackName", default, skip_serializing_if = "Option::is_none")]
pub cloud_rack_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created: Option<String>,
#[serde(rename = "nodesCount")]
pub nodes_count: i64,
#[serde(rename = "placementGroupId")]
pub placement_group_id: String,
#[serde(rename = "placementGroupName", default, skip_serializing_if = "Option::is_none")]
pub placement_group_name: Option<String>,
#[serde(rename = "privateCloudId", default, skip_serializing_if = "Option::is_none")]
pub private_cloud_id: Option<String>,
#[serde(rename = "privateCloudName", default, skip_serializing_if = "Option::is_none")]
pub private_cloud_name: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "purchaseId")]
pub purchase_id: String,
#[serde(rename = "skuDescription", default, skip_serializing_if = "Option::is_none")]
pub sku_description: Option<SkuDescription>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<dedicated_cloud_node_properties::Status>,
#[serde(rename = "vmwareClusterName", default, skip_serializing_if = "Option::is_none")]
pub vmware_cluster_name: Option<String>,
}
pub mod dedicated_cloud_node_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "unused")]
Unused,
#[serde(rename = "used")]
Used,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DedicatedCloudService {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<DedicatedCloudServiceProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DedicatedCloudServiceListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<DedicatedCloudService>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DedicatedCloudServiceProperties {
#[serde(rename = "gatewaySubnet")]
pub gateway_subnet: String,
#[serde(rename = "isAccountOnboarded", default, skip_serializing_if = "Option::is_none")]
pub is_account_onboarded: Option<dedicated_cloud_service_properties::IsAccountOnboarded>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nodes: Option<i64>,
#[serde(rename = "serviceURL", default, skip_serializing_if = "Option::is_none")]
pub service_url: Option<String>,
}
pub mod dedicated_cloud_service_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum IsAccountOnboarded {
#[serde(rename = "notOnBoarded")]
NotOnBoarded,
#[serde(rename = "onBoarded")]
OnBoarded,
#[serde(rename = "onBoardingFailed")]
OnBoardingFailed,
#[serde(rename = "onBoarding")]
OnBoarding,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GuestOsCustomization {
#[serde(rename = "dnsServers", default, skip_serializing_if = "Vec::is_empty")]
pub dns_servers: Vec<Ipv4Address>,
#[serde(rename = "hostName", default, skip_serializing_if = "Option::is_none")]
pub host_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
#[serde(rename = "policyId", default, skip_serializing_if = "Option::is_none")]
pub policy_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GuestOsnicCustomization {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub allocation: Option<guest_osnic_customization::Allocation>,
#[serde(rename = "dnsServers", default, skip_serializing_if = "Vec::is_empty")]
pub dns_servers: Vec<Ipv4Address>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub gateway: Vec<Ipv4Address>,
#[serde(rename = "ipAddress", default, skip_serializing_if = "Option::is_none")]
pub ip_address: Option<Ipv4Address>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mask: Option<Ipv4Address>,
#[serde(rename = "primaryWinsServer", default, skip_serializing_if = "Option::is_none")]
pub primary_wins_server: Option<Ipv4Address>,
#[serde(rename = "secondaryWinsServer", default, skip_serializing_if = "Option::is_none")]
pub secondary_wins_server: Option<Ipv4Address>,
}
pub mod guest_osnic_customization {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Allocation {
#[serde(rename = "static")]
Static,
#[serde(rename = "dynamic")]
Dynamic,
}
}
pub type Ipv4Address = String;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationError {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationResource {
#[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")]
pub end_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<OperationError>,
#[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 = "startTime", default, skip_serializing_if = "Option::is_none")]
pub start_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PatchPayload {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateCloud {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<PrivateCloudProperties>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<private_cloud::Type>,
}
pub mod private_cloud {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
#[serde(rename = "Microsoft.VMwareCloudSimple/privateClouds")]
MicrosoftVMwareCloudSimplePrivateClouds,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateCloudList {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<PrivateCloud>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrivateCloudProperties {
#[serde(rename = "availabilityZoneId", default, skip_serializing_if = "Option::is_none")]
pub availability_zone_id: Option<String>,
#[serde(rename = "availabilityZoneName", default, skip_serializing_if = "Option::is_none")]
pub availability_zone_name: Option<String>,
#[serde(rename = "clustersNumber", default, skip_serializing_if = "Option::is_none")]
pub clusters_number: Option<i64>,
#[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")]
pub created_by: Option<String>,
#[serde(rename = "createdOn", default, skip_serializing_if = "Option::is_none")]
pub created_on: Option<String>,
#[serde(rename = "dnsServers", default, skip_serializing_if = "Vec::is_empty")]
pub dns_servers: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires: Option<String>,
#[serde(rename = "nsxType", default, skip_serializing_if = "Option::is_none")]
pub nsx_type: Option<String>,
#[serde(rename = "placementGroupId", default, skip_serializing_if = "Option::is_none")]
pub placement_group_id: Option<String>,
#[serde(rename = "placementGroupName", default, skip_serializing_if = "Option::is_none")]
pub placement_group_name: Option<String>,
#[serde(rename = "privateCloudId", default, skip_serializing_if = "Option::is_none")]
pub private_cloud_id: Option<String>,
#[serde(rename = "resourcePools", default, skip_serializing_if = "Vec::is_empty")]
pub resource_pools: Vec<ResourcePool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
#[serde(rename = "totalCpuCores", default, skip_serializing_if = "Option::is_none")]
pub total_cpu_cores: Option<i64>,
#[serde(rename = "totalNodes", default, skip_serializing_if = "Option::is_none")]
pub total_nodes: Option<i64>,
#[serde(rename = "totalRam", default, skip_serializing_if = "Option::is_none")]
pub total_ram: Option<i64>,
#[serde(rename = "totalStorage", default, skip_serializing_if = "Option::is_none")]
pub total_storage: Option<f64>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
#[serde(rename = "vSphereVersion", default, skip_serializing_if = "Option::is_none")]
pub v_sphere_version: Option<String>,
#[serde(rename = "vcenterFqdn", default, skip_serializing_if = "Option::is_none")]
pub vcenter_fqdn: Option<String>,
#[serde(rename = "vcenterRefid", default, skip_serializing_if = "Option::is_none")]
pub vcenter_refid: Option<String>,
#[serde(rename = "virtualMachineTemplates", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_machine_templates: Vec<VirtualMachineTemplate>,
#[serde(rename = "virtualNetworks", default, skip_serializing_if = "Vec::is_empty")]
pub virtual_networks: Vec<VirtualNetwork>,
#[serde(rename = "vrOpsEnabled", default, skip_serializing_if = "Option::is_none")]
pub vr_ops_enabled: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourcePool {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "privateCloudId", default, skip_serializing_if = "Option::is_none")]
pub private_cloud_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<ResourcePoolProperties>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourcePoolProperties {
#[serde(rename = "fullName", default, skip_serializing_if = "Option::is_none")]
pub full_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResourcePoolsListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<ResourcePool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Sku {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capacity: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub family: Option<String>,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuAvailability {
#[serde(rename = "dedicatedAvailabilityZoneId", default, skip_serializing_if = "Option::is_none")]
pub dedicated_availability_zone_id: Option<String>,
#[serde(rename = "dedicatedAvailabilityZoneName", default, skip_serializing_if = "Option::is_none")]
pub dedicated_availability_zone_name: Option<String>,
#[serde(rename = "dedicatedPlacementGroupId", default, skip_serializing_if = "Option::is_none")]
pub dedicated_placement_group_id: Option<String>,
#[serde(rename = "dedicatedPlacementGroupName", default, skip_serializing_if = "Option::is_none")]
pub dedicated_placement_group_name: Option<String>,
pub limit: i64,
#[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")]
pub resource_type: Option<String>,
#[serde(rename = "skuId", default, skip_serializing_if = "Option::is_none")]
pub sku_id: Option<String>,
#[serde(rename = "skuName", default, skip_serializing_if = "Option::is_none")]
pub sku_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuAvailabilityListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SkuAvailability>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkuDescription {
pub id: String,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tags {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Usage {
#[serde(rename = "currentValue")]
pub current_value: i64,
pub limit: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<UsageName>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<usage::Unit>,
}
pub mod usage {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Unit {
Count,
Bytes,
Seconds,
Percent,
CountPerSecond,
BytesPerSecond,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Usage>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageName {
#[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")]
pub localized_value: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualDisk {
#[serde(rename = "controllerId")]
pub controller_id: String,
#[serde(rename = "independenceMode")]
pub independence_mode: virtual_disk::IndependenceMode,
#[serde(rename = "totalSize")]
pub total_size: i64,
#[serde(rename = "virtualDiskId", default, skip_serializing_if = "Option::is_none")]
pub virtual_disk_id: Option<String>,
#[serde(rename = "virtualDiskName", default, skip_serializing_if = "Option::is_none")]
pub virtual_disk_name: Option<String>,
}
pub mod virtual_disk {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum IndependenceMode {
#[serde(rename = "persistent")]
Persistent,
#[serde(rename = "independent_persistent")]
IndependentPersistent,
#[serde(rename = "independent_nonpersistent")]
IndependentNonpersistent,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualDiskController {
#[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 = "subType", default, skip_serializing_if = "Option::is_none")]
pub sub_type: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachine {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<VirtualMachineProperties>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Tags>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachineListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<VirtualMachine>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachineProperties {
#[serde(rename = "amountOfRam")]
pub amount_of_ram: i64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub controllers: Vec<VirtualDiskController>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub customization: Option<GuestOsCustomization>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub disks: Vec<VirtualDisk>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dnsname: Option<String>,
#[serde(rename = "exposeToGuestVM", default, skip_serializing_if = "Option::is_none")]
pub expose_to_guest_vm: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub folder: Option<String>,
#[serde(rename = "guestOS", default, skip_serializing_if = "Option::is_none")]
pub guest_os: Option<String>,
#[serde(rename = "guestOSType", default, skip_serializing_if = "Option::is_none")]
pub guest_os_type: Option<virtual_machine_properties::GuestOsType>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub nics: Vec<VirtualNic>,
#[serde(rename = "numberOfCores")]
pub number_of_cores: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
#[serde(rename = "privateCloudId")]
pub private_cloud_id: String,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<String>,
#[serde(rename = "publicIP", default, skip_serializing_if = "Option::is_none")]
pub public_ip: Option<String>,
#[serde(rename = "resourcePool", default, skip_serializing_if = "Option::is_none")]
pub resource_pool: Option<ResourcePool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<virtual_machine_properties::Status>,
#[serde(rename = "templateId", default, skip_serializing_if = "Option::is_none")]
pub template_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(rename = "vSphereNetworks", default, skip_serializing_if = "Vec::is_empty")]
pub v_sphere_networks: Vec<String>,
#[serde(rename = "vmId", default, skip_serializing_if = "Option::is_none")]
pub vm_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vmwaretools: Option<String>,
}
pub mod virtual_machine_properties {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum GuestOsType {
#[serde(rename = "linux")]
Linux,
#[serde(rename = "windows")]
Windows,
#[serde(rename = "other")]
Other,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Status {
#[serde(rename = "running")]
Running,
#[serde(rename = "suspended")]
Suspended,
#[serde(rename = "poweredoff")]
Poweredoff,
#[serde(rename = "updating")]
Updating,
#[serde(rename = "deallocating")]
Deallocating,
#[serde(rename = "deleting")]
Deleting,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachineStopMode {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<virtual_machine_stop_mode::Mode>,
}
pub mod virtual_machine_stop_mode {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Mode {
#[serde(rename = "reboot")]
Reboot,
#[serde(rename = "suspend")]
Suspend,
#[serde(rename = "shutdown")]
Shutdown,
#[serde(rename = "poweroff")]
Poweroff,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachineTemplate {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<VirtualMachineTemplateProperties>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachineTemplateListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<VirtualMachineTemplate>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualMachineTemplateProperties {
#[serde(rename = "amountOfRam", default, skip_serializing_if = "Option::is_none")]
pub amount_of_ram: Option<i64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub controllers: Vec<VirtualDiskController>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub disks: Vec<VirtualDisk>,
#[serde(rename = "exposeToGuestVM", default, skip_serializing_if = "Option::is_none")]
pub expose_to_guest_vm: Option<bool>,
#[serde(rename = "guestOS", default, skip_serializing_if = "Option::is_none")]
pub guest_os: Option<String>,
#[serde(rename = "guestOSType", default, skip_serializing_if = "Option::is_none")]
pub guest_os_type: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub nics: Vec<VirtualNic>,
#[serde(rename = "numberOfCores", default, skip_serializing_if = "Option::is_none")]
pub number_of_cores: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(rename = "privateCloudId")]
pub private_cloud_id: String,
#[serde(rename = "vSphereNetworks", default, skip_serializing_if = "Vec::is_empty")]
pub v_sphere_networks: Vec<String>,
#[serde(rename = "vSphereTags", default, skip_serializing_if = "Vec::is_empty")]
pub v_sphere_tags: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vmwaretools: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetwork {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub assignable: Option<bool>,
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<VirtualNetworkProperties>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkListResponse {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<VirtualNetwork>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNetworkProperties {
#[serde(rename = "privateCloudId", default, skip_serializing_if = "Option::is_none")]
pub private_cloud_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VirtualNic {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub customization: Option<GuestOsnicCustomization>,
#[serde(rename = "ipAddresses", default, skip_serializing_if = "Vec::is_empty")]
pub ip_addresses: Vec<String>,
#[serde(rename = "macAddress", default, skip_serializing_if = "Option::is_none")]
pub mac_address: Option<String>,
pub network: VirtualNetwork,
#[serde(rename = "nicType")]
pub nic_type: virtual_nic::NicType,
#[serde(rename = "powerOnBoot", default, skip_serializing_if = "Option::is_none")]
pub power_on_boot: Option<bool>,
#[serde(rename = "virtualNicId", default, skip_serializing_if = "Option::is_none")]
pub virtual_nic_id: Option<String>,
#[serde(rename = "virtualNicName", default, skip_serializing_if = "Option::is_none")]
pub virtual_nic_name: Option<String>,
}
pub mod virtual_nic {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum NicType {
E1000,
#[serde(rename = "E1000E")]
E1000e,
#[serde(rename = "PCNET32")]
Pcnet32,
#[serde(rename = "VMXNET")]
Vmxnet,
#[serde(rename = "VMXNET2")]
Vmxnet2,
#[serde(rename = "VMXNET3")]
Vmxnet3,
}
}
|
#[doc = "Register `AHB2ENR` reader"]
pub type R = crate::R<AHB2ENR_SPEC>;
#[doc = "Register `AHB2ENR` writer"]
pub type W = crate::W<AHB2ENR_SPEC>;
#[doc = "Field `GPIOAEN` reader - IO port A clock enable"]
pub type GPIOAEN_R = crate::BitReader;
#[doc = "Field `GPIOAEN` writer - IO port A clock enable"]
pub type GPIOAEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOBEN` reader - IO port B clock enable"]
pub type GPIOBEN_R = crate::BitReader;
#[doc = "Field `GPIOBEN` writer - IO port B clock enable"]
pub type GPIOBEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOCEN` reader - IO port C clock enable"]
pub type GPIOCEN_R = crate::BitReader;
#[doc = "Field `GPIOCEN` writer - IO port C clock enable"]
pub type GPIOCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIODEN` reader - IO port D clock enable"]
pub type GPIODEN_R = crate::BitReader;
#[doc = "Field `GPIODEN` writer - IO port D clock enable"]
pub type GPIODEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOEEN` reader - IO port E clock enable"]
pub type GPIOEEN_R = crate::BitReader;
#[doc = "Field `GPIOEEN` writer - IO port E clock enable"]
pub type GPIOEEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOFEN` reader - IO port F clock enable"]
pub type GPIOFEN_R = crate::BitReader;
#[doc = "Field `GPIOFEN` writer - IO port F clock enable"]
pub type GPIOFEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOGEN` reader - IO port G clock enable"]
pub type GPIOGEN_R = crate::BitReader;
#[doc = "Field `GPIOGEN` writer - IO port G clock enable"]
pub type GPIOGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOHEN` reader - IO port H clock enable"]
pub type GPIOHEN_R = crate::BitReader;
#[doc = "Field `GPIOHEN` writer - IO port H clock enable"]
pub type GPIOHEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `GPIOIEN` reader - IO port I clock enable"]
pub type GPIOIEN_R = crate::BitReader;
#[doc = "Field `GPIOIEN` writer - IO port I clock enable"]
pub type GPIOIEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OTGFSEN` reader - OTG full speed clock enable"]
pub type OTGFSEN_R = crate::BitReader;
#[doc = "Field `OTGFSEN` writer - OTG full speed clock enable"]
pub type OTGFSEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ADCEN` reader - ADC clock enable"]
pub type ADCEN_R = crate::BitReader<ADCEN_A>;
#[doc = "ADC clock enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ADCEN_A {
#[doc = "0: ADC clock disabled"]
Disabled = 0,
#[doc = "1: ADC clock enabled"]
Enabled = 1,
}
impl From<ADCEN_A> for bool {
#[inline(always)]
fn from(variant: ADCEN_A) -> Self {
variant as u8 != 0
}
}
impl ADCEN_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ADCEN_A {
match self.bits {
false => ADCEN_A::Disabled,
true => ADCEN_A::Enabled,
}
}
#[doc = "ADC clock disabled"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ADCEN_A::Disabled
}
#[doc = "ADC clock enabled"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ADCEN_A::Enabled
}
}
#[doc = "Field `ADCEN` writer - ADC clock enable"]
pub type ADCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, ADCEN_A>;
impl<'a, REG, const O: u8> ADCEN_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "ADC clock disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut crate::W<REG> {
self.variant(ADCEN_A::Disabled)
}
#[doc = "ADC clock enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut crate::W<REG> {
self.variant(ADCEN_A::Enabled)
}
}
#[doc = "Field `DCMIEN` reader - DCMI clock enable"]
pub type DCMIEN_R = crate::BitReader;
#[doc = "Field `DCMIEN` writer - DCMI clock enable"]
pub type DCMIEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `AESEN` reader - AES accelerator clock enable"]
pub type AESEN_R = crate::BitReader;
#[doc = "Field `AESEN` writer - AES accelerator clock enable"]
pub type AESEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HASHEN` reader - HASH clock enable"]
pub type HASHEN_R = crate::BitReader;
#[doc = "Field `HASHEN` writer - HASH clock enable"]
pub type HASHEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RNGEN` reader - Random Number Generator clock enable"]
pub type RNGEN_R = crate::BitReader;
#[doc = "Field `RNGEN` writer - Random Number Generator clock enable"]
pub type RNGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OSPIMEN` reader - OctoSPI IO manager clock enable"]
pub type OSPIMEN_R = crate::BitReader;
#[doc = "Field `OSPIMEN` writer - OctoSPI IO manager clock enable"]
pub type OSPIMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SDMMC1EN` reader - SDMMC1 clock enable"]
pub type SDMMC1EN_R = crate::BitReader;
#[doc = "Field `SDMMC1EN` writer - SDMMC1 clock enable"]
pub type SDMMC1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - IO port A clock enable"]
#[inline(always)]
pub fn gpioaen(&self) -> GPIOAEN_R {
GPIOAEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - IO port B clock enable"]
#[inline(always)]
pub fn gpioben(&self) -> GPIOBEN_R {
GPIOBEN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - IO port C clock enable"]
#[inline(always)]
pub fn gpiocen(&self) -> GPIOCEN_R {
GPIOCEN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - IO port D clock enable"]
#[inline(always)]
pub fn gpioden(&self) -> GPIODEN_R {
GPIODEN_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - IO port E clock enable"]
#[inline(always)]
pub fn gpioeen(&self) -> GPIOEEN_R {
GPIOEEN_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - IO port F clock enable"]
#[inline(always)]
pub fn gpiofen(&self) -> GPIOFEN_R {
GPIOFEN_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - IO port G clock enable"]
#[inline(always)]
pub fn gpiogen(&self) -> GPIOGEN_R {
GPIOGEN_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - IO port H clock enable"]
#[inline(always)]
pub fn gpiohen(&self) -> GPIOHEN_R {
GPIOHEN_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - IO port I clock enable"]
#[inline(always)]
pub fn gpioien(&self) -> GPIOIEN_R {
GPIOIEN_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 12 - OTG full speed clock enable"]
#[inline(always)]
pub fn otgfsen(&self) -> OTGFSEN_R {
OTGFSEN_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - ADC clock enable"]
#[inline(always)]
pub fn adcen(&self) -> ADCEN_R {
ADCEN_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - DCMI clock enable"]
#[inline(always)]
pub fn dcmien(&self) -> DCMIEN_R {
DCMIEN_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 16 - AES accelerator clock enable"]
#[inline(always)]
pub fn aesen(&self) -> AESEN_R {
AESEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - HASH clock enable"]
#[inline(always)]
pub fn hashen(&self) -> HASHEN_R {
HASHEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - Random Number Generator clock enable"]
#[inline(always)]
pub fn rngen(&self) -> RNGEN_R {
RNGEN_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 20 - OctoSPI IO manager clock enable"]
#[inline(always)]
pub fn ospimen(&self) -> OSPIMEN_R {
OSPIMEN_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 22 - SDMMC1 clock enable"]
#[inline(always)]
pub fn sdmmc1en(&self) -> SDMMC1EN_R {
SDMMC1EN_R::new(((self.bits >> 22) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - IO port A clock enable"]
#[inline(always)]
#[must_use]
pub fn gpioaen(&mut self) -> GPIOAEN_W<AHB2ENR_SPEC, 0> {
GPIOAEN_W::new(self)
}
#[doc = "Bit 1 - IO port B clock enable"]
#[inline(always)]
#[must_use]
pub fn gpioben(&mut self) -> GPIOBEN_W<AHB2ENR_SPEC, 1> {
GPIOBEN_W::new(self)
}
#[doc = "Bit 2 - IO port C clock enable"]
#[inline(always)]
#[must_use]
pub fn gpiocen(&mut self) -> GPIOCEN_W<AHB2ENR_SPEC, 2> {
GPIOCEN_W::new(self)
}
#[doc = "Bit 3 - IO port D clock enable"]
#[inline(always)]
#[must_use]
pub fn gpioden(&mut self) -> GPIODEN_W<AHB2ENR_SPEC, 3> {
GPIODEN_W::new(self)
}
#[doc = "Bit 4 - IO port E clock enable"]
#[inline(always)]
#[must_use]
pub fn gpioeen(&mut self) -> GPIOEEN_W<AHB2ENR_SPEC, 4> {
GPIOEEN_W::new(self)
}
#[doc = "Bit 5 - IO port F clock enable"]
#[inline(always)]
#[must_use]
pub fn gpiofen(&mut self) -> GPIOFEN_W<AHB2ENR_SPEC, 5> {
GPIOFEN_W::new(self)
}
#[doc = "Bit 6 - IO port G clock enable"]
#[inline(always)]
#[must_use]
pub fn gpiogen(&mut self) -> GPIOGEN_W<AHB2ENR_SPEC, 6> {
GPIOGEN_W::new(self)
}
#[doc = "Bit 7 - IO port H clock enable"]
#[inline(always)]
#[must_use]
pub fn gpiohen(&mut self) -> GPIOHEN_W<AHB2ENR_SPEC, 7> {
GPIOHEN_W::new(self)
}
#[doc = "Bit 8 - IO port I clock enable"]
#[inline(always)]
#[must_use]
pub fn gpioien(&mut self) -> GPIOIEN_W<AHB2ENR_SPEC, 8> {
GPIOIEN_W::new(self)
}
#[doc = "Bit 12 - OTG full speed clock enable"]
#[inline(always)]
#[must_use]
pub fn otgfsen(&mut self) -> OTGFSEN_W<AHB2ENR_SPEC, 12> {
OTGFSEN_W::new(self)
}
#[doc = "Bit 13 - ADC clock enable"]
#[inline(always)]
#[must_use]
pub fn adcen(&mut self) -> ADCEN_W<AHB2ENR_SPEC, 13> {
ADCEN_W::new(self)
}
#[doc = "Bit 14 - DCMI clock enable"]
#[inline(always)]
#[must_use]
pub fn dcmien(&mut self) -> DCMIEN_W<AHB2ENR_SPEC, 14> {
DCMIEN_W::new(self)
}
#[doc = "Bit 16 - AES accelerator clock enable"]
#[inline(always)]
#[must_use]
pub fn aesen(&mut self) -> AESEN_W<AHB2ENR_SPEC, 16> {
AESEN_W::new(self)
}
#[doc = "Bit 17 - HASH clock enable"]
#[inline(always)]
#[must_use]
pub fn hashen(&mut self) -> HASHEN_W<AHB2ENR_SPEC, 17> {
HASHEN_W::new(self)
}
#[doc = "Bit 18 - Random Number Generator clock enable"]
#[inline(always)]
#[must_use]
pub fn rngen(&mut self) -> RNGEN_W<AHB2ENR_SPEC, 18> {
RNGEN_W::new(self)
}
#[doc = "Bit 20 - OctoSPI IO manager clock enable"]
#[inline(always)]
#[must_use]
pub fn ospimen(&mut self) -> OSPIMEN_W<AHB2ENR_SPEC, 20> {
OSPIMEN_W::new(self)
}
#[doc = "Bit 22 - SDMMC1 clock enable"]
#[inline(always)]
#[must_use]
pub fn sdmmc1en(&mut self) -> SDMMC1EN_W<AHB2ENR_SPEC, 22> {
SDMMC1EN_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 = "AHB2 peripheral clock enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb2enr::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 [`ahb2enr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct AHB2ENR_SPEC;
impl crate::RegisterSpec for AHB2ENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ahb2enr::R`](R) reader structure"]
impl crate::Readable for AHB2ENR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ahb2enr::W`](W) writer structure"]
impl crate::Writable for AHB2ENR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets AHB2ENR to value 0"]
impl crate::Resettable for AHB2ENR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::operator::Operator;
use std::fmt::Formatter;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Name<'a> {
Attribute(&'a str),
Operator(Operator),
}
impl Name<'_> {
pub fn as_str(&self) -> &str {
match self {
Name::Attribute(s) => *s,
Name::Operator(o) => o.name(),
}
}
pub fn do_each<T>(self, op: impl FnOnce(Operator) -> T, attr: impl FnOnce(&str) -> T) -> T {
match self {
Name::Attribute(s) => attr(s),
Name::Operator(o) => op(o),
}
}
}
impl std::fmt::Display for Name<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Name::Attribute(s) => s.fmt(f),
Name::Operator(o) => o.name().fmt(f),
}
}
}
impl From<Operator> for Name<'_> {
fn from(x: Operator) -> Self {
Name::Operator(x)
}
}
impl<'a> From<&'a str> for Name<'a> {
fn from(x: &'a str) -> Self {
Name::Attribute(x)
}
}
|
/// Since we're not using the standard Result (`core::result::Result`)
/// We can't use the `?` operator for injecting immediate return from a function in case of an `Err(..)`
///
/// So instead, we're adding a macro named `safe_try` that will function very similarly to the `?` of standard `Result`
#[macro_export]
macro_rules! safe_try {
($expr:expr) => {{
use svm_sdk_std::Result;
let result = $expr;
if (result.is_ok()) {
result.unwrap()
} else {
let err = result.unwrap_err();
return Result::Err(err);
}
}};
}
|
fn main() {
println!("cargo:rustc-link-lib=dylib=Cbc");
println!("cargo:rustc-link-lib=dylib=CoinUtils");
println!("cargo:rustc-link-lib=dylib=OsiClp");
}
|
#![allow(non_upper_case_globals)]
use core::{
iter::FusedIterator,
marker::PhantomData,
mem,
task::Poll,
pin::Pin,
};
use std::io;
use super::setup;
use crate::{
DeviceDescriptor,
InterfaceDescriptor,
Speed
};
use winapi::{
um::{
winnt::{
HANDLE,
GENERIC_READ, GENERIC_WRITE,
FILE_SHARE_READ, FILE_SHARE_WRITE,
FILE_ATTRIBUTE_NORMAL,
LANG_NEUTRAL,
},
winbase::{FILE_FLAG_OVERLAPPED},
minwinbase::{OVERLAPPED},
fileapi::{CreateFileW, OPEN_EXISTING},
handleapi::{CloseHandle, INVALID_HANDLE_VALUE},
errhandlingapi::GetLastError,
winusb::{
WinUsb_Initialize, WinUsb_Free,
WinUsb_GetDescriptor,
WinUsb_GetOverlappedResult,
WinUsb_QueryDeviceInformation,
WinUsb_QueryInterfaceSettings,
WinUsb_QueryPipe,
WinUsb_ReadPipe,
WinUsb_WritePipe,
WinUsb_FlushPipe,
WinUsb_ResetPipe,
WinUsb_AbortPipe,
WINUSB_INTERFACE_HANDLE,
USB_INTERFACE_DESCRIPTOR,
},
},
shared::{
minwindef::{FALSE, DWORD, UCHAR},
winerror::{
ERROR_NO_MORE_ITEMS,
ERROR_IO_PENDING,
ERROR_IO_INCOMPLETE,
},
usbiodef::GUID_DEVINTERFACE_USB_DEVICE,
usbspec::{
USB_DEVICE_DESCRIPTOR,
USB_DEVICE_DESCRIPTOR_TYPE,
USB_DEVICE_SPEED,
UsbLowSpeed, UsbFullSpeed, UsbHighSpeed, UsbSuperSpeed,
},
winusbio::{
DEVICE_SPEED,
WINUSB_PIPE_INFORMATION,
},
},
};
pub trait ListOptionsExt<'g, 'h> {
fn all_usb_interfaces() -> setup::ListOptions<'g, setup::Interface, InfoHandle<'h>>;
}
impl<'g, 'h> ListOptionsExt<'g, 'h> for setup::ListOptions<'g, setup::Interface, InfoHandle<'h>> {
fn all_usb_interfaces() -> setup::ListOptions<'g, setup::Interface, InfoHandle<'h>> {
setup::ListOptions::interface_by_class(&GUID_DEVINTERFACE_USB_DEVICE)
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct InfoHandle<'h> {
inner: setup::InfoHandle<'h>,
}
impl<'h> From<setup::InfoHandle<'h>> for InfoHandle<'h> {
fn from(src: setup::InfoHandle<'h>) -> InfoHandle {
InfoHandle { inner: src }
}
}
impl<'h> InfoHandle<'h> {
pub fn iter<'a>(&self) -> InfoIter<'a> {
InfoIter { inner: self.inner.iter(&GUID_DEVINTERFACE_USB_DEVICE) }
}
}
#[derive(Debug, Clone)]
pub struct InfoIter<'iter> {
inner: setup::InfoIter<'iter>,
}
impl<'iter> Iterator for InfoIter<'iter> {
type Item = io::Result<Info<'iter>>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|r| r.map(|i| Info { inner: i }))
}
}
impl<'iter> FusedIterator for InfoIter<'iter> {}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct Info<'a> {
inner: setup::Info<'a>,
}
impl<'a> Info<'a> {
pub fn open<'h>(&self) -> io::Result<WinUsbInterface<'h>> {
let device_handle = unsafe { CreateFileW(
self.inner.path_ptr(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
core::ptr::null_mut(),
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
core::ptr::null_mut()
) };
if device_handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error())
}
let winusb_handle: WINUSB_INTERFACE_HANDLE = core::ptr::null_mut();
let result = unsafe { WinUsb_Initialize(
device_handle,
&winusb_handle as *const _ as *mut _
) };
if result == FALSE {
let err = io::Error::last_os_error();
unsafe { CloseHandle(device_handle) };
return Err(err)
}
Ok(WinUsbInterface::new(device_handle, winusb_handle))
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct WinUsbInterface<'h> {
device_handle: HANDLE,
winusb_handle: WINUSB_INTERFACE_HANDLE,
_lifetime_of_handles: PhantomData<&'h ()>,
}
impl<'h> WinUsbInterface<'h> {
fn new(device_handle: HANDLE, winusb_handle: WINUSB_INTERFACE_HANDLE) -> Self {
WinUsbInterface {
device_handle, winusb_handle, _lifetime_of_handles: PhantomData
}
}
pub fn device_descriptor(&self) -> io::Result<USB_DEVICE_DESCRIPTOR> {
let mut dest = mem::MaybeUninit::<USB_DEVICE_DESCRIPTOR>::uninit();
let len = 0;
// This function not only fails when handle is null (which is impossible here),
// but also fails when there being an error while reading.
// When this fails, `len` remains zero and `ans` is set `FALSE`.
// ref: https://docs.microsoft.com/en-us/windows/desktop/api/winusb/nf-winusb-winusb_getdescriptor
let ans = unsafe { WinUsb_GetDescriptor(
self.winusb_handle,
USB_DEVICE_DESCRIPTOR_TYPE,
0,
LANG_NEUTRAL,
dest.as_mut_ptr() as *mut u8,
core::mem::size_of::<USB_DEVICE_DESCRIPTOR>() as DWORD,
&len as *const _ as *mut _
) };
if ans == FALSE {
return Err(io::Error::last_os_error())
}
Ok(unsafe { dest.assume_init() })
}
pub fn speed(&self) -> io::Result<USB_DEVICE_SPEED> {
let device_speed = 0 as UCHAR;
// this variable cannot be `static`: otherwise there would be a
// STATUS_ACCESS_VIOLATION error with exit code 0xc0000005 returned
let buf_size = core::mem::size_of::<UCHAR>() as DWORD;
let ans = unsafe {
WinUsb_QueryDeviceInformation(
self.winusb_handle,
DEVICE_SPEED,
&buf_size as *const _ as *mut _,
&device_speed as *const _ as *mut _
)
};
// If the device is unplugged during this operation,
// an error code 22 would be returned indicating the device
// does not identify the speed command
if ans == FALSE {
return Err(io::Error::last_os_error())
}
Ok(device_speed.into())
}
pub fn interface_settings(&self, alternate_interface_number: u8)
-> io::Result<Option<USB_INTERFACE_DESCRIPTOR>>
{
let mut dest = mem::MaybeUninit::<USB_INTERFACE_DESCRIPTOR>::uninit();
let ans = unsafe {
WinUsb_QueryInterfaceSettings(
self.winusb_handle,
alternate_interface_number,
dest.as_mut_ptr()
)
};
if ans == FALSE {
if unsafe { GetLastError() } == ERROR_NO_MORE_ITEMS {
return Ok(None);
}
return Err(io::Error::last_os_error());
}
Ok(Some(unsafe { dest.assume_init() }))
}
pub fn query_pipe(&self, interface_number: u8, pipe_index: u8)
-> io::Result<Option<WINUSB_PIPE_INFORMATION>>
{
let mut dest = mem::MaybeUninit::<WINUSB_PIPE_INFORMATION>::uninit();
let ans = unsafe {
WinUsb_QueryPipe(
self.winusb_handle,
interface_number,
pipe_index,
dest.as_mut_ptr()
)
};
if ans == FALSE {
if unsafe { GetLastError() } == ERROR_NO_MORE_ITEMS {
return Ok(None);
}
return Err(io::Error::last_os_error());
}
Ok(Some(unsafe { dest.assume_init() }))
}
pub fn write_pipe(&self, pipe_index: u8, buf: &[u8]) -> io::Result<usize> {
let mut len = mem::MaybeUninit::<DWORD>::uninit();
let ans = unsafe { WinUsb_WritePipe(
self.winusb_handle,
pipe_index,
buf.as_ptr() as *mut u8,
buf.len() as DWORD,
len.as_mut_ptr(),
core::ptr::null_mut(),
) };
if ans == FALSE {
return Err(io::Error::last_os_error())
}
Ok(unsafe { len.assume_init() } as usize)
}
pub fn read_pipe(&self, pipe_index: u8, buf: &mut [u8]) -> io::Result<usize> {
let mut len = mem::MaybeUninit::<DWORD>::uninit();
let ans = unsafe { WinUsb_ReadPipe(
self.winusb_handle,
pipe_index,
buf.as_ptr() as *mut u8,
buf.len() as DWORD,
len.as_mut_ptr(),
core::ptr::null_mut(),
) };
if ans == FALSE {
return Err(io::Error::last_os_error())
}
Ok(unsafe { len.assume_init() } as usize)
}
pub fn flush_pipe(&self, pipe_index: u8) -> io::Result<()> {
let ans = unsafe { WinUsb_FlushPipe (
self.winusb_handle,
pipe_index,
) };
if ans == FALSE {
return Err(io::Error::last_os_error())
}
Ok(())
}
pub fn reset_pipe(&self, pipe_index: u8) -> io::Result<()> {
let ans = unsafe { WinUsb_ResetPipe (
self.winusb_handle,
pipe_index,
) };
if ans == FALSE {
return Err(io::Error::last_os_error())
}
Ok(())
}
pub fn abort_pipe(&self, pipe_index: u8) -> io::Result<()> {
let ans = unsafe { WinUsb_AbortPipe (
self.winusb_handle,
pipe_index,
) };
if ans == FALSE {
return Err(io::Error::last_os_error())
}
Ok(())
}
// WinUsb_WritePipe with OVERLAPPED
pub fn write_pipe_overlapped(&self, pipe_index: u8, buf: &[u8])
-> io::Result<Pin<Box<OVERLAPPED>>>
{
let mut overlapped = Box::pin(unsafe {
mem::MaybeUninit::<OVERLAPPED>::uninit().assume_init()
});
overlapped.hEvent = core::ptr::null_mut();
let ans = unsafe { WinUsb_WritePipe(
self.winusb_handle,
pipe_index,
buf.as_ptr() as *mut u8,
buf.len() as DWORD,
core::ptr::null_mut(),
&*overlapped as *const _ as *mut _,
) };
if ans == FALSE {
if unsafe { GetLastError() } == ERROR_IO_PENDING {
return Ok(overlapped)
}
return Err(io::Error::last_os_error())
}
// todo: check if correct
// return Ok(unsafe { overlapped.assume_init() })
panic!("returned true for overlapped write")
}
pub fn read_pipe_overlapped(&self, pipe_index: u8, buf: &mut [u8])
-> io::Result<Pin<Box<OVERLAPPED>>>
{
let mut overlapped = Box::pin(unsafe {
mem::MaybeUninit::<OVERLAPPED>::uninit().assume_init()
});
overlapped.hEvent = core::ptr::null_mut();
let ans = unsafe { WinUsb_ReadPipe(
self.winusb_handle,
pipe_index,
buf.as_ptr() as *mut u8,
buf.len() as DWORD,
core::ptr::null_mut(),
&*overlapped as *const _ as *mut _,
) };
if ans == FALSE {
if unsafe { GetLastError() } == ERROR_IO_PENDING {
return Ok(overlapped)
}
return Err(io::Error::last_os_error())
}
// todo: check if correct
// return Ok(unsafe { overlapped.assume_init() })
panic!("returned true for overlapped read")
}
pub fn poll_overlapped(&self, overlapped: Pin<&OVERLAPPED>)
-> Poll<io::Result<usize>>
{
let mut bytes_transferred = mem::MaybeUninit::uninit();
let ans = unsafe { WinUsb_GetOverlappedResult(
self.winusb_handle,
&*overlapped as *const _ as *mut _,
bytes_transferred.as_mut_ptr(),
FALSE,
) };
if ans == FALSE {
if unsafe { GetLastError() } == ERROR_IO_INCOMPLETE {
return Poll::Pending;
}
return Poll::Ready(Err(io::Error::last_os_error()))
}
return Poll::Ready(Ok(unsafe { bytes_transferred.assume_init() as usize }))
}
}
impl Drop for WinUsbInterface<'_> {
fn drop(&mut self) {
unsafe {
// reversed free order in destructor
WinUsb_Free(self.winusb_handle);
CloseHandle(self.device_handle);
}
}
}
impl From<USB_DEVICE_DESCRIPTOR> for DeviceDescriptor {
fn from(src: USB_DEVICE_DESCRIPTOR) -> DeviceDescriptor {
DeviceDescriptor {
length: src.bLength,
descriptor_type: src.bDescriptorType,
bcd_usb: src.bcdUSB,
device_class: src.bDeviceClass,
device_sub_class: src.bDeviceSubClass,
device_protocol: src.bDeviceProtocol,
max_packet_size_0: src.bMaxPacketSize0,
id_vendor: src.idVendor,
id_product: src.idProduct,
bcd_device: src.bcdDevice,
manufacturer: src.iManufacturer,
product: src.iProduct,
serial_number: src.iSerialNumber,
num_configurations: src.bNumConfigurations,
}
}
}
impl From<USB_INTERFACE_DESCRIPTOR> for InterfaceDescriptor {
fn from(src: USB_INTERFACE_DESCRIPTOR) -> InterfaceDescriptor {
InterfaceDescriptor {
length: src.bLength,
descriptor_type: src.bDescriptorType,
interface_number: src.bInterfaceNumber,
alternate_setting: src.bAlternateSetting,
num_endpoints: src.bNumEndpoints,
interface_class: src.bInterfaceClass,
interface_subclass: src.bInterfaceSubClass,
interface_protocol: src.bInterfaceProtocol,
index_interface: src.iInterface,
}
}
}
impl From<USB_DEVICE_SPEED> for Speed {
fn from(src: USB_DEVICE_SPEED) -> Speed {
match src {
UsbLowSpeed => Speed::Low,
UsbFullSpeed => Speed::Full,
UsbHighSpeed => Speed::High,
UsbSuperSpeed => Speed::Super,
_ => Speed::Unknown,
}
}
}
|
mod day1;
mod util;
mod day2;
mod day3;
mod day4;
mod day5;
mod day6;
mod day7;
mod day8;
mod day9;
mod day10;
mod day11;
mod day12;
mod day13;
mod day14;
mod day15;
mod day16;
mod day17;
mod day18;
mod day19;
mod day20;
mod day21;
mod day22;
mod day23;
mod day24;
fn main() {
day1::day1();
day2::day2();
day3::day3();
day4::day4();
day5::day5();
day6::day6();
day7::day7();
day8::day8();
day9::day9();
day10::day10();
day11::day11();
day12::day12();
day13::day13();
day14::day14();
day15::day15();
day16::day16();
day17::day17();
day18::day18();
day19::day19();
day20::day20();
day21::day21();
day22::day22();
day23::day23();
day24::day24();
} |
#[doc = "Register `CEVR` writer"]
pub type W = crate::W<CEVR_SPEC>;
#[doc = "Field `CFCF` writer - clear frame complete flag (whatever the I3C is acting as controller/target)"]
pub type CFCF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRXTGTENDF` writer - clear target-initiated read end flag (when the I3C is acting as controller)"]
pub type CRXTGTENDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CERRF` writer - clear error flag (whatever the I3C is acting as controller/target)"]
pub type CERRF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CIBIF` writer - clear IBI request flag (when the I3C is acting as controller)"]
pub type CIBIF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CIBIENDF` writer - clear IBI end flag (when the I3C is acting as target)"]
pub type CIBIENDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CCRF` writer - clear controller-role request flag (when the I3C is acting as controller)"]
pub type CCRF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CCRUPDF` writer - clear controller-role update flag (when the I3C is acting as target)"]
pub type CCRUPDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CHJF` writer - clear hot-join flag (when the I3C is acting as controller)"]
pub type CHJF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CWKPF` writer - clear wakeup flag (when the I3C is acting as target)"]
pub type CWKPF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CGETF` writer - clear GETxxx CCC flag (when the I3C is acting as target)"]
pub type CGETF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CSTAF` writer - clear GETSTATUS CCC flag (when the I3C is acting as target)"]
pub type CSTAF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CDAUPDF` writer - clear ENTDAA/RSTDAA/SETNEWDA CCC flag (when the I3C is acting as target)"]
pub type CDAUPDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CMWLUPDF` writer - clear SETMWL CCC flag (when the I3C is acting as target)"]
pub type CMWLUPDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CMRLUPDF` writer - clear SETMRL CCC flag (when the I3C is acting as target)"]
pub type CMRLUPDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRSTF` writer - clear reset pattern flag (when the I3C is acting as target)"]
pub type CRSTF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CASUPDF` writer - clear ENTASx CCC flag (when the I3C is acting as target)"]
pub type CASUPDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CINTUPDF` writer - clear ENEC/DISEC CCC flag (when the I3C is acting as target)"]
pub type CINTUPDF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CDEFF` writer - clear DEFTGTS CCC flag (when the I3C is acting as target)"]
pub type CDEFF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CGRPF` writer - clear DEFGRPA CCC flag (when the I3C is acting as target)"]
pub type CGRPF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl W {
#[doc = "Bit 9 - clear frame complete flag (whatever the I3C is acting as controller/target)"]
#[inline(always)]
#[must_use]
pub fn cfcf(&mut self) -> CFCF_W<CEVR_SPEC, 9> {
CFCF_W::new(self)
}
#[doc = "Bit 10 - clear target-initiated read end flag (when the I3C is acting as controller)"]
#[inline(always)]
#[must_use]
pub fn crxtgtendf(&mut self) -> CRXTGTENDF_W<CEVR_SPEC, 10> {
CRXTGTENDF_W::new(self)
}
#[doc = "Bit 11 - clear error flag (whatever the I3C is acting as controller/target)"]
#[inline(always)]
#[must_use]
pub fn cerrf(&mut self) -> CERRF_W<CEVR_SPEC, 11> {
CERRF_W::new(self)
}
#[doc = "Bit 15 - clear IBI request flag (when the I3C is acting as controller)"]
#[inline(always)]
#[must_use]
pub fn cibif(&mut self) -> CIBIF_W<CEVR_SPEC, 15> {
CIBIF_W::new(self)
}
#[doc = "Bit 16 - clear IBI end flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cibiendf(&mut self) -> CIBIENDF_W<CEVR_SPEC, 16> {
CIBIENDF_W::new(self)
}
#[doc = "Bit 17 - clear controller-role request flag (when the I3C is acting as controller)"]
#[inline(always)]
#[must_use]
pub fn ccrf(&mut self) -> CCRF_W<CEVR_SPEC, 17> {
CCRF_W::new(self)
}
#[doc = "Bit 18 - clear controller-role update flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn ccrupdf(&mut self) -> CCRUPDF_W<CEVR_SPEC, 18> {
CCRUPDF_W::new(self)
}
#[doc = "Bit 19 - clear hot-join flag (when the I3C is acting as controller)"]
#[inline(always)]
#[must_use]
pub fn chjf(&mut self) -> CHJF_W<CEVR_SPEC, 19> {
CHJF_W::new(self)
}
#[doc = "Bit 21 - clear wakeup flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cwkpf(&mut self) -> CWKPF_W<CEVR_SPEC, 21> {
CWKPF_W::new(self)
}
#[doc = "Bit 22 - clear GETxxx CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cgetf(&mut self) -> CGETF_W<CEVR_SPEC, 22> {
CGETF_W::new(self)
}
#[doc = "Bit 23 - clear GETSTATUS CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cstaf(&mut self) -> CSTAF_W<CEVR_SPEC, 23> {
CSTAF_W::new(self)
}
#[doc = "Bit 24 - clear ENTDAA/RSTDAA/SETNEWDA CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cdaupdf(&mut self) -> CDAUPDF_W<CEVR_SPEC, 24> {
CDAUPDF_W::new(self)
}
#[doc = "Bit 25 - clear SETMWL CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cmwlupdf(&mut self) -> CMWLUPDF_W<CEVR_SPEC, 25> {
CMWLUPDF_W::new(self)
}
#[doc = "Bit 26 - clear SETMRL CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cmrlupdf(&mut self) -> CMRLUPDF_W<CEVR_SPEC, 26> {
CMRLUPDF_W::new(self)
}
#[doc = "Bit 27 - clear reset pattern flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn crstf(&mut self) -> CRSTF_W<CEVR_SPEC, 27> {
CRSTF_W::new(self)
}
#[doc = "Bit 28 - clear ENTASx CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn casupdf(&mut self) -> CASUPDF_W<CEVR_SPEC, 28> {
CASUPDF_W::new(self)
}
#[doc = "Bit 29 - clear ENEC/DISEC CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cintupdf(&mut self) -> CINTUPDF_W<CEVR_SPEC, 29> {
CINTUPDF_W::new(self)
}
#[doc = "Bit 30 - clear DEFTGTS CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cdeff(&mut self) -> CDEFF_W<CEVR_SPEC, 30> {
CDEFF_W::new(self)
}
#[doc = "Bit 31 - clear DEFGRPA CCC flag (when the I3C is acting as target)"]
#[inline(always)]
#[must_use]
pub fn cgrpf(&mut self) -> CGRPF_W<CEVR_SPEC, 31> {
CGRPF_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 = "I3C clear event 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 [`cevr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct CEVR_SPEC;
impl crate::RegisterSpec for CEVR_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [`cevr::W`](W) writer structure"]
impl crate::Writable for CEVR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets CEVR to value 0"]
impl crate::Resettable for CEVR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::parser::parser_defs;
pub fn vertical_line_relative(v: f32, position: (f32, f32)) -> parser_defs::SVGPoint {
parser_defs::SVGPoint {
x: position.0,
y: position.1 + v
}
}
pub fn horizontal_line_relative(h: f32, position: (f32, f32)) -> parser_defs::SVGPoint {
parser_defs::SVGPoint {
x: position.0 + h,
y: position.1
}
}
pub fn line_relative(point: (f32, f32), position: (f32, f32)) -> parser_defs::SVGPoint {
parser_defs::SVGPoint {
x: position.0 + point.0,
y: position.1 + point.1
}
}
pub fn line_absolute(point: (f32, f32)) -> parser_defs::SVGPoint {
parser_defs::SVGPoint {
x: point.0,
y: point.1
}
}
pub fn vertical_line_absolute(point: (f32, f32)) -> parser_defs::SVGPoint {
line_absolute(point)
}
pub fn horizontal_line_absolute(point: (f32, f32)) -> parser_defs::SVGPoint {
line_absolute(point)
} |
pub fn mincore(addr: u64, length: u64, vec: u64) -> u64 {
let addr = addr as usize;
let length = length as usize;
let vec = vec as usize;
println!("Syscall: mincore addr={:x} length={:x} vex={:x}", addr, length, vec);
0
}
|
use crate::*;
use numeric_types::*;
pub const CURSOR_IMAGE: &str = "cursor.png";
pub const INFO_BAR_IMAGE: &str = "infobar.png";
pub const UNIT_INFO_BAR_IMAGE: &str = "unit-infobar.png";
pub const ZERO_TILES: MapDistance = map_dist(0);
pub const ONE_TILE: MapDistance = map_dist(1);
pub const UNREACHABLE: MapDistance = map_dist(-1);
pub const UP: Vector<MapDistance> = Vector {
x: ZERO_TILES,
y: map_dist(-1),
};
pub const DOWN: Vector<MapDistance> = Vector {
x: ZERO_TILES,
y: ONE_TILE,
};
pub const LEFT: Vector<MapDistance> = Vector {
x: map_dist(-1),
y: ZERO_TILES,
};
pub const RIGHT: Vector<MapDistance> = Vector {
x: ONE_TILE,
y: ZERO_TILES,
};
pub const ZERO_HP: HitPoints = hp(0);
pub const BASE_EVADE_BONUS: AccuracyPoints = accuracy_pts(0);
|
// use std::time::Duration;
// use anyhow::*;
// use graphql_client::*;
// use log::*;
// // use prettytable::*;
// use serde::*;
// use structopt::StructOpt;
// // use chrono::Utc;
// use chrono::Local;
// use csv::WriterBuilder;
// type URI = String;
// type DateTime = chrono::DateTime<Local>;
// #[derive(GraphQLQuery)]
// #[graphql(
// schema_path = "./data/schema.graphql",
// query_path = "./data/issues.graphql",
// response_derives = "Debug"
// )]
// struct ListIssuesQuery;
// #[derive(Serialize, Debug)]
// struct IssueRow<'x> {
// pub id: &'x str,
// pub number: i64,
// pub title: &'x str,
// pub url: &'x str,
// pub assignees: &'x str,
// pub active_lock_reason: Option<&'x list_issues_query::LockReason>,
// pub author_email: &'x str,
// pub author_login: &'x str,
// pub author_association: i32,
// pub body: &'x str,
// pub closed: bool,
// pub closed_at: Option<DateTime>,
// pub created_at: DateTime,
// pub comments_count: i32,
// pub created_via_email: bool,
// pub database_id: Option<i64>,
// pub editor_login: &'x str,
// pub includes_created_edit: bool,
// pub labels: &'x str,
// pub last_edited_at: Option<DateTime>,
// pub locked: bool,
// pub milestone_title: &'x str,
// pub milestone_number: i32,
// pub published_at: Option<DateTime>,
// pub resource_path: String,
// pub state: &'x list_issues_query::IssueState,
// pub updated_at: DateTime,
// // participants(first: 100) {
// // totalCount
// // nodes {
// // login
// // name
// // }
// // }
// }
// use list_issues_query::ListIssuesQueryRepositoryIssuesNodesAuthorOn::User;
// fn get_issues_via_graphql() -> Result<()> {
// env_logger::init();
// let config: Env = envy::from_env().context("while reading from environment")?;
// let args = Command::from_args();
// let owner = args.owner;
// let name = args.name;
// let mut has_next = true;
// let mut has_header = true;
// let mut first = true;
// let mut cursor = String::from("");
// while has_next {
// let after: Option<String> = if first { None } else { Some(cursor.clone()) };
// let q = ListIssuesQuery::build_query(list_issues_query::Variables {
// name: name.clone(),
// owner: owner.clone(),
// after: after,
// });
// let client = reqwest::blocking::Client::builder()
// .timeout(Duration::from_secs(120))
// .user_agent("ghex(graphql-rust/0.9.0)")
// .build()?;
// let res = client
// .post(&config.github_api_url)
// .bearer_auth(config.github_api_token.clone())
// .json(&q)
// .send()?;
// res.error_for_status_ref()?;
// let response_body: Response<list_issues_query::ResponseData> = res.json()?;
// if let Some(errors) = response_body.errors {
// error!("there are errors:");
// for error in &errors {
// error!("{:?}", error);
// }
// bail!("Request failed")
// }
// let response_data = response_body.data.expect("missing response data");
// debug!("{:?}", response_data);
// let issues = &response_data
// .repository
// .as_ref()
// .expect("No Repo Found")
// .issues;
// has_next = issues.page_info.has_next_page;
// if has_next {
// first = false;
// let cursor_ = issues.page_info.end_cursor.as_ref();
// cursor = String::from(cursor_.unwrap());
// }
// let nodes = issues.nodes.as_ref().expect("No Issues");
// let mut wtr = WriterBuilder::new()
// .has_headers(has_header)
// .from_writer(vec![]);
// for issue in nodes {
// let issue = issue.as_ref().unwrap();
// let author = issue.author.as_ref().unwrap();
// if let User(author) = &author.on {
// let row = IssueRow {
// id: &issue.id,
// number: issue.number,
// title: &issue.title,
// url: &issue.url,
// assignees: "",
// active_lock_reason: issue.active_lock_reason.as_ref(),
// author_email: &author.email,
// author_login: &author.login,
// author_association: 0,
// body: &issue.body,
// closed: issue.closed,
// closed_at: issue.closed_at,
// created_at: issue.created_at,
// comments_count: 0,
// created_via_email: issue.created_via_email,
// database_id: issue.database_id,
// editor_login: "",
// includes_created_edit: false,
// labels: "",
// last_edited_at: issue.last_edited_at,
// locked: issue.locked,
// milestone_title: "",
// milestone_number: 1,
// published_at: issue.published_at,
// resource_path: issue.resource_path.clone(),
// state: &issue.state,
// updated_at: issue.updated_at,
// };
// wtr.serialize(&row)?;
// }
// }
// println!("{}", String::from_utf8(wtr.into_inner()?)?);
// eprintln!("Iterated");
// has_header = false; // Force false in 2nd loop
// }
// Ok(())
// }
|
#[doc = "Register `FMC_PMEM` reader"]
pub type R = crate::R<FMC_PMEM_SPEC>;
#[doc = "Register `FMC_PMEM` writer"]
pub type W = crate::W<FMC_PMEM_SPEC>;
#[doc = "Field `MEMSET` reader - MEMSET"]
pub type MEMSET_R = crate::FieldReader;
#[doc = "Field `MEMSET` writer - MEMSET"]
pub type MEMSET_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `MEMWAIT` reader - MEMWAIT"]
pub type MEMWAIT_R = crate::FieldReader;
#[doc = "Field `MEMWAIT` writer - MEMWAIT"]
pub type MEMWAIT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `MEMHOLD` reader - MEMHOLD"]
pub type MEMHOLD_R = crate::FieldReader;
#[doc = "Field `MEMHOLD` writer - MEMHOLD"]
pub type MEMHOLD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `MEMHIZ` reader - MEMHIZ"]
pub type MEMHIZ_R = crate::FieldReader;
#[doc = "Field `MEMHIZ` writer - MEMHIZ"]
pub type MEMHIZ_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bits 0:7 - MEMSET"]
#[inline(always)]
pub fn memset(&self) -> MEMSET_R {
MEMSET_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - MEMWAIT"]
#[inline(always)]
pub fn memwait(&self) -> MEMWAIT_R {
MEMWAIT_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - MEMHOLD"]
#[inline(always)]
pub fn memhold(&self) -> MEMHOLD_R {
MEMHOLD_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - MEMHIZ"]
#[inline(always)]
pub fn memhiz(&self) -> MEMHIZ_R {
MEMHIZ_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - MEMSET"]
#[inline(always)]
#[must_use]
pub fn memset(&mut self) -> MEMSET_W<FMC_PMEM_SPEC, 0> {
MEMSET_W::new(self)
}
#[doc = "Bits 8:15 - MEMWAIT"]
#[inline(always)]
#[must_use]
pub fn memwait(&mut self) -> MEMWAIT_W<FMC_PMEM_SPEC, 8> {
MEMWAIT_W::new(self)
}
#[doc = "Bits 16:23 - MEMHOLD"]
#[inline(always)]
#[must_use]
pub fn memhold(&mut self) -> MEMHOLD_W<FMC_PMEM_SPEC, 16> {
MEMHOLD_W::new(self)
}
#[doc = "Bits 24:31 - MEMHIZ"]
#[inline(always)]
#[must_use]
pub fn memhiz(&mut self) -> MEMHIZ_W<FMC_PMEM_SPEC, 24> {
MEMHIZ_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 = "The FMC_PMEM read/write register contains NAND Flash memory bank timing information. This information is used to access the NAND Flash common memory space for command, address write accesses or data read/write accesses.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fmc_pmem::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 [`fmc_pmem::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct FMC_PMEM_SPEC;
impl crate::RegisterSpec for FMC_PMEM_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`fmc_pmem::R`](R) reader structure"]
impl crate::Readable for FMC_PMEM_SPEC {}
#[doc = "`write(|w| ..)` method takes [`fmc_pmem::W`](W) writer structure"]
impl crate::Writable for FMC_PMEM_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets FMC_PMEM to value 0x0a0a_0a0a"]
impl crate::Resettable for FMC_PMEM_SPEC {
const RESET_VALUE: Self::Ux = 0x0a0a_0a0a;
}
|
pub mod lobby;
pub mod out_of_lobby;
pub mod page_not_found;
|
use std::io;
// use std::io::Write;
// use std::io::Read;
// https://doc.rust-lang.org/std/io/prelude/index.html
// If not "prelude", we have to use io::Write and io::Read
use std::io::prelude::*;
use std::net::TcpListener;
use std::thread::spawn;
use hex_slice::AsHex;
/// Accept connections forever, spawning a thread for each one.
fn echo_main(addr: &str) -> io::Result<()> {
let listener = TcpListener::bind(addr)?;
println!("listening on {}", addr);
loop {
// Wait for a client to connect.
let (mut stream, addr) = listener.accept()?;
println!("connection received from {}", addr);
// Spawn a thread to handle this client.
let mut write_stream = stream.try_clone()?;
spawn(move || {
// Echo everything we receive from `stream` back to it.
// io::copy(&mut stream, &mut write_stream).expect("error in client thread: ");
let mut buf = [0u8; 512];
let mut written = 0;
loop {
let len = match stream.read(&mut buf) {
Ok(0) => {
println!("connection closed, written: {}", written);
return Ok(written)
},
Ok(len) => len,
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) => {
println!("connection error {}", e);
return Err(e)
},
};
println!("Read and write: {:X}, Length: {}", &buf[..len].as_hex(), len);
write_stream.write_all(&buf[..len])?;
written += len as u64;
}
});
}
}
fn main() {
echo_main("127.0.0.1:17007").expect("error: ");
}
|
#![allow(non_snake_case)]
#[allow(unused_imports)]
use std::io::{self, Write};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
macro_rules! input {
(source = $s:expr, $($r:tt)*) => {
let mut iter = $s.split_whitespace();
let mut next = || { iter.next().unwrap() };
input_inner!{next, $($r)*}
};
($($r:tt)*) => {
let stdin = std::io::stdin();
let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
let mut next = move || -> String{
bytes
.by_ref()
.map(|r|r.unwrap() as char)
.skip_while(|c|c.is_whitespace())
.take_while(|c|!c.is_whitespace())
.collect()
};
input_inner!{next, $($r)*}
};
}
macro_rules! input_inner {
($next:expr) => {};
($next:expr, ) => {};
($next:expr, $var:ident : $t:tt $($r:tt)*) => {
let $var = read_value!($next, $t);
input_inner!{$next $($r)*}
};
}
macro_rules! read_value {
($next:expr, ( $($t:tt),* )) => {
( $(read_value!($next, $t)),* )
};
($next:expr, [ $t:tt ; $len:expr ]) => {
(0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
};
($next:expr, chars) => {
read_value!($next, String).chars().collect::<Vec<char>>()
};
($next:expr, char) => {
read_value!($next, String).chars().collect::<Vec<char>>()[0]
};
($next:expr, usize1) => {
read_value!($next, usize) - 1
};
($next:expr, isize1) => {
read_value!($next, isize) - 1
};
($next:expr, $t:ty) => {
$next().parse::<$t>().expect("Parse error")
};
}
macro_rules! printvec {
( $item:expr ) => {
for &i in &$item {
print!("{} ", i);
}
println!("");
}
}
macro_rules! debug {
($($a:expr),*) => {
println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
}
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Rev<T>(pub T);
impl<T: PartialOrd> PartialOrd for Rev<T> {
fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
other.0.partial_cmp(&self.0)
}
}
impl<T: Ord> Ord for Rev<T> {
fn cmp(&self, other: &Rev<T>) -> Ordering {
other.0.cmp(&self.0)
}
}
#[derive(PartialEq, PartialOrd, Clone, Debug)]
pub struct Total<T>(pub T);
impl<T: PartialEq> Eq for Total<T> {}
impl<T: PartialOrd> Ord for Total<T> {
fn cmp(&self, other: &Total<T>) -> Ordering {
self.0.partial_cmp(&other.0).unwrap()
}
}
#[allow(dead_code)]
const MOD: usize = 1000000007;
#[derive(Eq, PartialEq, Clone, Debug)]
struct FactInv {
fact: Vec<usize>,
inv: Vec<usize>,
factinv: Vec<usize>,
m: usize,
}
#[allow(dead_code)]
impl FactInv {
fn new(n: usize, m: usize) -> Self {
let mut fact: Vec<usize> = vec![0; n + 1];
fact[0] = 1;
for i in 1..n+1 {
fact[i] = i * &fact[i - 1] % m;
}
let mut inv = vec![0; n + 1];
inv[0] = 0;
inv[1] = 1;
for i in 2..n+1 {
inv[i] = inv[m % i] * (m - m / i) % m;
}
let mut factinv = vec![0; n + 1];
factinv[0] = 1;
for i in 1..n+1 {
factinv[i] = factinv[i - 1] * inv[i] % m;
}
FactInv {
fact: fact,
inv: inv,
factinv: factinv,
m: m,
}
}
fn comb(&self, n: usize, r: usize) -> usize {
if n < r {
0
} else {
(self.fact[n] * self.factinv[r] % self.m) * self.factinv[n-r] % self.m
}
}
}
fn main() {
input!{
X: usize, Y: usize,
}
let mut ans = 0;
if (X + Y) % 3 != 0 {
println!("{}",ans);
} else if X * 2 < Y || X > Y * 2 {
println!("{}", ans);
} else {
let n = (X + Y) / 3;
let (X, Y) = if X > Y {(Y, X)} else {(X, Y)};
let mut x = n;
let mut y = 2 * n;
let mut l = 0;
let mut r = n;
loop {
if x == X && y == Y {
break
} else {
x += 1;
y -= 1;
l += 1;
r -= 1;
}
}
let fi = FactInv::new(n, MOD);
println!("{}", fi.comb(n, r));
}
} |
use super::FileOperation;
use crate::error::{Error, UnderlyingError};
use std::path;
impl FileOperation {
pub fn get_relative_path<'a>(
&self,
relative_to_path: &'a path::Path,
) -> Result<&'a path::Path, Error> {
let file_path = match self {
FileOperation::Create(path) => path,
FileOperation::Replace(path) => path,
FileOperation::Store(path) => path,
};
let relative_path = relative_to_path
.strip_prefix(file_path)
.map_err(|err| Error::invalid_parameter(Some(UnderlyingError::from(err))))?;
Ok(relative_path)
}
// TODO: This isn't enough, this must return the path relative to another path, the other path being the working directory
pub fn get_filename(&self) -> Result<&str, Error> {
match self {
FileOperation::Create(path) => FileOperation::get_str(path)
.map_err(|error| error.add_generic_message("While creating a file")),
FileOperation::Replace(path) => FileOperation::get_str(path)
.map_err(|err| err.add_generic_message("While replacing a file")),
FileOperation::Store(path) => FileOperation::get_str(path)
.map_err(|err| err.add_generic_message("While storing a file")),
}
}
fn get_str(path: &path::Path) -> Result<&str, Error> {
let file_name = path
.file_name()
.ok_or(Error::invalid_parameter(None).add_generic_message(
"A path used for an atomic operation did not have a file name",
))?
.to_str()
.ok_or(Error::invalid_parameter(None).add_generic_message(
"A path used for an atomic operation was not a valid UTF8 string",
))?;
Ok(file_name)
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - TIM12 control register 1"]
pub timx_cr1: TIMX_CR1,
_reserved1: [u8; 6usize],
#[doc = "0x08 - slave mode control register"]
pub timx_smcr: TIMX_SMCR,
#[doc = "0x0c - TIM12 Interrupt enable register"]
pub timx_dier: TIMX_DIER,
_reserved3: [u8; 2usize],
#[doc = "0x10 - TIM12 status register"]
pub timx_sr: TIMX_SR,
_reserved4: [u8; 2usize],
#[doc = "0x14 - event generation register"]
pub timx_egr: TIMX_EGR,
_reserved_5_timx_ccmr1: [u8; 4usize],
_reserved6: [u8; 4usize],
#[doc = "0x20 - TIM12 capture/compare enable register"]
pub timx_ccer: TIMX_CCER,
_reserved7: [u8; 2usize],
#[doc = "0x24 - TIM12 counter"]
pub timx_cnt: TIMX_CNT,
#[doc = "0x28 - TIM12 prescaler"]
pub timx_psc: TIMX_PSC,
_reserved9: [u8; 2usize],
#[doc = "0x2c - TIM12 auto-reload register"]
pub timx_arr: TIMX_ARR,
_reserved10: [u8; 6usize],
#[doc = "0x34 - TIM12 capture/compare register 1"]
pub timx_ccr1: TIMX_CCR1,
_reserved11: [u8; 2usize],
#[doc = "0x38 - TIM12 capture/compare register 2"]
pub timx_ccr2: TIMX_CCR2,
_reserved12: [u8; 46usize],
#[doc = "0x68 - TIMx timer input selection register"]
pub timx_tisel: TIMX_TISEL,
}
impl RegisterBlock {
#[doc = "0x18 - capture/compare mode register 1 (input mode)"]
#[inline(always)]
pub fn timx_ccmr1_input(&self) -> &TIMX_CCMR1_INPUT {
unsafe { &*(((self as *const Self) as *const u8).add(24usize) as *const TIMX_CCMR1_INPUT) }
}
#[doc = "0x18 - capture/compare mode register 1 (input mode)"]
#[inline(always)]
pub fn timx_ccmr1_input_mut(&self) -> &mut TIMX_CCMR1_INPUT {
unsafe { &mut *(((self as *const Self) as *mut u8).add(24usize) as *mut TIMX_CCMR1_INPUT) }
}
#[doc = "0x18 - capture/compare mode register 1 (output mode)"]
#[inline(always)]
pub fn timx_ccmr1_output(&self) -> &TIMX_CCMR1_OUTPUT {
unsafe { &*(((self as *const Self) as *const u8).add(24usize) as *const TIMX_CCMR1_OUTPUT) }
}
#[doc = "0x18 - capture/compare mode register 1 (output mode)"]
#[inline(always)]
pub fn timx_ccmr1_output_mut(&self) -> &mut TIMX_CCMR1_OUTPUT {
unsafe { &mut *(((self as *const Self) as *mut u8).add(24usize) as *mut TIMX_CCMR1_OUTPUT) }
}
}
#[doc = "TIM12 control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_cr1](timx_cr1) module"]
pub type TIMX_CR1 = crate::Reg<u16, _TIMX_CR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_CR1;
#[doc = "`read()` method returns [timx_cr1::R](timx_cr1::R) reader structure"]
impl crate::Readable for TIMX_CR1 {}
#[doc = "`write(|w| ..)` method takes [timx_cr1::W](timx_cr1::W) writer structure"]
impl crate::Writable for TIMX_CR1 {}
#[doc = "TIM12 control register 1"]
pub mod timx_cr1;
#[doc = "slave mode control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_smcr](timx_smcr) module"]
pub type TIMX_SMCR = crate::Reg<u32, _TIMX_SMCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_SMCR;
#[doc = "`read()` method returns [timx_smcr::R](timx_smcr::R) reader structure"]
impl crate::Readable for TIMX_SMCR {}
#[doc = "`write(|w| ..)` method takes [timx_smcr::W](timx_smcr::W) writer structure"]
impl crate::Writable for TIMX_SMCR {}
#[doc = "slave mode control register"]
pub mod timx_smcr;
#[doc = "TIM12 Interrupt enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_dier](timx_dier) module"]
pub type TIMX_DIER = crate::Reg<u16, _TIMX_DIER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_DIER;
#[doc = "`read()` method returns [timx_dier::R](timx_dier::R) reader structure"]
impl crate::Readable for TIMX_DIER {}
#[doc = "`write(|w| ..)` method takes [timx_dier::W](timx_dier::W) writer structure"]
impl crate::Writable for TIMX_DIER {}
#[doc = "TIM12 Interrupt enable register"]
pub mod timx_dier;
#[doc = "TIM12 status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_sr](timx_sr) module"]
pub type TIMX_SR = crate::Reg<u16, _TIMX_SR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_SR;
#[doc = "`read()` method returns [timx_sr::R](timx_sr::R) reader structure"]
impl crate::Readable for TIMX_SR {}
#[doc = "`write(|w| ..)` method takes [timx_sr::W](timx_sr::W) writer structure"]
impl crate::Writable for TIMX_SR {}
#[doc = "TIM12 status register"]
pub mod timx_sr;
#[doc = "event generation register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_egr](timx_egr) module"]
pub type TIMX_EGR = crate::Reg<u32, _TIMX_EGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_EGR;
#[doc = "`write(|w| ..)` method takes [timx_egr::W](timx_egr::W) writer structure"]
impl crate::Writable for TIMX_EGR {}
#[doc = "event generation register"]
pub mod timx_egr;
#[doc = "capture/compare mode register 1 (output mode)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_ccmr1_output](timx_ccmr1_output) module"]
pub type TIMX_CCMR1_OUTPUT = crate::Reg<u32, _TIMX_CCMR1_OUTPUT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_CCMR1_OUTPUT;
#[doc = "`read()` method returns [timx_ccmr1_output::R](timx_ccmr1_output::R) reader structure"]
impl crate::Readable for TIMX_CCMR1_OUTPUT {}
#[doc = "`write(|w| ..)` method takes [timx_ccmr1_output::W](timx_ccmr1_output::W) writer structure"]
impl crate::Writable for TIMX_CCMR1_OUTPUT {}
#[doc = "capture/compare mode register 1 (output mode)"]
pub mod timx_ccmr1_output;
#[doc = "capture/compare mode register 1 (input mode)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_ccmr1_input](timx_ccmr1_input) module"]
pub type TIMX_CCMR1_INPUT = crate::Reg<u32, _TIMX_CCMR1_INPUT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_CCMR1_INPUT;
#[doc = "`read()` method returns [timx_ccmr1_input::R](timx_ccmr1_input::R) reader structure"]
impl crate::Readable for TIMX_CCMR1_INPUT {}
#[doc = "`write(|w| ..)` method takes [timx_ccmr1_input::W](timx_ccmr1_input::W) writer structure"]
impl crate::Writable for TIMX_CCMR1_INPUT {}
#[doc = "capture/compare mode register 1 (input mode)"]
pub mod timx_ccmr1_input;
#[doc = "TIM12 capture/compare enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_ccer](timx_ccer) module"]
pub type TIMX_CCER = crate::Reg<u16, _TIMX_CCER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_CCER;
#[doc = "`read()` method returns [timx_ccer::R](timx_ccer::R) reader structure"]
impl crate::Readable for TIMX_CCER {}
#[doc = "`write(|w| ..)` method takes [timx_ccer::W](timx_ccer::W) writer structure"]
impl crate::Writable for TIMX_CCER {}
#[doc = "TIM12 capture/compare enable register"]
pub mod timx_ccer;
#[doc = "TIM12 counter\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_cnt](timx_cnt) module"]
pub type TIMX_CNT = crate::Reg<u32, _TIMX_CNT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_CNT;
#[doc = "`read()` method returns [timx_cnt::R](timx_cnt::R) reader structure"]
impl crate::Readable for TIMX_CNT {}
#[doc = "`write(|w| ..)` method takes [timx_cnt::W](timx_cnt::W) writer structure"]
impl crate::Writable for TIMX_CNT {}
#[doc = "TIM12 counter"]
pub mod timx_cnt;
#[doc = "TIM12 prescaler\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_psc](timx_psc) module"]
pub type TIMX_PSC = crate::Reg<u16, _TIMX_PSC>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_PSC;
#[doc = "`read()` method returns [timx_psc::R](timx_psc::R) reader structure"]
impl crate::Readable for TIMX_PSC {}
#[doc = "`write(|w| ..)` method takes [timx_psc::W](timx_psc::W) writer structure"]
impl crate::Writable for TIMX_PSC {}
#[doc = "TIM12 prescaler"]
pub mod timx_psc;
#[doc = "TIM12 auto-reload register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_arr](timx_arr) module"]
pub type TIMX_ARR = crate::Reg<u16, _TIMX_ARR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_ARR;
#[doc = "`read()` method returns [timx_arr::R](timx_arr::R) reader structure"]
impl crate::Readable for TIMX_ARR {}
#[doc = "`write(|w| ..)` method takes [timx_arr::W](timx_arr::W) writer structure"]
impl crate::Writable for TIMX_ARR {}
#[doc = "TIM12 auto-reload register"]
pub mod timx_arr;
#[doc = "TIM12 capture/compare register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_ccr1](timx_ccr1) module"]
pub type TIMX_CCR1 = crate::Reg<u16, _TIMX_CCR1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_CCR1;
#[doc = "`read()` method returns [timx_ccr1::R](timx_ccr1::R) reader structure"]
impl crate::Readable for TIMX_CCR1 {}
#[doc = "`write(|w| ..)` method takes [timx_ccr1::W](timx_ccr1::W) writer structure"]
impl crate::Writable for TIMX_CCR1 {}
#[doc = "TIM12 capture/compare register 1"]
pub mod timx_ccr1;
#[doc = "TIM12 capture/compare register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_ccr2](timx_ccr2) module"]
pub type TIMX_CCR2 = crate::Reg<u16, _TIMX_CCR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_CCR2;
#[doc = "`read()` method returns [timx_ccr2::R](timx_ccr2::R) reader structure"]
impl crate::Readable for TIMX_CCR2 {}
#[doc = "`write(|w| ..)` method takes [timx_ccr2::W](timx_ccr2::W) writer structure"]
impl crate::Writable for TIMX_CCR2 {}
#[doc = "TIM12 capture/compare register 2"]
pub mod timx_ccr2;
#[doc = "TIMx timer input selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [timx_tisel](timx_tisel) module"]
pub type TIMX_TISEL = crate::Reg<u32, _TIMX_TISEL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TIMX_TISEL;
#[doc = "`read()` method returns [timx_tisel::R](timx_tisel::R) reader structure"]
impl crate::Readable for TIMX_TISEL {}
#[doc = "`write(|w| ..)` method takes [timx_tisel::W](timx_tisel::W) writer structure"]
impl crate::Writable for TIMX_TISEL {}
#[doc = "TIMx timer input selection register"]
pub mod timx_tisel;
|
use crate::headers::from_headers::*;
use crate::resources::Trigger;
use crate::ResourceQuota;
use azure_core::headers::{
continuation_token_from_headers_optional, item_count_from_headers, session_token_from_headers,
};
use chrono::{DateTime, Utc};
use http::response::Response;
#[derive(Debug, Clone, PartialEq)]
pub struct ListTriggersResponse {
pub rid: String,
pub triggers: Vec<Trigger>,
pub content_location: String,
pub server: String,
pub last_state_change: DateTime<Utc>,
pub continuation_token: Option<String>,
pub resource_quota: Vec<ResourceQuota>,
pub resource_usage: Vec<ResourceQuota>,
pub lsn: u64,
pub item_count: u32,
pub schema_version: String,
pub alt_content_path: String,
pub content_path: String,
pub role: u32,
pub global_committed_lsn: u64,
pub number_of_read_regions: u32,
pub transport_request_id: u64,
pub cosmos_llsn: u64,
pub session_token: String,
pub charge: f64,
pub service_version: String,
pub activity_id: uuid::Uuid,
pub gateway_version: String,
pub date: DateTime<Utc>,
}
impl std::convert::TryFrom<Response<bytes::Bytes>> for ListTriggersResponse {
type Error = crate::Error;
fn try_from(response: Response<bytes::Bytes>) -> Result<Self, Self::Error> {
let headers = response.headers();
let body = response.body();
#[derive(Debug, Deserialize)]
struct Response<'a> {
#[serde(rename = "_rid")]
rid: &'a str,
#[serde(rename = "Triggers")]
triggers: Vec<Trigger>,
#[serde(rename = "_count")]
count: u32,
}
let response: Response = serde_json::from_slice(body)?;
Ok(Self {
rid: response.rid.to_owned(),
triggers: response.triggers,
content_location: content_location_from_headers(headers)?.to_owned(),
server: server_from_headers(headers)?.to_owned(),
last_state_change: last_state_change_from_headers(headers)?,
continuation_token: continuation_token_from_headers_optional(headers)?,
resource_quota: resource_quota_from_headers(headers)?,
resource_usage: resource_usage_from_headers(headers)?,
lsn: lsn_from_headers(headers)?,
item_count: item_count_from_headers(headers)?,
schema_version: schema_version_from_headers(headers)?.to_owned(),
alt_content_path: alt_content_path_from_headers(headers)?.to_owned(),
content_path: content_path_from_headers(headers)?.to_owned(),
role: role_from_headers(headers)?,
global_committed_lsn: global_committed_lsn_from_headers(headers)?,
number_of_read_regions: number_of_read_regions_from_headers(headers)?,
transport_request_id: transport_request_id_from_headers(headers)?,
cosmos_llsn: cosmos_llsn_from_headers(headers)?,
session_token: session_token_from_headers(headers)?,
charge: request_charge_from_headers(headers)?,
service_version: service_version_from_headers(headers)?.to_owned(),
activity_id: activity_id_from_headers(headers)?,
gateway_version: gateway_version_from_headers(headers)?.to_owned(),
date: date_from_headers(headers)?,
})
}
}
|
use std::hash::Hash;
use bloom_filter::BloomFilter;
use hash::{DefaultHasher, NthHash};
// parameter `s`
const GROWTH_FACTOR: usize = 2;
/// Scalable bloom filter.
///
/// See the [paper] about scalable bloom filters.
///
/// [paper]: http://haslab.uminho.pt/cbm/files/dbloom.pdf
///
/// # Note
///
/// For simplicity, this implementation uses static parameters as follows:
///
/// - growth factor: `s = 2`
/// - tightening ratio: `r = 0.5`
#[derive(Debug)]
pub struct ScalableBloomFilter<T: ?Sized, H = DefaultHasher> {
hasher: H,
filters: Vec<BloomFilter<T>>,
}
impl<T: Hash + ?Sized> ScalableBloomFilter<T, DefaultHasher> {
/// Makes a new `ScalableBloomFilter` instance.
///
/// `initial_capacity` is the expected number of elements in ordinaly cases.
/// `error_probability` is the maximum allowable probability of false positives.
///
/// # Panics
///
/// `error_probability` must be a value greater than `0.0` and smaller than or equal to `1.0`.
pub fn new(initial_capacity: usize, error_probability: f64) -> Self {
Self::with_hasher(initial_capacity, error_probability, DefaultHasher)
}
}
impl<T: Hash + ?Sized, H: NthHash> ScalableBloomFilter<T, H> {
/// Makes a new `ScalableBloomFilter` with the given hasher.
pub fn with_hasher(initial_capacity: usize, error_probability: f64, hasher: H) -> Self {
assert!(0.0 < error_probability && error_probability <= 1.0);
let initial_bits =
error_probability.ln().abs() * (initial_capacity as f64) / 2.0f64.ln().powi(2);
let slice_count = (1.0 / error_probability).log2().ceil() as usize;
let filter = BloomFilter::new(initial_bits.ceil() as usize / slice_count, slice_count);
ScalableBloomFilter {
filters: vec![filter],
hasher,
}
}
/// Inserts a element to the filter.
pub fn insert(&mut self, element: &T) {
let last = self.filters.len();
for (i, filter) in self.filters.iter_mut().enumerate() {
if i + 1 == last {
filter.insert(element, &self.hasher);
} else {
if filter.contains(element, &self.hasher) {
return;
}
}
}
if self.is_growth_needed() {
self.grow();
}
}
/// Queries whether there is possibility that the element is contains in the filter.
pub fn contains(&self, element: &T) -> bool {
self.filters
.iter()
.any(|f| f.contains(element, &self.hasher))
}
/// The number of bits allocated by the filter.
///
/// As the filter grows, this value will also increase.
pub fn allocated_bits(&self) -> usize {
self.filters.iter().map(|f| f.bits().number_of_bits()).sum()
}
/// The number of bits used by the filter for storing elements.
///
/// This is the number of one bits in the allocated bits.
pub fn used_bits(&self) -> usize {
self.filters
.iter()
.map(|f| f.bits().number_of_one_bits())
.sum()
}
fn grow(&mut self) {
let filter = {
let last = self.filters.last().expect("Never fails");
let next_slice_bitwidth = last.slice_bitwidth() * GROWTH_FACTOR;
let next_number_of_slices = last.number_of_slices() + 1;
BloomFilter::new(next_slice_bitwidth, next_number_of_slices)
};
self.filters.push(filter);
}
fn is_growth_needed(&self) -> bool {
let bits = self.filters.last().expect("Never fails").bits();
debug_assert_ne!(bits.number_of_one_bits(), 0);
bits.number_of_bits() / bits.number_of_one_bits() < 2
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn new_works() {
let filter = ScalableBloomFilter::<(), _>::new(18232, 0.001);
assert_eq!(filter.used_bits(), 0);
assert_eq!(filter.allocated_bits(), 262144);
}
#[test]
fn insert_and_contains_works() {
let mut filter = ScalableBloomFilter::new(3, 0.01);
for x in &["foo", "bar", "baz"] {
assert!(!filter.contains(x));
filter.insert(x);
assert!(filter.contains(x));
}
}
#[test]
fn growth_works() {
let mut filter = ScalableBloomFilter::new(32, 0.000001);
let initial_bits = filter.allocated_bits();
for i in 0..10000 {
assert!(!filter.contains(&i));
filter.insert(&i);
assert!(filter.contains(&i));
}
assert!((0..10000).all(|i| filter.contains(&i)));
assert_ne!(filter.allocated_bits(), initial_bits);
}
}
|
use core::{raw, slice};
use def;
use std::default::Default;
use std::cell::RefCell;
use std::rc::Rc;
use std::{mem, os, iter, ptr, io};
use std::sync::{Arc};
use page::{Page, PageManager, PageHeader, DbRecord, RecordFlags, DbKey, DbValue, PageFlags};
use libc;
#[repr(C)]
pub struct TransactionInfo {
pub magic_id: u32,
pub lock_format: u32,
pub last_txn_id: TxnID,
pub num_of_readers: u32
}
impl Default for TransactionInfo {
#[inline]
fn default() -> TransactionInfo {
TransactionInfo {
magic_id: ROBIGO_MAGIC,
lock_format: ROBIGO_MAGIC,
last_txn_id: 0,
num_of_readers: 0
}
}
}
#[repr(C)]
pub struct ReaderRecord {
pub txn_id: TxnID,
pub process_id: ProcessID,
pub thread_id: Thread
}
bitflags!(
flags EnvFlags: u32 {
const FlagFatalError = 0x80000000
}
);
pub struct DbParams {
pub is_read_only: bool,
pub file_access: io::FileAccess
}
impl Default for DbParams {
#[inline]
fn default() -> DbParams {
DbParams {
is_read_only: false,
file_access: io::FileAccess::ReadWrite
}
}
}
bitflags!(
flags DbFlags: u16 {
const FlagValid = 0x8000
}
);
#[derive(Clone)]
pub struct DatabaseInfo {
pub db_flags: DbFlags,
pub btree_depth: u16,
pub branch_page_num: PageNum,
pub leaf_page_num: PageNum,
pub overflow_page_num: PageNum,
pub entries_num: libc::size_t,
pub root_page: Option<PageNum>,
}
impl DatabaseInfo {
pub fn encode(&self, w: &mut io::MemWriter) -> Result<(), EncodeError> {
w.write_be_u16(self.db_flags.bits());
w.write_be_u16(self.btree_depth);
w.write_be_u64(self.branch_page_num);
w.write_be_u64(self.leaf_page_num);
w.write_be_u64(self.overflow_page_num);
w.write_be_u64(self.entries_num);
if self.root_page.is_none() {
w.write_be_u64(0 as u64);
} else {
w.write_be_u64(self.root_page.unwrap());
}
Ok(())
}
pub fn decode(r: &mut io::BufReader) -> Result<Self, DecodeError> {
// 46 bytes
let db_flags_raw_bits = r.read_be_u16().unwrap();
let db_flags: DbFlags = DbFlags::from_bits(db_flags_raw_bits).unwrap();
let btree_depth = r.read_be_u16().unwrap();
let branch_page_num = r.read_be_u64().unwrap();
let leaf_page_num = r.read_be_u64().unwrap();
let overflow_page_num = r.read_be_u64().unwrap();
let entries_num = r.read_be_u64().unwrap();
let root_page = r.read_be_u64().unwrap();
let info = DatabaseInfo {
db_flags: db_flags,
btree_depth: btree_depth,
branch_page_num: branch_page_num,
leaf_page_num: leaf_page_num,
overflow_page_num: overflow_page_num,
entries_num: entries_num,
root_page: Some(root_page)
};
Ok(info)
}
}
impl Default for DatabaseInfo {
#[inline]
fn default() -> DatabaseInfo {
DatabaseInfo {
db_flags: DbFlags::empty(),
btree_depth: 0,
branch_page_num: 0 ,
leaf_page_num: 0,
overflow_page_num: 0,
entries_num: 0,
root_page: None
}
}
}
pub struct ReaderTable {
pub mapped_region: MemoryMap
}
impl ReaderTable {
pub fn new(filedesc: &file::FileDesc) -> Option<ReaderTable> {
let current_filesize = filedesc.seek(0 as i64, io::SeekStyle::SeekEnd).ok().unwrap();
let mut mapped_size = (DEFAULT_MAX_READER_NUM * mem::size_of::<ReaderRecord>()) + mem::size_of::<TransactionInfo>();
if current_filesize < (mapped_size as u64) {
filedesc.truncate(mapped_size as i64);
} else {
mapped_size = current_filesize as usize;
//FIXME: fix the current reader record number
}
debug!("mmap file size: {}", mapped_size);
let options = [MapOption::MapReadable, MapOption::MapWritable, MapOption::MapFd(filedesc.fd())];
let region = match MemoryMap::new(mapped_size, &options) {
Ok(map) => map,
Err(e) => panic!("mmap for dbpage of size {} paniced", DEFAULT_MAPSIZE)
};
debug!("mmap len: {}, granularity: {}", region.len(), MemoryMap::granularity());
let ptr: *mut u8 = region.data();
let t = ReaderTable {
mapped_region: region
};
let txninfo = Default::default();
t.set_txninfo(txninfo);
Some(t)
}
#[inline]
pub fn get_txninfo(&self) -> &mut TransactionInfo {
unsafe {
let ptr: *mut TransactionInfo = mem::transmute(self.mapped_region.data().offset(0));
&mut *ptr
}
}
#[inline]
pub fn set_txninfo(&self, txninfo: TransactionInfo) {
unsafe {
let dst_ptr: *mut TransactionInfo = mem::transmute(self.mapped_region.data().offset(0));
ptr::write(dst_ptr, txninfo)
};
}
#[inline]
pub fn get_reader_records(&self) -> &mut [ReaderRecord] {
unsafe {
let off: isize = mem::size_of::<TransactionInfo>() as isize;
let ptr: *const ReaderRecord = mem::transmute(self.mapped_region.data().offset(off));
mem::transmute(raw::Slice {
data: ptr,
len: DEFAULT_MAX_READER_NUM
})
}
}
pub fn add_reader_record(&self, pid: ProcessID, tid: Thread) {
let mut txninfo = self.get_txninfo();
let reader_records = self.get_reader_records();
let mut i: usize = 0;
loop {
if (i >= (txninfo.num_of_readers as usize)) {
break;
}
if reader_records[i].process_id == 0 {
break;
}
}
reader_records[i].txn_id = INVALID_TXN_ID;
reader_records[i].process_id = pid;
reader_records[i].thread_id = tid;
txninfo.num_of_readers += 1;
}
}
#[derive(Clone)]
pub struct MetaInfo {
pub magic: u32,
pub version: u32,
pub last_page: PageNum,
pub txn_id: TxnID,
pub free_db: DatabaseInfo,
pub main_db: DatabaseInfo
}
impl MetaInfo {
pub fn new() -> MetaInfo {
MetaInfo {
magic: ROBIGO_MAGIC,
version: ROBIGO_DATA_VERSION,
last_page: 1,
txn_id: 0,
free_db: Default::default(),
main_db: Default::default()
}
}
pub fn encode(&self, w: &mut io::MemWriter) -> Result<(), EncodeError> {
w.write_be_u32(self.magic);
w.write_be_u32(self.version);
w.write_be_u64(self.last_page);
w.write_be_u64(self.txn_id);
self.free_db.encode(w);
self.main_db.encode(w);
Ok(())
}
pub fn decode(r: &mut io::BufReader) -> Result<Self, DecodeError> {
//24 bytes
let magic: u32 = r.read_be_u32().unwrap();
let version: u32 = r.read_be_u32().unwrap();
let last_page: PageNum = r.read_be_u64().unwrap();
let txn_id: TxnID = r.read_be_u64().unwrap();
let free_db_info = DatabaseInfo::decode(r).ok().unwrap();
let main_db_info = DatabaseInfo::decode(r).ok().unwrap();
let m = MetaInfo {
magic: magic,
version: version,
last_page: last_page,
txn_id: txn_id,
free_db: free_db_info,
main_db: main_db_info
};
Ok(m)
}
}
pub struct MetaPage {
pub header: PageHeader,
pub meta: MetaInfo
}
impl MetaPage {
pub fn from_metainfo(meta: MetaInfo) -> MetaPage {
MetaPage {
header: PageHeader::new(),
meta: meta
}
}
pub fn encode(&self, w: &mut io::MemWriter) -> Result<(), EncodeError> {
self.header.encode(w);
self.meta.encode(w);
Ok(())
}
}
pub struct Environ {
pub env_flags: EnvFlags,
pub db_pagesize: usize,
pub os_pagesize: usize,
pub max_reader_num: usize,
pub reader_num: usize,
pub max_dbs_num: usize,
pub dbs_num: usize,
pub this_process_id: ProcessID,
pub db_path: Path,
pub db_fd: Rc<RefCell<file::FileDesc>>,
pub db_mapsize: usize,
pub reader_table: Arc<RefCell<ReaderTable>>,
pub meta_infos: (Rc<RefCell<MetaInfo>>, Rc<RefCell<MetaInfo>>),
pub txkey: Option<thread_local_storage::Key>,
pub dbs: RefCell<Vec<DatabaseInfo>>,
pub dbs_flags: Vec<DbFlags>,
pub db_pgno_upperbound: PageNum,
pub record_maxsize: usize
}
impl Environ {
pub fn open(path: &Path, dbparams: &DbParams) -> Option<Rc<RefCell<Environ>>> {
fn read_header(fd: &mut file::FileDesc) -> LoadResult<(MetaInfo, MetaInfo)> {
//
// The Database Header Layout
//
// 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | MAGIC |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | VERSION |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | LAST PAGE NUMBER |
// | |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
// | TXN ID |
// | |
// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
//
//
//
fn read_meta_info(buf: &[u8]) -> Result<MetaInfo, LoadError> {
let mut r = io::BufReader::new(buf);
let m = MetaInfo::decode(&mut r).ok().unwrap();
if m.magic != ROBIGO_MAGIC {
return Err(LoadError::ParseError(ErrorCode::Invalid))
};
if m.version != ROBIGO_DATA_VERSION {
return Err(LoadError::ParseError(ErrorCode::VersionMisMatch))
};
Ok(m)
}
// 24 + 46 + 46 = 116 bytes
let mut buf: [u8; 116] = [0 as u8; 116];
let mut offset: i64 = 0;
let mut metas: Vec<MetaInfo> = Vec::new();
for i in range(0, 2) {
match fd.pread(&mut buf, offset) {
Ok(read_size) => {},
Err(e) => {
if e.kind == io::EndOfFile {
return Err(LoadError::FileDoesNotExist)
} else {
return Err(LoadError::UnknownError)
}
}
};
let meta: MetaInfo = match read_meta_info(&buf) {
Ok(m) => { m },
Err(e) => { return Err(e); }
};
metas.push(meta);
offset += 116;
}
let m2 = metas.pop().unwrap();
let m1 = metas.pop().unwrap();
Ok((m1, m2))
}
fn init_meta_page(fd: &mut file::FileDesc) -> SaveResult<(MetaInfo, MetaInfo)> {
// Assume the db page size is the same as os virtual memory size
let m1 = MetaInfo::new();
let m2 = MetaInfo::new();
let mut w = io::MemWriter::from_vec(Vec::new());
{
let mp1 = MetaPage::from_metainfo(m1.clone());
let mp2 = MetaPage::from_metainfo(m2.clone());
mp1.encode(&mut w);
mp2.encode(&mut w);
}
match fd.pwrite(w.get_ref(), 0 as i64) {
Ok(_) => { debug!("sucessfully writing to data file"); },
Err(e) => { debug!("ignore pwrite error for the time being, it's rust's runtime lib bug"); }
};
Ok((m1, m2))
}
// if the directory doesn't exist, implicitly create one
if path.exists() {
if !path.is_dir() {
panic!("{} have already existed, and it is not a directory", path.display());
}
} else {
match io::fs::mkdir(path, io::USER_RWX) {
Ok(_) => {},
Err(e) => {
panic!("Unable to create {}", path.display())
}
}
};
let dbpath = path.join("data.rdb");
let file_mode = if dbparams.is_read_only {
io::FileMode::Open
} else {
io::FileMode::Append
};
let mut data_fd = match file::open(&dbpath, file_mode, dbparams.file_access) {
Ok(fd) => { fd }
Err(e) => {
panic!("Unable to open {}", dbpath.display())
}
};
let lockpath = path.join("lock.rdb");
let lock_fd = match file::open(&lockpath, io::FileMode::Open, io::FileAccess::ReadWrite) {
Ok(fd) => { fd }
Err(e) => {
panic!("Unable to open {}", lockpath.display())
}
};
let meta_infos = match read_header(&mut data_fd) {
Ok((m1, m2))=> {
(Rc::new(RefCell::new(m1)), Rc::new(RefCell::new(m2)))
},
Err(e) => {
match e {
LoadError::FileDoesNotExist => {
debug!("database file does not exist, create an meta");
// The first time we create the MetaInfo
// Write them back into file
match init_meta_page(&mut data_fd) {
Ok((m1, m2)) => {
(Rc::new(RefCell::new(m1)), Rc::new(RefCell::new(m2)))
},
Err(e) => { panic!("writing meta pages failed"); }
}
},
LoadError::ParseError(pe) => {
match pe {
ErrorCode::Invalid => {
panic!("database file is invalid")
},
ErrorCode::VersionMisMatch => {
panic!("magic number doesn't match")
}
}
},
_ => {
panic!("unknown error happens");
}
}
}
};
let os_pagesize = os::page_size();
let process_id: ProcessID = unsafe { libc::getpid() as libc::pid_t } as ProcessID;
debug!("os page size: {}, process_id: {}", os_pagesize, process_id);
//setup locks
let reader_table: ReaderTable = ReaderTable::new(&lock_fd).unwrap();
let mut txkey = unsafe { thread_local_storage::create() };
let db_pagesize = os_pagesize;
let db_mapsize = DEFAULT_MAPSIZE;
let db_pgno_upperbound: PageNum = (db_mapsize / db_pagesize).to_u64().unwrap();
let rc_db_fd = Rc::new(RefCell::new(data_fd));
let record_maxsize: usize = round_up_even((db_pagesize - PAGE_HEADER_SIZE) / MIN_KEYS_IN_PAGE);
let env = Environ {
env_flags: EnvFlags::empty(),
db_pagesize: db_pagesize,
os_pagesize: os_pagesize,
max_reader_num: 10,
reader_num: 1,
max_dbs_num: 2,
dbs_num: 2,
this_process_id: process_id,
db_path: dbpath,
db_fd: rc_db_fd.clone(),
db_mapsize: db_mapsize,
db_pgno_upperbound: db_pgno_upperbound,
record_maxsize: record_maxsize,
reader_table: Arc::new(RefCell::new(reader_table)),
meta_infos: meta_infos,
txkey: Some(txkey),
dbs: RefCell::new(Vec::with_capacity(MAX_DATABASEINFO_IN_TXN)),
dbs_flags: Vec::new()
};
debug!("sucessfully create environment");
Some(Rc::new(RefCell::new(env)))
}
pub fn current_metainfo(&self) -> Rc<RefCell<MetaInfo>> {
let (ref m1, ref m2) = self.meta_infos;
if (m1.borrow().txn_id < m2.borrow().txn_id) {
m2.clone()
} else {
m1.clone()
}
}
pub fn overflow_pages_needed_num(&self, data_size: usize) -> u64 {
let n = (PAGE_HEADER_SIZE -1 + data_size) / (self.db_pagesize + 1);
n.to_u64().unwrap()
}
pub fn stat() {
}
pub fn close(&self) {
}
}
|
pub mod entity;
pub mod enum_event_data;
pub mod event_data;
use proc_macro2::Span;
use syn::{Attribute, Meta, NestedMeta, Path};
/// Attempt to assign a value to a variable, failing if the variable is already populated.
///
/// Prevents attributes from being defined twice
macro_rules! try_set {
($i:ident, $v:expr, $t:expr) => {
match $i {
None => $i = Some($v),
Some(_) => return Err(syn::Error::new_spanned($t, "duplicate attribute")),
}
};
}
macro_rules! fail {
($t:expr, $m:expr) => {
return Err(syn::Error::new_spanned($t, $m));
};
}
struct EventDataAttributes {
entity: Path,
}
fn parse_event_data_attributes(input: &[Attribute]) -> syn::Result<EventDataAttributes> {
let mut entity = None;
for attr in input {
let meta = attr
.parse_meta()
.map_err(|e| syn::Error::new_spanned(attr, e))?;
match meta {
Meta::List(list) if list.path.is_ident("event_sauce") => {
for value in list.nested.iter() {
match value {
NestedMeta::Meta(meta) => match meta {
Meta::Path(path) => try_set!(entity, path.clone(), path),
u => fail!(u, "unexpected attribute"),
},
u => fail!(u, "unexpected attribute"),
}
}
}
_ => {}
}
}
let entity = entity.ok_or_else(|| {
syn::Error::new(
Span::call_site(),
"Associated entity must be defined, e.g. #[event_sauce(User)]",
)
})?;
Ok(EventDataAttributes { entity })
}
|
use crate::error::Error;
use laz::las::laszip::LazVlr;
use crate::reader::{read_point_from, PointReader};
use std::fmt::Debug;
/// Module with functions and structs specific to brigde the las crate and laz crate to allow
/// writing & reading LAZ data
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use crate::writer::{write_header_and_vlrs_to, write_point_to, PointWriter};
use crate::{Header, Point, Result, Vlr};
fn is_laszip_vlr(vlr: &Vlr) -> bool {
vlr.user_id == LazVlr::USER_ID && vlr.record_id == LazVlr::RECORD_ID
}
fn create_laszip_vlr(laszip_vlr: &LazVlr) -> std::io::Result<Vlr> {
let mut cursor = Cursor::new(Vec::<u8>::new());
laszip_vlr.write_to(&mut cursor)?;
Ok(Vlr {
user_id: LazVlr::USER_ID.to_owned(),
record_id: LazVlr::RECORD_ID,
description: LazVlr::DESCRIPTION.to_owned(),
data: cursor.into_inner(),
})
}
/// struct that knows how to decompress LAZ
///
/// Decompression is done in 2 steps:
/// 1) call the decompressor that reads & decompress the next point
/// and put its data in an in-memory buffer
/// 2) read the buffer to get the decompress point
pub(crate) struct CompressedPointReader<'a, R: Read + Seek + Send> {
/// decompressor that does the actual job
decompressor: laz::las::laszip::LasZipDecompressor<'a, R>,
header: Header,
/// in-memory buffer where the decompressor writes decompression result
decompressor_output: Cursor<Vec<u8>>,
last_point_idx: u64,
}
impl<'a, R: Read + Seek + Send> CompressedPointReader<'a, R> {
pub(crate) fn new(source: R, header: Header) -> Result<Self> {
let laszip_vlr = match header.vlrs().iter().find(|vlr| is_laszip_vlr(*vlr)) {
None => return Err(Error::LasZipVlrNotFound),
Some(vlr) => laz::las::laszip::LazVlr::from_buffer(&vlr.data)?,
};
let decompressor_output = Cursor::new(vec![0u8; header.point_format().len() as usize]);
Ok(Self {
decompressor: laz::las::laszip::LasZipDecompressor::new(source, laszip_vlr)?,
header,
decompressor_output,
last_point_idx: 0,
})
}
}
impl<'a, R: Read + Seek + Send> Debug for CompressedPointReader<'a, R> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"CompressedPointReader(num_read: {}, header: {:?})",
self.last_point_idx, self.header
)
}
}
impl<'a, R: Read + Seek + Send> PointReader for CompressedPointReader<'a, R> {
fn read_next(&mut self) -> Option<Result<Point>> {
if self.last_point_idx < self.header.number_of_points() {
self.last_point_idx += 1;
let res = self.decompressor
.decompress_one(&mut self.decompressor_output.get_mut());
if let Err(e) = res {
Some(Err(e.into()))
} else if let Err(e) = self.decompressor_output.seek(SeekFrom::Start(0)) {
Some(Err(e.into()))
} else {
Some(read_point_from(&mut self.decompressor_output, &self.header))
}
} else {
None
}
}
fn seek(&mut self, position: u64) -> Result<()> {
self.last_point_idx = position;
self.decompressor.seek(position)?;
Ok(())
}
fn header(&self) -> &Header {
&self.header
}
}
fn laz_vlr_from_point_format(point_format: &crate::point::Format) -> LazVlr {
let mut laz_items = laz::las::laszip::LazItemRecordBuilder::new();
if !point_format.is_extended {
laz_items.add_item(laz::LazItemType::Point10);
if point_format.has_gps_time {
laz_items.add_item(laz::LazItemType::GpsTime);
}
if point_format.has_color {
laz_items.add_item(laz::LazItemType::RGB12);
}
if point_format.extra_bytes > 0 {
laz_items.add_item(laz::LazItemType::Byte(point_format.extra_bytes));
}
} else {
laz_items.add_item(laz::LazItemType::Point14);
if point_format.has_color {
// Point format 7 & 8 both have RGB
if point_format.has_nir {
laz_items.add_item(laz::LazItemType::RGBNIR14);
} else {
laz_items.add_item(laz::LazItemType::RGB14);
}
}
if point_format.extra_bytes > 0 {
laz_items.add_item(laz::LazItemType::Byte14(point_format.extra_bytes));
}
}
laz::LazVlr::from_laz_items(laz_items.build())
}
/// struct that knows how to write LAZ
///
/// Writing a point compressed is done in 2 steps
/// 1) write the point to a in-memory buffer
/// 2) call the laz compressor on this buffer
pub(crate) struct CompressedPointWriter<'a, W: Write + Seek + Send> {
header: Header,
/// buffer used to write the uncompressed point
compressor_input: Cursor<Vec<u8>>,
/// The compressor that actually does the job of compressing the data
compressor: laz::las::laszip::LasZipCompressor<'a, W>,
}
impl<'a, W: Write + Seek + Send> CompressedPointWriter<'a, W> {
pub(crate) fn new(mut dest: W, mut header: Header) -> Result<Self> {
let laz_vlr = laz_vlr_from_point_format(header.point_format());
// Clear any existing laszip vlr as they might not be correct
header.vlrs_mut().retain(|vlr| !is_laszip_vlr(vlr));
header.vlrs_mut().push(create_laszip_vlr(&laz_vlr)?);
write_header_and_vlrs_to(&mut dest, &header)?;
let compressor_input = Cursor::new(vec![0u8; header.point_format().len() as usize]);
let compressor = laz::las::laszip::LasZipCompressor::new(dest, laz_vlr)?;
Ok(Self {
header,
compressor_input,
compressor,
})
}
}
impl<'a, W: Write + Seek + Send> PointWriter<W> for CompressedPointWriter<'a, W> {
fn write_next(&mut self, point: Point) -> Result<()> {
self.header.add_point(&point);
self.compressor_input.seek(SeekFrom::Start(0))?;
write_point_to(&mut self.compressor_input, point, &self.header)?;
self.compressor
.compress_one(self.compressor_input.get_ref())?;
Ok(())
}
fn into_inner(self: Box<Self>) -> W {
self.compressor.into_inner()
}
fn get_mut(&mut self) -> &mut W {
self.compressor.get_mut()
}
fn header(&self) -> &Header {
&self.header
}
fn done(&mut self) -> Result<()> {
self.compressor.done()?;
Ok(())
}
}
impl<'a, W: Write + Seek + Send> Debug for CompressedPointWriter<'a, W> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "CompressedPointWriter(header: {:?})", self.header)
}
}
|
//! # Efficient and safe bytes
//!
//! [`Bytes`] can be used when secret byte sequences ([`ByteSeq`]) are used but
//! they are too slow for using hacspec in a release version that interacts with
//! other Rust code, i.e. requires a lot conversions between [`U8`] and [`u8`].
#![allow(non_snake_case, dead_code)]
use super::*;
#[cfg(feature = "release")]
pub type Byte = u8;
#[cfg(not(feature = "release"))]
pub type Byte = U8;
#[cfg(feature = "release")]
pub type DoubleByte = u16;
#[cfg(not(feature = "release"))]
pub type DoubleByte = U16;
#[cfg(feature = "release")]
pub type QuadByte = u32;
#[cfg(not(feature = "release"))]
pub type QuadByte = U32;
#[cfg(feature = "release")]
pub type Bytes = PublicSeq<Byte>;
#[cfg(not(feature = "release"))]
pub type Bytes = Seq<Byte>;
#[cfg(feature = "release")]
#[macro_export]
macro_rules! create_bytes {
($( $b:expr ),+) => {
Bytes::from_vec(
vec![
$(
$b
),+
]
)
};
}
#[cfg(not(feature = "release"))]
#[macro_export]
macro_rules! create_bytes {
($( $b:expr ),+) => {
Bytes::from_vec(
vec![
$(
U8($b)
),+
]
)
};
}
impl PublicSeq<u8> {
#[inline(always)]
#[cfg_attr(feature = "use_attributes", not_hacspec)]
pub fn from_public_slice(v: &[u8]) -> PublicSeq<u8> {
Self { b: v.to_vec() }
}
#[inline(always)]
#[cfg_attr(feature = "use_attributes", not_hacspec)]
pub fn from_native(b: Vec<u8>) -> PublicSeq<u8> {
Self { b }
}
#[inline(always)]
#[cfg_attr(feature = "use_attributes", not_hacspec)]
pub fn to_native(&self) -> Vec<u8> {
self.b.clone()
}
#[inline(always)]
#[cfg_attr(feature = "use_attributes", not_hacspec)]
pub fn into_native(self) -> Vec<u8> {
self.b
}
#[inline(always)]
#[cfg_attr(feature = "use_attributes", not_hacspec)]
pub fn as_slice(&self) -> &[u8] {
self.b.as_slice()
}
}
impl Seq<U8> {
#[inline(always)]
#[cfg_attr(feature = "use_attributes", not_hacspec)]
pub fn from_native(b: Vec<u8>) -> Self {
Self::from_public_slice(&b)
}
#[inline(always)]
#[cfg_attr(feature = "use_attributes", not_hacspec)]
pub fn as_slice(&self) -> &[U8] {
self.b.as_slice()
}
}
#[cfg(feature = "release")]
#[inline(always)]
pub fn Byte(x: u8) -> Byte {
x
}
#[cfg(not(feature = "release"))]
#[inline(always)]
pub fn Byte(x: u8) -> Byte {
U8(x)
}
pub trait ByteTrait {
fn declassify(self) -> u8;
}
impl ByteTrait for u8 {
#[inline(always)]
fn declassify(self) -> u8 {
self
}
}
#[inline(always)]
pub fn declassify_usize_from_U8(x: Byte) -> usize {
x.into()
}
// === FIXME: NOT BYTES ANYMORE - MOVE ===
pub trait U16Trait {
fn into_bytes(self) -> Bytes;
}
impl U16Trait for u16 {
#[cfg(feature = "release")]
fn into_bytes(self) -> Bytes {
Bytes::from_native_slice(&u16::to_be_bytes(self))
}
#[cfg(not(feature = "release"))]
fn into_bytes(self) -> Bytes {
Bytes::from_seq(&U16_to_be_bytes(U16(self)))
}
}
#[cfg(not(feature = "release"))]
impl U16Trait for U16 {
fn into_bytes(self) -> Bytes {
Bytes::from_seq(&U16_to_be_bytes(self))
}
}
#[cfg(feature = "release")]
impl U16Trait for U16 {
fn into_bytes(self) -> Bytes {
Bytes::from_native(u16::to_be_bytes(self.0).to_vec())
}
}
pub trait U32Trait {
fn into_bytes(self) -> Bytes;
}
impl U32Trait for u32 {
#[cfg(feature = "release")]
fn into_bytes(self) -> Bytes {
Bytes::from_native_slice(&u32::to_be_bytes(self))
}
#[cfg(not(feature = "release"))]
fn into_bytes(self) -> Bytes {
Bytes::from_seq(&U32_to_be_bytes(U32(self)))
}
}
#[cfg(not(feature = "release"))]
impl U32Trait for U32 {
fn into_bytes(self) -> Bytes {
Bytes::from_seq(&U32_to_be_bytes(self))
}
}
#[cfg(feature = "release")]
impl U32Trait for U32 {
fn into_bytes(self) -> Bytes {
Bytes::from_native(u32::to_be_bytes(self.0).to_vec())
}
}
#[cfg(feature = "release")]
#[inline(always)]
pub fn DoubleByte(x: u16) -> DoubleByte {
x
}
#[cfg(not(feature = "release"))]
#[inline(always)]
pub fn DoubleByte(x: u16) -> DoubleByte {
U16(x)
}
#[cfg(feature = "release")]
#[inline(always)]
pub fn QuadByte(x: u32) -> QuadByte {
x
}
#[cfg(not(feature = "release"))]
#[inline(always)]
pub fn QuadByte(x: u32) -> QuadByte {
U32(x)
}
|
use std::fs::File;
use std::io::{Read, BufReader, Result};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::mem;
use byteorder::{BigEndian, ReadBytesExt};
use bytecode::*;
use cst::ConstantTable;
use environment::Environment;
use io;
pub const INVALID_FUNCTION_ID: u32 = 0xFFFFFFFF;
pub struct Function {
/// The ID of the function in the current environment.
pub id: u32,
/// The unique name of the function.
pub name: String,
pub sizes: Sizes,
pub constant_table: Arc<ConstantTable>,
pub instructions: Instructions,
}
pub struct Sizes {
/// The amount of stack elements that are returned from the function.
pub return_count: u8,
/// The expected amount of arguments.
pub argument_count: u8,
/// The amount of locals that the function needs.
/// Includes the argument count.
pub locals_count: u16,
/// The maximum size that the operand stack needs to be.
pub max_operands: u16,
}
pub enum Instructions {
File {
path: PathBuf,
offset: u64,
},
Bytecode(Vec<Instruction>),
}
impl Function {
pub fn new(name: String, sizes: Sizes,
constant_table: Arc<ConstantTable>,
instructions: Instructions) -> Function {
Function {
id: INVALID_FUNCTION_ID,
name: name,
sizes: sizes,
constant_table: constant_table,
instructions: instructions,
}
}
// TODO Split into from_file and from_read.
pub fn from_file(environment: &mut Environment, path: &Path) -> Result<Function> {
let mut read = try!(Function::open_reader(path));
// Read name.
let name = try!(io::read_string(&mut read));
// Read sizes.
let sizes = try!(Sizes::from_read(&mut read));
// Read constant table name.
let constant_table_name = try!(io::read_string(&mut read));
// Calculate offset in file.
let file_offset = Function::calculate_instructions_offset(&name[..], &constant_table_name[..]);
// Fetch constant table.
let mut cst_path = PathBuf::from(path.parent().unwrap_or(Path::new("")));
cst_path.push(constant_table_name);
let constant_table = environment.fetch_constant_table(cst_path.as_path());
Ok(
Function {
id: INVALID_FUNCTION_ID,
name: name,
sizes: sizes,
constant_table: constant_table,
instructions: Instructions::File {
path: PathBuf::from(path),
offset: file_offset,
},
}
)
}
pub fn open_reader(path: &Path) -> Result<BufReader<File>> {
let mut with_extension = PathBuf::from(path);
with_extension.set_extension("func");
let file = try!(File::open(with_extension.as_path()));
Ok(BufReader::new(file))
}
pub fn calculate_instructions_offset(name: &str, constant_table_name: &str) -> u64 {
let mut offset = io::string_disk_size(name);
offset += Sizes::disk_size();
offset += io::string_disk_size(constant_table_name);
offset as u64
}
}
impl Sizes {
pub fn new(return_count: u8, argument_count: u8,
locals_count: u16, max_operands: u16) -> Sizes {
Sizes {
return_count: return_count,
argument_count: argument_count,
locals_count: locals_count,
max_operands: max_operands,
}
}
pub fn from_read(read: &mut Read) -> Result<Sizes> {
let return_count = try!(read.read_u8());
let argument_count = try!(read.read_u8());
let locals_count = try!(read.read_u16::<BigEndian>());
let max_operands = try!(read.read_u16::<BigEndian>());
Ok(
Sizes {
return_count: return_count,
argument_count: argument_count,
locals_count: locals_count,
max_operands: max_operands,
}
)
}
pub fn disk_size() -> usize {
return mem::size_of::<u8>() * 2 + mem::size_of::<u16>() * 2;
}
}
impl Instructions {
pub fn from_read(read: &mut Read) -> Result<Instructions> {
// Read instruction count.
let count = try!(read.read_u32::<BigEndian>()) as usize;
let mut instructions = Vec::with_capacity(count);
for _ in 0..count {
let instruction = try!(Instruction::from_read(read));
instructions.push(instruction);
}
Ok(Instructions::Bytecode(instructions))
}
}
|
use rand::prelude::*;
pub fn run() {
let mut test_runner = TestRunner::new(vec![
Box::from(WinterBooking),
Box::from(SummerBooking),
]);
let results = test_runner.compare_strategies(1_000_000);
println!("{:#?}", results);
}
struct TestRunner {
rng: ThreadRng,
booking_strategies: Vec<Box<dyn BookingStrategy>>,
}
impl TestRunner {
/// Initializes a new `Testrunner`.
fn new(booking_strategies: Vec<Box<dyn BookingStrategy>>) -> Self {
Self {
rng: rand::thread_rng(),
booking_strategies,
}
}
/// Compares the strategies against each other.
///
/// # Arguments
/// * `runs` - The number of runs to do.
fn compare_strategies(&mut self, runs: u32) -> Vec<TestResult> {
let mut cost_sums: Vec<u32> = vec![0; self.booking_strategies.len()];
for _ in 0..runs {
let lucky: bool = self.rng.gen();
for (i, strategy) in self.booking_strategies.iter().enumerate() {
let cost = strategy.calculate_cost(lucky);
cost_sums[i] += cost;
}
}
cost_sums
.iter()
.enumerate()
.map(|(i, &sum)| TestResult {
strategy_name: self.booking_strategies[i].name(),
average_cost: f64::from(sum) / f64::from(runs),
})
.collect()
}
}
#[derive(Debug)]
struct TestResult {
strategy_name: &'static str,
average_cost: f64,
}
trait BookingStrategy {
/// Returns the cost of a lucky or unlucky booking.
///
/// # Arguments
/// * `lucky` - Whether you get the cheap option or not.
fn calculate_cost(&self, lucky: bool) -> u32;
/// Returns the name of this booking strategy.
fn name(&self) -> &'static str;
}
struct WinterBooking;
impl BookingStrategy for WinterBooking {
fn calculate_cost(&self, _lucky: bool) -> u32 {
500
}
fn name(&self) -> &'static str {
"Winter booking"
}
}
struct SummerBooking;
impl BookingStrategy for SummerBooking {
fn calculate_cost(&self, lucky: bool) -> u32 {
match lucky {
true => 250,
false => 1000,
}
}
fn name(&self) -> &'static str {
"Summer booking"
}
}
|
use crate::backend::result::Result;
use diesel::r2d2::ConnectionManager;
use diesel::sqlite::SqliteConnection;
use r2d2::Pool;
pub type DbPool = Pool<ConnectionManager<SqliteConnection>>;
pub fn create_pool(database_url: &str) -> Result<DbPool> {
let manager = ConnectionManager::new(database_url);
let pool = DbPool::builder().build(manager)?;
Ok(pool)
}
|
use std::{cell::RefCell, rc::Rc};
use chiropterm::*;
use crate::ui::{UI, UIContext};
use super::{Widgetlike, common::WidgetCommon};
pub struct WidgetMenu<'frame, T: Widgetlike> {
pub ui: UI,
pub(in super) state: Rc<RefCell<WidgetCommon<T>>>,
pub menu: Menu<'frame>,
pub(in super) brush_offset: CellVector,
}
impl<'frame, T: Widgetlike> WidgetMenu<'frame, T> {
pub fn share(&self) -> WidgetMenu<'frame, T> {
WidgetMenu {
ui: self.ui.share(),
state: self.state.clone(),
menu: self.menu.share(),
brush_offset: self.brush_offset,
}
}
pub fn on_key(&self, k: KeyRecognizer<'frame>, cb: impl 'frame+Fn(UI, &mut WidgetCommon<T>, KeyEvent) -> Signal) {
let state = self.state.clone();
let ui = self.ui.share();
self.menu.on_key(k, move |inp| {
cb(ui.share(), &mut state.borrow_mut(), inp)
})
}
pub fn on_key_hprio(&self, k: KeyRecognizer<'frame>, cb: impl 'frame+Fn(UI, &mut WidgetCommon<T>, KeyEvent) -> Signal) {
let state = self.state.clone();
let ui = self.ui.share();
self.menu.on_key_hprio(k, move |inp| {
cb(ui.share(), &mut state.borrow_mut(), inp)
})
}
pub fn on_mouse(&self, cb: impl 'frame+Fn(UI, &mut WidgetCommon<T>, MouseEvent) -> Signal) -> Interactor {
let state = self.state.clone();
let o = self.brush_offset;
let ui = self.ui.share();
self.menu.on_mouse(move |inp| {
cb(ui.share(), &mut state.borrow_mut(), inp.offset(-o))
})
}
pub fn on_text(&self, cb: impl 'frame+Fn(UI, &mut WidgetCommon<T>, char) -> Signal) {
let state = self.state.clone();
let ui = self.ui.share();
self.menu.on_text(move |inp| {
cb(ui.share(), &mut state.borrow_mut(), inp)
})
}
pub(crate) fn on_text_hprio(&self, cb: impl 'frame+Fn(UI, &mut WidgetCommon<T>, char) -> Signal) {
let state = self.state.clone();
let ui = self.ui.share();
self.menu.on_text_hprio(move |inp| {
cb(ui.share(), &mut state.borrow_mut(), inp)
})
}
pub(crate) fn with_context(mut self, on_ctx: impl FnOnce(&mut UIContext)) -> Self {
self.ui = self.ui.with_context(on_ctx);
self
}
} |
/*
* 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
*/
/// SloHistoryResponse : A service level objective history response.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SloHistoryResponse {
#[serde(rename = "data", skip_serializing_if = "Option::is_none")]
pub data: Option<Box<crate::models::SloHistoryResponseData>>,
/// A list of errors while querying the history data for the service level objective.
#[serde(rename = "errors", skip_serializing_if = "Option::is_none")]
pub errors: Option<Vec<crate::models::SloHistoryResponseError>>,
}
impl SloHistoryResponse {
/// A service level objective history response.
pub fn new() -> SloHistoryResponse {
SloHistoryResponse {
data: None,
errors: None,
}
}
}
|
use std::mem;
use super::{Table, TableId, TableIterator, TableRow};
/// Flag table does not hold Rows. Designed for 0 sized 'flag' components
#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct SparseFlagTable<Id, Row>
where
Id: TableId,
Row: TableRow + Default,
{
ids: Vec<Id>,
default: Row,
}
impl<Id, Row> SparseFlagTable<Id, Row>
where
Id: TableId,
Row: TableRow + Default,
{
pub fn contains(&self, id: &Id) -> bool {
self.ids.binary_search(id).is_ok()
}
pub fn iter(&self) -> impl TableIterator<Id, ()> + '_ {
self.ids.iter().map(move |id| (*id, ()))
}
pub fn clear(&mut self) {
self.ids.clear();
}
pub fn insert(&mut self, id: Id) {
match self.ids.binary_search(&id) {
Ok(_) => {}
Err(i) => {
self.ids.insert(i, id);
}
}
}
}
impl<Id, Row> Table for SparseFlagTable<Id, Row>
where
Id: TableId,
Row: TableRow + Default,
{
type Id = Id;
type Row = Row;
fn delete(&mut self, id: Self::Id) -> Option<Self::Row> {
self.ids.binary_search(&id).ok().map(|i| {
self.ids.remove(i);
mem::take(&mut self.default)
})
}
fn get(&self, id: Self::Id) -> Option<&Self::Row> {
self.ids.binary_search(&id).map(|_| &self.default).ok()
}
}
|
use std::hash::{Hash, Hasher};
use std::io::{BufReader, Read};
use std::path::Path;
use std::pin::Pin;
use anyhow::*;
use bevy_math::{vec2, IVec2, UVec2, Vec4};
use bevy_utils::AHasher;
use xml::attribute::OwnedAttribute;
use xml::reader::{EventReader, XmlEvent};
use crate::tmx::map::Map;
use crate::TmxLoadContext;
use super::*;
enum Data {
U8(Vec<u8>),
U32(Vec<u32>),
}
impl Data {
fn into_vec_u8(self) -> Vec<u8> {
match self {
Data::U8(v) => v,
Data::U32(_) => unimplemented!("u8 to u32 conversion is not needed"),
}
}
fn into_vec_u32(self) -> Vec<u32> {
match self {
Data::U8(v) => v
.chunks_exact(4)
.map(|chunk| {
(chunk[0] as u32)
| (chunk[1] as u32) << 8
| (chunk[2] as u32) << 16
| (chunk[3] as u32) << 24
})
.collect(),
Data::U32(v) => v,
}
}
}
impl Map {
pub(crate) async fn load_from_xml_reader<R: Read + Send>(
env: TmxLoadContext<'_>,
mut reader: EventReader<R>,
) -> Result<Self> {
loop {
if let XmlEvent::StartElement {
name, attributes, ..
} = reader.next()?
{
if name.local_name == "map" {
return Map::parse(env, attributes, &mut reader).await;
} else {
parse_empty(&mut reader)?;
}
}
}
}
async fn parse<R: Read + Send>(
env: TmxLoadContext<'_>,
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<Self> {
let mut result = Map {
properties: HashMap::new(),
tilesets: Vec::new(),
layers: Vec::new(),
width: 0,
height: 0,
tile_type: TileType::Ortho {
width: 0,
height: 0,
render_order: RenderOrder::RightDown,
},
background: [0; 4],
};
let mut render_order = RenderOrder::RightDown;
let mut tile_type = 0;
let mut tile_width = 0;
let mut tile_height = 0;
let mut stagger_y = false;
let mut stagger_i = true;
let mut hex_side_length = 0;
for a in attributes {
match a.name.local_name.as_ref() {
"width" => result.width = a.value.parse()?,
"height" => result.height = a.value.parse()?,
"tilewidth" => tile_width = a.value.parse()?,
"tileheight" => tile_height = a.value.parse()?,
"renderorder" => {
render_order = match a.value.as_ref() {
"right-down" => RenderOrder::RightDown,
"right-up" => RenderOrder::RightUp,
"left-down" => RenderOrder::LeftDown,
"left-up" => RenderOrder::LeftUp,
_ => bail!("invalid renderorder"),
}
}
"orientation" => {
tile_type = match a.value.as_ref() {
"orthogonal" => 0,
"isometric" => 1,
"staggered" => 2,
"hexagonal" => 3,
_ => bail!("invalid orientation"),
}
}
"backgroundcolor" => {
result.background = [1; 4];
}
"staggeraxis" => {
stagger_y = match a.value.as_ref() {
"x" => false,
"y" => true,
_ => bail!("invalid staggeraxis"),
}
}
"staggerindex" => {
stagger_i = match a.value.as_ref() {
"odd" => true,
"even" => false,
_ => bail!("invalid staggerindex"),
}
}
"hexsidelength" => hex_side_length = a.value.parse()?,
_ => (), // skip
}
}
result.tile_type = match tile_type {
0 => TileType::Ortho {
width: tile_width,
height: tile_height,
render_order,
},
1 => TileType::Isometric {
width: tile_width,
height: tile_height,
stagger: false,
stagger_odd: stagger_i,
stagger_y,
render_order,
},
2 => TileType::Isometric {
width: tile_width,
height: tile_height,
stagger: true,
stagger_odd: stagger_i,
stagger_y,
render_order,
},
3 => TileType::Hexagonal {
width: tile_width,
height: tile_width,
stagger_odd: stagger_i,
stagger_y,
side_length: hex_side_length,
render_order,
},
_ => unreachable!(),
};
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"properties" => {
result.properties = parse_properties(reader)?;
}
"tileset" => {
result.tilesets.push(Arc::new(
Tileset::parse(env.clone(), attributes, reader).await?,
));
}
"layer" => {
result.layers.push(Layer::parse_tiles(attributes, reader)?);
}
"objectgroup" => {
result = Layer::parse_objects(env.clone(), attributes, reader)
.await?
.process(result)
.await?;
}
"imagelayer" => {
result
.layers
.push(Layer::parse_image(env.clone(), attributes, reader).await?);
}
"group" => {
result
.layers
.push(Layer::parse_group(env.clone(), attributes, reader).await?);
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
Ok(result)
}
}
impl Tileset {
/// Parse a tileset element. This can be either an external reference or an actual tileset.
async fn parse<R: Read + Send>(
env: TmxLoadContext<'_>,
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<Self> {
let mut result = Tileset {
first_gid: 0,
source: "embedded#".to_string(),
tiles: Vec::new(),
image: None,
tile_size: Vec2::ZERO,
};
let mut found_source = false;
for a in attributes.iter() {
match a.name.local_name.as_ref() {
"firstgid" => {
result.first_gid = a.value.parse()?;
}
"name" => {
result.source = format!("embedded#{}", a.value.clone());
}
"source" => {
found_source = true;
let source_path = Path::new(a.value.as_str());
let file_name = env.file_path(source_path);
let sub_env = env.file_directory(source_path);
let file = env.load_file(source_path).await?;
let file = BufReader::new(file.as_slice());
let mut reader = EventReader::new(file);
loop {
if let XmlEvent::StartElement {
name, attributes, ..
} = reader.next()?
{
if name.local_name == "tileset" {
result =
Tileset::parse_tsx(result, sub_env, attributes, &mut reader)
.await?;
result.source = format!("{}", file_name.display());
break;
} else {
parse_empty(&mut reader)?;
}
}
}
}
_ => (),
}
}
if found_source {
// The actual XML element will be parsed in Tileset::parse_tmx(..).
// If we parse the TMX from an external file, this means the element is not handled. To correct for
// this we call parse_empty(..) if an external file was found.
parse_empty(reader)?;
Ok(result)
} else {
Tileset::parse_tsx(result, env, attributes, reader).await
}
}
/// Parse the actual tileset content
async fn parse_tsx<R: Read + Send>(
mut tileset: Tileset,
env: TmxLoadContext<'_>,
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<Tileset> {
let mut tile_width = 0;
let mut tile_height = 0;
let mut spacing = 0;
let mut margin = 0;
let mut tile_count: Option<u32> = None;
let mut columns: Option<i32> = None;
for a in attributes.iter() {
match a.name.local_name.as_ref() {
"tilewidth" => tile_width = a.value.parse()?,
"tileheight" => tile_height = a.value.parse()?,
"spacing" => spacing = a.value.parse()?,
"margin" => margin = a.value.parse()?,
"tilecount" => tile_count = Some(a.value.parse()?),
"columns" => columns = Some(a.value.parse()?),
_ => (),
}
}
tileset.tile_size.x = tile_width as f32;
tileset.tile_size.y = tile_height as f32;
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"image" => {
let columns = columns;
let spacing = spacing;
let margin = margin;
let tile_width = tile_width;
let mut tiles_added = 0;
let image = parse_image(env.clone(), attributes, reader).await?;
tileset.image = Some(image.clone());
let (width, height) = (image.width(), image.height());
let (width, height) = (width as i32, height as i32);
let columns = columns.unwrap_or_else(|| {
let mut space = width - margin * 2;
let mut cols = 0;
while space >= tile_width {
space -= tile_width + spacing;
space -= spacing;
cols += 1;
}
cols
});
let rows = {
let mut space = height - margin * 2;
let mut rows = 0;
while space >= tile_height {
space -= tile_height + spacing;
rows += 1;
}
rows
};
for y in 0..rows {
for x in 0..columns {
if tile_count.map_or(true, |tc| tiles_added < tc) {
let u = (margin + x * tile_width + x * spacing) as f32
/ width as f32;
let v = (margin + y * tile_height + y * spacing) as f32
/ height as f32;
let w = tile_width as f32 / width as f32;
let h = tile_height as f32 / height as f32;
tileset.tiles.push(Some(Tile {
image: Some(image.clone()),
top_left: Vec2::new(u, v),
bottom_right: Vec2::new(u + w, v + h),
width: tile_width,
height: tile_height,
animation: Vec::new(),
properties: HashMap::new(),
object_group: Vec::new(),
}));
tiles_added += 1;
} else {
break;
}
}
}
}
"tile" => {
let (id, tile) = Tile::parse(env.clone(), attributes, reader).await?;
if id < tileset.tiles.len() {
if tileset.tiles[id].is_none() {
tileset.tiles[id].replace(tile);
} else {
// we already checked if the tile exists, unwrap is safe.
tileset.tiles[id].as_mut().unwrap().join(tile);
}
} else {
while id > tileset.tiles.len() {
tileset.tiles.push(None);
}
tileset.tiles.push(Some(tile));
}
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
Ok(tileset)
}
}
impl Tile {
fn join(&mut self, mut new_data: Tile) {
self.properties = new_data.properties;
self.animation = new_data.animation;
if new_data.image.is_some() {
self.top_left = new_data.top_left;
self.bottom_right = new_data.bottom_right;
self.image = new_data.image;
}
self.object_group.append(&mut new_data.object_group);
}
async fn parse<R: Read + Send>(
env: TmxLoadContext<'_>,
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<(usize, Tile)> {
let mut id = 0;
for a in attributes.iter() {
if a.name.local_name == "id" {
id = a.value.parse()?
}
}
let mut result = Tile {
image: None,
top_left: Vec2::new(0.0, 0.0),
bottom_right: Vec2::new(1.0, 1.0),
width: 0,
height: 0,
animation: Vec::new(),
properties: HashMap::new(),
object_group: Vec::new(),
};
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"properties" => {
result.properties = parse_properties(reader)?;
}
"image" => {
let image = parse_image(env.clone(), attributes, reader).await?;
result.width = image.width() as i32;
result.height = image.height() as i32;
result.image = Some(image);
}
"animation" => {
result.animation = parse_animation(reader)?;
}
"objectgroup" => {
let group = Layer::parse_objects(env.clone(), attributes, reader).await?;
if let Layer::ObjectLayer {
mut objects,
offset,
..
} = group
{
assert_eq!(offset, IVec2::ZERO);
result.object_group.append(&mut objects);
}
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
Ok((id, result))
}
}
impl Layer {
fn parse_tiles<R: Read + Send>(
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<Self> {
let mut position = IVec2::ZERO;
let mut size = UVec2::ZERO;
let mut color = Vec4::new(1.0, 1.0, 1.0, 1.0);
let mut visible = true;
let mut offset = IVec2::ZERO;
let mut parallax = Vec2::new(1.0, 1.0);
let mut data = Vec::new();
for a in attributes {
match a.name.local_name.as_ref() {
"x" => position.x = a.value.parse()?,
"y" => position.y = a.value.parse()?,
"width" => size.x = a.value.parse()?,
"height" => size.y = a.value.parse()?,
"offsetx" => offset.x = a.value.parse()?,
"offsety" => offset.y = a.value.parse()?,
"parallaxx" => parallax.x = a.value.parse()?,
"parallaxy" => parallax.y = a.value.parse()?,
"opacity" => color.w *= a.value.parse::<f32>()?,
"tintcolor" => color *= parse_color_vec4(a.value.as_str())?,
"visible" => visible = a.value == "true",
_ => (), // skip
}
}
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"data" => data = parse_data(attributes, reader)?.into_vec_u32(),
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {}
Ok(Layer::TileLayer {
position,
size,
color,
visible,
offset,
parallax,
data,
})
}
async fn parse_objects<R: Read + Send>(
env: TmxLoadContext<'_>,
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<Self> {
let mut offset = IVec2::ZERO;
let mut parallax = Vec2::new(1.0, 1.0);
let mut color = Vec4::new(1.0, 1.0, 1.0, 1.0);
let mut visible = true;
let mut draworder_index = false;
let mut objects = Vec::new();
for a in attributes {
match a.name.local_name.as_ref() {
"offsetx" => offset.x = a.value.parse()?,
"offsety" => offset.y = a.value.parse()?,
"parallaxx" => parallax.x = a.value.parse()?,
"parallaxy" => parallax.y = a.value.parse()?,
"opacity" => color.w *= a.value.parse::<f32>()?,
"tintcolor" => color *= parse_color_vec4(a.value.as_str())?,
"visible" => visible = a.value == "true",
"draworder" => draworder_index = a.value == "index",
_ => (), // skip
}
}
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"object" => {
objects.push(Object::parse(env.clone(), attributes, reader).await?);
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
Ok(Layer::ObjectLayer {
offset,
parallax,
color,
visible,
draworder_index,
objects,
})
}
async fn process(mut self, mut map: Map) -> Result<Map> {
//let mut new_tilesets = Vec::new();
//let mut next_first_gid = map.tilesets
// .last()
// .map(|ts| ts.first_gid + ts.tiles.len() as u32)
// .unwrap_or(1);
match &mut self {
Layer::ObjectLayer { objects, .. } => {
for object in objects.iter_mut() {
if let Some(&Property::File(ref tileset_source)) =
object.properties.get("__include_tileset__")
{
let mut found = false;
for tileset in map.tilesets.iter() {
if tileset.source == tileset_source.as_ref() {
object.tile = object.tile.map(|t| tileset.first_gid + t);
found = true;
}
}
if !found {
// tileset needs to be added to the map
//object.tile = object.tile.map(|t| tileset.)
println!("Can't find the tileset back in the map!!");
println!(
"Tilesets in map: {:#?}",
map.tilesets
.iter()
.map(|ts| ts.source.as_str())
.collect::<Vec<_>>()
);
println!("Tileset in template: {}", tileset_source);
todo!("Tilesets referenced in templates must also exist in the map for now.");
//
}
}
}
}
&mut _ => unreachable!(),
}
map.layers.push(self);
Ok(map)
}
async fn parse_image<R: Read + Send>(
env: TmxLoadContext<'_>,
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<Self> {
let mut image = Err(anyhow!("no image found"));
let mut offset = IVec2::ZERO;
let mut parallax = Vec2::new(1.0, 1.0);
let mut color = Vec4::new(1.0, 1.0, 1.0, 1.0);
let mut visible: bool = true;
for a in attributes {
match a.name.local_name.as_ref() {
"offsetx" => offset.x = a.value.parse()?,
"offsety" => offset.y = a.value.parse()?,
"parallaxx" => parallax.x = a.value.parse()?,
"parallaxy" => parallax.y = a.value.parse()?,
"opacity" => color.w *= a.value.parse::<f32>()?,
"tintcolor" => color *= parse_color_vec4(a.value.as_str())?,
"visible" => visible = a.value == "true",
_ => (), // skip
}
}
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"image" => {
image = parse_image(env.clone(), attributes, reader).await;
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
image.map(|image| Layer::ImageLayer {
image,
color,
visible,
offset,
parallax,
})
}
fn parse_group<'a, R: Read + Send>(
env: TmxLoadContext<'a>,
attributes: Vec<OwnedAttribute>,
reader: &'a mut EventReader<R>,
) -> Pin<Box<dyn Future<Output = Result<Self>> + Send + 'a>> {
Box::pin(async move {
let mut offset = IVec2::ZERO;
let mut parallax = Vec2::new(1.0, 1.0);
let mut color = Vec4::new(1.0, 1.0, 1.0, 1.0);
//let mut visible: Option<bool> = None;
for a in attributes {
match a.name.local_name.as_ref() {
"offsetx" => offset.x = a.value.parse()?,
"offsety" => offset.y = a.value.parse()?,
"parallaxx" => parallax.x = a.value.parse()?,
"parallaxy" => parallax.y = a.value.parse()?,
"opacity" => color.w *= a.value.parse::<f32>()?,
"tintcolor" => color *= parse_color_vec4(a.value.as_str())?,
//"visible" => visible = Some(a.value == "true"),
_ => (), // skip
}
}
let mut layers = Vec::new();
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"layer" => {
layers.push(Layer::parse_tiles(attributes, reader)?);
}
"objectgroup" => {
layers
.push(Layer::parse_objects(env.clone(), attributes, reader).await?);
}
"imagelayer" => {
layers.push(Layer::parse_image(env.clone(), attributes, reader).await?);
}
"group" => {
layers.push(Layer::parse_group(env.clone(), attributes, reader).await?);
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
for l in layers.iter_mut() {
l.add_offset(offset.x, offset.y);
l.mul_parallax(parallax.x, parallax.y);
l.mul_color(color);
}
Ok(Layer::Group { layers })
})
}
}
impl Object {
fn parse<'a, R: Read + Send>(
env: TmxLoadContext<'a>,
attributes: Vec<OwnedAttribute>,
reader: &'a mut EventReader<R>,
) -> Pin<Box<dyn Future<Output = Result<Object>> + Send + 'a>> {
Box::pin(async move {
let mut result = Object {
id: 0,
properties: HashMap::new(),
tile: None,
shape: Shape {
points: Vec::new(),
closed: false,
},
name: String::from(""),
ty: String::from(""),
x: 0.0,
y: 0.0,
width: 0.0,
height: 0.0,
rotation: 0.0,
visible: true,
};
// see if there is a template
for a in attributes.iter() {
if a.name.local_name == "template" {
let sub_env = env.file_directory(Path::new(a.value.as_str()));
let file = env
.load_file(Path::new(a.value.as_str()).to_path_buf())
.await?;
let file = BufReader::new(file.as_slice());
let mut reader = EventReader::new(file);
loop {
if let XmlEvent::StartElement { name, .. } = reader.next()? {
if name.local_name == "template" {
result =
Object::parse_template(sub_env.clone(), &mut reader).await?;
break;
} else {
parse_empty(&mut reader)?;
}
}
}
}
}
// apply properties
for a in attributes.iter() {
match a.name.local_name.as_ref() {
"id" => result.id = a.value.parse()?,
"gid" => result.tile = Some(a.value.parse()?),
"name" => result.name = a.value.clone(),
"type" => result.ty = a.value.clone(),
"x" => result.x = a.value.parse()?,
"y" => result.y = a.value.parse()?,
"width" => result.width = a.value.parse()?,
"height" => result.height = a.value.parse()?,
"rotation" => result.rotation = a.value.parse()?,
"visible" => result.visible = a.value == "true",
_ => (),
}
}
result.shape = Shape {
points: vec![
vec2(0.0, 0.0),
vec2(result.width, 0.0),
vec2(result.width, result.height),
vec2(0.0, result.height),
],
closed: true,
};
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"properties" => {
for (k, v) in parse_properties(reader)?.into_iter() {
result.properties.insert(k, v);
}
}
"polyline" | "polygon" => {
let points: Result<Vec<Vec2>> = attributes
.iter()
.filter(|a| a.name.local_name == "points")
.flat_map(|a| a.value.split(' '))
.map(|pt| {
let mut i = pt.split(',').map(|x| x.parse::<f32>());
let x = i.next();
let y = i.next();
match (x, y) {
(Some(Ok(x)), Some(Ok(y))) => Ok(Vec2::new(x, y)),
_ => Err(anyhow!("invalid point")),
}
})
.fold(Ok(Vec::new()), |vec, result| match vec {
Ok(mut vec) => {
vec.push(result?);
Ok(vec)
}
Err(e) => Err(e),
});
result.shape = Shape {
points: points?,
closed: name.local_name == "polygon",
};
parse_empty(reader)?;
}
"ellipse" => {
let offset = vec2(result.width * 0.5, result.height * 0.5);
result.shape = Shape {
points: (0..16)
.into_iter()
.map(|i| {
let a = i as f32 * std::f32::consts::PI / 8.0;
offset
+ vec2(
a.cos() * result.width * 0.5,
a.sin() * result.height * 0.5,
)
})
.collect(),
closed: true,
};
parse_empty(reader)?;
}
"point" => {
result.shape = Shape {
points: vec![vec2(0.0, 0.0)],
closed: false,
};
parse_empty(reader)?;
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {}
Ok(result)
})
}
async fn parse_template<R: Read + Send>(
env: TmxLoadContext<'_>,
reader: &mut EventReader<R>,
) -> Result<Object> {
let mut tileset = Err(anyhow!("tileset not found"));
let mut object = Err(anyhow!("object not found"));
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"tileset" => {
let mut first_gid = 0;
let mut source = "".to_string();
for a in attributes.iter() {
match a.name.local_name.as_ref() {
"firstgid" => first_gid = a.value.parse()?,
"source" => {
source = format!(
"{}",
env.file_path(Path::new(a.value.as_str())).display()
);
}
_ => (),
}
}
tileset = Ok((first_gid, source));
parse_empty(reader)?;
}
"object" => {
object = Object::parse(env.clone(), attributes, reader).await;
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
let mut object = object?;
if object.tile.is_some() {
let (first_gid, source) = tileset?;
object.tile = object.tile.map(|t| t - first_gid);
object
.properties
.insert("__include_tileset__".to_string(), Property::File(source));
}
Ok(object)
}
}
async fn parse_image<R: Read + Send>(
env: TmxLoadContext<'_>,
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<texture::Texture> {
let mut source: Option<String> = None;
//let mut trans: Option<[u8; 4]> = None;
let mut width: Option<u32> = None;
let mut height: Option<u32> = None;
let mut data: Option<Vec<u8>> = None;
//let mut format: Option<String> = None;
for a in attributes.iter() {
match a.name.local_name.as_ref() {
"source" => source = Some(a.value.clone()),
//"trans" => trans = Some(parse_color(a.value.as_str())),
"width" => width = Some(a.value.parse()?),
"height" => height = Some(a.value.parse()?),
//"format" => format = Some(a.value.clone()),
_ => (),
}
}
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"data" => data = Some(parse_data(attributes, reader)?.into_vec_u8()),
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
let mut image = if let Some(source) = source.as_ref() {
Texture::from_path(env.file_path(Path::new(source)))
} else if let Some(data) = data {
let mut h = AHasher::default();
data.hash(&mut h);
Texture::from_bytes(data.as_slice(), format!("embedded#{}", h.finish()))?
} else {
bail!("invalid image")
};
if let (Some(width), Some(height)) = (width, height) {
image = image.resize(width, height).await?;
}
Ok(image)
}
fn parse_data<R: Read + Send>(
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<Data> {
let mut decode_csv = false;
let mut decode_base64 = false;
let mut decompress_z = false;
let mut decompress_g = false;
for a in attributes.iter() {
match a.name.local_name.as_ref() {
"encoding" => match a.value.as_ref() {
"csv" => decode_csv = true,
"base64" => decode_base64 = true,
_ => (),
},
"compression" => match a.value.as_ref() {
"zlib" => decompress_z = true,
"glib" => decompress_g = true,
_ => (),
},
_ => (),
}
}
let mut result = Data::U32(Vec::new());
while match reader.next()? {
XmlEvent::StartElement { .. } => {
parse_empty(reader)?;
true
}
XmlEvent::Characters(s) => {
if decode_csv {
result = Data::U32(
s.split(',')
.filter(|v| v.trim() != "")
.map(|v| v.replace('\r', "").parse().unwrap_or(0))
.collect(),
);
} else if decode_base64 {
let bytes = base64::decode(s.trim().as_bytes())?;
let bytes = if decompress_z {
let mut zd = libflate::zlib::Decoder::new(BufReader::new(&bytes[..]))?;
let mut bytes = Vec::new();
zd.read_to_end(&mut bytes)?;
bytes
} else if decompress_g {
let mut zd = libflate::gzip::Decoder::new(BufReader::new(&bytes[..]))?;
let mut bytes = Vec::new();
zd.read_to_end(&mut bytes)?;
bytes
} else {
bytes
};
result = Data::U8(bytes)
} else {
bail!("<tile> based data is not supported");
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
Ok(result)
}
fn parse_properties<R: Read + Send>(
reader: &mut EventReader<R>,
) -> Result<HashMap<String, Property>> {
let mut result = HashMap::new();
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"property" => {
let (k, v) = parse_property(attributes, reader)?;
result.insert(k, v);
}
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
Ok(result)
}
fn parse_property<R: Read + Send>(
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<(String, Property)> {
let mut key = String::from("");
let mut value = Property::Int(0);
let mut ty = 0;
for a in attributes {
match a.name.local_name.as_ref() {
"name" => key = a.value.clone(),
"type" => {
ty = match a.value.as_ref() {
"string" => 0,
"int" => 1,
"float" => 2,
"bool" => 3,
"color" => 4,
"file" => 5,
_ => bail!("invalid property type"),
}
}
"value" => {
value = match ty {
0 => Property::String(a.value.clone()),
1 => Property::Int(a.value.parse()?),
2 => Property::Float(a.value.parse()?),
3 => Property::Bool(a.value == "true"),
4 => Property::Color(parse_color(a.value.as_str())?),
5 => Property::File(a.value.clone()),
_ => unreachable!(),
}
}
_ => (), // skip
}
}
parse_empty(reader)?;
Ok((key, value))
}
fn parse_animation<R: Read + Send>(reader: &mut EventReader<R>) -> Result<Vec<Frame>> {
let mut result = Vec::new();
while match reader.next()? {
XmlEvent::StartElement {
name, attributes, ..
} => {
match name.local_name.as_ref() {
"frame" => result.push(parse_frame(attributes, reader)?),
_ => parse_empty(reader)?, // skip
}
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
Ok(result)
}
fn parse_frame<R: Read + Send>(
attributes: Vec<OwnedAttribute>,
reader: &mut EventReader<R>,
) -> Result<Frame> {
let mut frame = Frame {
tile: 0,
duration: 0,
};
for a in attributes {
match a.name.local_name.as_ref() {
"tileid" => frame.tile = a.value.parse()?,
"duration" => frame.duration = a.value.parse()?,
_ => (), // skip
}
}
parse_empty(reader)?;
Ok(frame)
}
fn parse_empty<R: Read + Send>(reader: &mut EventReader<R>) -> Result<()> {
while match reader.next()? {
XmlEvent::StartElement { .. } => {
parse_empty(reader)?;
true
}
XmlEvent::EndElement { .. } => false,
_ => true,
} {
continue;
}
Ok(())
}
fn parse_color(text: &str) -> Result<[u8; 4]> {
let lowercase: Vec<char> = text
.chars()
.filter(|&c| c != '#')
.map(|c| c.to_ascii_lowercase())
.collect();
let mut result = [255u8; 4];
let nibble = |c| match c {
'0' => 0,
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9,
'a' => 10,
'b' => 11,
'c' => 12,
'd' => 13,
'e' => 14,
'f' => 15,
_ => 0,
};
match lowercase.len() {
6 => {
for (i, e) in lowercase.chunks_exact(2).enumerate() {
result[i + 1] = nibble(e[0]) << 4 | nibble(e[1]);
}
Ok(result)
}
8 => {
for (i, e) in lowercase.chunks_exact(2).enumerate() {
result[i] = nibble(e[0]) << 4 | nibble(e[1]);
}
Ok(result)
}
_ => bail!("invalid color"),
}
}
fn parse_color_vec4(text: &str) -> Result<Vec4> {
let [a, r, g, b] = parse_color(text)?;
Ok(Vec4::new(r as f32, g as f32, b as f32, a as f32) * (1.0 / 255.0))
}
|
pub mod color;
pub mod document;
pub mod intersection;
pub mod layers;
pub mod operation;
pub mod response;
pub use intersection::Quad;
pub use operation::Operation;
pub use response::DocumentResponse;
pub type LayerId = u64;
#[derive(Debug, Clone, PartialEq)]
pub enum DocumentError {
LayerNotFound,
InvalidPath,
IndexOutOfBounds,
NotAFolder,
NonReorderableSelection,
NotAShape,
InvalidFile(String),
}
|
extern crate chrono;
extern crate futures;
extern crate log;
extern crate tokio;
extern crate tokio_timer;
extern crate trust_dns;
extern crate trust_dns_server;
use std::time::{Duration, Instant};
use futures::future::Either;
use futures::{Future, Stream};
use std::str::FromStr;
use tokio::runtime::current_thread::Runtime;
use tokio_timer::Delay;
use trust_dns::error::*;
use trust_dns::multicast::MdnsQueryType;
use trust_dns::multicast::MdnsStream;
use trust_dns::op::Message;
use trust_dns::rr::rdata::{SRV, TXT};
use trust_dns::rr::{DNSClass, Name, RData, Record, RecordType};
use trust_dns::serialize::binary::BinDecodable;
fn main() {
mdns_responder();
}
fn mdns_responder() {
let mut io_loop = Runtime::new().unwrap();
// a max time for the test to run
let mut timeout = Delay::new(Instant::now() + Duration::from_millis(1000));
// FIXME: ipv6 if is hardcoded, need a different strategy
let (mdns_stream, mdns_handle) = MdnsStream::new_ipv4::<ClientError>(
MdnsQueryType::Continuous,
None,
None,
);
let mut stream = io_loop
.block_on(mdns_stream)
.expect("failed to create server stream")
.into_future();
loop {
match io_loop
.block_on(stream.select2(timeout))
.ok()
.expect("server stream closed")
{
Either::A((data_src_stream_tmp, timeout_tmp)) => {
let (data_src, stream_tmp) = data_src_stream_tmp;
let (data, src) = data_src.expect("no buffer received");
stream = stream_tmp.into_future();
timeout = timeout_tmp;
let mut message = Message::from_bytes(&data).expect("message decode failed");
println!("Message {:?} - {:?}", message, src);
let answers = message
.queries()
.iter()
.filter_map(|ref query| {
//println!("Query: {}", query);
match (
&*query.name().to_lowercase().to_ascii(),
query.query_type(),
query.query_class(),
) {
("_services._dns-sd._udp.local.", RecordType::PTR, DNSClass::IN) => {
let mut record =
Record::with(query.name().clone(), RecordType::A, 60);
record.set_rdata(RData::PTR(
Name::from_str("_devpolterg._tcp.local.")
.unwrap(),
));
Some(record)
}
("_devpolterg._tcp.local.", RecordType::PTR, DNSClass::IN) => {
let mut record =
Record::with(query.name().clone(), RecordType::A, 60);
record.set_rdata(RData::PTR(
Name::from_str("deadbeefdeadbeef._devpolterg._tcp.local.")
.unwrap(),
));
Some(record)
}
(
"deadbeefdeadbeef._devpolterg._tcp.local.",
RecordType::TXT,
DNSClass::IN,
) => {
let mut record =
Record::with(query.name().clone(), RecordType::A, 60);
record.set_rdata(RData::TXT(TXT::new(vec![])));
Some(record)
}
(
"deadbeefdeadbeef._devpolterg._tcp.local.",
RecordType::SRV,
DNSClass::IN,
) => {
let mut record =
Record::with(query.name().clone(), RecordType::A, 60);
record.set_rdata(RData::SRV(SRV::new(
0,
0,
8883,
Name::from_str("deadbeefdeadbeef._devpolterg._tcp.local.")
.unwrap(),
)));
Some(record)
}
_ => {
println!("Unknown query {}", query.name());
None
}
}
})
.collect::<Vec<_>>();
message.add_answers(answers);
println!("Response: {:?}", message);
mdns_handle
.unbounded_send((message.to_vec().expect("message encode failed"), src))
.unwrap();
}
Either::B(((), data_src_stream_tmp)) => {
stream = data_src_stream_tmp;
timeout = Delay::new(Instant::now() + Duration::from_millis(1000));
}
}
}
}
|
#![feature(proc_macro_hygiene, decl_macro)]
mod blockchain;
mod criptografia;
mod models;
use blockchain::*;
use models::report::*;
use std::env;
use std::io::prelude::*;
use std::sync::RwLock;
#[macro_use]
extern crate rocket;
use rocket::config::{Config, Environment};
use rocket::http::RawStr;
use rocket::http::Status;
use rocket::response::content::Json;
use rocket::response::status;
use rocket::{Data, State};
#[allow(deprecated, unreachable_code)]
fn main() {
let bc = Blockchain::inicializar();
let port: u16 = env::var("PORT").unwrap().parse().unwrap();
let config = Config::build(Environment::Staging)
.port(port)
.finalize()
.unwrap();
rocket::custom(config)
.mount(
"/",
routes![
consultar_placa,
submeter_relatorio,
prestadores,
todos_veiculos,
login,
],
)
.manage(RwLock::new(bc))
.launch();
}
#[get("/login/<api_key>")]
// TODO: Embalar o Json em um HTTPStatus
fn login(bc: State<RwLock<Blockchain>>, api_key: &RawStr) -> Json<String> {
// Confirma API key e retorna a struct Prestador procurada
match bc.read().unwrap().confirm_api_key(&api_key) {
Ok(s) => Json(s),
Err(_) => Json(r#"{"status": "Api Key não reconhecida"}"#.to_string()),
}
}
#[get("/prestadores")]
fn prestadores(bc: State<RwLock<Blockchain>>) -> Json<String> {
Json(bc.read().unwrap().get_all_prestadores())
}
#[get("/consulta/*")]
fn todos_veiculos(bc: State<RwLock<Blockchain>>) -> Json<String> {
Json(bc.read().unwrap().get_all_veiculos())
}
#[post("/submeter_relatorio", data = "<data>")]
fn submeter_relatorio(bc: State<RwLock<Blockchain>>, data: Data) -> status::Custom<String> {
let mut body = String::new();
data.open().read_to_string(&mut body).unwrap();
let pr: Result<Report, _> = serde_json::from_str(&body);
match pr {
Ok(s) => {
let mut x = bc.write().unwrap();
match x.inserir_report(s) {
Ok(()) => {
return status::Custom(
Status::Ok,
"Ok: #001 = Relatório submetido!".to_string(),
)
}
Err(e) => return status::Custom(Status::BadRequest, format!("Err: #005 = {}", e)),
}
}
Err(_) => {
return status::Custom(
Status::BadRequest,
"Err: #003 = Formatação do relatório inválida!".to_string(),
);
}
}
}
#[get("/consulta/<placa>")]
fn consultar_placa(bc: State<RwLock<Blockchain>>, placa: &RawStr) -> Json<String> {
let resultado = bc.read().unwrap().consultar_veiuculo(placa);
match resultado {
Some(v) => Json(serde_json::to_string(&v).unwrap()),
None => Json("{}".to_string()),
}
}
|
//! Declare functions defined in out-of-line asm files.
//!
//! Kernel calling conventions differ from userspace calling conventions,
//! so we also define inline function wrappers which reorder the arguments
//! so that they match with the kernel convention as closely as possible,
//! to minimize the amount of out-of-line code we need.
#[cfg(target_arch = "x86")]
use super::super::vdso_wrappers::SyscallType;
// Architectures that don't need reordering could use this.
#[cfg(any())]
extern "C" {
pub(crate) fn syscall0(nr: u32) -> usize;
pub(crate) fn syscall0_readonly(nr: u32) -> usize;
pub(crate) fn syscall1(nr: u32, a0: usize) -> usize;
pub(crate) fn syscall1_readonly(nr: u32, a0: usize) -> usize;
pub(crate) fn syscall1_noreturn(nr: u32, a0: usize) -> !;
pub(crate) fn syscall2(nr: u32, a0: usize, a1: usize) -> usize;
pub(crate) fn syscall2_readonly(nr: u32, a0: usize, a1: usize) -> usize;
pub(crate) fn syscall3(nr: u32, a0: usize, a1: usize, a2: usize) -> usize;
pub(crate) fn syscall3_readonly(nr: u32, a0: usize, a1: usize, a2: usize) -> usize;
pub(crate) fn syscall4(nr: u32, a0: usize, a1: usize, a2: usize, a3: usize) -> usize;
pub(crate) fn syscall4_readonly(nr: u32, a0: usize, a1: usize, a2: usize, a3: usize) -> usize;
pub(crate) fn syscall5(nr: u32, a0: usize, a1: usize, a2: usize, a3: usize, a4: usize)
-> usize;
pub(crate) fn syscall5_readonly(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
) -> usize;
pub(crate) fn syscall6(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
) -> usize;
pub(crate) fn syscall6_readonly(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
) -> usize;
}
// Some architectures' outline assembly code prefers to see the `nr` argument
// last, as that lines up the syscall calling convention with the userspace
// calling convention better.
//
// First we declare the actual assembly routines with `reordered_*` names and
// reorgered arguments.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
extern "C" {
fn reordered_syscall0(nr: u32) -> usize;
fn reordered_syscall0_readonly(nr: u32) -> usize;
fn reordered_syscall1(a0: usize, nr: u32) -> usize;
fn reordered_syscall1_readonly(a0: usize, nr: u32) -> usize;
fn reordered_syscall1_noreturn(a0: usize, nr: u32) -> !;
fn reordered_syscall2(a0: usize, a1: usize, nr: u32) -> usize;
fn reordered_syscall2_readonly(a0: usize, a1: usize, nr: u32) -> usize;
fn reordered_syscall3(a0: usize, a1: usize, a2: usize, nr: u32) -> usize;
fn reordered_syscall3_readonly(a0: usize, a1: usize, a2: usize, nr: u32) -> usize;
fn reordered_syscall4(a0: usize, a1: usize, a2: usize, a3: usize, nr: u32) -> usize;
fn reordered_syscall4_readonly(a0: usize, a1: usize, a2: usize, a3: usize, nr: u32) -> usize;
fn reordered_syscall5(a0: usize, a1: usize, a2: usize, a3: usize, a4: usize, nr: u32) -> usize;
fn reordered_syscall5_readonly(
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
nr: u32,
) -> usize;
fn reordered_syscall6(
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
nr: u32,
) -> usize;
fn reordered_syscall6_readonly(
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
nr: u32,
) -> usize;
}
// Then we define inline wrapper functions that do the reordering.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
mod reorder {
use super::*;
#[inline]
pub(crate) unsafe fn syscall0(nr: u32) -> usize {
reordered_syscall0(nr)
}
#[inline]
pub(crate) unsafe fn syscall0_readonly(nr: u32) -> usize {
reordered_syscall0_readonly(nr)
}
#[inline]
pub(crate) unsafe fn syscall1(nr: u32, a0: usize) -> usize {
reordered_syscall1(a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall1_readonly(nr: u32, a0: usize) -> usize {
reordered_syscall1_readonly(a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall1_noreturn(nr: u32, a0: usize) -> ! {
reordered_syscall1_noreturn(a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall2(nr: u32, a0: usize, a1: usize) -> usize {
reordered_syscall2(a0, a1, nr)
}
#[inline]
pub(crate) unsafe fn syscall2_readonly(nr: u32, a0: usize, a1: usize) -> usize {
reordered_syscall2_readonly(a0, a1, nr)
}
#[inline]
pub(crate) unsafe fn syscall3(nr: u32, a0: usize, a1: usize, a2: usize) -> usize {
reordered_syscall3(a0, a1, a2, nr)
}
#[inline]
pub(crate) unsafe fn syscall3_readonly(nr: u32, a0: usize, a1: usize, a2: usize) -> usize {
reordered_syscall3_readonly(a0, a1, a2, nr)
}
#[inline]
pub(crate) unsafe fn syscall4(nr: u32, a0: usize, a1: usize, a2: usize, a3: usize) -> usize {
reordered_syscall4(a0, a1, a2, a3, nr)
}
#[inline]
pub(crate) unsafe fn syscall4_readonly(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
) -> usize {
reordered_syscall4_readonly(a0, a1, a2, a3, nr)
}
#[inline]
pub(crate) unsafe fn syscall5(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
) -> usize {
reordered_syscall5(a0, a1, a2, a3, a4, nr)
}
#[inline]
pub(crate) unsafe fn syscall5_readonly(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
) -> usize {
reordered_syscall5_readonly(a0, a1, a2, a3, a4, nr)
}
#[inline]
pub(crate) unsafe fn syscall6(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
) -> usize {
reordered_syscall6(a0, a1, a2, a3, a4, a5, nr)
}
#[inline]
pub(crate) unsafe fn syscall6_readonly(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
) -> usize {
reordered_syscall6_readonly(a0, a1, a2, a3, a4, a5, nr)
}
}
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
pub(crate) use reorder::*;
// x86 (using fastcall) prefers to pass a1 and a2 first, before a0, because
// fastcall passes the first two arguments in ecx and edx, which are the second
// and third Linux syscall arguments.
//
// First we declare the actual assembly routines with `reordered_*` names and
// reorgered arguments.
#[cfg(target_arch = "x86")]
extern "fastcall" {
fn reordered_syscall0(nr: u32) -> usize;
fn reordered_syscall0_readonly(nr: u32) -> usize;
fn reordered_syscall1(a0: usize, nr: u32) -> usize;
fn reordered_syscall1_readonly(a0: usize, nr: u32) -> usize;
fn reordered_syscall1_noreturn(a0: usize, nr: u32) -> !;
fn reordered_syscall2(a1: usize, a0: usize, nr: u32) -> usize;
fn reordered_syscall2_readonly(a1: usize, a0: usize, nr: u32) -> usize;
fn reordered_syscall3(a1: usize, a2: usize, a0: usize, nr: u32) -> usize;
fn reordered_syscall3_readonly(a1: usize, a2: usize, a0: usize, nr: u32) -> usize;
fn reordered_syscall4(a1: usize, a2: usize, a0: usize, a3: usize, nr: u32) -> usize;
fn reordered_syscall4_readonly(a1: usize, a2: usize, a0: usize, a3: usize, nr: u32) -> usize;
fn reordered_syscall5(a1: usize, a2: usize, a0: usize, a3: usize, a4: usize, nr: u32) -> usize;
fn reordered_syscall5_readonly(
a1: usize,
a2: usize,
a0: usize,
a3: usize,
a4: usize,
nr: u32,
) -> usize;
fn reordered_syscall6(
a1: usize,
a2: usize,
a0: usize,
a3: usize,
a4: usize,
a5: usize,
nr: u32,
) -> usize;
fn reordered_syscall6_readonly(
a1: usize,
a2: usize,
a0: usize,
a3: usize,
a4: usize,
a5: usize,
nr: u32,
) -> usize;
}
// Then we define inline wrapper functions that do the reordering.
#[cfg(target_arch = "x86")]
mod reorder {
use super::*;
#[inline]
pub(crate) unsafe fn syscall0(nr: u32) -> usize {
reordered_syscall0(nr)
}
#[inline]
pub(crate) unsafe fn syscall0_readonly(nr: u32) -> usize {
reordered_syscall0_readonly(nr)
}
#[inline]
pub(crate) unsafe fn syscall1(nr: u32, a0: usize) -> usize {
reordered_syscall1(a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall1_readonly(nr: u32, a0: usize) -> usize {
reordered_syscall1_readonly(a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall1_noreturn(nr: u32, a0: usize) -> ! {
reordered_syscall1_noreturn(a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall2(nr: u32, a0: usize, a1: usize) -> usize {
reordered_syscall2(a1, a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall2_readonly(nr: u32, a0: usize, a1: usize) -> usize {
reordered_syscall2_readonly(a1, a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall3(nr: u32, a0: usize, a1: usize, a2: usize) -> usize {
reordered_syscall3(a1, a2, a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall3_readonly(nr: u32, a0: usize, a1: usize, a2: usize) -> usize {
reordered_syscall3_readonly(a1, a2, a0, nr)
}
#[inline]
pub(crate) unsafe fn syscall4(nr: u32, a0: usize, a1: usize, a2: usize, a3: usize) -> usize {
reordered_syscall4(a1, a2, a0, a3, nr)
}
#[inline]
pub(crate) unsafe fn syscall4_readonly(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
) -> usize {
reordered_syscall4_readonly(a1, a2, a0, a3, nr)
}
#[inline]
pub(crate) unsafe fn syscall5(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
) -> usize {
reordered_syscall5(a1, a2, a0, a3, a4, nr)
}
#[inline]
pub(crate) unsafe fn syscall5_readonly(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
) -> usize {
reordered_syscall5_readonly(a1, a2, a0, a3, a4, nr)
}
#[inline]
pub(crate) unsafe fn syscall6(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
) -> usize {
reordered_syscall6(a1, a2, a0, a3, a4, a5, nr)
}
#[inline]
pub(crate) unsafe fn syscall6_readonly(
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
) -> usize {
reordered_syscall6_readonly(a1, a2, a0, a3, a4, a5, nr)
}
}
#[cfg(target_arch = "x86")]
pub(crate) use reorder::*;
// x86 prefers to route all syscalls through the vDSO, though this isn't
// always possible, so it also has a special form for doing the dispatch.
//
// First we declare the actual assembly routines with `reordered_*` names and
// reorgered arguments.
#[cfg(target_arch = "x86")]
extern "fastcall" {
fn reordered_indirect_syscall0(nr: u32, callee: SyscallType) -> usize;
fn reordered_indirect_syscall1(a0: usize, nr: u32, callee: SyscallType) -> usize;
fn reordered_indirect_syscall1_noreturn(a0: usize, nr: u32, callee: SyscallType) -> !;
fn reordered_indirect_syscall2(a1: usize, a0: usize, nr: u32, callee: SyscallType) -> usize;
fn reordered_indirect_syscall3(
a1: usize,
a2: usize,
a0: usize,
nr: u32,
callee: SyscallType,
) -> usize;
fn reordered_indirect_syscall4(
a1: usize,
a2: usize,
a0: usize,
a3: usize,
nr: u32,
callee: SyscallType,
) -> usize;
fn reordered_indirect_syscall5(
a1: usize,
a2: usize,
a0: usize,
a3: usize,
a4: usize,
nr: u32,
callee: SyscallType,
) -> usize;
fn reordered_indirect_syscall6(
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
nr: u32,
callee: SyscallType,
) -> usize;
}
// Then we define inline wrapper functions that do the reordering.
#[cfg(target_arch = "x86")]
mod reorder_indirect {
use super::*;
#[inline]
pub(crate) unsafe fn indirect_syscall0(callee: SyscallType, nr: u32) -> usize {
reordered_indirect_syscall0(nr, callee)
}
#[inline]
pub(crate) unsafe fn indirect_syscall1(callee: SyscallType, nr: u32, a0: usize) -> usize {
reordered_indirect_syscall1(a0, nr, callee)
}
#[inline]
pub(crate) unsafe fn indirect_syscall1_noreturn(callee: SyscallType, nr: u32, a0: usize) -> ! {
reordered_indirect_syscall1_noreturn(a0, nr, callee)
}
#[inline]
pub(crate) unsafe fn indirect_syscall2(
callee: SyscallType,
nr: u32,
a0: usize,
a1: usize,
) -> usize {
reordered_indirect_syscall2(a1, a0, nr, callee)
}
#[inline]
pub(crate) unsafe fn indirect_syscall3(
callee: SyscallType,
nr: u32,
a0: usize,
a1: usize,
a2: usize,
) -> usize {
reordered_indirect_syscall3(a1, a2, a0, nr, callee)
}
#[inline]
pub(crate) unsafe fn indirect_syscall4(
callee: SyscallType,
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
) -> usize {
reordered_indirect_syscall4(a1, a2, a0, a3, nr, callee)
}
#[inline]
pub(crate) unsafe fn indirect_syscall5(
callee: SyscallType,
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
) -> usize {
reordered_indirect_syscall5(a1, a2, a0, a3, a4, nr, callee)
}
#[inline]
pub(crate) unsafe fn indirect_syscall6(
callee: SyscallType,
nr: u32,
a0: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
a5: usize,
) -> usize {
reordered_indirect_syscall6(a1, a2, a0, a3, a4, a5, nr, callee)
}
}
#[cfg(target_arch = "x86")]
pub(crate) use reorder_indirect::*;
|
pub mod account;
pub mod block;
pub mod message;
pub mod node;
pub mod tip;
pub mod utxo;
|
mod flags;
mod memory;
mod opcode;
mod pointers;
mod registers;
use flags::Flags;
use memory::Memory;
use opcode::Opcode;
use pointers::Pointer;
use registers::Register;
use std::fmt;
#[derive(Clone, Copy, Default)]
pub struct Cpu {
a: Register,
b: Register,
c: Register,
d: Register,
e: Register,
h: Register,
l: Register,
pc: Pointer,
sp: Pointer,
memory: Memory,
flags: Flags,
interrupts_enabled: bool,
}
impl Cpu {
pub fn new() -> Self {
Self::default()
}
pub fn load_rom_into_memory(&mut self, start_addr: usize, rom: &[u8; 0x7FF]) {
for b in 0..rom.len() {
self.memory.ram[start_addr + b] = rom[b];
}
}
pub fn execute_opcode(&mut self, count: &u128) -> u8 {
let mut op = self.get_current_opcode();
let mem_ref = self.get_memory_reference();
op.next_bytes = mem_ref;
debug!("{:?}", self);
debug!("{:?} | {}\n", op, count);
let mut changed_pc = false;
match op.code {
0x00 | 0x08 | 0x10 | 0x18 | 0x20 | 0x28 | 0x30 | 0x38 | 0xCB | 0xD9 | 0xDD | 0xED
| 0xFD => {}
0x01 | 0x11 | 0x21 | 0x31 => self.lxi_operation(op.code),
0x02 | 0x12 => self.stax_operation(op.code),
0x03 | 0x13 | 0x23 | 0x33 => self.inx_operation(op.code),
0x04 | 0x0C | 0x14 | 0x1C | 0x24 | 0x2C | 0x34 | 0x3C => self.inr_operation(op.code),
0x05 | 0x0D | 0x15 | 0x1D | 0x25 | 0x2D | 0x35 | 0x3D => self.dcr_operation(op.code),
0x06 | 0x0E | 0x16 | 0x1E | 0x26 | 0x2E | 0x36 | 0x3E => self.mvi_operation(op.code),
0x07 => self.rlc(),
0x09 | 0x19 | 0x29 | 0x39 => self.dad_operation(op.code),
0x0F => self.rrc(),
0x0A | 0x1A => self.ldax_operation(op.code),
0x0B | 0x1B | 0x2B | 0x3B => self.dcx_operation(op.code),
0x17 => self.ral(),
0x1F => self.rar(),
0x22 => self.shld(),
0x27 => self.daa(),
0x2A => self.lhld(),
0x2F => self.cma(),
0x32 => self.sta(),
0x37 => self.stc(),
0x3A => self.lda(),
0x3F => self.cmc(),
0x40...0x47 => self.mov_b_operation(op.code),
0x48...0x4F => self.mov_c_operation(op.code),
0x50...0x57 => self.mov_d_operation(op.code),
0x58...0x5F => self.mov_e_operation(op.code),
0x60...0x67 => self.mov_h_operation(op.code),
0x68...0x6F => self.mov_l_operation(op.code),
0x70...0x75 | 0x77 => self.mov_m_operation(op.code),
0x76 => self.hlt(),
0x78...0x7F => self.mov_a_operation(op.code),
0x80...0x87 => self.add_operation(op.code),
0x88...0x8F => self.adc_operation(op.code),
0x90...0x97 => self.sub_operation(op.code),
0x98...0x9F => self.sbb_operation(op.code),
0xA0...0xA7 => self.ana_operation(op.code),
0xA8...0xAF => self.xra_operation(op.code),
0xB0...0xB7 => self.ora_operation(op.code),
0xB8...0xBF => self.cmp_operation(op.code),
0xC0 | 0xC8 | 0xC9 | 0xD0 | 0xD8 | 0xE0 | 0xE8 | 0xF0 | 0xF8 => {
changed_pc = self.do_return(op.code)
}
0xC1 | 0xD1 | 0xE1 | 0xF1 => self.pop_operation(op.code),
0xC2 | 0xC3 | 0xCA | 0xD2 | 0xDA | 0xE2 | 0xEA | 0xF2 | 0xFA => {
changed_pc = self.do_jump(op.code)
}
0xC4 | 0xCC | 0xCD | 0xD4 | 0xDC | 0xE4 | 0xEC | 0xF4 | 0xFC => {
changed_pc = self.do_call(op.code)
}
0xC5 | 0xD5 | 0xE5 | 0xF5 => self.push_operation(op.code),
0xC6 => self.adi(),
0xC7 | 0xCF | 0xD7 | 0xDF | 0xE7 | 0xEF | 0xF7 | 0xFF => self.rst_operation(op.code),
0xCE => self.aci(),
0xD3 => {
// handled elsewhere
}
0xD6 => self.sui(),
0xDB => {
// handled elsewhere
}
0xDE => self.sbi(),
0xE3 => self.xthl(),
0xE6 => self.ani(),
0xE9 => self.pchl(),
0xEB => self.xchg(),
0xEE => self.xri(),
0xF3 => self.disable_interrupts(),
0xF6 => self.ori(),
0xF9 => self.sphl(),
0xFB => self.enable_interrupts(),
0xFE => self.cpi(),
}
if !changed_pc {
self.pc += 1;
}
op.cycles
}
#[inline]
fn set_flags(&mut self, result: &u8, reg_value: u8, op: u8) {
self.flags.p = self.sets_parity_flag(&result);
self.flags.z = self.sets_zero_flag(&result);
self.flags.s = self.sets_sign_flag(&result);
self.set_ac_flag(®_value, &op);
}
#[inline]
fn set_carry_flag(&mut self, op1: &u8, op2: &u8) {
self.flags.cy = (0xFF - op1) <= *op2
}
#[inline]
fn set_ac_flag(&mut self, op1: &u8, op2: &u8) {
let v1 = op1 & 0xF;
let v2 = op2 & 0xF;
self.flags.ac = (0x10 - v1) <= v2
}
fn is_b7_set(val: u8) -> bool {
(val & 0x80) >> 7 == 1
}
fn is_b1_set(val: u8) -> bool {
(val & 0x1) == 1
}
#[inline]
fn sets_parity_flag(&mut self, val: &u8) -> bool {
let mut count = 0;
let temp_val = *val;
for i in 0..8 {
if (temp_val >> i) & 0x1 == 1 {
count += 1;
}
}
count % 2 == 0
}
#[inline]
fn sets_zero_flag(&mut self, val: &u8) -> bool {
*val == 0
}
#[inline]
fn sets_sign_flag(&mut self, val: &u8) -> bool {
(*val & 0x80) == 0x80
}
pub fn input(&mut self, val: u8) {
self.a = val.into()
}
pub fn output(&mut self) -> (u8, Register) {
(self.get_next_byte(), self.a)
}
fn addition(&mut self, val: u8) {
self.a = self.update_register(self.a, val, &wrapping_add_u8);
self.set_carry_flag(&self.a.into(), &val);
}
fn subtraction(&mut self, val: u8) {
self.a = self.update_register(self.a, !val + 1, &wrapping_add_u8);
self.set_carry_flag(&val, &self.a.into());
}
fn adc_operation(&mut self, code: u8) {
let operand = self.get_reg_value(code) + self.flags.cy as u8;
self.addition(operand);
}
fn add_operation(&mut self, code: u8) {
self.addition(self.get_reg_value(code));
}
fn adi(&mut self) {
self.addition(self.get_next_byte());
self.pc += 1;
}
fn aci(&mut self) {
let operand = self.get_next_byte() + self.flags.cy as u8;
self.addition(operand);
self.pc += 1;
}
fn sbb_operation(&mut self, code: u8) {
let operand = self.get_reg_value(code) + self.flags.cy as u8;
self.subtraction(operand);
}
fn sub_operation(&mut self, code: u8) {
self.subtraction(self.get_reg_value(code));
}
fn sui(&mut self) {
self.subtraction(self.get_next_byte());
self.pc += 1;
}
fn sbi(&mut self) {
let operand = self.get_next_byte() + self.flags.cy as u8;
self.subtraction(operand);
self.pc += 1;
}
fn compare(&mut self, operand: u8) {
self.update_register(self.a, !operand + 1, &wrapping_add_u8);
self.set_carry_flag(&self.a.into(), &operand);
}
fn cmp_operation(&mut self, code: u8) {
self.compare(self.get_reg_value(code));
}
fn cpi(&mut self) {
self.compare(self.get_next_byte());
}
fn logical_operation(&mut self, val: u8, f: &Fn(u8, u8) -> u8) {
self.a = self.update_register(self.a, val, f);
self.flags.cy = false;
}
fn ana_operation(&mut self, code: u8) {
self.logical_operation(self.get_reg_value(code), &logical_and);
}
fn ani(&mut self) {
self.logical_operation(self.get_next_byte(), &logical_and);
}
fn xra_operation(&mut self, code: u8) {
self.logical_operation(self.get_reg_value(code), &logical_xor);
}
fn xri(&mut self) {
self.logical_operation(self.get_next_byte(), &logical_xor);
}
fn ora_operation(&mut self, code: u8) {
self.logical_operation(self.get_reg_value(code), &logical_or);
}
fn ori(&mut self) {
self.logical_operation(self.get_next_byte(), &logical_or);
}
fn lxi_operation(&mut self, code: u8) {
let val1 = self.memory.ram[usize::from(self.pc + 1)].into();
let val2 = self.memory.ram[usize::from(self.pc + 2)].into();
match code {
0x01 => {
self.c = val1;
self.b = val2;
}
0x11 => {
self.e = val1;
self.d = val2;
}
0x21 => {
self.l = val1;
self.h = val2;
}
0x31 => {
self.sp = self.get_memory_reference().into();
}
_ => panic!("Bug in opcode routing."),
}
self.pc += 2;
}
fn stax_operation(&mut self, code: u8) {
let mem_ref = match code {
0x02 => self.get_reg_pair_value(self.b, self.c),
0x12 => self.get_reg_pair_value(self.d, self.e),
_ => panic!("Bug in opcode routing."),
};
self.memory.ram[mem_ref as usize] = self.a.into();
}
fn inx_operation(&mut self, code: u8) {
match code {
0x03 => {
let (x, y) = self.update_register_pair(self.b, self.c, 1, &wrapping_add_u16);
self.b = x;
self.c = y;
}
0x13 => {
let (x, y) = self.update_register_pair(self.d, self.e, 1, &wrapping_add_u16);
self.d = x;
self.e = y;
}
0x23 => {
let (x, y) = self.update_register_pair(self.h, self.l, 1, &wrapping_add_u16);
self.h = x;
self.l = y;
}
0x33 => {
let val: u16 = self.sp.into();
let result = val.wrapping_add(1);
self.sp = result.into();
}
_ => panic!("Bug in opcode routing"),
}
}
fn inr_operation(&mut self, code: u8) {
match code {
0x04 => self.b = self.update_register(self.b, 1, &wrapping_add_u8),
0x0C => self.c = self.update_register(self.c, 1, &wrapping_add_u8),
0x14 => self.d = self.update_register(self.d, 1, &wrapping_add_u8),
0x1C => self.e = self.update_register(self.e, 1, &wrapping_add_u8),
0x24 => self.h = self.update_register(self.h, 1, &wrapping_add_u8),
0x2C => self.l = self.update_register(self.l, 1, &wrapping_add_u8),
0x34 => {
let mem_ref = self.get_reg_pair_value(self.l, self.h);
let value = self.memory.ram[mem_ref as usize];
let result = value.wrapping_add(1);
self.set_flags(&result, value, 1);
self.set_carry_flag(&value, &1);
self.l = (result & 0xFF).into();
self.h = (result & 0x00FF).into();
}
0x3C => self.a = self.update_register(self.a, 1, &wrapping_add_u8),
_ => panic!("Bug exists in opcode routing"),
}
}
fn dcr_operation(&mut self, code: u8) {
match code {
0x05 => self.b = self.update_register(self.b, 1, &wrapping_sub_u8),
0x0D => self.c = self.update_register(self.c, 1, &wrapping_sub_u8),
0x15 => self.d = self.update_register(self.d, 1, &wrapping_sub_u8),
0x1D => self.e = self.update_register(self.e, 1, &wrapping_sub_u8),
0x25 => self.h = self.update_register(self.h, 1, &wrapping_sub_u8),
0x2D => self.l = self.update_register(self.l, 1, &wrapping_sub_u8),
0x35 => {
let mem_ref = self.get_reg_pair_value(self.h, self.l);
let value = self.memory.ram[mem_ref as usize];
let result = value.wrapping_sub(1);
self.set_flags(&result, value, 1);
self.set_carry_flag(&value, &1);
self.memory.ram[mem_ref as usize] = result;
}
0x3D => self.a = self.update_register(self.a, 1, &wrapping_sub_u8),
_ => panic!("Bug exists in opcode routing"),
}
}
fn mvi_operation(&mut self, code: u8) {
match code {
0x06 => self.b = self.memory.ram[(usize::from(self.pc) + 1)].into(),
0x0E => self.c = self.memory.ram[(usize::from(self.pc) + 1)].into(),
0x16 => self.d = self.memory.ram[(usize::from(self.pc) + 1)].into(),
0x1E => self.e = self.memory.ram[(usize::from(self.pc) + 1)].into(),
0x26 => self.h = self.memory.ram[(usize::from(self.pc) + 1)].into(),
0x2E => self.l = self.memory.ram[(usize::from(self.pc) + 1)].into(),
0x36 => {
let mem_ref = self.get_reg_pair_value(self.h, self.l);
self.memory.ram[mem_ref as usize] = self.memory.ram[(usize::from(self.pc) + 1)];
}
0x3E => self.a = self.memory.ram[(usize::from(self.pc) + 1)].into(),
_ => panic!("Bug exists in opcode routing"),
}
self.pc += 1
}
fn pop_operation(&mut self, code: u8) {
let (msb, lsb) = self.pop_off_stack();
match code {
0xC1 => {
self.b = msb.into();
self.c = lsb.into();
}
0xD1 => {
self.d = msb.into();
self.e = lsb.into();
}
0xE1 => {
self.h = msb.into();
self.l = lsb.into();
}
0xF1 => {
self.a = msb.into();
self.flags.s = (lsb & 0x80) >> 7 == 1;
self.flags.z = (lsb & 0x40) >> 6 == 1;
self.flags.ac = (lsb & 0x10) >> 4 == 1;
self.flags.p = (lsb & 0x4) >> 2 == 1;
self.flags.cy = (lsb & 0x1) == 1;
}
_ => panic!("Bug exists in opcode routing"),
}
}
fn push_operation(&mut self, code: u8) {
match code {
0xC5 => {
let val = self.get_reg_pair_value(self.b, self.c);
self.push_to_stack(val);
}
0xD5 => {
let val = self.get_reg_pair_value(self.d, self.e);
self.push_to_stack(val);
}
0xE5 => {
let val = self.get_reg_pair_value(self.h, self.l);
self.push_to_stack(val);
}
0xF5 => {
let msb: u8 = self.a.into();
let mut lsb: u8 = 0;
lsb += (self.flags.s as u8) << 7;
lsb += (self.flags.z as u8) << 6;
lsb += (self.flags.ac as u8) << 4;
lsb += (self.flags.p as u8) << 2;
lsb += 1 << 1;
lsb += self.flags.cy as u8;
self.push_to_stack(((msb as u16) << 8) | lsb as u16);
}
_ => panic!("Bug in opcode routing"),
}
}
fn rlc(&mut self) {
let reg_value: u8 = self.a.into();
let temp: u8 = ®_value << 1;
if Cpu::is_b7_set(reg_value) {
self.flags.cy = true;
self.a = (temp | 0x1).into();
} else {
self.flags.cy = false;
self.a = (temp | 0).into();
}
}
fn ral(&mut self) {
let reg_value: u8 = self.a.into();
let temp: u8 = ®_value << 1;
self.a = if self.flags.cy {
(temp | 0x1).into()
} else {
(temp | 0x0).into()
};
self.flags.cy = Cpu::is_b7_set(reg_value);
}
fn rrc(&mut self) {
let reg_value: u8 = self.a.into();
let carry_flag = Cpu::is_b1_set(reg_value);
let temp: u8 = ®_value >> 1;
if carry_flag {
self.flags.cy = true;
self.a = (temp | 0x80).into();
} else {
self.flags.cy = false;
self.a = (temp | 0).into();
}
}
fn rar(&mut self) {
let reg_value: u8 = self.a.into();
let temp: u8 = ®_value >> 1;
self.a = if self.flags.cy {
(temp | 0x80).into()
} else {
(temp | 0x0).into()
};
self.flags.cy = Cpu::is_b1_set(reg_value);
}
fn shld(&mut self) {
let mem_add = self.get_memory_reference();
self.memory.ram[mem_add as usize] = self.l.into();
self.memory.ram[(mem_add + 1) as usize] = self.h.into();
self.pc += 2;
}
fn daa(&mut self) {
let inc_6 = |val, flag| val + if val > 9 || flag { 6 } else { 0 };
let chk_over = |val| ((val & 0xF0) >> 4) == 1u8;
let split_bytes = |val: u8| ((val & 0xF), ((val & 0xF0) >> 4));
let (lsbits, mut msbits) = split_bytes(self.a.into());
let lsmod = inc_6(lsbits, self.flags.ac);
if chk_over(lsmod) {
msbits = msbits.wrapping_add(1);
}
let msmod = inc_6(msbits, self.flags.cy);
self.flags.ac = chk_over(lsmod);
self.flags.cy = chk_over(msmod);
self.a = (((msmod & 0xF) << 4) | lsmod & 0xF).into();
}
fn lhld(&mut self) {
let mem_add = self.get_memory_reference();
self.h = self.memory.ram[mem_add as usize].into();
self.l = self.memory.ram[(mem_add + 1) as usize].into();
self.pc += 2;
}
fn cma(&mut self) {
let val: u8 = self.a.into();
let inverted: u8 = !val;
self.a = inverted.into();
}
fn sta(&mut self) {
let mem_add = self.get_memory_reference();
self.memory.ram[mem_add as usize] = self.a.into();
self.pc += 2;
}
fn stc(&mut self) {
self.flags.cy = true;
}
fn lda(&mut self) {
let mem_add = self.get_memory_reference();
self.a = self.memory.ram[mem_add as usize].into();
self.pc += 2;
}
fn cmc(&mut self) {
self.flags.cy = !self.flags.cy;
}
fn hlt(&mut self) {
panic!("Halt called.");
}
fn jump_operation(&mut self, true_condition: bool) -> bool {
if true_condition {
self.pc = self.get_memory_reference().into();
true
} else {
self.pc += 2;
false
}
}
fn do_jump(&mut self, code: u8) -> bool {
self.jump_operation(match code {
0xC2 => !self.flags.z,
0xC3 => true,
0xCA => self.flags.z,
0xD2 => !self.flags.cy,
0xDA => self.flags.cy,
0xE2 => !self.flags.p,
0xEA => self.flags.p,
0xF2 => !self.flags.s,
0xFA => self.flags.s,
_ => panic!("Bug in opcode routing"),
})
}
fn call_subroutine(&mut self, true_condition: bool) -> bool {
if true_condition {
let mem_ref = self.get_memory_reference();
self.push_to_stack((self.pc + 3).into());
self.pc = mem_ref.into();
true
} else {
self.pc += 2;
false
}
}
fn do_call(&mut self, code: u8) -> bool {
self.call_subroutine(match code {
0xC4 => !self.flags.z,
0xCC => self.flags.z,
0xCD => true,
0xD4 => !self.flags.cy,
0xDC => self.flags.cy,
0xE4 => !self.flags.p,
0xEC => self.flags.p,
0xF4 => !self.flags.s,
0xFC => self.flags.s,
_ => panic!("Bug in opcode routing"),
})
}
fn return_from_subroutine(&mut self, true_condition: bool) -> bool {
if true_condition {
let (msb, lsb) = self.pop_off_stack();
self.pc = self.get_pair_value(msb, lsb).into();
return true;
}
false
}
fn do_return(&mut self, code: u8) -> bool {
self.return_from_subroutine(match code {
0xC0 => !self.flags.z,
0xC8 => self.flags.z,
0xC9 => true,
0xD0 => !self.flags.cy,
0xD8 => self.flags.cy,
0xE0 => !self.flags.p,
0xE8 => self.flags.p,
0xF0 => !self.flags.s,
0xF8 => self.flags.s,
_ => panic!("Bug in opcode routing"),
})
}
fn rst_operation(&mut self, code: u8) {
self.push_to_stack(self.pc.into());
self.pc = (code & 0x38).into();
}
fn mov_b_operation(&mut self, code: u8) {
self.b = self.get_reg_value(code).into();
}
fn mov_c_operation(&mut self, code: u8) {
self.c = self.get_reg_value(code).into();
}
fn mov_d_operation(&mut self, code: u8) {
self.d = self.get_reg_value(code).into();
}
fn mov_e_operation(&mut self, code: u8) {
self.e = self.get_reg_value(code).into();
}
fn mov_h_operation(&mut self, code: u8) {
self.h = self.get_reg_value(code).into();
}
fn mov_l_operation(&mut self, code: u8) {
self.l = self.get_reg_value(code).into();
}
fn mov_a_operation(&mut self, code: u8) {
self.a = self.get_reg_value(code).into();
}
fn mov_m_operation(&mut self, code: u8) {
let mem_ref = self.get_reg_pair_value(self.h, self.l);
self.memory.ram[mem_ref as usize] = self.get_reg_value(code).into();
}
fn dad_operation(&mut self, code: u8) {
match code {
0x09 => {
let hl_reg = self.get_reg_pair_value(self.h, self.l);
let (x, y) = self.update_register_pair(self.b, self.c, hl_reg, &wrapping_add_u16);
self.h = x;
self.l = y;
}
0x19 => {
let hl_reg = self.get_reg_pair_value(self.h, self.l);
let (x, y) = self.update_register_pair(self.d, self.e, hl_reg, &wrapping_add_u16);
self.h = x;
self.l = y;
}
0x29 => {
// This is just doubled. :)
let hl_reg: u32 = self.get_reg_pair_value(self.h, self.l) as u32;
let result = hl_reg << 1;
let (x, y) = Cpu::return_split_registers((&result & 0xFFFF) as u16);
self.h = x;
self.l = y;
let overflow = (&result & 0xFF0000) >> 16;
self.flags.cy = if overflow == 0 { true } else { false };
}
0x39 => {
let hl_reg = self.get_reg_pair_value(self.h, self.l);
let (a, b) = Cpu::return_split_registers(self.sp.into());
let (x, y) = self.update_register_pair(a, b, hl_reg, &wrapping_add_u16);
self.h = x;
self.l = y;
}
_ => panic!("Bug in opcode router"),
}
}
fn pchl(&mut self) {
let value = self.get_reg_pair_value(self.h, self.l);
self.pc = value.into();
}
fn xthl(&mut self) {
let l_val: u8 = self.l.into();
let h_val: u8 = self.h.into();
let sp_1: u8 = self.memory.ram[usize::from(self.sp)];
let sp_2: u8 = self.memory.ram[usize::from(self.sp + 1)];
self.l = sp_1.into();
self.h = sp_2.into();
self.memory.ram[usize::from(self.sp)] = l_val.into();
self.memory.ram[usize::from(self.sp + 1)] = h_val.into();
}
fn xchg(&mut self) {
let h_val: u8 = self.h.into();
let l_val: u8 = self.l.into();
let d_val: u8 = self.d.into();
let e_val: u8 = self.e.into();
self.l = e_val.into();
self.h = d_val.into();
self.d = h_val.into();
self.e = l_val.into();
}
fn sphl(&mut self) {
self.sp = self.get_reg_pair_value(self.h, self.l).into()
}
fn ldax_operation(&mut self, code: u8) {
match code {
0x0A => {
let val = self.get_reg_pair_value(self.b, self.c);
self.a = self.memory.ram[val as usize].into();
}
0x1A => {
let val = self.get_reg_pair_value(self.d, self.e);
self.a = self.memory.ram[val as usize].into();
}
_ => panic!("Bug in opcode router"),
}
}
fn dcx_operation(&mut self, code: u8) {
match code {
0x0B => {
let (x, y) = self.update_register_pair(self.b, self.c, 1, &wrapping_sub_u16);
self.b = x.into();
self.c = y.into();
}
0x1B => {
let (x, y) = self.update_register_pair(self.d, self.e, 1, &wrapping_sub_u16);
self.b = x.into();
self.c = y.into();
}
0x2B => {
let (x, y) = self.update_register_pair(self.h, self.l, 1, &wrapping_sub_u16);
self.b = x.into();
self.c = y.into();
}
0x3B => {
let (a, b) = Cpu::return_split_registers(self.sp.into());
let (x, y) = self.update_register_pair(a, b, 1, &wrapping_sub_u16);
self.b = x.into();
self.c = y.into();
}
_ => panic!("Bug in opcode router"),
}
}
fn disable_interrupts(&mut self) {
self.interrupts_enabled = false
}
fn enable_interrupts(&mut self) {
self.interrupts_enabled = true;
}
fn update_register(&mut self, reg: Register, op: u8, f: &Fn(u8, u8) -> u8) -> Register {
let val: u8 = reg.into();
let result = f(val, op);
self.set_flags(&result, reg.into(), op);
result.into()
}
fn update_register_pair(
&mut self,
msb: Register,
lsb: Register,
op: u16,
f: &Fn(u16, u16) -> u16,
) -> (Register, Register) {
let concat_val = self.get_reg_pair_value(msb, lsb);
let result = f(concat_val, op);
Cpu::return_split_registers(result)
}
fn get_reg_value(self, code: u8) -> u8 {
self.get_register(code).into()
}
fn get_register(self, code: u8) -> Register {
match code % 8 {
0 => self.b,
1 => self.c,
2 => self.d,
3 => self.e,
4 => self.h,
5 => self.l,
6 => {
let mem_ref = self.get_reg_pair_value(self.h, self.l);
Register::from(self.memory.ram[mem_ref as usize])
}
7 => self.a,
_ => panic!("Input not valid"),
}
}
fn get_reg_pair_value(self, msb: Register, lsb: Register) -> u16 {
self.get_pair_value(msb.into(), lsb.into())
}
fn get_pair_value(self, msb: u8, lsb: u8) -> u16 {
((msb as u16) << 8) | lsb as u16
}
fn get_memory_reference(self) -> u16 {
let low_adr: u16 = self.memory.ram[usize::from(self.pc + 1)].into();
let high_adr: u16 = self.memory.ram[usize::from(self.pc + 2)].into();
(high_adr << 8) | low_adr
}
pub fn get_next_byte(self) -> u8 {
self.memory.ram[usize::from(self.pc + 1)]
}
fn push_to_stack(&mut self, val: u16) {
let (msb, lsb) = Cpu::return_split_values(val);
self.memory.ram[usize::from(self.sp - 1)] = msb;
self.memory.ram[usize::from(self.sp - 2)] = lsb;
self.sp -= 2;
}
fn pop_off_stack(&mut self) -> (u8, u8) {
let lsb = self.memory.ram[usize::from(self.sp)].into();
let msb = self.memory.ram[usize::from(self.sp + 1)].into();
self.sp += 2;
(msb, lsb)
}
fn return_split_registers(val: u16) -> (Register, Register) {
let (x, y) = Cpu::return_split_values(val);
(x.into(), y.into())
}
fn return_split_values(val: u16) -> (u8, u8) {
(((val & 0xFF00) >> 8) as u8, (val & 0xFF) as u8)
}
pub fn get_current_opcode(&mut self) -> Opcode {
let code = self.memory.ram[usize::from(self.pc)];
Opcode::new(code)
}
pub fn interrupts_enabled(&mut self) -> bool {
self.interrupts_enabled
}
pub fn get_video_memory(&self) -> &[u8] {
&self.memory.ram[0x2400..0x4000]
}
pub fn increment_pc(&mut self, val: u8) {
self.pc += val.into();
}
}
fn wrapping_add_u16(val: u16, operand: u16) -> u16 {
val.wrapping_add(operand)
}
fn wrapping_add_u8(val: u8, operand: u8) -> u8 {
val.wrapping_add(operand)
}
fn wrapping_sub_u16(val: u16, operand: u16) -> u16 {
val.wrapping_sub(operand)
}
fn wrapping_sub_u8(val: u8, operand: u8) -> u8 {
val.wrapping_sub(operand)
}
fn logical_and(val: u8, operand: u8) -> u8 {
val & operand
}
fn logical_or(val: u8, operand: u8) -> u8 {
val | operand
}
fn logical_xor(val: u8, operand: u8) -> u8 {
val ^ operand
}
impl fmt::Debug for Cpu {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"pc: {:4} sp: {:4} | a:{:2} bc:{:2}{:2} de:{:2}{:2} hl:{:2}{:2}",
self.pc, self.sp, self.a, self.b, self.c, self.d, self.e, self.h, self.l
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::prelude::*;
#[test]
fn test_new_and_init() {
let cpu = Cpu::new();
let addr1 = get_random_number(0xFFFF) as usize;
let addr2 = get_random_number(0xFFFF) as usize;
let addr3 = get_random_number(0xFFFF) as usize;
assert_eq!(cpu.pc, 0);
assert_eq!(cpu.memory.ram[addr1], 0);
assert_eq!(cpu.memory.ram[addr2], 0);
assert_eq!(cpu.memory.ram[addr3], 0);
}
#[test]
fn test_load_rom_into_memory() {
let mut cpu = Cpu::new();
let mut rom: [u8; 0x7FF] = [0; 0x7FF];
let addr1 = get_random_number(0x7FF) as usize;
let addr2 = get_random_number(0x7FF) as usize;
let val1 = get_random_number(0xFF) as u8;
let val2 = get_random_number(0xFF) as u8;
rom[addr1] = val1;
rom[addr2] = val2;
let start_addr: usize = 0;
cpu.load_rom_into_memory(start_addr, &rom);
assert_eq!(cpu.memory.ram[addr1], val1);
assert_eq!(cpu.memory.ram[addr2], val2);
}
// opcode tests
#[test]
fn test_lxi_operation() {
let mut cpu = Cpu::new();
let opcode = 0x11;
let rand_addr: usize = get_random_number(0xFFFF) as usize;
let reg_val_1: u8 = get_random_number(0xFF) as u8;
let reg_val_2: u8 = get_random_number(0xFF) as u8;
cpu.pc = (rand_addr as u16).into();
cpu.memory.ram[rand_addr] = opcode;
cpu.memory.ram[rand_addr + 1] = reg_val_1;
cpu.memory.ram[rand_addr + 2] = reg_val_2;
cpu.lxi_operation(opcode);
assert_eq!(cpu.d, reg_val_2);
assert_eq!(cpu.e, reg_val_1);
}
#[test]
fn test_stax_operation() {
let mut cpu = Cpu::new();
let acc_val = get_random_number(0xFF);
cpu.a = acc_val.into();
cpu.b = (0x3F as u8).into();
cpu.c = (0x16 as u8).into();
cpu.stax_operation(0x02);
assert_eq!(cpu.memory.ram[0x3F16], acc_val as u8);
}
#[test]
fn test_inx_operation() {
let mut cpu = Cpu::new();
cpu.d = (0x38 as u8).into();
cpu.e = (0xFF as u8).into();
cpu.inx_operation(0x13);
assert_eq!(cpu.d, 0x39);
assert_eq!(cpu.e, 0x0);
}
#[test]
fn test_inr_operation() {
let mut cpu = Cpu::new();
cpu.c = (0x99 as u8).into();
cpu.inr_operation(0x0C);
assert_eq!(cpu.c, 0x9A);
}
#[test]
fn test_dcr_operation() {
let mut cpu = Cpu::new();
cpu.h = (0x3A as u8).into();
cpu.l = (0x7C as u8).into();
cpu.memory.ram[0x3A7C] = 0x40;
cpu.dcr_operation(0x35);
assert_eq!(cpu.memory.ram[0x3A7C], 0x3F);
}
#[test]
fn test_mvi_operation() {
let mut cpu = Cpu::new();
let pc = get_random_number(0xFFFF);
let old_val = get_random_number(0xFF) as u8;
let new_val = get_random_number(0xFF) as u8;
cpu.pc = pc.into();
cpu.memory.ram[(pc + 1) as usize] = new_val;
cpu.d = old_val.into();
cpu.mvi_operation(0x16);
assert_eq!(cpu.d, new_val);
}
#[test]
fn test_dad_operation() {
let mut cpu = Cpu::new();
cpu.b = (0x33 as u8).into();
cpu.c = (0x9F as u8).into();
cpu.h = (0xA1 as u8).into();
cpu.l = (0x7B as u8).into();
cpu.dad_operation(0x09);
assert_eq!(cpu.h, 0xD5);
assert_eq!(cpu.l, 0x1A);
}
#[test]
fn test_ldax_operation() {
let mut cpu = Cpu::new();
cpu.d = (0x93 as u8).into();
cpu.e = (0x8B as u8).into();
cpu.a = (0xFF as u8).into();
let val: u8 = 0x34;
cpu.memory.ram[0x938B as usize] = val;
cpu.ldax_operation(0x1A);
assert_eq!(cpu.a, val);
}
#[test]
fn test_add_operation() {
let mut cpu = Cpu::new();
let val: u8 = 0x2E;
cpu.b = val.into();
let acc_val: u8 = 0x6C;
cpu.a = acc_val.into();
cpu.add_operation(0x80);
assert_eq!(cpu.a, 0x9A);
assert_eq!(cpu.flags.cy, false);
assert_eq!(cpu.flags.z, false);
assert_eq!(cpu.flags.p, true);
assert_eq!(cpu.flags.s, true);
assert_eq!(cpu.flags.ac, true);
}
#[test]
fn test_adc_operation_not_set() {
let mut cpu = Cpu::new();
let val: u8 = 0x3D;
cpu.b = val.into();
let acc_val: u8 = 0x42;
cpu.a = acc_val.into();
cpu.adc_operation(0x88);
assert_eq!(cpu.a, 0x7F);
assert_eq!(cpu.flags.cy, false);
assert_eq!(cpu.flags.z, false);
assert_eq!(cpu.flags.p, false);
assert_eq!(cpu.flags.s, false);
assert_eq!(cpu.flags.ac, false);
}
#[test]
fn test_adc_operation_set() {
let mut cpu = Cpu::new();
cpu.flags.cy = true;
let val: u8 = 0x3D;
cpu.b = val.into();
let acc_val: u8 = 0x42;
cpu.a = acc_val.into();
cpu.adc_operation(0x88);
assert_eq!(cpu.a, 0x80);
assert_eq!(cpu.flags.cy, false);
assert_eq!(cpu.flags.z, false);
assert_eq!(cpu.flags.p, false);
assert_eq!(cpu.flags.s, true);
assert_eq!(cpu.flags.ac, true);
}
#[test]
fn test_sub_operation() {
let mut cpu = Cpu::new();
cpu.flags.cy = true;
let val: u8 = 0x3E;
cpu.b = val.into();
let acc_val: u8 = 0x3E;
cpu.a = acc_val.into();
cpu.sub_operation(0x80);
assert_eq!(cpu.a, 0x0);
assert_eq!(cpu.flags.ac, true);
assert_eq!(cpu.flags.cy, false);
assert_eq!(cpu.flags.p, true);
assert_eq!(cpu.flags.z, true);
}
#[test]
fn test_sbb_operation_not_set() {
let mut cpu = Cpu::new();
let val: u8 = 0x2;
cpu.l = val.into();
let acc_val: u8 = 0x4;
cpu.a = acc_val.into();
cpu.sbb_operation(0x9D);
assert_eq!(cpu.a, 0x2);
}
#[test]
fn test_sbb_operation_set() {
let mut cpu = Cpu::new();
cpu.flags.cy = true;
let val: u8 = 0x2;
cpu.l = val.into();
let acc_val: u8 = 0x4;
cpu.a = acc_val.into();
cpu.sbb_operation(0x9D);
assert_eq!(cpu.a, 0x1);
assert_eq!(cpu.flags.cy, false);
assert_eq!(cpu.flags.z, false);
assert_eq!(cpu.flags.p, false);
assert_eq!(cpu.flags.ac, true);
}
#[test]
fn test_sui_operation() {
let mut cpu = Cpu::new();
let pc = get_random_number(0xFFFF);
cpu.pc = pc.into();
cpu.memory.ram[(pc + 1) as usize] = 0x1;
cpu.sui();
assert_eq!(cpu.a, 0xFF);
assert_eq!(cpu.flags.cy, true);
assert_eq!(cpu.flags.s, true);
assert_eq!(cpu.flags.p, true);
assert_eq!(cpu.flags.ac, false);
assert_eq!(cpu.flags.z, false);
}
#[test]
fn test_ana_operation() {
let mut cpu = Cpu::new();
let reg_val: u8 = 0xF;
let acc_val: u8 = 0xFC;
cpu.a = acc_val.into();
cpu.c = reg_val.into();
cpu.ana_operation(0xA1);
assert_eq!(cpu.a, 0xC);
}
#[test]
fn test_xra_operation() {
let mut cpu = Cpu::new();
let acc_val: u8 = 0xF;
cpu.a = acc_val.into();
cpu.xra_operation(0xAF);
assert_eq!(cpu.a, 0x0);
}
#[test]
fn test_ora_operation() {
let mut cpu = Cpu::new();
let reg_val: u8 = 0x33;
let acc_val: u8 = 0x0F;
cpu.a = acc_val.into();
cpu.c = reg_val.into();
cpu.ora_operation(0xB1);
assert_eq!(cpu.a, 0x3F);
}
#[test]
fn test_cmp_operation() {
let mut cpu = Cpu::new();
let reg_val: u8 = 0x5;
let acc_val: u8 = 0xA;
cpu.a = acc_val.into();
cpu.e = reg_val.into();
cpu.cmp_operation(0xBB);
assert_eq!(cpu.a, acc_val);
assert_eq!(cpu.e, reg_val);
assert_eq!(cpu.flags.cy, false);
assert_eq!(cpu.flags.z, false);
}
#[test]
fn test_rlc() {
let mut cpu = Cpu::new();
let val: u8 = 0xF2;
cpu.a = val.into();
cpu.rlc();
assert_eq!(cpu.a, 0xE5);
}
#[test]
fn test_rrc() {
let mut cpu = Cpu::new();
let val: u8 = 0xF2;
cpu.a = val.into();
cpu.rrc();
assert_eq!(cpu.a, 0x79);
}
#[test]
fn test_ral() {
let mut cpu = Cpu::new();
cpu.a = (0xB5 as u8).into();
cpu.ral();
assert_eq!(cpu.a, 0x6A);
}
#[test]
fn test_rar() {
let mut cpu = Cpu::new();
cpu.a = (0x6A as u8).into();
cpu.flags.cy = true;
cpu.rar();
assert_eq!(cpu.a, 0xB5);
}
#[test]
fn test_shld() {
let mut cpu = Cpu::new();
cpu.h = (0xAE as u8).into();
cpu.l = (0x29 as u8).into();
let rand: u16 = get_random_number(0xFFFC);
cpu.pc = rand.into();
cpu.memory.ram[(rand + 1) as usize] = 0x0A;
cpu.memory.ram[(rand + 2) as usize] = 0x01;
cpu.shld();
assert_eq!(cpu.memory.ram[0x10A], 0x29);
assert_eq!(cpu.memory.ram[0x10B], 0xAE);
}
#[test]
fn test_daa() {
let mut cpu = Cpu::new();
cpu.a = 0x9Bu8.into();
cpu.daa();
assert_eq!(cpu.a, 1);
}
#[test]
fn test_lhld() {
let mut cpu = Cpu::new();
let rand: u16 = 0x10;
cpu.pc = rand.into();
cpu.memory.ram[(rand + 1) as usize] = 0xCB;
cpu.memory.ram[(rand + 2) as usize] = 0x50;
cpu.memory.ram[0x50CB] = 0xFF;
cpu.memory.ram[0x50CC] = 0x03;
cpu.lhld();
assert_eq!(cpu.h, 0xFF);
assert_eq!(cpu.l, 0x03);
}
#[test]
fn test_cma() {
let mut cpu = Cpu::new();
cpu.a = 0x51u8.into();
cpu.cma();
assert_eq!(cpu.a, 0xAE);
}
#[test]
fn test_sta() {
let mut cpu = Cpu::new();
let rand: u8 = get_random_number(0xFF) as u8;
cpu.a = rand.into();
let pc = get_random_number(0xFFFC);
cpu.pc = pc.into();
cpu.memory.ram[(pc + 1) as usize] = 0x23;
cpu.memory.ram[(pc + 2) as usize] = 0xC8;
cpu.sta();
assert_eq!(cpu.memory.ram[0xC823], rand);
}
#[test]
fn test_stc() {
let mut cpu = Cpu::new();
cpu.stc();
assert_eq!(cpu.flags.cy, true);
}
#[test]
fn test_lda() {
let mut cpu = Cpu::new();
let pc: u8 = get_random_number(0xFFFC) as u8;
cpu.pc = pc.into();
cpu.memory.ram[(pc + 1) as usize] = 0x39;
cpu.memory.ram[(pc + 2) as usize] = 0xB2;
cpu.memory.ram[0xB239] = 0xEE;
cpu.lda();
assert_eq!(cpu.a, 0xEE);
}
#[test]
fn test_cmc() {
let mut cpu = Cpu::new();
cpu.flags.cy = true;
cpu.cmc();
assert_eq!(cpu.flags.cy, false);
cpu.cmc();
assert_eq!(cpu.flags.cy, true);
}
#[test]
fn test_mov_b() {
let mut cpu = Cpu::new();
cpu.c = 0x23u8.into();
cpu.b = 0xAAu8.into();
cpu.mov_b_operation(0x41);
assert_eq!(cpu.b, 0x23);
}
#[test]
fn test_mov_c() {
let mut cpu = Cpu::new();
cpu.d = 0x66u8.into();
cpu.c = 0xE3u8.into();
cpu.mov_c_operation(0x4A);
assert_eq!(cpu.c, 0x66);
}
#[test]
fn test_mov_d() {
let mut cpu = Cpu::new();
cpu.l = 0x01u8.into();
cpu.h = 0xA9u8.into();
cpu.memory.ram[0xA901] = 0x4C;
cpu.d = 0x77u8.into();
cpu.mov_d_operation(0x56);
assert_eq!(cpu.d, 0x4C);
}
#[test]
fn test_pop_non_psw() {
let mut cpu = Cpu::new();
cpu.memory.ram[0x1239] = 0x3D;
cpu.memory.ram[0x123A] = 0x93;
cpu.sp = 0x1239u16.into();
cpu.pop_operation(0xE1);
assert_eq!(cpu.l, 0x3D);
assert_eq!(cpu.h, 0x93);
}
#[test]
fn test_pop_psw() {
let mut cpu = Cpu::new();
cpu.memory.ram[0x2C00] = 0xC3;
cpu.memory.ram[0x2C01] = 0xFF;
cpu.sp = 0x2C00u16.into();
cpu.pop_operation(0xF1);
assert_eq!(cpu.a, 0xFF);
assert_eq!(cpu.flags.s, true);
assert_eq!(cpu.flags.z, true);
assert_eq!(cpu.flags.ac, false);
assert_eq!(cpu.flags.p, false);
assert_eq!(cpu.flags.cy, true);
}
#[test]
fn test_call_subroutine() {
let mut cpu = Cpu::new();
let pc = get_random_number(0xFFFF);
let sp = get_random_number(0xFFFF);
let mem_val_1 = get_random_number(0xFF) as u8;
let mem_val_2 = get_random_number(0xFF) as u8;
let concat = ((mem_val_2 as u16) << 8) | mem_val_1 as u16;
cpu.pc = pc.into();
cpu.sp = sp.into();
cpu.memory.ram[(pc + 2) as usize] = mem_val_2;
cpu.memory.ram[(pc + 1) as usize] = mem_val_1;
cpu.call_subroutine(true);
assert_eq!(cpu.pc, concat);
assert_eq!(cpu.sp, sp - 2);
}
#[test]
fn test_return_from_subroutine() {
let mut cpu = Cpu::new();
let pc = get_random_number(0xFFFF);
let sp = get_random_number(0xFFFF);
cpu.pc = pc.into();
cpu.sp = sp.into();
let msb: u16 = cpu.memory.ram[(sp - 1) as usize].into();
let lsb: u16 = cpu.memory.ram[(sp - 2) as usize].into();
let result = (msb << 8) | lsb;
cpu.return_from_subroutine(true);
assert_eq!(cpu.pc, result);
}
#[test]
fn test_jmp() {
let mut cpu = Cpu::new();
let pc: u8 = get_random_number(0xFFF0) as u8;
cpu.pc = pc.into();
cpu.memory.ram[(pc + 1) as usize] = 0x00;
cpu.memory.ram[(pc + 2) as usize] = 0x3E;
cpu.jump_operation(true);
assert_eq!(u16::from(cpu.pc), 0x3E00);
}
#[test]
fn test_push_operation() {
let mut cpu = Cpu::new();
cpu.d = 0x8Fu8.into();
cpu.e = 0x9Du8.into();
cpu.sp = 0x3A2Cu16.into();
cpu.push_operation(0xD5);
assert_eq!(cpu.sp, 0x3A2A);
assert_eq!(cpu.memory.ram[0x3A2B], 0x8F);
assert_eq!(cpu.memory.ram[0x3A2A], 0x9D);
}
#[test]
fn test_push_operation_psw() {
let mut cpu = Cpu::new();
cpu.a = 0x1Fu8.into();
cpu.sp = 0x502Au16.into();
cpu.flags.cy = true;
cpu.flags.z = true;
cpu.flags.p = true;
cpu.flags.s = false;
cpu.flags.ac = false;
cpu.push_operation(0xF5);
assert_eq!(cpu.sp, 0x5028);
assert_eq!(cpu.memory.ram[0x5029], 0x1F);
assert_eq!(cpu.memory.ram[0x5028], 0x47);
}
#[test]
fn test_adi() {
let mut cpu = Cpu::new();
cpu.a = 0x14u8.into();
let pc = get_random_number(0xFFF0);
cpu.pc = pc.into();
cpu.memory.ram[(pc + 1) as usize] = 0x42u8;
cpu.adi();
assert_eq!(cpu.a, 0x56);
assert_eq!(cpu.flags.p, true);
assert_eq!(cpu.flags.ac, false);
assert_eq!(cpu.flags.cy, false);
assert_eq!(cpu.flags.z, false);
assert_eq!(cpu.flags.s, false);
}
#[test]
fn test_aci_carry_set() {
let mut cpu = Cpu::new();
cpu.flags.cy = true;
cpu.a = 0x14u8.into();
let pc = get_random_number(0xFFF0);
cpu.pc = pc.into();
cpu.memory.ram[(pc + 1) as usize] = 0x42u8;
cpu.aci();
assert_eq!(cpu.a, 0x57);
}
#[test]
fn test_aci_carry_unset() {
let mut cpu = Cpu::new();
cpu.flags.cy = false;
cpu.a = 0x14u8.into();
let pc = get_random_number(0xFFF0);
cpu.pc = pc.into();
cpu.memory.ram[(pc + 1) as usize] = 0x42u8;
cpu.aci();
assert_eq!(cpu.a, 0x56);
}
#[test]
fn test_rst_operation() {
let mut cpu = Cpu::new();
cpu.sp = get_random_number(0xFFF0).into();
cpu.pc = get_random_number(0xFFF0).into();
cpu.rst_operation(0xDF);
assert_eq!(cpu.pc, 0x18);
}
#[test]
fn test_xthl() {
let mut cpu = Cpu::new();
cpu.sp = 0x10ADu16.into();
cpu.h = 0x0Bu8.into();
cpu.l = 0x3Cu8.into();
cpu.memory.ram[0x10AD] = 0xF0;
cpu.memory.ram[0x10AE] = 0x0D;
cpu.xthl();
assert_eq!(cpu.h, 0x0D);
assert_eq!(cpu.l, 0xF0);
assert_eq!(cpu.memory.ram[0x10AD], 0x3C);
assert_eq!(cpu.memory.ram[0x10AE], 0x0B);
}
#[test]
fn test_xchg() {
let mut cpu = Cpu::new();
cpu.h = 0x00u8.into();
cpu.l = 0xFFu8.into();
cpu.d = 0x33u8.into();
cpu.e = 0x55u8.into();
cpu.xchg();
assert_eq!(cpu.h, 0x33);
assert_eq!(cpu.l, 0x55);
assert_eq!(cpu.d, 0x00);
assert_eq!(cpu.e, 0xFF);
}
#[test]
fn test_pchl() {
let mut cpu = Cpu::new();
cpu.l = 0x3Eu8.into();
cpu.h = 0x41u8.into();
cpu.pchl();
assert_eq!(cpu.pc, 0x413E);
}
#[test]
fn test_sphl() {
let mut cpu = Cpu::new();
cpu.h = 0x50u8.into();
cpu.l = 0x6Cu8.into();
cpu.sphl();
assert_eq!(cpu.sp, 0x506C);
}
fn get_random_number(max: u16) -> u16 {
let mut rand = rand::thread_rng();
rand.gen_range(0x0, max)
}
}
|
use std::{ops::Range, path::PathBuf};
use anyhow::Result;
use las_rs::point::Format;
use pasture_core::{
containers::PointBuffer,
containers::{PerAttributeVecPointStorage, PointBufferExt},
layout::attributes,
math::AABB,
nalgebra::{Point3, Vector3},
};
use super::point_layout_from_las_point_format;
/// Returns the path to a LAS test file with the given `format`
pub(crate) fn get_test_las_path(format: u8) -> PathBuf {
let mut test_file_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
test_file_path.push(format!("resources/test/10_points_format_{}.las", format));
test_file_path
}
/// Returns the path to a LAZ test file with the given `format`
pub(crate) fn get_test_laz_path(format: u8) -> PathBuf {
let mut test_file_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
test_file_path.push(format!("resources/test/10_points_format_{}.laz", format));
test_file_path
}
pub(crate) fn format_has_gps_times(format: u8) -> bool {
match format {
1 => true,
3..=10 => true,
_ => false,
}
}
pub(crate) fn format_has_colors(format: u8) -> bool {
match format {
2..=3 => true,
5 => true,
7..=8 => true,
10 => true,
_ => false,
}
}
pub(crate) fn format_has_nir(format: u8) -> bool {
match format {
8 => true,
10 => true,
_ => false,
}
}
pub(crate) fn format_has_wavepacket(format: u8) -> bool {
match format {
4..=5 => true,
9..=10 => true,
_ => false,
}
}
fn format_is_extended(format: u8) -> bool {
format >= 6
}
pub(crate) fn test_data_point_count() -> usize {
10
}
pub(crate) fn test_data_bounds() -> AABB<f64> {
AABB::from_min_max_unchecked(Point3::new(0.0, 0.0, 0.0), Point3::new(9.0, 9.0, 9.0))
}
pub(crate) fn test_data_positions() -> Vec<Vector3<f64>> {
vec![
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(1.0, 1.0, 1.0),
Vector3::new(2.0, 2.0, 2.0),
Vector3::new(3.0, 3.0, 3.0),
Vector3::new(4.0, 4.0, 4.0),
Vector3::new(5.0, 5.0, 5.0),
Vector3::new(6.0, 6.0, 6.0),
Vector3::new(7.0, 7.0, 7.0),
Vector3::new(8.0, 8.0, 8.0),
Vector3::new(9.0, 9.0, 9.0),
]
}
pub(crate) fn test_data_intensities() -> Vec<u16> {
vec![
0,
255,
2 * 255,
3 * 255,
4 * 255,
5 * 255,
6 * 255,
7 * 255,
8 * 255,
9 * 255,
]
}
pub(crate) fn test_data_return_numbers() -> Vec<u8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 0, 1]
}
pub(crate) fn test_data_return_numbers_extended() -> Vec<u8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_number_of_returns() -> Vec<u8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 0, 1]
}
pub(crate) fn test_data_number_of_returns_extended() -> Vec<u8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
fn test_data_classification_flags() -> Vec<u8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
fn test_data_scanner_channels() -> Vec<u8> {
vec![0, 1, 2, 3, 0, 1, 2, 3, 0, 1]
}
pub(crate) fn test_data_scan_direction_flags() -> Vec<bool> {
vec![
false, true, false, true, false, true, false, true, false, true,
]
}
pub(crate) fn test_data_edge_of_flight_lines() -> Vec<bool> {
vec![
false, true, false, true, false, true, false, true, false, true,
]
}
pub(crate) fn test_data_classifications() -> Vec<u8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_scan_angle_ranks() -> Vec<i8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_scan_angles_extended() -> Vec<i16> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_user_data() -> Vec<u8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_point_source_ids() -> Vec<u16> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_gps_times() -> Vec<f64> {
vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
}
pub(crate) fn test_data_colors() -> Vec<Vector3<u16>> {
vec![
Vector3::new(0, 1 << 4, 2 << 8),
Vector3::new(1, 2 << 4, 3 << 8),
Vector3::new(2, 3 << 4, 4 << 8),
Vector3::new(3, 4 << 4, 5 << 8),
Vector3::new(4, 5 << 4, 6 << 8),
Vector3::new(5, 6 << 4, 7 << 8),
Vector3::new(6, 7 << 4, 8 << 8),
Vector3::new(7, 8 << 4, 9 << 8),
Vector3::new(8, 9 << 4, 10 << 8),
Vector3::new(9, 10 << 4, 11 << 8),
]
}
pub(crate) fn test_data_nirs() -> Vec<u16> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_wavepacket_index() -> Vec<u8> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_wavepacket_offset() -> Vec<u64> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_wavepacket_size() -> Vec<u32> {
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
pub(crate) fn test_data_wavepacket_location() -> Vec<f32> {
vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
}
pub(crate) fn test_data_wavepacket_parameters() -> Vec<Vector3<f32>> {
vec![
Vector3::new(1.0, 2.0, 3.0),
Vector3::new(2.0, 3.0, 4.0),
Vector3::new(3.0, 4.0, 5.0),
Vector3::new(4.0, 5.0, 6.0),
Vector3::new(5.0, 6.0, 7.0),
Vector3::new(6.0, 7.0, 8.0),
Vector3::new(7.0, 8.0, 9.0),
Vector3::new(8.0, 9.0, 10.0),
Vector3::new(9.0, 10.0, 11.0),
Vector3::new(10.0, 11.0, 12.0),
]
}
pub(crate) fn compare_to_reference_data_range(
points: &dyn PointBuffer,
point_format: u8,
range: Range<usize>,
) {
let positions = points
.iter_attribute::<Vector3<f64>>(&attributes::POSITION_3D)
.collect::<Vec<_>>();
assert_eq!(
&test_data_positions()[range.clone()],
positions,
"Positions do not match"
);
let intensities = points
.iter_attribute::<u16>(&attributes::INTENSITY)
.collect::<Vec<_>>();
assert_eq!(
&test_data_intensities()[range.clone()],
intensities,
"Intensities do not match"
);
let return_numbers = points
.iter_attribute::<u8>(&attributes::RETURN_NUMBER)
.collect::<Vec<_>>();
let expected_return_numbers = if format_is_extended(point_format) {
test_data_return_numbers_extended()
} else {
test_data_return_numbers()
};
assert_eq!(
&expected_return_numbers[range.clone()],
return_numbers,
"Return numbers do not match"
);
let number_of_returns = points
.iter_attribute::<u8>(&attributes::NUMBER_OF_RETURNS)
.collect::<Vec<_>>();
let expected_number_of_returns = if format_is_extended(point_format) {
test_data_number_of_returns_extended()
} else {
test_data_number_of_returns()
};
assert_eq!(
&expected_number_of_returns[range.clone()],
number_of_returns,
"Number of returns do not match"
);
if format_is_extended(point_format) {
let classification_flags = points
.iter_attribute::<u8>(&attributes::CLASSIFICATION_FLAGS)
.collect::<Vec<_>>();
assert_eq!(
&test_data_classification_flags()[range.clone()],
classification_flags,
"Classification flags do not match"
);
let scanner_channels = points
.iter_attribute::<u8>(&attributes::SCANNER_CHANNEL)
.collect::<Vec<_>>();
assert_eq!(
&test_data_scanner_channels()[range.clone()],
scanner_channels,
"Scanner channels do not match"
);
}
let scan_direction_flags = points
.iter_attribute::<bool>(&attributes::SCAN_DIRECTION_FLAG)
.collect::<Vec<_>>();
assert_eq!(
&test_data_scan_direction_flags()[range.clone()],
scan_direction_flags,
"Scan direction flags do not match"
);
let eof = points
.iter_attribute::<bool>(&attributes::EDGE_OF_FLIGHT_LINE)
.collect::<Vec<_>>();
assert_eq!(
&test_data_edge_of_flight_lines()[range.clone()],
eof,
"Edge of flight lines do not match"
);
let classifications = points
.iter_attribute::<u8>(&attributes::CLASSIFICATION)
.collect::<Vec<_>>();
assert_eq!(
&test_data_classifications()[range.clone()],
classifications,
"Classifications do not match"
);
if point_format < 6 {
let scan_angle_ranks = points
.iter_attribute::<i8>(&attributes::SCAN_ANGLE_RANK)
.collect::<Vec<_>>();
assert_eq!(
&test_data_scan_angle_ranks()[range.clone()],
scan_angle_ranks,
"Scan angle ranks do not match"
);
} else {
let scan_angles = points
.iter_attribute::<i16>(&attributes::SCAN_ANGLE)
.collect::<Vec<_>>();
assert_eq!(
&test_data_scan_angles_extended()[range.clone()],
scan_angles,
"Scan angles do not match"
);
}
let user_data = points
.iter_attribute::<u8>(&attributes::USER_DATA)
.collect::<Vec<_>>();
assert_eq!(
&test_data_user_data()[range.clone()],
user_data,
"User data do not match"
);
let point_source_ids = points
.iter_attribute::<u16>(&attributes::POINT_SOURCE_ID)
.collect::<Vec<_>>();
assert_eq!(
&test_data_point_source_ids()[range.clone()],
point_source_ids,
"Point source IDs do not match"
);
if format_has_gps_times(point_format) {
let gps_times = points
.iter_attribute::<f64>(&attributes::GPS_TIME)
.collect::<Vec<_>>();
assert_eq!(
&test_data_gps_times()[range.clone()],
gps_times,
"GPS times do not match"
);
}
if format_has_colors(point_format) {
let colors = points
.iter_attribute::<Vector3<u16>>(&attributes::COLOR_RGB)
.collect::<Vec<_>>();
assert_eq!(
&test_data_colors()[range.clone()],
colors,
"Colors do not match"
);
}
if format_has_nir(point_format) {
let nirs = points
.iter_attribute::<u16>(&attributes::NIR)
.collect::<Vec<_>>();
assert_eq!(
&test_data_nirs()[range.clone()],
nirs,
"NIR values do not match"
);
}
if format_has_wavepacket(point_format) {
let wp_indices = points
.iter_attribute::<u8>(&attributes::WAVE_PACKET_DESCRIPTOR_INDEX)
.collect::<Vec<_>>();
assert_eq!(
&test_data_wavepacket_index()[range.clone()],
wp_indices,
"Wave Packet Descriptor Indices do not match"
);
let wp_offsets = points
.iter_attribute::<u64>(&attributes::WAVEFORM_DATA_OFFSET)
.collect::<Vec<_>>();
assert_eq!(
&test_data_wavepacket_offset()[range.clone()],
wp_offsets,
"Waveform data offsets do not match"
);
let wp_sizes = points
.iter_attribute::<u32>(&attributes::WAVEFORM_PACKET_SIZE)
.collect::<Vec<_>>();
assert_eq!(
&test_data_wavepacket_size()[range.clone()],
wp_sizes,
"Waveform packet sizes do not match"
);
let wp_return_points = points
.iter_attribute::<f32>(&attributes::RETURN_POINT_WAVEFORM_LOCATION)
.collect::<Vec<_>>();
assert_eq!(
&test_data_wavepacket_location()[range.clone()],
wp_return_points,
"WAveform return point locations do not match"
);
let wp_parameters = points
.iter_attribute::<Vector3<f32>>(&attributes::WAVEFORM_PARAMETERS)
.collect::<Vec<_>>();
assert_eq!(
&test_data_wavepacket_parameters()[range.clone()],
wp_parameters,
"Waveform parameters do not match"
);
}
}
/// Compare the `points` in the given `point_format` to the reference data for the format
pub(crate) fn compare_to_reference_data(points: &dyn PointBuffer, point_format: u8) {
compare_to_reference_data_range(points, point_format, 0..test_data_point_count());
}
pub(crate) fn get_test_points_in_las_format(point_format: u8) -> Result<Box<dyn PointBuffer>> {
let format = Format::new(point_format)?;
let layout = point_layout_from_las_point_format(&format)?;
let mut buffer = PerAttributeVecPointStorage::with_capacity(10, layout);
let mut pusher = buffer.begin_push_attributes();
pusher.push_attribute_range(&attributes::POSITION_3D, test_data_positions().as_slice());
pusher.push_attribute_range(&attributes::INTENSITY, test_data_intensities().as_slice());
if format.is_extended {
pusher.push_attribute_range(
&attributes::RETURN_NUMBER,
test_data_return_numbers_extended().as_slice(),
);
pusher.push_attribute_range(
&attributes::NUMBER_OF_RETURNS,
test_data_number_of_returns_extended().as_slice(),
);
pusher.push_attribute_range(
&attributes::CLASSIFICATION_FLAGS,
test_data_classification_flags().as_slice(),
);
pusher.push_attribute_range(
&attributes::SCANNER_CHANNEL,
test_data_scanner_channels().as_slice(),
);
} else {
pusher.push_attribute_range(
&attributes::RETURN_NUMBER,
test_data_return_numbers().as_slice(),
);
pusher.push_attribute_range(
&attributes::NUMBER_OF_RETURNS,
test_data_number_of_returns().as_slice(),
);
}
pusher.push_attribute_range(
&attributes::SCAN_DIRECTION_FLAG,
test_data_scan_direction_flags().as_slice(),
);
pusher.push_attribute_range(
&attributes::EDGE_OF_FLIGHT_LINE,
test_data_edge_of_flight_lines().as_slice(),
);
pusher.push_attribute_range(
&attributes::CLASSIFICATION,
test_data_classifications().as_slice(),
);
if format.is_extended {
pusher.push_attribute_range(&attributes::USER_DATA, test_data_user_data().as_slice());
pusher.push_attribute_range(
&attributes::SCAN_ANGLE,
test_data_scan_angles_extended().as_slice(),
);
} else {
pusher.push_attribute_range(
&attributes::SCAN_ANGLE_RANK,
test_data_scan_angle_ranks().as_slice(),
);
pusher.push_attribute_range(&attributes::USER_DATA, test_data_user_data().as_slice());
}
pusher.push_attribute_range(
&attributes::POINT_SOURCE_ID,
test_data_point_source_ids().as_slice(),
);
if format.has_gps_time {
pusher.push_attribute_range(&attributes::GPS_TIME, test_data_gps_times().as_slice());
}
if format.has_color {
pusher.push_attribute_range(&attributes::COLOR_RGB, test_data_colors().as_slice());
}
if format.has_nir {
pusher.push_attribute_range(&attributes::NIR, test_data_nirs().as_slice());
}
if format.has_waveform {
pusher.push_attribute_range(
&attributes::WAVE_PACKET_DESCRIPTOR_INDEX,
test_data_wavepacket_index().as_slice(),
);
pusher.push_attribute_range(
&attributes::WAVEFORM_DATA_OFFSET,
test_data_wavepacket_offset().as_slice(),
);
pusher.push_attribute_range(
&attributes::WAVEFORM_PACKET_SIZE,
test_data_wavepacket_size().as_slice(),
);
pusher.push_attribute_range(
&attributes::RETURN_POINT_WAVEFORM_LOCATION,
test_data_wavepacket_location().as_slice(),
);
pusher.push_attribute_range(
&attributes::WAVEFORM_PARAMETERS,
test_data_wavepacket_parameters().as_slice(),
);
}
pusher.done();
Ok(Box::new(buffer))
}
pub(crate) fn _epsilon_compare_vec3f32(expected: &Vector3<f32>, actual: &Vector3<f32>) -> bool {
const EPSILON: f32 = 1e-5;
let dx = (expected.x - actual.x).abs();
let dy = (expected.y - actual.y).abs();
let dz = (expected.z - actual.z).abs();
dx <= EPSILON && dy <= EPSILON && dz <= EPSILON
}
pub(crate) fn epsilon_compare_vec3f64(expected: &Vector3<f64>, actual: &Vector3<f64>) -> bool {
const EPSILON: f64 = 1e-7;
let dx = (expected.x - actual.x).abs();
let dy = (expected.y - actual.y).abs();
let dz = (expected.z - actual.z).abs();
dx <= EPSILON && dy <= EPSILON && dz <= EPSILON
}
pub(crate) fn epsilon_compare_point3f64(expected: &Point3<f64>, actual: &Point3<f64>) -> bool {
const EPSILON: f64 = 1e-7;
let dx = (expected.x - actual.x).abs();
let dy = (expected.y - actual.y).abs();
let dz = (expected.z - actual.z).abs();
dx <= EPSILON && dy <= EPSILON && dz <= EPSILON
}
|
fn run_program(ops: &mut [u32]) -> bool {
let mut position = 0;
loop {
let instruction = ops[position];
match instruction {
1 => {
// Add
let arg1 = ops[ops[position + 1] as usize];
let arg2 = ops[ops[position + 2] as usize];
let output_pos = ops[position + 3];
ops[output_pos as usize] = arg1 + arg2;
}
2 => {
// Multiply
let arg1 = ops[ops[position + 1] as usize];
let arg2 = ops[ops[position + 2] as usize];
let output_pos = ops[position + 3];
ops[output_pos as usize] = arg1 * arg2;
}
99 => {
// End
break true;
}
_ => {
break false;
}
}
position += 4;
}
}
fn main() {
let input = include_str!("../input/day2.txt");
let original_input = input.split(',').map(|s| s.parse::<u32>()).flatten().collect::<Vec<_>>();
for verb in 0..=99 {
for noun in 0..=99 {
let mut opcodes = original_input.clone();
opcodes[1] = noun;
opcodes[2] = verb;
if run_program(&mut opcodes) {
if opcodes[0] == 19690720 {
println!("noun: {} verb: {}", noun, verb);
// break
}
}
else {
println!("Bad program");
}
}
}
} |
#[doc = "Register `PRIVCFGR2` reader"]
pub type R = crate::R<PRIVCFGR2_SPEC>;
#[doc = "Register `PRIVCFGR2` writer"]
pub type W = crate::W<PRIVCFGR2_SPEC>;
#[doc = "Field `PRIV37` reader - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV37_R = crate::BitReader;
#[doc = "Field `PRIV37` writer - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV37_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV38` reader - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV38_R = crate::BitReader;
#[doc = "Field `PRIV38` writer - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV38_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV39` reader - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV39_R = crate::BitReader;
#[doc = "Field `PRIV39` writer - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV39_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV40` reader - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV40_R = crate::BitReader;
#[doc = "Field `PRIV40` writer - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV40_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV41` reader - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV41_R = crate::BitReader;
#[doc = "Field `PRIV41` writer - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV41_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV42` reader - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV42_R = crate::BitReader;
#[doc = "Field `PRIV42` writer - Privilege enable on event input x (x = 42 to 37)"]
pub type PRIV42_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV47` reader - Privilege enable on event input x"]
pub type PRIV47_R = crate::BitReader;
#[doc = "Field `PRIV47` writer - Privilege enable on event input x"]
pub type PRIV47_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV49` reader - Privilege enable on event input x (x = 50 to 49)"]
pub type PRIV49_R = crate::BitReader;
#[doc = "Field `PRIV49` writer - Privilege enable on event input x (x = 50 to 49)"]
pub type PRIV49_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV50` reader - Privilege enable on event input x (x = 50 to 49)"]
pub type PRIV50_R = crate::BitReader;
#[doc = "Field `PRIV50` writer - Privilege enable on event input x (x = 50 to 49)"]
pub type PRIV50_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PRIV53` reader - Privilege enable on event input x"]
pub type PRIV53_R = crate::BitReader;
#[doc = "Field `PRIV53` writer - Privilege enable on event input x"]
pub type PRIV53_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 5 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
pub fn priv37(&self) -> PRIV37_R {
PRIV37_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
pub fn priv38(&self) -> PRIV38_R {
PRIV38_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
pub fn priv39(&self) -> PRIV39_R {
PRIV39_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
pub fn priv40(&self) -> PRIV40_R {
PRIV40_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
pub fn priv41(&self) -> PRIV41_R {
PRIV41_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
pub fn priv42(&self) -> PRIV42_R {
PRIV42_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 15 - Privilege enable on event input x"]
#[inline(always)]
pub fn priv47(&self) -> PRIV47_R {
PRIV47_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 17 - Privilege enable on event input x (x = 50 to 49)"]
#[inline(always)]
pub fn priv49(&self) -> PRIV49_R {
PRIV49_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - Privilege enable on event input x (x = 50 to 49)"]
#[inline(always)]
pub fn priv50(&self) -> PRIV50_R {
PRIV50_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 21 - Privilege enable on event input x"]
#[inline(always)]
pub fn priv53(&self) -> PRIV53_R {
PRIV53_R::new(((self.bits >> 21) & 1) != 0)
}
}
impl W {
#[doc = "Bit 5 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
#[must_use]
pub fn priv37(&mut self) -> PRIV37_W<PRIVCFGR2_SPEC, 5> {
PRIV37_W::new(self)
}
#[doc = "Bit 6 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
#[must_use]
pub fn priv38(&mut self) -> PRIV38_W<PRIVCFGR2_SPEC, 6> {
PRIV38_W::new(self)
}
#[doc = "Bit 7 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
#[must_use]
pub fn priv39(&mut self) -> PRIV39_W<PRIVCFGR2_SPEC, 7> {
PRIV39_W::new(self)
}
#[doc = "Bit 8 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
#[must_use]
pub fn priv40(&mut self) -> PRIV40_W<PRIVCFGR2_SPEC, 8> {
PRIV40_W::new(self)
}
#[doc = "Bit 9 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
#[must_use]
pub fn priv41(&mut self) -> PRIV41_W<PRIVCFGR2_SPEC, 9> {
PRIV41_W::new(self)
}
#[doc = "Bit 10 - Privilege enable on event input x (x = 42 to 37)"]
#[inline(always)]
#[must_use]
pub fn priv42(&mut self) -> PRIV42_W<PRIVCFGR2_SPEC, 10> {
PRIV42_W::new(self)
}
#[doc = "Bit 15 - Privilege enable on event input x"]
#[inline(always)]
#[must_use]
pub fn priv47(&mut self) -> PRIV47_W<PRIVCFGR2_SPEC, 15> {
PRIV47_W::new(self)
}
#[doc = "Bit 17 - Privilege enable on event input x (x = 50 to 49)"]
#[inline(always)]
#[must_use]
pub fn priv49(&mut self) -> PRIV49_W<PRIVCFGR2_SPEC, 17> {
PRIV49_W::new(self)
}
#[doc = "Bit 18 - Privilege enable on event input x (x = 50 to 49)"]
#[inline(always)]
#[must_use]
pub fn priv50(&mut self) -> PRIV50_W<PRIVCFGR2_SPEC, 18> {
PRIV50_W::new(self)
}
#[doc = "Bit 21 - Privilege enable on event input x"]
#[inline(always)]
#[must_use]
pub fn priv53(&mut self) -> PRIV53_W<PRIVCFGR2_SPEC, 21> {
PRIV53_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "EXTI privilege configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`privcfgr2::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 [`privcfgr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PRIVCFGR2_SPEC;
impl crate::RegisterSpec for PRIVCFGR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`privcfgr2::R`](R) reader structure"]
impl crate::Readable for PRIVCFGR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`privcfgr2::W`](W) writer structure"]
impl crate::Writable for PRIVCFGR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PRIVCFGR2 to value 0"]
impl crate::Resettable for PRIVCFGR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[feature(globs)];
#[link_args="-lJudy"];
use capi::*;
use std::ptr::{mut_null,to_unsafe_ptr};
use std::cast;
use std::sys::size_of;
pub mod capi {
use std::libc::{c_void, c_int, c_ulong};
pub type Pvoid_t = *mut c_void;
pub type PPvoid_t = *mut Pvoid_t;
pub type Pcvoid_t = *c_void;
pub type Word_t = c_ulong;
pub type PWord_t = *Word_t;
pub type JU_Errno_t = c_int;
pub static JU_ERRNO_NONE: JU_Errno_t = 0;
pub static JU_ERRNO_FULL: JU_Errno_t = 1;
pub static JU_ERRNO_NFMAX: JU_Errno_t = JU_ERRNO_FULL;
pub static JU_ERRNO_NOMEM: JU_Errno_t = 2;
pub static JU_ERRNO_NULLPPARRAY: JU_Errno_t = 3;
pub static JU_ERRNO_NONNULLPARRAY: JU_Errno_t = 10;
pub static JU_ERRNO_NULLPINDEX: JU_Errno_t = 4;
pub static JU_ERRNO_NULLPVALUE: JU_Errno_t = 11;
pub static JU_ERRNO_NOTJUDY1: JU_Errno_t = 5;
pub static JU_ERRNO_NOTJUDYL: JU_Errno_t = 6;
pub static JU_ERRNO_NOTJUDYSL: JU_Errno_t = 7;
pub static JU_ERRNO_UNSORTED: JU_Errno_t = 12;
pub static JU_ERRNO_OVERRUN: JU_Errno_t = 8;
pub static JU_ERRNO_CORRUPT: JU_Errno_t = 9;
pub struct JError_t {
je_Errno: JU_Errno_t,
je_ErrID: c_int,
je_reserved: [Word_t, ..4],
}
pub type PJError_t = *mut JError_t;
impl JError_t {
pub fn new() -> JError_t {
JError_t{
je_Errno: JU_ERRNO_NONE,
je_ErrID: 0,
je_reserved: [0, ..4],
}
}
}
extern {
pub fn JudyHSGet(array: Pcvoid_t, key: *c_void, size: Word_t) -> PPvoid_t;
pub fn JudyHSIns(array: PPvoid_t, key: *c_void, size: Word_t, err: PJError_t) -> PPvoid_t;
pub fn JudyHSDel(array: PPvoid_t, key: *c_void, size: Word_t, err: PJError_t) -> c_int;
pub fn JudyHSFreeArray(array: PPvoid_t, err: PJError_t) -> Word_t;
pub fn JudyLIns(array: PPvoid_t, index: Word_t, err: PJError_t) -> PPvoid_t;
pub fn JudyLDel(array: PPvoid_t, index: Word_t, err: PJError_t) -> c_int;
pub fn JudyLGet(array: Pcvoid_t, index: Word_t, err: PJError_t) -> PPvoid_t;
pub fn JudyLCount(array: Pcvoid_t, index1: Word_t, index2: Word_t, err: PJError_t) -> Word_t;
pub fn JudyLByCount(array: Pcvoid_t, nth: Word_t, pindex: *Word_t, err: PJError_t) -> PPvoid_t;
pub fn JudyLFreeArray(array: PPvoid_t, err: PJError_t) -> Word_t;
pub fn JudyLMemUsed(array: Pcvoid_t) -> Word_t;
pub fn JudyLFirst(array: Pcvoid_t, pindex: *Word_t, err: PJError_t) -> PPvoid_t;
pub fn JudyLNext(array: Pcvoid_t, pindex: *Word_t, err: PJError_t) -> PPvoid_t;
pub fn JudyLLast(array: Pcvoid_t, pindex: *Word_t, err: PJError_t) -> PPvoid_t;
pub fn JudyLPrev(array: Pcvoid_t, pindex: *Word_t, err: PJError_t) -> PPvoid_t;
pub fn JudyLFirstEmpty(array: Pcvoid_t, pindex: *Word_t, err: PJError_t) -> c_int;
pub fn JudyLNextEmpty(array: Pcvoid_t, pindex: *Word_t, err: PJError_t) -> c_int;
pub fn JudyLLastEmpty(array: Pcvoid_t, pindex: *Word_t, err: PJError_t) -> c_int;
pub fn JudyLPrevEmpty(array: Pcvoid_t, pindex: *Word_t, err: PJError_t) -> c_int;
}
}
struct JudyL<V> {
m: Pvoid_t,
}
impl<V> JudyL<V> {
fn new() -> JudyL<V> {
JudyL{m: mut_null()}
}
#[fixed_stack_segment]
fn insert(&mut self, index: Word_t, value: ~V) -> bool {
unsafe {
let v = JudyLIns(&mut self.m, index, mut_null());
if v == mut_null() {
false
} else if *v != mut_null() {
false
} else {
*v = cast::transmute(value);
true
}
}
}
#[fixed_stack_segment]
fn get<'a>(&'a self, index: Word_t) -> Option<&'a V> {
unsafe {
let v = JudyLGet(self.m as Pcvoid_t, index, mut_null());
if v == mut_null() {
None
} else {
Some(cast::transmute(*v))
}
}
}
#[fixed_stack_segment]
fn free(&mut self) -> Word_t {
if self.m != mut_null() {
unsafe {
JudyLFreeArray(&mut self.m, mut_null())
}
//assert!(self.m == mut_null());
} else {
0
}
}
fn iter<'a>(&'a self) -> JudyLIterator<'a, V> {
JudyLIterator{ m: self.m as Pcvoid_t, i: 0, lifetime: None}
}
#[fixed_stack_segment]
fn count(&self, index1: Word_t, index2: Word_t) -> Word_t {
unsafe {
JudyLCount(self.m as Pcvoid_t, index1, index2, mut_null())
}
}
}
struct JudyHS<K, V> {
m: Pvoid_t,
}
impl<K, V> JudyHS<K, V> {
fn new() -> JudyHS<K, V> {
JudyHS{m: mut_null()}
}
#[fixed_stack_segment]
fn insert(&mut self, key: K, value: ~V) -> bool {
unsafe {
let v = JudyHSIns(&mut self.m, to_unsafe_ptr(&key) as Pcvoid_t, size_of::<K>() as Word_t, mut_null());
if v == mut_null() {
false
} else if *v != mut_null() {
false
} else {
*v = cast::transmute(value);
true
}
}
}
#[fixed_stack_segment]
fn get<'a>(&'a self, key: K) -> Option<&'a V> {
unsafe {
let v = JudyHSGet(self.m as Pcvoid_t, to_unsafe_ptr(&key) as Pcvoid_t, size_of::<K>() as Word_t);
if v == mut_null() {
None
} else {
Some(cast::transmute(*v))
}
}
}
#[fixed_stack_segment]
fn free(&mut self) -> Word_t {
if self.m != mut_null() {
unsafe { JudyHSFreeArray(&mut self.m, mut_null()) }
//assert!(self.m == mut_null());
} else {
0
}
}
}
#[deriving(Clone)]
struct JudyLIterator<'self, V> {
priv m: Pcvoid_t,
priv i: Word_t,
priv lifetime: Option<&'self ()> // FIXME: #5922
}
impl<'self, V> Iterator<(Word_t, &'self V)> for JudyLIterator<'self, V> {
#[fixed_stack_segment]
fn next(&mut self) -> Option<(Word_t, &'self V)> {
unsafe {
let v = JudyLNext(self.m, &self.i, mut_null());
if v == mut_null() {
None
} else {
Some((self.i, cast::transmute(*v)))
}
}
}
}
impl<'self, V> RandomAccessIterator<(Word_t, &'self V)> for JudyLIterator<'self, V> {
#[fixed_stack_segment]
fn indexable(&self) -> uint {
unsafe {
JudyLCount(self.m, 0, -1, mut_null()) as uint
}
}
#[fixed_stack_segment]
fn idx(&self, index: uint) -> Option<(Word_t, &'self V)> {
unsafe {
// TODO: maybe JudyLByCount would be better here?
let v = JudyLGet(self.m, index as Word_t, mut_null());
if v == mut_null() {
None
} else {
Some((index as Word_t, cast::transmute(*v)))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_JudyHS() {
let mut h = JudyHS::<int, int>::new();
assert!(h.insert(123, ~456));
match h.get(123) {
Some(x) => assert_eq!(456, *x),
None => fail!(),
}
assert!(h.free() > 0);
}
#[test]
fn test_JudyL() {
let mut h = JudyL::<int>::new();
assert!(h.insert(123, ~456));
match h.get(123) {
Some(x) => assert_eq!(456, *x),
None => fail!(),
}
for (i, v) in h.iter() {
debug2!("i: {:?} v: {:?}", i, v);
}
assert!(h.free() > 0);
}
}
|
// _ _
// | |_| |__ ___ ___ __ _
// | __| '_ \ / _ \/ __/ _` |
// | |_| | | | __/ (_| (_| |
// \__|_| |_|\___|\___\__,_|
//
// licensed under the MIT license <http://opensource.org/licenses/MIT>
//
// util.rs
// various utility functions for doings things we need to do.
// std imports
use std::fs::{PathExt, read_dir, File};
use std::io::{Write, Read};
use std::os::errno;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::env::{var, home_dir};
use std::cmp::{Ordering};
use std::iter::{repeat};
// time imports
use time::{get_time};
use time::{strftime, strptime, at, Tm};
// term imports
use term::{stdout};
use term::attr::Attr::{Bold};
// json imports
use rustc_serialize::json::{as_pretty_json, decode};
// tempdir imports
use tempdir::{TempDir};
// old imports
use std::old_io::stdio::{stdin};
use std::old_io::{IoError};
// theca imports
use ::{DATEFMT, DATEFMT_SHORT, ThecaItem, ThecaProfile};
use errors::{ThecaError, GenericError};
use lineformat::{LineFormat};
pub use libc::{
STDIN_FILENO,
STDOUT_FILENO,
STDERR_FILENO
};
// c calls for TIOCGWINSZ
pub mod c {
extern crate libc;
pub use self::libc::{
c_int,
c_uint,
c_ushort,
c_ulong,
c_uchar,
STDOUT_FILENO,
isatty
};
use std::mem::zeroed;
#[derive(Copy)]
pub struct Winsize {
pub ws_row: c_ushort,
pub ws_col: c_ushort
}
#[repr(C)]
#[derive(Copy)]
pub struct Termios {
pub c_iflag: c_uint,
pub c_oflag: c_uint,
pub c_cflag: c_uint,
pub c_lflag: c_uint,
pub c_line: c_uchar,
pub c_cc: [c_uchar; 32usize],
pub c_ispeed: c_uint,
pub c_ospeed: c_uint,
}
impl Termios {
pub fn new() -> Termios {
unsafe {zeroed()}
}
}
pub fn tcgetattr(fd: c_int, termios_p: &mut Termios) -> c_int {
extern {fn tcgetattr(fd: c_int, termios_p: *mut Termios) -> c_int;}
unsafe {tcgetattr(fd, termios_p as *mut _)}
}
pub fn tcsetattr(
fd: c_int,
optional_actions: c_int,
termios_p: &Termios
) -> c_int {
extern {fn tcsetattr(fd: c_int, optional_actions: c_int,
termios_p: *const Termios) -> c_int;}
unsafe {tcsetattr(fd, optional_actions, termios_p as *const _)}
}
pub const ECHO:c_uint = 8;
pub const TCSANOW: c_int = 0;
#[cfg(any(target_os = "linux", target_os = "android"))]
static TIOCGWINSZ: c_ulong = 0x5413;
#[cfg(any(target_os = "macos", target_os = "ios"))]
static TIOCGWINSZ: c_ulong = 0x40087468;
extern {
pub fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
}
pub unsafe fn dimensions() -> Winsize {
let mut window: Winsize = zeroed();
ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window as *mut Winsize);
window
}
pub fn istty(fd: c_int) -> bool {
let isit = unsafe {isatty(fd as i32)};
isit != 0
}
}
fn set_term_echo(echo: bool) -> Result<(), ThecaError> {
let mut t = c::Termios::new();
try_errno!(c::tcgetattr(STDIN_FILENO, &mut t));
match echo {
true => t.c_lflag |= c::ECHO, // on
false => t.c_lflag &= !c::ECHO // off
};
try_errno!(c::tcsetattr(STDIN_FILENO, c::TCSANOW, &mut t));
Ok(())
}
// unsafety wrapper
pub fn termsize() -> usize {
let ws = unsafe {c::dimensions()};
if ws.ws_col <= 0 || ws.ws_row <= 0 {
0
}
else {
ws.ws_col as usize
}
}
pub fn drop_to_editor(contents: &String) -> Result<String, ThecaError> {
// setup temporary directory
let tmpdir = try!(TempDir::new("theca"));
// setup temporary file to write/read
let tmppath = tmpdir.path().join(&format!("{}", get_time().sec)[..]);
let mut tmpfile = try!(File::create(&tmppath));
// let mut tmpfile = try!(File::open_mode(&tmppath, Open, ReadWrite));
try!(tmpfile.write_all(contents.as_bytes()));
let editor = match var("VISUAL") {
Ok(v) => v,
Err(_) => match var("EDITOR") {
Ok(v) => v,
Err(_) => specific_fail_str!("neither $VISUAL nor $EDITOR is set.")
}
};
// lets start `editor` and edit the file at `tmppath`
// first we need to set STDIN, STDOUT, and STDERR to those that theca is
// currently using so we can display the editor
let mut editor_command = Command::new(&editor);
editor_command.arg(&tmppath.display().to_string());
editor_command.stdin(Stdio::inherit());
editor_command.stdout(Stdio::inherit());
editor_command.stderr(Stdio::inherit());
let editor_proc = editor_command.spawn();
match try!(editor_proc).wait().is_ok() {
true => {
// finished editing, time to read `tmpfile` for the final output
let mut tmpfile = try!(File::open(&tmppath));
let mut content = String::new();
try!(tmpfile.read_to_string(&mut content));
Ok(content)
}
false => specific_fail_str!("the editor broke... I think")
}
}
pub fn get_password() -> Result<String, ThecaError> {
// should really turn off terminal echo...
print!("Key: ");
let tty = c::istty(STDIN_FILENO);
if tty {try!(set_term_echo(false));}
let mut stdin = stdin();
// since this only reads one line of stdin it could still feasibly
// be used with `-` to set note body?
let key = try!(stdin.read_line());
if tty {try!(set_term_echo(true));}
println!("");
Ok(key.trim().to_string())
}
pub fn get_yn_input() -> Result<bool, ThecaError> {
let mut stdin = stdin();
let mut answer;
let yes = vec!["y", "Y", "yes", "YES", "Yes"];
let no = vec!["n", "N", "no", "NO", "No"];
loop {
print!("[y/n]# ");
let mut input = try!(stdin.read_line());
input = input.trim().to_string();
match yes.iter().any(|n| &n[..] == input) {
true => {
answer = true;
break;
},
false => {
match no.iter().any(|n| &n[..] == input) {
true => {
answer = false;
break;
},
false => ()
}
}
};
println!("invalid input.");
}
Ok(answer)
}
pub fn pretty_line(
bold: &str,
plain: &String,
tty: bool
) -> Result<(), ThecaError> {
let mut t = match stdout() {
Some(t) => t,
None => specific_fail_str!("could not retrieve standard output.")
};
if tty {try!(t.attr(Bold));}
try!(write!(t, "{}", bold.to_string()));
if tty {try!(t.reset());}
try!(write!(t, "{}", plain));
Ok(())
}
pub fn format_field(value: &String, width: usize, truncate: bool) -> String {
if value.len() > width && width > 3 && truncate {
format!("{: <1$.1$}...", value, width-3)
} else {
format!("{: <1$.1$}", value, width)
}
}
fn print_header(line_format: &LineFormat) -> Result<(), ThecaError> {
let mut t = match stdout() {
Some(t) => t,
None => specific_fail_str!("could not retrieve standard output.")
};
let column_seperator: String = repeat(' ').take(line_format.colsep)
.collect();
let header_seperator: String = repeat('-').take(line_format.line_width())
.collect();
let tty = c::istty(STDOUT_FILENO);
let status = match line_format.status_width == 0 {
true => "".to_string(),
false => format_field(
&"status".to_string(),
line_format.status_width,
false
)+&*column_seperator
};
if tty {try!(t.attr(Bold));}
try!(write!(
t,
"{1}{0}{2}{0}{3}{4}\n{5}\n",
column_seperator,
format_field(&"id".to_string(), line_format.id_width, false),
format_field(
&"title".to_string(),
line_format.title_width,
false
),
status,
format_field(
&"last touched".to_string(),
line_format.touched_width,
false
),
header_seperator
));
if tty {try!(t.reset());}
Ok(())
}
pub fn sorted_print(
notes: &mut Vec<ThecaItem>,
limit: usize,
condensed: bool,
json: bool,
datesort: bool,
reverse: bool,
search_body: bool,
no_status: bool,
started_status: bool,
urgent_status: bool
) -> Result<(), ThecaError> {
if no_status {
notes.retain(|n| n.status == "");
} else if started_status {
notes.retain(|n| n.status == "Started");
} else if urgent_status {
notes.retain(|n| n.status == "Urgent");
}
let limit = match limit != 0 && notes.len() >= limit {
true => limit,
false => notes.len()
};
if datesort {
notes.sort_by(|a, b| match cmp_last_touched(
&*a.last_touched,
&*b.last_touched
) {
Ok(o) => o,
Err(_) => a.last_touched.cmp(&b.last_touched)
});
}
match json {
false => {
if reverse {notes.reverse();}
let line_format = try!(LineFormat::new(¬es[0..limit].to_vec(), condensed, search_body));
if !condensed && !json {
try!(print_header(&line_format));
}
for n in notes[0..limit].iter() {
try!(n.print(&line_format, search_body));
}
},
true => {
if reverse { notes.reverse(); }
println!("{}", as_pretty_json(¬es[0..limit].to_vec()))
}
};
Ok(())
}
pub fn find_profile_folder(
profile_folder: &String
) -> Result<PathBuf, ThecaError> {
if !profile_folder.is_empty() {
Ok(PathBuf::new(profile_folder))
} else {
match home_dir() {
Some(ref p) => Ok(p.join(".theca")),
None => specific_fail_str!("failed to find your home directory")
}
}
}
pub fn parse_last_touched(lt: &str) -> Result<Tm, ThecaError> {
Ok(at(try!(strptime(lt, DATEFMT)).to_timespec()))
}
pub fn localize_last_touched_string(lt: &str) -> Result<String, ThecaError> {
let t = try!(parse_last_touched(lt));
Ok(try!(strftime(DATEFMT_SHORT, &t)))
}
pub fn cmp_last_touched(a: &str, b: &str) -> Result<Ordering, ThecaError> {
let a_tm = try!(parse_last_touched(a));
let b_tm = try!(parse_last_touched(b));
Ok(a_tm.cmp(&b_tm))
}
pub fn validate_profile_from_path(profile_path: &PathBuf) -> (bool, bool) {
// return (is_a_profile, encrypted(?))
match profile_path.extension().unwrap() == "json" {
true => match File::open(profile_path) {
Ok(mut f) => {
let mut contents_buf: Vec<u8> = vec![];
match f.read_to_end(&mut contents_buf) {
Ok(c) => c,
// nopnopnopppppp
Err(_) => return (false, false)
};
match String::from_utf8(contents_buf) {
Ok(s) => {
// well it's a .json and valid utf-8 at least
match decode::<ThecaProfile>(&*s) {
// yup
Ok(_) => return (true, false),
// noooooop
Err(_) => return (false, false)
};
},
// possibly encrypted
Err(_) => return (true, true)
}
},
// nooppp
Err(_) => return (false, false)
},
// noooppp
false => return (false, false)
};
}
// this is pretty gross
pub fn path_to_profile_name(profile_path: &PathBuf) -> Result<String, ThecaError> {
let just_f = profile_path.file_stem().unwrap();
Ok(just_f.to_str().unwrap().to_string())
}
pub fn profiles_in_folder(folder: &Path) -> Result<(), ThecaError> {
if folder.is_dir() {
println!("# profiles in {}", folder.display());
for file in try!(read_dir(folder)) {
let file = try!(file);
let is_prof = validate_profile_from_path(&file.path());
if is_prof.0 {
let mut msg = try!(path_to_profile_name(&file.path()));
if is_prof.1 {
msg = format!("{} [encrypted]", msg);
}
println!(" {}", msg);
}
}
}
Ok(())
}
|
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#![allow(unused_must_use)]
extern crate rustls;
extern crate bytes;
extern crate webpki;
extern crate webpki_roots;
extern crate mio;
use bytes::{Bytes, BytesMut, Buf, BufMut, IntoBuf, BigEndian};
use header::rustls::{Session, ProtocolVersion};
use header::rustls::internal::msgs::handshake::{ClientHelloPayload, ClientExtension, ConvertProtocolNameList, ProtocolNameList, SessionID, Random};
use header::rustls::internal::msgs::enums::{Compression, CipherSuite};
use header::webpki::DNSNameRef;
use mio::net::UdpSocket;
use std::sync::Arc;
use std::str::from_utf8;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::Read;
use std::io::Write;
use std::io::Error;
use std::io::stdout;
use std::io::{self, BufReader};
use std::io::prelude::*;
use std::fs::File;
use std::result::Result;
use std::convert::AsRef;
use std::string::String;
use std::fmt;
use mio::{Poll, Ready, Token, PollOpt};
/// Buffer for holding connection-specific TLS messages
pub struct ConnectionBuffer{
pub buf : [u8;10000],
pub offset : usize
}
impl fmt::Debug for ConnectionBuffer{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", &self.buf[0..self.offset])
}
}
/// Socket which can hold client or server address info (ie. SocketAddr of intended recipient)
pub struct QuicSocket {
pub sock : UdpSocket,
pub addr : SocketAddr,
}
/// Calls recv_from on UDP socket
impl Read for QuicSocket {
fn read (&mut self, mut output : &mut [u8]) -> Result<usize, Error> {
let res = UdpSocket::recv_from(&mut self.sock, output)?;
self.addr = res.1;
Ok(res.0)
}
}
/// Calls send_to on UDP socket
///
/// Implemented as write trait to mimic writing to a stream
impl Write for QuicSocket {
fn write(&mut self, input : &[u8]) -> Result<usize, Error>{
UdpSocket::send_to(&mut self.sock, input, &self.addr)?;
Ok(input.len())
}
//TODO: find fix for this - problems with infinite recursion
fn flush(&mut self) -> Result<(), Error>{
&mut self.flush()?;
Ok(())
}
}
/*
impl mio::Evented for QuicSocket {
fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
self.sock.selector_id.associate_selector(poll)?;
self.sock.sys.register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
self.sock.sys.reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
self.sock.sys.deregister(poll)
}
}
*/
#[derive(Debug, PartialEq)]
/// ID to keep track of clients
pub struct ConnectionID(pub u64);
#[derive(Debug, PartialEq)]
/// How many octets are being used for the packet number section of a ShortHeader packet and the associated value
pub enum PacketNumber{
OneOctet(u8),
TwoOctet(u16),
FourOctet(u32)
}
#[derive(Debug)]
/// How many octets are being used for the packet number section of a ShortHeader packet - only a description, no associated value
pub enum PacketTypeShort{
OneOctet,
TwoOctet,
FourOctet
}
#[derive(Debug, PartialEq)]
/// Type of LongHeader packet
pub enum PacketTypeLong {
Initial,
Retry,
Handshake,
ZeroRTTProtected,
}
#[derive(Debug)]
/// Two Header types which can be sent
pub enum HeaderType {
LongHeader,
ShortHeader
}
#[derive(Debug, PartialEq)]
/// Format of messages which will be sent between client and server
pub enum Header {
LongHeader {
packet_type : PacketTypeLong,
connection_id : u64,
packet_number : u32,
version : u32,
//Payload is not a fixed size number of bits
payload : Vec<u8>,
},
ShortHeader {
key_phase : bool,
//connection_id is present only if the bit for connection ID flag is set to 0
connection_id : Option<ConnectionID>,
packet_number : PacketNumber,
//Payload is not a fixed size number of bits
payload : Vec<u8>,
}
}
impl Header {
///Return a representation of Header as Bytes
pub fn encode(self) -> Bytes {
//Determine which type of Header is being operated on
match self {
//LongHeader variant
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//+-+-+-+-+-+-+-+-+
//|1| Type (7) |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| |
//+ Connection ID (64) +
//| |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Packet Number (32) |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Version (32) |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Payload (*) ...
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Header::LongHeader{packet_type, connection_id, packet_number, version, payload} => {
//Packet capacity will need to be larger for TLS handshake messages
//Not subject to 1200 octet limit like packets carrying application data
let mut buf = match packet_type {
PacketTypeLong::Handshake => BytesMut::with_capacity(7000),
_ => BytesMut::with_capacity(1200)
};
//128 added to all values to mark this as a long header
//AVTCORE compliance: packet numbers in range 127-122 (descending)
//NOTE: quic-transport draft 08 has a typo in packet type values - values used here are correct
match packet_type {
PacketTypeLong::Initial => buf.put_u8(128 + 0x7F),
PacketTypeLong::Retry => buf.put_u8(128 + 0x7E),
PacketTypeLong::Handshake => buf.put_u8(128 + 0x7D),
PacketTypeLong::ZeroRTTProtected => buf.put_u8(128 + 0x7C)
}
buf.put_u64::<BigEndian>(connection_id);
buf.put_u32::<BigEndian>(packet_number);
buf.put_u32::<BigEndian>(version);
buf.put_slice(&payload);
println!("Length of packet: {}", BytesMut::len(&buf));
println!("Capacity of packet: {}", BytesMut::capacity(&buf));
println!("Remaining capacity of packet: {}", BytesMut::remaining_mut(&buf));
//println!("{:?}", buf);
//All non-Handshake and non-initial LongHeader packets must be padded to 1200 octets minimum according to IETF QUIC document v7
/*
if packet_type != PacketTypeLong::Initial && packet_type != PacketTypeLong::Handshake {
let padding = vec![0; BytesMut::remaining_mut(&buf)];
//Can't use array - complains about non-constant value being supplied
//let padding = [0; BytesMut::remaining_mut(&buf)];
buf.put_slice(&padding);
println!("Padding added - any space left?: {:?}", BytesMut::has_remaining_mut(&buf));
}
*/
//Freeze buf to allow it to be used elsewhere
buf.freeze()
}
//ShortHeader variant
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//+-+-+-+-+-+-+-+-+
//|0|C|K| Type (5)|
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| |
//+ [Connection ID (64)] +
//| |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Packet Number (8/16/32) ...
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Protected Payload (*) ...
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Header::ShortHeader{key_phase, connection_id, packet_number, payload} => {
//Packet size limited to 1200 for v7 quic-transport spec
let mut buf = BytesMut::with_capacity(1200);
//AVTCORE compliance: connection_flag is 0 for present ConnectionID, 1 for absent
//counterintuitive, but necessary for multiplexing compatibility
let connection_flag_bit = match connection_id {
Some(_) => 0b00000000,
None => 0b01000000
};
let key_phase_bit = match key_phase {
true => 0b00100000,
false => 0b00000000
};
//AVTCORE compliance: packet types in descending order
//Last 5 bits - types range from 31 - 29 in current implementation
let packet_type = match packet_number {
PacketNumber::OneOctet(_) => 0x1F,
PacketNumber::TwoOctet(_) => 0x1E,
PacketNumber::FourOctet(_) => 0x1D,
};
let initial_octet = 0b01111111 & (connection_flag_bit | key_phase_bit | packet_type);
buf.put_u8(initial_octet);
match connection_id {
Some(ConnectionID(num)) => buf.put_u64::<BigEndian>(num),
None => {}
}
match packet_number {
PacketNumber::OneOctet(num) => buf.put_u8(num),
PacketNumber::TwoOctet(num) => buf.put_u16::<BigEndian>(num),
PacketNumber::FourOctet(num) => buf.put_u32::<BigEndian>(num),
}
buf.put_slice(&payload);
//Freeze buf to allow it to be used elsewhere
buf.freeze()
}
}
//Freeze buf to allow it to be used elsewhere
//buf.freeze()
}
///DEPRECATED: NO LONGER USED
pub fn is_new_connection(&self) -> bool{
match self {
&Header::LongHeader{ref packet_type, ref connection_id, ref packet_number, ref version, ref payload} => {
match packet_type {
&PacketTypeLong::Initial => {println!("Initial received - potential new connection detected."); return true;},
&PacketTypeLong::Handshake => {println!("Handshake received - not a new connection."); return false;},
_ => {println!("Nothing of interest received."); return false;},
}
}
_ => return false,
}
}
/// DEPRECATED: DO NOT USE
pub fn is_compatible_version(&self) -> bool{
match self {
&Header::LongHeader{ref packet_type, ref connection_id, ref packet_number, ref version, ref payload} => {
match version {
&0b00000001 => {println!("Compatible version detected: {:?}\n", &version); return true;},
_ => {println!("Incompatible version detected: {:?}\n", version); return false;},
}
}
_ => return false,
}
}
/// Obtain a Header's packet number, if it is present
pub fn get_conn_id(&self) -> Option<u64> {
let conn_id = match self {
&Header::LongHeader {ref packet_type, ref connection_id, ref packet_number, ref version, ref payload} => Some(*connection_id),
&Header::ShortHeader {ref key_phase, ref connection_id, ref packet_number, ref payload} => match connection_id {
&Some(ConnectionID(id)) => Some(id),
&None => None
}
};
conn_id
}
/// Obtain a Header's packet number
///
/// Note that OneOctet(u8) and TwoOctet(u16) packet numbers will be cast to u32
pub fn get_packet_number(&self) -> u32 {
let packet_number = match self {
&Header::LongHeader {ref packet_type, ref connection_id, ref packet_number, ref version, ref payload} => *packet_number,
&Header::ShortHeader {ref key_phase, ref connection_id, ref packet_number, ref payload} => match packet_number {
&PacketNumber::OneOctet(num) => num as u32,
&PacketNumber::TwoOctet(num) => num as u32,
&PacketNumber::FourOctet(num) => num
}
};
packet_number
}
/// Obtain a Header's version number, if present
///
/// Will always return None for ShortHeader variants
pub fn get_version(&self) -> Option<u32> {
let version = match self {
&Header::LongHeader {ref packet_type, ref connection_id, ref packet_number, ref version, ref payload} => Some(*version),
&Header::ShortHeader {ref key_phase, ref connection_id, ref packet_number, ref payload} => None
};
version
}
/// Obtain an immutable reference to a Header's payload - payload data should not be modified within the struct, only read by other functions
pub fn get_payload(&self) -> &Vec<u8> {
let payload = match self {
&Header::LongHeader {ref packet_type, ref connection_id, ref packet_number, ref version, ref payload} => payload,
&Header::ShortHeader {ref key_phase, ref connection_id, ref packet_number, ref payload} => payload
};
payload
}
}
///Reconstruct a Header from Bytes
pub fn decode(input : Bytes) -> Header{
println!("Length of received packet: {}", Bytes::len(&input));
//Change this to vec?
let mut input = Bytes::into_buf(input);
let initial_octet = input.get_u8();
//Determine which packet type has been received
//First bit is 0 for ShortHeader
if ((0b10000000 & initial_octet) >> 7) == 0 {
//Get connection_omit, key_phase, and PacketTypeShort info
let packet_info = get_short_info(initial_octet).unwrap();
//Parse Connection ID if present
let connection_id = match connection_id_present(packet_info.0) {
true => Some(ConnectionID(input.get_u64::<BigEndian>())),
false => None
};
//Parse packet number
let packet_number = match packet_info.2 {
PacketTypeShort::OneOctet => PacketNumber::OneOctet(input.get_u8()),
PacketTypeShort::TwoOctet => PacketNumber::TwoOctet(input.get_u16::<BigEndian>()),
PacketTypeShort::FourOctet => PacketNumber::FourOctet(input.get_u32::<BigEndian>()),
};
//Retrieve payload from the rest of the packet
let payload = bytes::Buf::bytes(&input).to_vec();
Header::ShortHeader {
key_phase : packet_info.1,
connection_id,
packet_number,
payload,
}
//First bit is 1 for LongHeader
} else {
let packet_type = get_long_info(initial_octet).unwrap();
let connection_id = input.get_u64::<BigEndian>();
let packet_number = input.get_u32::<BigEndian>();
let version = input.get_u32::<BigEndian>();
let payload = bytes::Buf::bytes(&input).to_vec();
Header::LongHeader{
packet_type,
connection_id,
packet_number,
version,
payload
}
}
}
/// Parse info from first octet of LongHeader - currently this only consists of PacketTypeLong
///
/// Will return an error if packet type is not recognised
pub fn get_long_info(input : u8) -> Result<PacketTypeLong, &'static str> {
//LongHeader always has initial bit set to 1 (ie. value of input is 128 + value of packet type)
match input & 0b01111111 {
0x7F => return Ok(PacketTypeLong::Initial),
0x7E => return Ok(PacketTypeLong::Retry),
0x7D => return Ok(PacketTypeLong::Handshake),
0x7C => return Ok(PacketTypeLong::ZeroRTTProtected),
_ => return Err("Unrecognised packet type for LongHeader"),
};
}
/// Get information for ShortHeader packet
///
/// Returns a tuple detailing if connection_ID is omitted, which key phase is being used, and PacketTypeShort being used (ie. how many octets will be read for the packet number)
pub fn get_short_info(input : u8) -> Result<(bool, bool, PacketTypeShort), &'static str> {
//Second bit of first octet determines if ConnectionID is omitted or not
let connection_omit = match (input & 0b01000000) >> 6 {
0 => false,
_ => true
};
//Third bit of first octet determines which key phase is being used
let key_phase = match (input & 0b00100000) >> 5{
1 => true,
_ => false
};
//Final five bits of first octet determines how many octets will be used for the packet number
let packet_type = match input & 0b00011111 {
0x1F => PacketTypeShort::OneOctet,
0x1E => PacketTypeShort::TwoOctet,
0x1D => PacketTypeShort::FourOctet,
_ => return Err("Unrecognised packet type for ShortHeader.")
};
Ok((connection_omit, key_phase, packet_type))
}
//ConnectionID flag is confusing - created two functions to give a straightforward answer
/// Used for getting a straightforward answer to whether a Connection ID is present
///
/// get_short_info returns a bool signalling if Connection ID is omitted - this function just inverts it
pub fn connection_id_present(flag : bool) -> bool {
match flag {
true => false,
false => true
}
}
/// This function is primarily for readability - returns the bool given for connection_omit by get_short_info
pub fn connection_id_omitted(flag : bool) -> bool {
flag
}
|
use web_sys::HtmlImageElement;
use wasm_bindgen::JsCast;
use js_sys::Promise;
use wasm_bindgen_futures::JsFuture;
use futures::channel::oneshot::Sender;
use wasm_bindgen::JsValue;
/// This struct represent an image.
/// It is useful when using the [Sprite struct](../sprite/struct.Sprite.html).
///
/// # Example
///
/// ```rust
/// use wasm_game_lib::graphics::image::Image;
///
/// # async fn test() {
/// // load a texture encoded in text
/// let ferris = Image::load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAAC3CAMAAAAGjUrGAAABL1BMVEX////3TAAAAAClKwD3SAD5TQD3RQD3PQD/TwD3QAD2NwD3QwCgKQD3OgCeAAD3PwCiHgD/+/mjIgDySgD5hmb91sz8zMD91MmhFgDZQAD4cEf5elX+6+X6n4f+8Ov8vq7ANgD4aDv4YC38w7T6pY/6l337tKL5gV/+5t+lMwCyMADOnZb7rJj+5+D93tT6j3GBKABEFQBpIADmRQDJOgC2XkuoNBLhwbvq1M/Ii3/TPgDXrKP3Vx34aTz4YC76kneZmZnW1tY0EACTLQBeHQCrPSHAeWu8bl7GbFeBUEXncFCXa2LCpJ7n6Ok3NzdzIwB1AAAnJyc+Pj4ALTKpqankMgAZAACYPCHDw8MAICSfn59qamo7OzshCgCAgIDf399WVlbKRRuxUTxQGADlysRe1l77AAAQuUlEQVR4nO1daWPbthkWJfAQaeq2TFmHlVg+YvlIIjmSr7iJY3tX13Xrum7rNSf//zeMIAgQAC+JpES65fPJoiERePheeF8ALBRy5MiRI0eOHDly5MiRI0eOHDly5MiRI8fvDO12Pe0uZAyDpi6XD9PuRZo43e1xV7qaIIBr7uJgd3NdPUodZ6qsHjNX2rpgQt5nL5rNttfZrxTRVs3xqzv0JQFATgSdNimbsJl8XPhdoGsRoG45V0ZlixJBajnXTmR4xaVPv03UVUSATkzqQBdsqKfkmgS4K79l7NhCAbSBfeVAwpyAl/al+jWiRND6afVzlTjdZR/1C4AJEJD52FIFAmxmX2CaAGC+fPKbcEV7pvc4oz73iKIIEpIKLBKIFIsn6JrxBcruFEbmj3XX2PnVwPIe5WsnHjl2hito0NUeVylKBA3yd0ZdouxufRvaXX3HfZfnhZFFAZB38QVGKrTu2Tb9GXJw02oxLJWxg96UJI6kZ4qWbRiw/pzqDANA4iiBlyTmM6ZzpKKm4EV6o0kG7/GYNaQ/e5qwJIAVyyK9QSSlO6L4cNTA0p9Dl1iEQzddzSZwhEfnJ0vPDD1aVfSuoLuHHA5ZO1ApLhlP9AyxJdODAxGkBH2R/lDeD79vlrFfjshCALS9tEe1JE7PWm3q460UPsZlAegEwiZ7vyxiS9Uk/SUJRgp89JEMKc7tblRJUjOuS5brBXITx5pLe95FINtRXPulblGupzbchYDnvDI4hh3vyUFji8yJ5Xh2rmVbCNVBSK/SBVEVUNZGg+MVWFiLlL3BviCTe6nZzvg3Kfuh6SvRHPTTZepGGefk5SpsahjUtEcdjPfPipP1FJS6aXAiRevrjryeXG8qnAhReroP5DXVBA5S4AQ0l+/nrlAF60p/t1YQy4dy8n7ZXh7ewGBPZicFwUHOTnTflgonyybe+ijzwIV6wdLWUkeLs9K+7W85rZdPoyXAyQG5fX1zdBaWwj65tiNJNl83CJ42HZfL0qLzqpGqabL+ot+2SB+k4oubJxYfW6NtWdYkNTiHvaPbXQQ3zPVdOdB97VZNEq8XclQDVK8Cmiy/3GufRk4axQKQ21v9FyYfC5RT90iBjcv/30pykIQdwgwhYCpVfqDS8JCXVCgxQfiwPuz697frTEq1EfMfAQTaarvKrTXDRWUQKcG6Wuj+3e5Sk1I2hQkfrn7CEyE46XDbUIIFsjXXaYmGPzRfB3FAz9NZV9zX3InegaA6bUh2TA/Vn1UkF+MB+K5t6jPZHJmpxsM0OGBL0QMAKP06IwOVwyrWOytKkUSHb3hKr18QOBVrQ7oAM0moNwHNL5ULKoeQcpg5gyL75KzrGqvmTOnsxh3FbUPBcFaTtSkhq4aUrFeSXYwD3SdI58NJut0pEiFadEbWwByCmYevBy+zS2cm7A+/GaHLQ9LZOduAUhXGQ8SSE8TUme8HLyk7TiGaD4Lk4xZcsw6Kk7Y9XoqTG/tROzUBOq0aMhffzJjylH2i0SrfkKqA4OE6nGCWhCr5ObZUVWYjPhb1jHGieycU265ulsn/brEIOe6ZEEBWHfKCpgdNkzMWtfmsTum7VJxw0iY+mvDZc9y2jmWHK8xoAYIyyliA4rO068b15LDuUHU58uyp0j/JznCSxgYzhZOzg1brdm90vL+/s5+9+KS/u7+/P+rftloHLaIMbmG2bezAmcs7i7YPqOhct90xH4npdBx8ompAkjQT5XI5Y14HQqvCfmmaJAEJr2Cvu6UZVUAGlDtxXBZtD7BA1DkrzSjPWQZ58AOWfC9OYMx2SGd8qiTJwIhE2Z4ssCuD2HnVStZPrArAlxMYx+7Ta8IoV8LOjOwAjY9OqxQnbhOeXZCprnv6rg9624w8SE5e19Oc8lEfHQj3WBYzDeJJ3RED2NaBd1tX2VuzmOXXoTGTyG7mciZ+cDyJR5GFY8mJzuhkCYIMl9DxYR+TltvMnP/1gxOZhy821Kkcwy4f9cKJ8AnvjJl1uqmsqIgCpzxxEqbwjBtxT1jgBkbuJ9hlLzsZm+P4gQ4hwqYgKpOgdscbep+dGbtmEc/E89B5s5B1ZDI7fRm4xUpusc6YL8mOngUpzNQneP4u8TXnkSu3IHBbSPily1ks67jBJsNuA54jkFwJy9Dpvqu0xjurLIIranioA4FHKjF0Gasr77ubsQyBFzQukeyf1VC9Uv1bwZ7KXUZ6Ft6YXyjAR2kYqne6sh1ICl9xr+8/C2es9Vnx3vQepA8lIaRoDhunO/2uoD4DzYHQVLC9t7NJmOm7nUkAJTD/7qsOdrXxtN+9lvWyls4ik4gAWlnWhe09lBS7cbkGoAftGhu89Hv6aB9EW31ebFAAQEOHi9R5DysJ/PoKDmfe+mOXMvws1DMBShi1We2Rt0MX7rU1j7jGzqgkHaaJEAs2W6BdKFAtmAnPgRpUuMKon6kuacDOO0HFEYGiNCeTSVNRgocLFOFyOu2IIc0WAUq/0pqwyDosC6cvOVur4YxcclWLcucPfyxa+Hg3CRgu0P/0Z9Tu9USJe09rdkKF30C9XYwRiB1A21p8IEfBXpCRAPS/mD/29V/RaIvfCH6kaNvw0X6Fmt3FExWUcKs7YlK9Xu7QkGPNYYXauzBIJirBAeC3NinFifdolXvUziblUyyroh6yYhJYAvdE3Zka0CuhdpPQHjJP+IA5KTa9Rqv87UOBIe9NDFJQduSMRN96lK2mjh+nv95KIG3irGf4O+bkjYexEKf/wO2+s5u9imxTUPqnRSiRIh1xRoX6lMOqx/c94j/Jr31FBOXIPVrl+59xu1/sVt9H5sSa1ndJaAKkaJssqHqF3CU/ETJ/XgDKv8gtfiCcFF2jFYfF70hD3GoaUXmgqNdvHBlXI57JRIuEpJGU0l5MOyuCX704GfKjVd54cPI2mqBIXVgqp84KiXwOHhPe6DfY/cTceCEe/duLE3604qRY/A9u9zVp5uu2g1EvbFLrQMsxzh5isgdA7XoXkpeE8rZIbuDYk2KRG6zyqlj8r5u7SMoD3heOqaG4stHRSTFZuTGD/FZM3VGKxR/w7/9IccLFKMon8xpu9zNpdRdJeQC1GcMM3uJt0N5iJz9AFrpxzUmnWPzV/vUPFCW8BCjw2leonaM6xc/RDAq9wMadoF8ShwIbzsd2xcqROTLbeH5Lc8IaWVG0Lv7At/sp7qwHaPHPYqJOu0oE0E4gASDzHU9OJujqzx9++Y5pFtHIYgAtJIO0GEbu5EEMKHdobL/+WCwGcdIsesNzFrAwgJTQiV2n1wkmpJGceGDqpTtuxJITcJ3cOSn95ETFside4P3OR+9msebG1SSPJ+jxq5wiAxuKMAFQXnu28posLoFqoqdnbiVV91N+8hzsJz6OnXo2ixafONCTPD7zJF5fHPgYFNfE2Ft5fLJPi0O7TuzIk56WlEURvQXFZSc8BeWbuOHJYlthF8IgyZR9x2OwHtki5RtXq5+SqWl0kzh9qd5MNEQZugbLWxMIUXnDtXoTLzghkEB8/+OqJ8aEwqvFZ8/nLzZZLXuVQI0HYbFSVyDeu0sY8YRYaX6iB/vaZ7Bi87PT6K65vC0RBb8QT475yokbV15aFDtBlaoFOqtckuG+7fj+lKgMkf58OhKWvZ8oirDS2PQprMY753vbTcmktLFxdBkrzBaVyd2bj59eD5uBgxUVoWPyH1ZBdX9PbHamRxsQpWHHg5ZYx60e8JMdAP63UTKxsTE0hSU6L6ICEfoDUQropoQMIRulRu0d7Glp2uQfbNBmvjC4VjsB0LsySiXEytFlMxH3mChMETyynlrJuJ+jrm40jrlqXZzjm10nNIBBoW5zgmjpxDS4ycLsS8dmpFG5KMxQV42x6wzo6JS4tmdIUA9nFcxJzdIhL4WNPCYIpFYRvq1MphuIkVLlqVconDfQB36fVzVOMMtvGUPbph5r6FaNcc1ApgVKSzz/rNhETDrT4au7128/Hy1tV6GI2IwY72ZmPwfo4VW+cCuKohxyR4FfZ4v2IrxD/BtXhbFhYCUKdiEhODJ5+PTmIxW2LDffE8XJEBNSMkpXVjeR5as9FrgTBNSYh8FzQSxaZN6ztadmStK4YTSwyZ1EXWflCuSXmu9BnSlhQhrGxpXd93vEEJzf0LsytLgZg16VrWegQ81sk2JYd589VWq2yTWjAb8wKXhUlzwni4qJeTNICGakVnma4a7PrU5WrM90qc7/vKVFsel54s4FsujvUJuTi5rRIK5oCtVoSV5w8hpjuIiYmNZYmAwdQkpG5WHu9PyhgTWH2XDkubh+SbDlQMnenPpkcWCQh/LlseLQYvGynLyw2UaPxRcuPkwBuTzacAipVe6vaAmoV4jm0K5YOygkgB2GFLQKqlBHBNxTfZg9GpiWEoqqJ8LiAkNn4KYhlIgweKcFxCSkdDFnuz02iObQW4Mjrj3hccxU021BobXVoeWhQcTFsi+mwExEZSGRUSa2qNwJ/pTA6MWUD4aPRq3S4AkxYVH1gP52pvZJaI6FEU0KXtFyVaEsioP5+NwwahQvpiYNL9EMNZgac7SXR8OOT7iGvj5Bc7uSQ4hReRq7CSnYMSwSCmfzb2yfQ5FChTxkb6BlZ42Zu3Ud8kLJC1Ilk5mOSY0SwI3Xf0TrqmlMO5dDa6rL8FF6mPkUsqDBg9EaBFEdamVrfPQpUnS8agmFzj7fmF89lCoGTYwlMyY1U5obSALFEnPF4qJpkVFi2TD1xag0Hq78a51QtQ1bc5zDT+JGa76kkBNi6jCeNa78vzT4Mn64NyWmRjNjDQ+SY7Jj0tOZwEXmJqzfhn/AVeedzuV0Ojw6wo15Os4v/OTDBnxeWK/JrK2c8FtqKFLIglsrnjVCxLE+n40f7ysVaGUYbjA7vmAblxoNw6hU7h/Hs/BSOOxZBZsZfFZB8i8vpUghe5lhPItte1gv51fjhyfTBEByXOz4o9Go1SAXRun84WoBNhAeGzBDgEBOm1OTP+PfIUUih0CO6eexCOqD+exqfPF4/vSuVqlAghBqFOxL8N+1d0/nDxdXs/lgKeNoWpMGCZ3w8Q0ree+vQ4pzBsRjrdR4ivh79XpvPp/PZlcmxiYuIOAf5ufZl/m8txwRFExrUiEidb3S9woSUqiDuO4bXOCWAZhiUiGmHwcn8ore0kNIcRLfg4a/P04LD7XGOflgW1g94JTqeCCkOLvZzYcS5I9TgDn7c5yhnWFLZurnDUwK5ddM5+OK8FPF2KC02X4JLFjle4twmF92NvZcGNmyKO8MKjxAayKibjtYEHiWTJ0FcW6cB3xh3TCV2fmAjvQpr/oVKjYp1HyqXqtk6NVrF7TUWutEln/zytKwSdGc47u/VMYB7deMGiW0SEzUNbzJdt8+0topHV1kxx3PaZm1xGQ9bwu3SaH4v8+M8owpkbXOWZPW9FZ5lKOlwuXBMpOeleKC+hvuwIq6+2957FqkyNl+/al1bH2yeaRA2KRkRmW8APdYJ51HCoRV9/E5/TkbgCsA6JMt1wDrDPjgFwKkC2hh1/1CeVg29X+zS/o4kNbkhmnA1IS+2plEHJTX5oZpmDYlu4KyJa9dcyyYwdsKMr/JoK+tfOrnc2NZW+K8mbXiRor0ctYE0Kr6vKEidahrjNY4dBMr1SeLXsgLJVeK7UVerrh+bAW+DWbVyOakp52a5uTIkSNHjhw5cuTIkSNHjhw5cuTIkSNHjhw5ksL/AeXaaJJsHYwiAAAAAElFTkSuQmCC").await.unwrap();
/// // load a texture from the web
/// let ferris2 = Image::load("https://rustacean.net/assets/cuddlyferris.svg").await.unwrap();
/// # }
/// ```
#[derive(Debug, PartialEq)]
pub struct Image {
element: HtmlImageElement,
}
impl Image {
/// Load an Image.
/// Return a Result because it may fail.
///
/// # Example
///
/// ```rust
/// # use wasm_game_lib::graphics::image::Image;
/// # async fn test() {
/// // load a texture encoded in text
/// let ferris = Image::load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAAC3CAMAAAAGjUrGAAABL1BMVEX////3TAAAAAClKwD3SAD5TQD3RQD3PQD/TwD3QAD2NwD3QwCgKQD3OgCeAAD3PwCiHgD/+/mjIgDySgD5hmb91sz8zMD91MmhFgDZQAD4cEf5elX+6+X6n4f+8Ov8vq7ANgD4aDv4YC38w7T6pY/6l337tKL5gV/+5t+lMwCyMADOnZb7rJj+5+D93tT6j3GBKABEFQBpIADmRQDJOgC2XkuoNBLhwbvq1M/Ii3/TPgDXrKP3Vx34aTz4YC76kneZmZnW1tY0EACTLQBeHQCrPSHAeWu8bl7GbFeBUEXncFCXa2LCpJ7n6Ok3NzdzIwB1AAAnJyc+Pj4ALTKpqankMgAZAACYPCHDw8MAICSfn59qamo7OzshCgCAgIDf399WVlbKRRuxUTxQGADlysRe1l77AAAQuUlEQVR4nO1daWPbthkWJfAQaeq2TFmHlVg+YvlIIjmSr7iJY3tX13Xrum7rNSf//zeMIAgQAC+JpES65fPJoiERePheeF8ALBRy5MiRI0eOHDly5MiRI0eOHDly5MiRI8fvDO12Pe0uZAyDpi6XD9PuRZo43e1xV7qaIIBr7uJgd3NdPUodZ6qsHjNX2rpgQt5nL5rNttfZrxTRVs3xqzv0JQFATgSdNimbsJl8XPhdoGsRoG45V0ZlixJBajnXTmR4xaVPv03UVUSATkzqQBdsqKfkmgS4K79l7NhCAbSBfeVAwpyAl/al+jWiRND6afVzlTjdZR/1C4AJEJD52FIFAmxmX2CaAGC+fPKbcEV7pvc4oz73iKIIEpIKLBKIFIsn6JrxBcruFEbmj3XX2PnVwPIe5WsnHjl2hito0NUeVylKBA3yd0ZdouxufRvaXX3HfZfnhZFFAZB38QVGKrTu2Tb9GXJw02oxLJWxg96UJI6kZ4qWbRiw/pzqDANA4iiBlyTmM6ZzpKKm4EV6o0kG7/GYNaQ/e5qwJIAVyyK9QSSlO6L4cNTA0p9Dl1iEQzddzSZwhEfnJ0vPDD1aVfSuoLuHHA5ZO1ApLhlP9AyxJdODAxGkBH2R/lDeD79vlrFfjshCALS9tEe1JE7PWm3q460UPsZlAegEwiZ7vyxiS9Uk/SUJRgp89JEMKc7tblRJUjOuS5brBXITx5pLe95FINtRXPulblGupzbchYDnvDI4hh3vyUFji8yJ5Xh2rmVbCNVBSK/SBVEVUNZGg+MVWFiLlL3BviCTe6nZzvg3Kfuh6SvRHPTTZepGGefk5SpsahjUtEcdjPfPipP1FJS6aXAiRevrjryeXG8qnAhReroP5DXVBA5S4AQ0l+/nrlAF60p/t1YQy4dy8n7ZXh7ewGBPZicFwUHOTnTflgonyybe+ijzwIV6wdLWUkeLs9K+7W85rZdPoyXAyQG5fX1zdBaWwj65tiNJNl83CJ42HZfL0qLzqpGqabL+ot+2SB+k4oubJxYfW6NtWdYkNTiHvaPbXQQ3zPVdOdB97VZNEq8XclQDVK8Cmiy/3GufRk4axQKQ21v9FyYfC5RT90iBjcv/30pykIQdwgwhYCpVfqDS8JCXVCgxQfiwPuz697frTEq1EfMfAQTaarvKrTXDRWUQKcG6Wuj+3e5Sk1I2hQkfrn7CEyE46XDbUIIFsjXXaYmGPzRfB3FAz9NZV9zX3InegaA6bUh2TA/Vn1UkF+MB+K5t6jPZHJmpxsM0OGBL0QMAKP06IwOVwyrWOytKkUSHb3hKr18QOBVrQ7oAM0moNwHNL5ULKoeQcpg5gyL75KzrGqvmTOnsxh3FbUPBcFaTtSkhq4aUrFeSXYwD3SdI58NJut0pEiFadEbWwByCmYevBy+zS2cm7A+/GaHLQ9LZOduAUhXGQ8SSE8TUme8HLyk7TiGaD4Lk4xZcsw6Kk7Y9XoqTG/tROzUBOq0aMhffzJjylH2i0SrfkKqA4OE6nGCWhCr5ObZUVWYjPhb1jHGieycU265ulsn/brEIOe6ZEEBWHfKCpgdNkzMWtfmsTum7VJxw0iY+mvDZc9y2jmWHK8xoAYIyyliA4rO068b15LDuUHU58uyp0j/JznCSxgYzhZOzg1brdm90vL+/s5+9+KS/u7+/P+rftloHLaIMbmG2bezAmcs7i7YPqOhct90xH4npdBx8ompAkjQT5XI5Y14HQqvCfmmaJAEJr2Cvu6UZVUAGlDtxXBZtD7BA1DkrzSjPWQZ58AOWfC9OYMx2SGd8qiTJwIhE2Z4ssCuD2HnVStZPrArAlxMYx+7Ta8IoV8LOjOwAjY9OqxQnbhOeXZCprnv6rg9624w8SE5e19Oc8lEfHQj3WBYzDeJJ3RED2NaBd1tX2VuzmOXXoTGTyG7mciZ+cDyJR5GFY8mJzuhkCYIMl9DxYR+TltvMnP/1gxOZhy821Kkcwy4f9cKJ8AnvjJl1uqmsqIgCpzxxEqbwjBtxT1jgBkbuJ9hlLzsZm+P4gQ4hwqYgKpOgdscbep+dGbtmEc/E89B5s5B1ZDI7fRm4xUpusc6YL8mOngUpzNQneP4u8TXnkSu3IHBbSPily1ks67jBJsNuA54jkFwJy9Dpvqu0xjurLIIranioA4FHKjF0Gasr77ubsQyBFzQukeyf1VC9Uv1bwZ7KXUZ6Ft6YXyjAR2kYqne6sh1ICl9xr+8/C2es9Vnx3vQepA8lIaRoDhunO/2uoD4DzYHQVLC9t7NJmOm7nUkAJTD/7qsOdrXxtN+9lvWyls4ik4gAWlnWhe09lBS7cbkGoAftGhu89Hv6aB9EW31ebFAAQEOHi9R5DysJ/PoKDmfe+mOXMvws1DMBShi1We2Rt0MX7rU1j7jGzqgkHaaJEAs2W6BdKFAtmAnPgRpUuMKon6kuacDOO0HFEYGiNCeTSVNRgocLFOFyOu2IIc0WAUq/0pqwyDosC6cvOVur4YxcclWLcucPfyxa+Hg3CRgu0P/0Z9Tu9USJe09rdkKF30C9XYwRiB1A21p8IEfBXpCRAPS/mD/29V/RaIvfCH6kaNvw0X6Fmt3FExWUcKs7YlK9Xu7QkGPNYYXauzBIJirBAeC3NinFifdolXvUziblUyyroh6yYhJYAvdE3Zka0CuhdpPQHjJP+IA5KTa9Rqv87UOBIe9NDFJQduSMRN96lK2mjh+nv95KIG3irGf4O+bkjYexEKf/wO2+s5u9imxTUPqnRSiRIh1xRoX6lMOqx/c94j/Jr31FBOXIPVrl+59xu1/sVt9H5sSa1ndJaAKkaJssqHqF3CU/ETJ/XgDKv8gtfiCcFF2jFYfF70hD3GoaUXmgqNdvHBlXI57JRIuEpJGU0l5MOyuCX704GfKjVd54cPI2mqBIXVgqp84KiXwOHhPe6DfY/cTceCEe/duLE3604qRY/A9u9zVp5uu2g1EvbFLrQMsxzh5isgdA7XoXkpeE8rZIbuDYk2KRG6zyqlj8r5u7SMoD3heOqaG4stHRSTFZuTGD/FZM3VGKxR/w7/9IccLFKMon8xpu9zNpdRdJeQC1GcMM3uJt0N5iJz9AFrpxzUmnWPzV/vUPFCW8BCjw2leonaM6xc/RDAq9wMadoF8ShwIbzsd2xcqROTLbeH5Lc8IaWVG0Lv7At/sp7qwHaPHPYqJOu0oE0E4gASDzHU9OJujqzx9++Y5pFtHIYgAtJIO0GEbu5EEMKHdobL/+WCwGcdIsesNzFrAwgJTQiV2n1wkmpJGceGDqpTtuxJITcJ3cOSn95ETFside4P3OR+9msebG1SSPJ+jxq5wiAxuKMAFQXnu28posLoFqoqdnbiVV91N+8hzsJz6OnXo2ixafONCTPD7zJF5fHPgYFNfE2Ft5fLJPi0O7TuzIk56WlEURvQXFZSc8BeWbuOHJYlthF8IgyZR9x2OwHtki5RtXq5+SqWl0kzh9qd5MNEQZugbLWxMIUXnDtXoTLzghkEB8/+OqJ8aEwqvFZ8/nLzZZLXuVQI0HYbFSVyDeu0sY8YRYaX6iB/vaZ7Bi87PT6K65vC0RBb8QT475yokbV15aFDtBlaoFOqtckuG+7fj+lKgMkf58OhKWvZ8oirDS2PQprMY753vbTcmktLFxdBkrzBaVyd2bj59eD5uBgxUVoWPyH1ZBdX9PbHamRxsQpWHHg5ZYx60e8JMdAP63UTKxsTE0hSU6L6ICEfoDUQropoQMIRulRu0d7Glp2uQfbNBmvjC4VjsB0LsySiXEytFlMxH3mChMETyynlrJuJ+jrm40jrlqXZzjm10nNIBBoW5zgmjpxDS4ycLsS8dmpFG5KMxQV42x6wzo6JS4tmdIUA9nFcxJzdIhL4WNPCYIpFYRvq1MphuIkVLlqVconDfQB36fVzVOMMtvGUPbph5r6FaNcc1ApgVKSzz/rNhETDrT4au7128/Hy1tV6GI2IwY72ZmPwfo4VW+cCuKohxyR4FfZ4v2IrxD/BtXhbFhYCUKdiEhODJ5+PTmIxW2LDffE8XJEBNSMkpXVjeR5as9FrgTBNSYh8FzQSxaZN6ztadmStK4YTSwyZ1EXWflCuSXmu9BnSlhQhrGxpXd93vEEJzf0LsytLgZg16VrWegQ81sk2JYd589VWq2yTWjAb8wKXhUlzwni4qJeTNICGakVnma4a7PrU5WrM90qc7/vKVFsel54s4FsujvUJuTi5rRIK5oCtVoSV5w8hpjuIiYmNZYmAwdQkpG5WHu9PyhgTWH2XDkubh+SbDlQMnenPpkcWCQh/LlseLQYvGynLyw2UaPxRcuPkwBuTzacAipVe6vaAmoV4jm0K5YOygkgB2GFLQKqlBHBNxTfZg9GpiWEoqqJ8LiAkNn4KYhlIgweKcFxCSkdDFnuz02iObQW4Mjrj3hccxU021BobXVoeWhQcTFsi+mwExEZSGRUSa2qNwJ/pTA6MWUD4aPRq3S4AkxYVH1gP52pvZJaI6FEU0KXtFyVaEsioP5+NwwahQvpiYNL9EMNZgac7SXR8OOT7iGvj5Bc7uSQ4hReRq7CSnYMSwSCmfzb2yfQ5FChTxkb6BlZ42Zu3Ud8kLJC1Ilk5mOSY0SwI3Xf0TrqmlMO5dDa6rL8FF6mPkUsqDBg9EaBFEdamVrfPQpUnS8agmFzj7fmF89lCoGTYwlMyY1U5obSALFEnPF4qJpkVFi2TD1xag0Hq78a51QtQ1bc5zDT+JGa76kkBNi6jCeNa78vzT4Mn64NyWmRjNjDQ+SY7Jj0tOZwEXmJqzfhn/AVeedzuV0Ojw6wo15Os4v/OTDBnxeWK/JrK2c8FtqKFLIglsrnjVCxLE+n40f7ysVaGUYbjA7vmAblxoNw6hU7h/Hs/BSOOxZBZsZfFZB8i8vpUghe5lhPItte1gv51fjhyfTBEByXOz4o9Go1SAXRun84WoBNhAeGzBDgEBOm1OTP+PfIUUih0CO6eexCOqD+exqfPF4/vSuVqlAghBqFOxL8N+1d0/nDxdXs/lgKeNoWpMGCZ3w8Q0ree+vQ4pzBsRjrdR4ivh79XpvPp/PZlcmxiYuIOAf5ufZl/m8txwRFExrUiEidb3S9woSUqiDuO4bXOCWAZhiUiGmHwcn8ore0kNIcRLfg4a/P04LD7XGOflgW1g94JTqeCCkOLvZzYcS5I9TgDn7c5yhnWFLZurnDUwK5ddM5+OK8FPF2KC02X4JLFjle4twmF92NvZcGNmyKO8MKjxAayKibjtYEHiWTJ0FcW6cB3xh3TCV2fmAjvQpr/oVKjYp1HyqXqtk6NVrF7TUWutEln/zytKwSdGc47u/VMYB7deMGiW0SEzUNbzJdt8+0topHV1kxx3PaZm1xGQ9bwu3SaH4v8+M8owpkbXOWZPW9FZ5lKOlwuXBMpOeleKC+hvuwIq6+2957FqkyNl+/al1bH2yeaRA2KRkRmW8APdYJ51HCoRV9/E5/TkbgCsA6JMt1wDrDPjgFwKkC2hh1/1CeVg29X+zS/o4kNbkhmnA1IS+2plEHJTX5oZpmDYlu4KyJa9dcyyYwdsKMr/JoK+tfOrnc2NZW+K8mbXiRor0ctYE0Kr6vKEidahrjNY4dBMr1SeLXsgLJVeK7UVerrh+bAW+DWbVyOakp52a5uTIkSNHjhw5cuTIkSNHjhw5cuTIkSNHjhw5ksL/AeXaaJJsHYwiAAAAAElFTkSuQmCC").await.unwrap();
/// // load a texture from the web
/// let ferris2 = Image::load("https://rustacean.net/assets/cuddlyferris.svg").await.unwrap();
/// # }
/// ```
pub async fn load(url: &str) -> Result<Image, JsValue> {
let document = web_sys::window().unwrap().document().unwrap();
let element = document
.create_element("img")
.unwrap()
.dyn_into::<web_sys::HtmlImageElement>()
.unwrap();
element.set_src(url);
JsFuture::from(Promise::new(&mut |yes, no| {
element.add_event_listener_with_callback("load", &yes).unwrap();
element.add_event_listener_with_callback("error", &no).unwrap();
})).await.unwrap();
Ok(Image {
element
})
}
/// Load an Image and send it trought a [oneshot channel](https://docs.rs/futures/0.3.4/futures/channel/oneshot/fn.channel.html).
///
/// # Example
///
/// ```rust
/// use wasm_game_lib::graphics::image::Image;
/// use wasm_game_lib::system::sleep;
/// use futures::channel::oneshot::Receiver;
/// use futures::channel::oneshot;
/// use futures::join;
/// use wasm_bindgen::JsValue;
/// use std::time::Duration;
///
/// // the function which will be executed during the load
/// async fn loading_tracker(mut receivers: Vec<Receiver<Result<Image, JsValue>>>) -> Vec<Result<Image, JsValue>> {
/// let mut images = Vec::new();
/// for _ in 0..receivers.len() {
/// images.push(None);
/// }
///
/// loop {
/// for i in 0..images.len() {
/// if images[i].is_none() {
/// if let Ok(Some(result)) = receivers[i].try_recv() {
/// images[i] = Some(result);
/// }
/// }
/// }
///
/// if !images.contains(&None) {
/// // break when every image is ready
/// break;
/// }
///
/// // you may want to display a progress bar here
///
/// sleep(Duration::from_millis(20)).await;
/// }
///
/// let mut unwraped_images = Vec::new();
/// for image in images {
/// unwraped_images.push(image.unwrap());
/// }
///
/// return unwraped_images;
/// }
///
/// async fn start() {
/// // create 2 oneshot channels
/// let (sender1, receiver1) = oneshot::channel::<Result<Image, JsValue>>();
/// let (sender2, receiver2) = oneshot::channel::<Result<Image, JsValue>>();
///
/// // create futures
/// let loading_tracker_future = loading_tracker(vec![receiver1, receiver2]);
/// let image1_future = Image::load_and_send("https://images.pexels.com/photos/1086723/pexels-photo-1086723.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=7000&w=7000", sender1);
/// let image2_future = Image::load_and_send("https://c.wallhere.com/photos/c1/ff/Moon_rocks_sky_8k-1430191.jpg!d", sender2);
///
/// // execute the three futures simultaneously and get the images
/// let images = join!(loading_tracker_future, image1_future, image2_future).0;
/// }
/// ```
pub async fn load_and_send(url: &str, sender: Sender<Result<Image, JsValue>>) {
let image = Image::load(url).await;
sender.send(image).expect("can't send the loaded image trought the oneshot shannel");
}
pub fn get_html_element(&self) -> &HtmlImageElement {
&self.element
}
/// Return the width of the image.
pub fn get_width<T: From<u32>>(&self) -> T {
self.element.width().into()
}
/// Return the height of the image.
pub fn get_height<T: From<u32>>(&self) -> T {
self.element.height().into()
}
/// Return a tuple containing width and height.
pub fn get_size<T: From<u32>>(&self) -> (T, T) {
(self.element.width().into(), self.element.height().into())
}
} |
// On peut créer une hiérarchie de modules.
pub mod instrument {
pub fn clarinette() {
println!("Une clarinette joue Rhapsody in Blue");
}
}
mod voix {
fn tenor() {
}
}
|
#[doc = "Reader of register ADV_PARAMS"]
pub type R = crate::R<u32, super::ADV_PARAMS>;
#[doc = "Writer for register ADV_PARAMS"]
pub type W = crate::W<u32, super::ADV_PARAMS>;
#[doc = "Register ADV_PARAMS `reset()`'s with value 0xe0"]
impl crate::ResetValue for super::ADV_PARAMS {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xe0
}
}
#[doc = "Reader of field `TX_ADDR`"]
pub type TX_ADDR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TX_ADDR`"]
pub struct TX_ADDR_W<'a> {
w: &'a mut W,
}
impl<'a> TX_ADDR_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) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `ADV_TYPE`"]
pub type ADV_TYPE_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADV_TYPE`"]
pub struct ADV_TYPE_W<'a> {
w: &'a mut W,
}
impl<'a> ADV_TYPE_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 << 1)) | (((value as u32) & 0x03) << 1);
self.w
}
}
#[doc = "Reader of field `ADV_FILT_POLICY`"]
pub type ADV_FILT_POLICY_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADV_FILT_POLICY`"]
pub struct ADV_FILT_POLICY_W<'a> {
w: &'a mut W,
}
impl<'a> ADV_FILT_POLICY_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 << 3)) | (((value as u32) & 0x03) << 3);
self.w
}
}
#[doc = "Reader of field `ADV_CHANNEL_MAP`"]
pub type ADV_CHANNEL_MAP_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `ADV_CHANNEL_MAP`"]
pub struct ADV_CHANNEL_MAP_W<'a> {
w: &'a mut W,
}
impl<'a> ADV_CHANNEL_MAP_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 & !(0x07 << 5)) | (((value as u32) & 0x07) << 5);
self.w
}
}
#[doc = "Reader of field `RX_ADDR`"]
pub type RX_ADDR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RX_ADDR`"]
pub struct RX_ADDR_W<'a> {
w: &'a mut W,
}
impl<'a> RX_ADDR_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 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `RX_SEC_ADDR`"]
pub type RX_SEC_ADDR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RX_SEC_ADDR`"]
pub struct RX_SEC_ADDR_W<'a> {
w: &'a mut W,
}
impl<'a> RX_SEC_ADDR_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `ADV_LOW_DUTY_CYCLE`"]
pub type ADV_LOW_DUTY_CYCLE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ADV_LOW_DUTY_CYCLE`"]
pub struct ADV_LOW_DUTY_CYCLE_W<'a> {
w: &'a mut W,
}
impl<'a> ADV_LOW_DUTY_CYCLE_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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `INITA_RPA_CHECK`"]
pub type INITA_RPA_CHECK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `INITA_RPA_CHECK`"]
pub struct INITA_RPA_CHECK_W<'a> {
w: &'a mut W,
}
impl<'a> INITA_RPA_CHECK_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 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `TX_ADDR_PRIV`"]
pub type TX_ADDR_PRIV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TX_ADDR_PRIV`"]
pub struct TX_ADDR_PRIV_W<'a> {
w: &'a mut W,
}
impl<'a> TX_ADDR_PRIV_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 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `ADV_RCV_IA_IN_PRIV`"]
pub type ADV_RCV_IA_IN_PRIV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ADV_RCV_IA_IN_PRIV`"]
pub struct ADV_RCV_IA_IN_PRIV_W<'a> {
w: &'a mut W,
}
impl<'a> ADV_RCV_IA_IN_PRIV_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 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `ADV_RPT_PEER_NRPA_ADDR_IN_PRIV`"]
pub type ADV_RPT_PEER_NRPA_ADDR_IN_PRIV_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ADV_RPT_PEER_NRPA_ADDR_IN_PRIV`"]
pub struct ADV_RPT_PEER_NRPA_ADDR_IN_PRIV_W<'a> {
w: &'a mut W,
}
impl<'a> ADV_RPT_PEER_NRPA_ADDR_IN_PRIV_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 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `RCV_TX_ADDR`"]
pub type RCV_TX_ADDR_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Device own address type. 1 - Address type is random. 0 - Address type is public."]
#[inline(always)]
pub fn tx_addr(&self) -> TX_ADDR_R {
TX_ADDR_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 1:2 - The Advertising type is used to determine the packet type that is used for advertising when advertising is enabled. 0x0 - Connectable undirected advertising. (adv_ind) 0x1 - Connectable directed advertising (adv_direct_ind). 0x2 - Discoverable undirected advertising (adv_discover_ind) 0x3 - Non connectable undirected advertising (adv_nonconn_ind)."]
#[inline(always)]
pub fn adv_type(&self) -> ADV_TYPE_R {
ADV_TYPE_R::new(((self.bits >> 1) & 0x03) as u8)
}
#[doc = "Bits 3:4 - Advertising filter policy. The set of devices that the advertising procedure uses for device filtering is called the White List. 0x0 - Allow scan request from any device, allow connect request from any device. 0x1 - Allow scan request from devices in white list only, allow connect request from any device. 0x2 - Allow scan request from any device, allow connect request from devices in white list only. 0x3 - Allow scan request from devices in white list only, allow connect request from devices in white list only."]
#[inline(always)]
pub fn adv_filt_policy(&self) -> ADV_FILT_POLICY_R {
ADV_FILT_POLICY_R::new(((self.bits >> 3) & 0x03) as u8)
}
#[doc = "Bits 5:7 - Advertising channel map indicates the advertising channels used for advertising. By setting the bit, corresponding channel is enabled for use. Atleast one channel bit should be set. 7 - enable channel 39. 6 - enable channel 38. 5 - enable channel 37."]
#[inline(always)]
pub fn adv_channel_map(&self) -> ADV_CHANNEL_MAP_R {
ADV_CHANNEL_MAP_R::new(((self.bits >> 5) & 0x07) as u8)
}
#[doc = "Bit 8 - Peer addresses type. This is the Direct_Address_type field programmed, only if ADV_DIRECT_IND type is sent. 1 - Rx addr type is random. 0 - Rx addr type is public"]
#[inline(always)]
pub fn rx_addr(&self) -> RX_ADDR_R {
RX_ADDR_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Peer secondary addresses type. This is the Direct_Address_type field programmed, only if ADV_DIRECT_IND type is sent. This address type corresponds to the PEER_SERC_ADDR register. Valid only if PRIV_1_2_ADV is set. 1 - Rx secondary addr type is random. 0 - Rx secondary addr type is public"]
#[inline(always)]
pub fn rx_sec_addr(&self) -> RX_SEC_ADDR_R {
RX_SEC_ADDR_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - This bit field is used to specify to the Controller the Low Duty Cycle connectable directed advertising variant being used. 1 - Low Duty Cycle Connectable Directed Advertising. 0 - High Duty Cycle Connectable Directed Advertising."]
#[inline(always)]
pub fn adv_low_duty_cycle(&self) -> ADV_LOW_DUTY_CYCLE_R {
ADV_LOW_DUTY_CYCLE_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - This bit field is used to specify the Advertiser behavior on receiving the same INITA in the connect_req as in the ADV_DIRECT_IND packet it sent. This bit is valid only if PRIV_1_2 and PRIV_1_2_ADV are set. 0 - Accept the connect_req packet 1 - Reject the connect_req packet"]
#[inline(always)]
pub fn inita_rpa_check(&self) -> INITA_RPA_CHECK_R {
INITA_RPA_CHECK_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - Device own address type subtype when Address type is random. This bit is valid only if PRIV_1_2 and PRIV_1_2_ADV are set. 1 - Random Address type is private. 0 - Random Address type is static."]
#[inline(always)]
pub fn tx_addr_priv(&self) -> TX_ADDR_PRIV_R {
TX_ADDR_PRIV_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Advertiser behavior when a peer Identity address is received in privacy mode. This bit is valid only if PRIV_1_2 and PRIV_1_2_ADV are set. 1 - Accept packets with peer identity address not in the Resolving list in privacy mode 0 - Reject packets with peer identity address not in the Resolving list in privacy mode"]
#[inline(always)]
pub fn adv_rcv_ia_in_priv(&self) -> ADV_RCV_IA_IN_PRIV_R {
ADV_RCV_IA_IN_PRIV_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - Advertiser behavior when a peer Non Resolvable Private Address is received in privacy mode. This bit is valid only if PRIV_1_2 and PRIV_1_2_ADV are set. This is applicable when whitelist is disabled. 1 - Only report the packets with peer NRPA address in privacy mode 0 - Respond to packets with peer NRPA address in privacy mode"]
#[inline(always)]
pub fn adv_rpt_peer_nrpa_addr_in_priv(&self) -> ADV_RPT_PEER_NRPA_ADDR_IN_PRIV_R {
ADV_RPT_PEER_NRPA_ADDR_IN_PRIV_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - Transmit address field of the received packet extracted from the receive packet. This field is used by firmware to report peer_addr_type parameter in the connection complete event."]
#[inline(always)]
pub fn rcv_tx_addr(&self) -> RCV_TX_ADDR_R {
RCV_TX_ADDR_R::new(((self.bits >> 15) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Device own address type. 1 - Address type is random. 0 - Address type is public."]
#[inline(always)]
pub fn tx_addr(&mut self) -> TX_ADDR_W {
TX_ADDR_W { w: self }
}
#[doc = "Bits 1:2 - The Advertising type is used to determine the packet type that is used for advertising when advertising is enabled. 0x0 - Connectable undirected advertising. (adv_ind) 0x1 - Connectable directed advertising (adv_direct_ind). 0x2 - Discoverable undirected advertising (adv_discover_ind) 0x3 - Non connectable undirected advertising (adv_nonconn_ind)."]
#[inline(always)]
pub fn adv_type(&mut self) -> ADV_TYPE_W {
ADV_TYPE_W { w: self }
}
#[doc = "Bits 3:4 - Advertising filter policy. The set of devices that the advertising procedure uses for device filtering is called the White List. 0x0 - Allow scan request from any device, allow connect request from any device. 0x1 - Allow scan request from devices in white list only, allow connect request from any device. 0x2 - Allow scan request from any device, allow connect request from devices in white list only. 0x3 - Allow scan request from devices in white list only, allow connect request from devices in white list only."]
#[inline(always)]
pub fn adv_filt_policy(&mut self) -> ADV_FILT_POLICY_W {
ADV_FILT_POLICY_W { w: self }
}
#[doc = "Bits 5:7 - Advertising channel map indicates the advertising channels used for advertising. By setting the bit, corresponding channel is enabled for use. Atleast one channel bit should be set. 7 - enable channel 39. 6 - enable channel 38. 5 - enable channel 37."]
#[inline(always)]
pub fn adv_channel_map(&mut self) -> ADV_CHANNEL_MAP_W {
ADV_CHANNEL_MAP_W { w: self }
}
#[doc = "Bit 8 - Peer addresses type. This is the Direct_Address_type field programmed, only if ADV_DIRECT_IND type is sent. 1 - Rx addr type is random. 0 - Rx addr type is public"]
#[inline(always)]
pub fn rx_addr(&mut self) -> RX_ADDR_W {
RX_ADDR_W { w: self }
}
#[doc = "Bit 9 - Peer secondary addresses type. This is the Direct_Address_type field programmed, only if ADV_DIRECT_IND type is sent. This address type corresponds to the PEER_SERC_ADDR register. Valid only if PRIV_1_2_ADV is set. 1 - Rx secondary addr type is random. 0 - Rx secondary addr type is public"]
#[inline(always)]
pub fn rx_sec_addr(&mut self) -> RX_SEC_ADDR_W {
RX_SEC_ADDR_W { w: self }
}
#[doc = "Bit 10 - This bit field is used to specify to the Controller the Low Duty Cycle connectable directed advertising variant being used. 1 - Low Duty Cycle Connectable Directed Advertising. 0 - High Duty Cycle Connectable Directed Advertising."]
#[inline(always)]
pub fn adv_low_duty_cycle(&mut self) -> ADV_LOW_DUTY_CYCLE_W {
ADV_LOW_DUTY_CYCLE_W { w: self }
}
#[doc = "Bit 11 - This bit field is used to specify the Advertiser behavior on receiving the same INITA in the connect_req as in the ADV_DIRECT_IND packet it sent. This bit is valid only if PRIV_1_2 and PRIV_1_2_ADV are set. 0 - Accept the connect_req packet 1 - Reject the connect_req packet"]
#[inline(always)]
pub fn inita_rpa_check(&mut self) -> INITA_RPA_CHECK_W {
INITA_RPA_CHECK_W { w: self }
}
#[doc = "Bit 12 - Device own address type subtype when Address type is random. This bit is valid only if PRIV_1_2 and PRIV_1_2_ADV are set. 1 - Random Address type is private. 0 - Random Address type is static."]
#[inline(always)]
pub fn tx_addr_priv(&mut self) -> TX_ADDR_PRIV_W {
TX_ADDR_PRIV_W { w: self }
}
#[doc = "Bit 13 - Advertiser behavior when a peer Identity address is received in privacy mode. This bit is valid only if PRIV_1_2 and PRIV_1_2_ADV are set. 1 - Accept packets with peer identity address not in the Resolving list in privacy mode 0 - Reject packets with peer identity address not in the Resolving list in privacy mode"]
#[inline(always)]
pub fn adv_rcv_ia_in_priv(&mut self) -> ADV_RCV_IA_IN_PRIV_W {
ADV_RCV_IA_IN_PRIV_W { w: self }
}
#[doc = "Bit 14 - Advertiser behavior when a peer Non Resolvable Private Address is received in privacy mode. This bit is valid only if PRIV_1_2 and PRIV_1_2_ADV are set. This is applicable when whitelist is disabled. 1 - Only report the packets with peer NRPA address in privacy mode 0 - Respond to packets with peer NRPA address in privacy mode"]
#[inline(always)]
pub fn adv_rpt_peer_nrpa_addr_in_priv(&mut self) -> ADV_RPT_PEER_NRPA_ADDR_IN_PRIV_W {
ADV_RPT_PEER_NRPA_ADDR_IN_PRIV_W { w: self }
}
}
|
use std::str;
use std::io::{Write};
use std::process::{Command, Stdio};
fn main() {
let tmux_window_info_format = "tmux,#{window_index},#{window_name}#{window_flags},(#{window_panes} panes)";
let tmux_list_windows_args = ["list-windows", "-F", tmux_window_info_format];
let output_tmux = Command::new("tmux").args(tmux_list_windows_args).output().expect("Failed to retrieve list of windows from Tmux");
let output_tmux = String::from_utf8_lossy(output_tmux.stdout.as_slice());
let output = Command::new("ratpoison").arg("-c").arg("windows %n,%c,%l,%s,%a,%t").output().expect("Failed to retrieve list of windows from Ratpoison");
let output = String::from_utf8_lossy(output.stdout.as_slice());
let dmenu_args = ["-i", "-l", "3"];
let mut ext_process = Command::new("dmenu").args(dmenu_args).stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().expect("Error opening dmenu");
let ext_process_stdin = ext_process.stdin.as_mut().unwrap();
let window_list = output_tmux.lines().chain(output.lines());
for line in window_list {
let line_ln = format!("{line}\n");
ext_process_stdin.write_all(line_ln.as_bytes()).expect("Error sending list of tmux windows to dmenu");
}
let output = ext_process.wait_with_output().expect("Error while getting chosen window form dmenu");
let chosen_window = str::from_utf8(&output.stdout).unwrap().trim();
//when we have not chosen anything in dmenu, the resulting string's length is 0 (after it is trimmed)
if !chosen_window.is_empty() {
let mut fields = chosen_window.split(',');
if chosen_window.starts_with("tmux") {
let window_number = fields.nth(1).unwrap();
let tmux_args = ["select-window", "-t", window_number];
Command::new("tmux").args(tmux_args).output().expect("Failed to switch windows in Tmux");
} else {
let window_number = fields.next();
if let Some(num) = window_number {
let num: i32 = num.parse().expect("The window number was not an integer"); //this will help us avoid any error in our formatting string "%n,%c".. Had we written "%n|%c" there won't be a number hwn split by ',' and we would catch the error here.
let rp_command = format!("select {num}");
Command::new("ratpoison").arg("-c").arg(rp_command).output().expect("Failed to switch windows in Ratpoison");
}
}
}
}
|
#[doc = "Register `WPCR2` reader"]
pub type R = crate::R<WPCR2_SPEC>;
#[doc = "Register `WPCR2` writer"]
pub type W = crate::W<WPCR2_SPEC>;
#[doc = "Field `TCLKPREP` reader - tCLK-PREPARE"]
pub type TCLKPREP_R = crate::FieldReader;
#[doc = "Field `TCLKPREP` writer - tCLK-PREPARE"]
pub type TCLKPREP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `TCLKZEO` reader - tCLK-ZERO"]
pub type TCLKZEO_R = crate::FieldReader;
#[doc = "Field `TCLKZEO` writer - tCLK-ZERO"]
pub type TCLKZEO_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `THSPREP` reader - tHS-PREPARE"]
pub type THSPREP_R = crate::FieldReader;
#[doc = "Field `THSPREP` writer - tHS-PREPARE"]
pub type THSPREP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `THSTRAIL` reader - tHSTRAIL"]
pub type THSTRAIL_R = crate::FieldReader;
#[doc = "Field `THSTRAIL` writer - tHSTRAIL"]
pub type THSTRAIL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
impl R {
#[doc = "Bits 0:7 - tCLK-PREPARE"]
#[inline(always)]
pub fn tclkprep(&self) -> TCLKPREP_R {
TCLKPREP_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - tCLK-ZERO"]
#[inline(always)]
pub fn tclkzeo(&self) -> TCLKZEO_R {
TCLKZEO_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bits 16:23 - tHS-PREPARE"]
#[inline(always)]
pub fn thsprep(&self) -> THSPREP_R {
THSPREP_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bits 24:31 - tHSTRAIL"]
#[inline(always)]
pub fn thstrail(&self) -> THSTRAIL_R {
THSTRAIL_R::new(((self.bits >> 24) & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - tCLK-PREPARE"]
#[inline(always)]
#[must_use]
pub fn tclkprep(&mut self) -> TCLKPREP_W<WPCR2_SPEC, 0> {
TCLKPREP_W::new(self)
}
#[doc = "Bits 8:15 - tCLK-ZERO"]
#[inline(always)]
#[must_use]
pub fn tclkzeo(&mut self) -> TCLKZEO_W<WPCR2_SPEC, 8> {
TCLKZEO_W::new(self)
}
#[doc = "Bits 16:23 - tHS-PREPARE"]
#[inline(always)]
#[must_use]
pub fn thsprep(&mut self) -> THSPREP_W<WPCR2_SPEC, 16> {
THSPREP_W::new(self)
}
#[doc = "Bits 24:31 - tHSTRAIL"]
#[inline(always)]
#[must_use]
pub fn thstrail(&mut self) -> THSTRAIL_W<WPCR2_SPEC, 24> {
THSTRAIL_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 = "DSI Wrapper PHY Configuration Register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wpcr2::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 [`wpcr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct WPCR2_SPEC;
impl crate::RegisterSpec for WPCR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`wpcr2::R`](R) reader structure"]
impl crate::Readable for WPCR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`wpcr2::W`](W) writer structure"]
impl crate::Writable for WPCR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets WPCR2 to value 0"]
impl crate::Resettable for WPCR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use ctaphid_dispatch::app as ctaphid;
#[allow(unused_imports)]
use crate::msp;
use crate::{Authenticator, TrussedRequirements, UserPresence};
use trussed::interrupt::InterruptFlag;
impl<UP, T> ctaphid::App<'static> for Authenticator<UP, T>
where
UP: UserPresence,
T: TrussedRequirements,
{
fn commands(&self) -> &'static [ctaphid::Command] {
&[ctaphid::Command::Cbor, ctaphid::Command::Msg]
}
#[inline(never)]
fn call(
&mut self,
command: ctaphid::Command,
request: &ctaphid::Message,
response: &mut ctaphid::Message,
) -> ctaphid::AppResult {
debug_now!(
"ctaphid-dispatch: remaining stack: {} bytes",
msp() - 0x2000_0000
);
if request.is_empty() {
debug_now!("invalid request length in ctaphid.call");
return Err(ctaphid::Error::InvalidLength);
}
// info_now!("request: ");
// blocking::dump_hex(request, request.len());
match command {
ctaphid::Command::Cbor => super::handle_ctap2(self, request, response),
ctaphid::Command::Msg => super::handle_ctap1_from_hid(self, request, response),
_ => {
debug_now!("ctaphid trying to dispatch {:?}", command);
}
};
Ok(())
}
fn interrupt(&self) -> Option<&'static InterruptFlag> {
self.trussed.interrupt()
}
}
|
use std::io;
use std::io::prelude::*;
use std::fs::File;
use toml:: { Parser, Decoder, Value };
use rustc_serialize:: { Decodable };
#[derive(RustcDecodable, RustcEncodable, Debug, PartialEq, Default)]
pub struct Config {
app: AppConfig,
window: WinConfig,
}
#[derive(RustcDecodable, RustcEncodable, Debug, PartialEq, Default)]
pub struct AppConfig {
// pub window_type: WindowType,
pub name: Option<String>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, PartialEq, Default)]
pub struct WinConfig {
// pub window_type: WindowType,
pub window_title: String,
pub window_height: u32,
pub window_width: u32,
}
// TODO graph config
//
// TODO default Config
impl Config {
pub fn get_config() -> Self
{
let mut file = File::open("src/config.toml").unwrap();
let mut buffer = String::new();
file.read_to_string(&mut buffer).unwrap();
let v = Parser::new(&buffer).parse().unwrap();
let mut d = Decoder::new(Value::Table(v));
let config = Config::decode(&mut d).unwrap();
assert_eq!(config.app.name, Some("game".to_string()));
config
}
} |
use std::env;
use std::fs;
use std::io;
use intcode;
fn main() {
let input_path: &String = &env::args().nth(1).unwrap();
let input_data = read_input(&input_path).unwrap();
let mut c = intcode::Computer::new(input_data.clone());
c.mem[1] = 12;
c.mem[2] = 2;
c.run().unwrap();
println!("Part 1 result: {}", c.mem[0]);
for i in 0..100 {
for j in 0..100 {
let mut c = intcode::Computer::new(input_data.clone());
c.mem[1] = i;
c.mem[2] = j;
if let Ok(_) = c.run() {
if c.mem[0] == 19690720 {
println!("Part 2 result: {}", i * 100 + j);
break;
}
}
}
}
}
fn read_input(path: &str) -> io::Result<Vec<i64>> {
let contents = fs::read_to_string(path)?;
let numbers: Vec<i64> = contents.trim().split(',').map(|x| x.parse::<i64>().unwrap()).collect();
Ok(numbers)
}
|
use super::{InterpreterKind, MAXIMUM_PYPY_MINOR, MAXIMUM_PYTHON_MINOR, MINIMUM_PYTHON_MINOR};
use crate::target::{Arch, Os};
use crate::Target;
use anyhow::{format_err, Context, Result};
use fs_err as fs;
use serde::Deserialize;
use std::fmt::Write as _;
use std::io::{BufRead, BufReader};
use std::path::Path;
const PYPY_ABI_TAG: &str = "pp73";
const GRAALPY_ABI_TAG: &str = "graalpy230_310_native";
/// Some of the sysconfigdata of Python interpreter we care about
#[derive(Debug, Clone, Deserialize, Eq, PartialEq)]
pub struct InterpreterConfig {
/// Python's major version
pub major: usize,
/// Python's minor version
pub minor: usize,
/// cpython, pypy, or graalpy
#[serde(rename = "interpreter")]
pub interpreter_kind: InterpreterKind,
/// For linux and mac, this contains the value of the abiflags, e.g. "m"
/// for python3.7m or "dm" for python3.6dm. Since python3.8, the value is
/// empty. On windows, the value was always None.
///
/// See PEP 261 and PEP 393 for details
pub abiflags: String,
/// Suffix to use for extension modules as given by sysconfig.
pub ext_suffix: String,
/// Pointer width
pub pointer_width: Option<usize>,
}
impl InterpreterConfig {
/// Lookup a wellknown sysconfig for a given Python interpreter
pub fn lookup_one(
target: &Target,
python_impl: InterpreterKind,
python_version: (usize, usize),
) -> Option<Self> {
use InterpreterKind::*;
let (major, minor) = python_version;
if major < 3 {
// Python 2 is not supported
return None;
}
let python_arch = if matches!(target.target_arch(), Arch::Armv6L | Arch::Armv7L) {
"arm"
} else if matches!(target.target_arch(), Arch::Powerpc64Le) && python_impl == PyPy {
"ppc_64"
} else if matches!(target.target_arch(), Arch::X86) && python_impl == PyPy {
"x86"
} else {
target.get_python_arch()
};
// See https://github.com/pypa/auditwheel/issues/349
let target_env = match python_impl {
CPython => {
if python_version >= (3, 11) {
target.target_env().to_string()
} else {
target.target_env().to_string().replace("musl", "gnu")
}
}
PyPy | GraalPy => "gnu".to_string(),
};
match (target.target_os(), python_impl) {
(Os::Linux, CPython) => {
let abiflags = if python_version < (3, 8) {
"m".to_string()
} else {
"".to_string()
};
let ldversion = format!("{}{}{}", major, minor, abiflags);
let ext_suffix = format!(
".cpython-{}-{}-linux-{}.so",
ldversion, python_arch, target_env
);
Some(Self {
major,
minor,
interpreter_kind: CPython,
abiflags,
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::Linux, PyPy) => {
let abi_tag = format!("pypy{}{}-{}", major, minor, PYPY_ABI_TAG);
let ext_suffix = format!(".{}-{}-linux-{}.so", abi_tag, python_arch, target_env);
Some(Self {
major,
minor,
interpreter_kind: PyPy,
abiflags: String::new(),
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::Macos, CPython) => {
let abiflags = if python_version < (3, 8) {
"m".to_string()
} else {
"".to_string()
};
let ldversion = format!("{}{}{}", major, minor, abiflags);
let ext_suffix = format!(".cpython-{}-darwin.so", ldversion);
Some(Self {
major,
minor,
interpreter_kind: CPython,
abiflags,
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::Macos, PyPy) => {
let ext_suffix = format!(".pypy{}{}-{}-darwin.so", major, minor, PYPY_ABI_TAG);
Some(Self {
major,
minor,
interpreter_kind: PyPy,
abiflags: String::new(),
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::Windows, CPython) => {
let ext_suffix = if python_version < (3, 8) {
".pyd".to_string()
} else {
let platform = match target.target_arch() {
Arch::Aarch64 => "win_arm64",
Arch::X86 => "win32",
Arch::X86_64 => "win_amd64",
_ => return None,
};
format!(".cp{}{}-{}.pyd", major, minor, platform)
};
Some(Self {
major,
minor,
interpreter_kind: CPython,
abiflags: String::new(),
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::Windows, PyPy) => {
if target.target_arch() != Arch::X86_64 {
// PyPy on Windows only supports x86_64
return None;
}
let ext_suffix = format!(".pypy{}{}-{}-win_amd64.pyd", major, minor, PYPY_ABI_TAG);
Some(Self {
major,
minor,
interpreter_kind: PyPy,
abiflags: String::new(),
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::FreeBsd, CPython) => {
let (abiflags, ext_suffix) = if python_version < (3, 8) {
("m".to_string(), ".so".to_string())
} else {
("".to_string(), format!(".cpython-{}{}.so", major, minor))
};
Some(Self {
major,
minor,
interpreter_kind: CPython,
abiflags,
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::NetBsd, CPython) => {
let ext_suffix = ".so".to_string();
Some(Self {
major,
minor,
interpreter_kind: CPython,
abiflags: String::new(),
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::OpenBsd, CPython) => {
let ldversion = format!("{}{}", major, minor);
let ext_suffix = format!(".cpython-{}.so", ldversion);
Some(Self {
major,
minor,
interpreter_kind: CPython,
abiflags: String::new(),
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(Os::Emscripten, CPython) => {
let ldversion = format!("{}{}", major, minor);
let ext_suffix = format!(".cpython-{}-{}-emscripten.so", ldversion, python_arch);
Some(Self {
major,
minor,
interpreter_kind: CPython,
abiflags: String::new(),
ext_suffix,
pointer_width: Some(target.pointer_width()),
})
}
(_, _) => None,
}
}
/// Lookup wellknown sysconfigs for a given target
pub fn lookup_target(target: &Target) -> Vec<Self> {
let mut configs = Vec::new();
for (python_impl, max_minor_ver) in [
(InterpreterKind::CPython, MAXIMUM_PYTHON_MINOR),
(InterpreterKind::PyPy, MAXIMUM_PYPY_MINOR),
] {
for minor in MINIMUM_PYTHON_MINOR..=max_minor_ver {
if let Some(config) = Self::lookup_one(target, python_impl, (3, minor)) {
configs.push(config);
}
}
}
configs
}
/// Construct a new InterpreterConfig from a pyo3 config file
pub fn from_pyo3_config(config_file: &Path, target: &Target) -> Result<Self> {
let config_file = fs::File::open(config_file)?;
let reader = BufReader::new(config_file);
let lines = reader.lines();
macro_rules! parse_value {
($variable:ident, $value:ident) => {
$variable = Some($value.trim().parse().context(format!(
concat!(
"failed to parse ",
stringify!($variable),
" from config value '{}'"
),
$value
))?)
};
}
let mut implementation = None;
let mut version = None;
let mut abiflags = None;
let mut ext_suffix = None;
let mut abi_tag = None;
let mut pointer_width = None;
for (i, line) in lines.enumerate() {
let line = line.context("failed to read line from config")?;
let (key, value) = line
.split_once('=')
.with_context(|| format!("expected key=value pair on line {}", i + 1))?;
match key {
"implementation" => parse_value!(implementation, value),
"version" => parse_value!(version, value),
"abiflags" => parse_value!(abiflags, value),
"ext_suffix" => parse_value!(ext_suffix, value),
"abi_tag" => parse_value!(abi_tag, value),
"pointer_width" => parse_value!(pointer_width, value),
_ => continue,
}
}
let version: String = version.context("missing value for version")?;
let (ver_major, ver_minor) = version
.split_once('.')
.context("Invalid python interpreter version")?;
let major = ver_major.parse::<usize>().with_context(|| {
format!("Invalid python interpreter major version '{ver_major}', expect a digit")
})?;
let minor = ver_minor.parse::<usize>().with_context(|| {
format!("Invalid python interpreter minor version '{ver_minor}', expect a digit")
})?;
let implementation = implementation.unwrap_or_else(|| "cpython".to_string());
let interpreter_kind = implementation.parse().map_err(|e| format_err!("{}", e))?;
let abi_tag = match interpreter_kind {
InterpreterKind::CPython => {
if (major, minor) >= (3, 8) {
abi_tag.unwrap_or_else(|| format!("{major}{minor}"))
} else {
abi_tag.unwrap_or_else(|| format!("{major}{minor}m"))
}
}
InterpreterKind::PyPy => abi_tag.unwrap_or_else(|| PYPY_ABI_TAG.to_string()),
InterpreterKind::GraalPy => abi_tag.unwrap_or_else(|| GRAALPY_ABI_TAG.to_string()),
};
let file_ext = if target.is_windows() { "pyd" } else { "so" };
let ext_suffix = if target.is_linux() || target.is_macos() {
// See https://github.com/pypa/auditwheel/issues/349
let target_env = if (major, minor) >= (3, 11) {
target.target_env().to_string()
} else {
target.target_env().to_string().replace("musl", "gnu")
};
match interpreter_kind {
InterpreterKind::CPython => ext_suffix.unwrap_or_else(|| {
// Eg: .cpython-38-x86_64-linux-gnu.so
format!(
".cpython-{}-{}-{}-{}.{}",
abi_tag,
target.get_python_arch(),
target.get_python_os(),
target_env,
file_ext,
)
}),
InterpreterKind::PyPy => ext_suffix.unwrap_or_else(|| {
// Eg: .pypy38-pp73-x86_64-linux-gnu.so
format!(
".pypy{}{}-{}-{}-{}-{}.{}",
major,
minor,
abi_tag,
target.get_python_arch(),
target.get_python_os(),
target_env,
file_ext,
)
}),
InterpreterKind::GraalPy => ext_suffix.unwrap_or_else(|| {
// e.g. .graalpy230-310-native-x86_64-linux.so
format!(
".{}-{}-{}.{}",
abi_tag.replace('_', "-"),
target.get_python_arch(),
target.get_python_os(),
file_ext,
)
}),
}
} else if target.is_emscripten() && matches!(interpreter_kind, InterpreterKind::CPython) {
ext_suffix.unwrap_or_else(|| {
format!(
".cpython-{}-{}-{}.{}",
abi_tag,
target.get_python_arch(),
target.get_python_os(),
file_ext
)
})
} else {
ext_suffix.context("missing value for ext_suffix")?
};
Ok(Self {
major,
minor,
interpreter_kind,
abiflags: abiflags.unwrap_or_default(),
ext_suffix,
pointer_width,
})
}
/// Generate pyo3 config file content
pub fn pyo3_config_file(&self) -> String {
let mut content = format!(
r#"implementation={implementation}
version={major}.{minor}
shared=true
abi3=false
build_flags=WITH_THREAD
suppress_build_script_link_lines=false"#,
implementation = self.interpreter_kind,
major = self.major,
minor = self.minor,
);
if let Some(pointer_width) = self.pointer_width {
write!(content, "\npointer_width={pointer_width}").unwrap();
}
content
}
}
#[cfg(test)]
mod test {
use super::*;
use expect_test::expect;
use pretty_assertions::assert_eq;
#[test]
fn test_well_known_sysconfigs_linux() {
// CPython
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310-x86_64-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("i686-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310-i386-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("aarch64-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310-aarch64-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("armv7-unknown-linux-gnueabihf".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310-arm-linux-gnueabihf.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("arm-unknown-linux-gnueabihf".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310-arm-linux-gnueabihf.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("powerpc64le-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(
sysconfig.ext_suffix,
".cpython-310-powerpc64le-linux-gnu.so"
);
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("s390x-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310-s390x-linux-gnu.so");
// PyPy
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.abiflags, "");
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-x86_64-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("i686-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-x86-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("aarch64-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-aarch64-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("armv7-unknown-linux-gnueabihf".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-arm-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("arm-unknown-linux-gnueabihf".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-arm-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("powerpc64le-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-ppc_64-linux-gnu.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("s390x-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-s390x-linux-gnu.so");
}
#[test]
fn test_well_known_sysconfigs_macos() {
// CPython
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-apple-darwin".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310-darwin.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("aarch64-apple-darwin".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310-darwin.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-apple-darwin".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 7),
)
.unwrap();
assert_eq!(sysconfig.abiflags, "m");
assert_eq!(sysconfig.ext_suffix, ".cpython-37m-darwin.so");
// PyPy
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-apple-darwin".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.abiflags, "");
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-darwin.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("aarch64-apple-darwin".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-darwin.so");
}
#[test]
fn test_well_known_sysconfigs_windows() {
// CPython
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-pc-windows-msvc".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cp310-win_amd64.pyd");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("i686-pc-windows-msvc".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cp310-win32.pyd");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("aarch64-pc-windows-msvc".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cp310-win_arm64.pyd");
// PyPy
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-pc-windows-msvc".to_string())).unwrap(),
InterpreterKind::PyPy,
(3, 9),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".pypy39-pp73-win_amd64.pyd");
}
#[test]
fn test_well_known_sysconfigs_freebsd() {
// CPython
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-freebsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 7),
)
.unwrap();
assert_eq!(sysconfig.abiflags, "m");
assert_eq!(sysconfig.ext_suffix, ".so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-freebsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.abiflags, "");
assert_eq!(sysconfig.ext_suffix, ".cpython-310.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("i686-unknown-freebsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("aarch64-unknown-freebsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("armv7-unknown-freebsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310.so");
}
#[test]
fn test_well_known_sysconfigs_netbsd() {
// CPython
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-netbsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 7),
)
.unwrap();
assert_eq!(sysconfig.abiflags, "");
assert_eq!(sysconfig.ext_suffix, ".so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-netbsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".so");
}
#[test]
fn test_well_known_sysconfigs_openbsd() {
// CPython
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-openbsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("i686-unknown-openbsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310.so");
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("aarch64-unknown-openbsd".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-310.so");
}
#[test]
fn test_well_known_sysconfigs_emscripten() {
// CPython
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("wasm32-unknown-emscripten".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
assert_eq!(sysconfig.abiflags, "");
assert_eq!(sysconfig.ext_suffix, ".cpython-310-wasm32-emscripten.so");
}
#[test]
fn test_pyo3_config_file() {
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-linux-gnu".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 10),
)
.unwrap();
let config_file = sysconfig.pyo3_config_file();
let expected = expect![[r#"
implementation=CPython
version=3.10
shared=true
abi3=false
build_flags=WITH_THREAD
suppress_build_script_link_lines=false
pointer_width=64"#]];
expected.assert_eq(&config_file);
}
#[test]
fn test_pyo3_config_file_musl_python_3_11() {
let sysconfig = InterpreterConfig::lookup_one(
&Target::from_target_triple(Some("x86_64-unknown-linux-musl".to_string())).unwrap(),
InterpreterKind::CPython,
(3, 11),
)
.unwrap();
assert_eq!(sysconfig.ext_suffix, ".cpython-311-x86_64-linux-musl.so");
let config_file = sysconfig.pyo3_config_file();
let expected = expect![[r#"
implementation=CPython
version=3.11
shared=true
abi3=false
build_flags=WITH_THREAD
suppress_build_script_link_lines=false
pointer_width=64"#]];
expected.assert_eq(&config_file);
}
}
|
extern crate cupi;
extern crate mio;
use mio::{EventLoop, Handler, Token, EventSet};
use cupi::{CuPi};
use cupi::sys::Edge;
const TERM_TOKEN: Token = Token(0);
const PRESS_TOKEN: Token = Token(1);
const DEBOUNCE_TOKEN: Token = Token(2);
struct PressHandler {
pressed: bool
}
impl Handler for PressHandler {
type Timeout = Token;
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<Self>, token: Token, _: EventSet) {
match token {
PRESS_TOKEN => {
if !self.pressed {
self.pressed = true;
event_loop.timeout_ms(DEBOUNCE_TOKEN, 200).unwrap();
println!("Pressed!");
//print!("{}", self.pinin.get().unwrap());
}
},
token => println!("Something with {:?} is ready", token)
}
}
fn timeout(&mut self, event_loop: &mut EventLoop<Self>, token: Token) {
match token {
DEBOUNCE_TOKEN => {
self.pressed = false
}
TERM_TOKEN => {
println!("Stopped.");
event_loop.shutdown();
}
token => println!("Something with {:?} timed out", token)
}
}
}
fn main() {
let cupi = CuPi::new().unwrap();
let _pull_up = cupi.pin(1).unwrap().pull_up().input();
let mut pin = cupi.pin_sys(1).unwrap();
pin.export().unwrap();
let mut event_loop = EventLoop::new().unwrap();
let mut pinin = pin.input().unwrap();
// bind trigger
pinin.trigger(&mut event_loop, PRESS_TOKEN, Edge::FallingEdge).unwrap();
let mut handler = PressHandler { pressed: false };
event_loop.timeout_ms(TERM_TOKEN, 15000).unwrap();
event_loop.run(&mut handler).unwrap();
}
|
use std::collections::VecDeque;
#[derive(Debug, Clone)]
#[allow(dead_code)]
enum Pattern {
Wildcard,
LogicVariable(String),
MemoryVariable(String),
// Repeats are hard. Need to think about thing closely
// RepeatZeroOrMore(Box<Pattern>),
Concat(Box<Pattern>, Box<Pattern>),
StringConstant(String),
IntegerConstant(i32),
Disjunction(Box<Pattern>, Box<Pattern>),
}
fn b<T>(t : T) -> Box<T> {
Box::new(t)
}
fn main() {
let mut states = to_state_machine(
Pattern::Disjunction(b(Pattern::IntegerConstant(2)), b(Pattern::IntegerConstant(3)))
);
states.sort_by_key(|s| s.label);
for state in states {
println!("{:?}", state)
}
}
type Label = i32;
#[derive(Debug)]
#[allow(dead_code)]
enum Op {
NOOP,
Return,
Fail,
SKIP,
CheckString(String),
CheckInteger(i32),
Accumulate(String),
LogicVariableAssign(String),
}
#[derive(Debug)]
struct State {
label: Label,
operation: Op,
then_case: Label, // Maybe Option?
else_case: Label // Maybe Option?
// Or should the be an enum? There are states that can't fail and that is good to know
}
// Should make an interator for patterns
fn to_state_machine(pattern : Pattern) -> Vec<State> {
let mut current_label = 0;
let start = State { label: current_label, operation: Op::NOOP, then_case: current_label + 1, else_case: -1 };
const END_STATE : i32 = std::i32::MAX;
let end = State { label: END_STATE, operation: Op::Return, then_case: -1, else_case: -1};
let mut states = vec!(start, end);
current_label += 1;
let mut queue = VecDeque::new();
queue.push_front(pattern);
let mut else_context = VecDeque::new();
else_context.push_front(END_STATE);
let mut next_context = VecDeque::new();
next_context.push_front(current_label + 1);
loop {
if let Some(pattern) = queue.pop_front() {
println!("{:?} {:?}", pattern, next_context);
let next = next_context.pop_front().unwrap();
let else_case = if queue.is_empty() { END_STATE } else { else_context.pop_front().unwrap_or(END_STATE) };
match pattern {
Pattern::Wildcard => {
states.push(State { label: current_label, operation: Op::SKIP, then_case: next, else_case: else_case });
}
// Really should go to current fail not end
Pattern::IntegerConstant(i) => {
states.push(State { label: current_label, operation: Op::CheckInteger(i), then_case: next, else_case: else_case });
}
Pattern::StringConstant(s) => {
states.push(State { label: current_label, operation: Op::CheckString(s), then_case: next, else_case: else_case });
}
Pattern::MemoryVariable(name) => {
states.push(State { label: current_label, operation: Op::Accumulate(name), then_case: next, else_case: else_case });
}
Pattern::LogicVariable(name) => {
states.push(State { label: current_label, operation: Op::LogicVariableAssign(name), then_case: next, else_case: else_case });
}
// Pattern::RepeatZeroOrMore(pattern) => {
// queue.push_front(*pattern);
// next_context.push_front(current_label);
// if else_case != std::i32::MAX {
// else_context.push_front(else_case);
// } else {
// else_context.push_front(next);
// }
// continue;
// }
Pattern::Concat(p1, p2) => {
queue.push_front(*p2);
queue.push_front(*p1);
next_context.push_front(next);
next_context.push_front(current_label + 1);
if else_case != std::i32::MAX {
else_context.push_front(else_case + 1);
else_context.push_front(else_case + 1);
}
continue;
}
Pattern::Disjunction(p1, p2) => {
queue.push_front(*p2);
queue.push_front(*p1);
next_context.push_front(else_case);
else_context.push_front(current_label + 1);
continue;
}
_ => break
}
current_label += 1;
// Need to figure out how to handle last node.
next_context.push_back(current_label + 1);
} else {
break;
}
}
println!("{:?}", next_context);
return states
}
|
use crate::input::{Input, InputState};
use crate::rom::Rom;
use crate::video::Video;
use cpu::{Cpu, CpuStep};
use mapper::Mapper;
use ppu::{Ppu, PpuStep};
use std::cell::Cell;
use std::ops::{Generator, GeneratorState};
use std::pin::Pin;
use std::u8;
pub mod cpu;
pub mod mapper;
pub mod ppu;
#[derive(Clone)]
pub struct Nes<'a, I>
where
I: NesIo,
{
pub io: &'a I,
input_reader: InputReader<&'a I::Input>,
pub mapper: Mapper,
pub ram: Cell<[u8; 0x0800]>,
pub cpu: Cpu,
pub ppu: Ppu,
}
impl<'a, I> Nes<'a, I>
where
I: NesIo,
{
pub fn new(io: &'a I, rom: Rom) -> Self {
let ram = Cell::new([0; 0x0800]);
let cpu = Cpu::new();
let ppu = Ppu::new();
let mapper = Mapper::from_rom(rom);
let input_reader = InputReader::new(io.input());
let nes = Nes {
io,
input_reader,
mapper,
ram,
cpu,
ppu,
};
let reset_addr = nes.read_u16(0xFFFC);
nes.cpu.pc.set(reset_addr);
nes
}
fn ram(&self) -> &[Cell<u8>] {
let ram: &Cell<[u8]> = &self.ram;
ram.as_slice_of_cells()
}
pub fn read_u8(&self, addr: u16) -> u8 {
let ram = self.ram();
match addr {
0x0000..=0x07FF => ram[addr as usize].get(),
0x2002 => self.ppu.ppustatus(),
0x2007 => self.ppu.read_ppudata(self),
0x4000..=0x4007 => {
// TODO: Return APU pulse
0x00
}
0x4008..=0x400B => {
// TODO: Return APU triangle
0x00
}
0x400C..=0x400F => {
// TODO: Return APU noise
0x00
}
0x4010..=0x4013 => {
// TODO: Return APU DMC
0x00
}
0x4015 => {
// TODO: Return APU status
0x00
}
0x4016 => {
// TODO: Handle open bus behavior!
match self.input_reader.read_port_1_data() {
true => 0b_0000_0001,
false => 0b_0000_0000,
}
}
0x4017 => {
// TODO: Return joystick state
0x40
}
0x6000..=0xFFFF => self.mapper.read_u8(addr),
_ => {
unimplemented!("Unhandled read from address: 0x{:X}", addr);
}
}
}
pub fn read_u16(&self, addr: u16) -> u16 {
let lo = self.read_u8(addr);
let hi = self.read_u8(addr.wrapping_add(1));
lo as u16 | ((hi as u16) << 8)
}
pub fn write_u8(&self, addr: u16, value: u8) {
let ram = self.ram();
match addr {
0x0000..=0x07FF => {
ram[addr as usize].set(value);
}
0x2000 => {
self.ppu.set_ppuctrl(value);
}
0x2001 => {
self.ppu.set_ppumask(value);
}
0x2003 => {
self.ppu.write_oamaddr(value);
}
0x2004 => {
self.ppu.write_oamdata(value);
}
0x2005 => {
self.ppu.write_ppuscroll(value);
}
0x2006 => {
self.ppu.write_ppuaddr(value);
}
0x2007 => {
self.ppu.write_ppudata(self, value);
}
0x4000..=0x4007 => {
// TODO: APU pulse
}
0x4008..=0x400B => {
// TODO: APU triangle
}
0x400C..=0x400F => {
// TODO: APU noise
}
0x4010..=0x4013 => {
// TODO: APU DMC
}
0x4014 => {
self.copy_oam_dma(value);
}
0x4015 => {
// TODO: APU sound channel control
}
0x4016 => {
let strobe = (value & 0b_0000_0001) != 0;
if strobe {
self.input_reader.start_strobe();
} else {
self.input_reader.stop_strobe();
}
}
0x4017 => {
// TODO: Implement APU frame counter
}
0x6000..=0xFFFF => {
self.mapper.write_u8(addr, value);
}
_ => {
unimplemented!("Unhandled write to address: 0x{:X}", addr);
}
}
}
fn push_u8(&self, value: u8) {
let s = self.cpu.s.get();
let stack_addr = 0x0100 | s as u16;
self.write_u8(stack_addr, value);
self.cpu.s.set(s.wrapping_sub(1));
}
fn push_u16(&self, value: u16) {
let value_hi = ((0xFF00 & value) >> 8) as u8;
let value_lo = (0x00FF & value) as u8;
self.push_u8(value_hi);
self.push_u8(value_lo);
}
pub fn read_ppu_u8(&self, addr: u16) -> u8 {
let palette_ram = self.ppu.palette_ram();
match addr {
0x0000..=0x3EFF => self.mapper.read_ppu_u8(self, addr),
0x3F10 => self.read_ppu_u8(0x3F00),
0x3F14 => self.read_ppu_u8(0x3F04),
0x3F18 => self.read_ppu_u8(0x3F08),
0x3F1C => self.read_ppu_u8(0x3F0C),
0x3F00..=0x3FFF => {
let offset = (addr - 0x3F00) as usize % palette_ram.len();
palette_ram[offset].get()
}
0x4000..=0xFFFF => {
unimplemented!("Tried to read from PPU address ${:04X}", addr);
}
}
}
pub fn write_ppu_u8(&self, addr: u16, value: u8) {
let palette_ram = self.ppu.palette_ram();
match addr {
0x0000..=0x3EFF => {
self.mapper.write_ppu_u8(self, addr, value);
}
0x3F10 => {
self.write_ppu_u8(0x3F00, value);
}
0x3F14 => {
self.write_ppu_u8(0x3F04, value);
}
0x3F18 => {
self.write_ppu_u8(0x3F08, value);
}
0x3F1C => {
self.write_ppu_u8(0x3F0C, value);
}
0x3F00..=0x3FFF => {
let offset = (addr - 0x3F00) as usize % palette_ram.len();
palette_ram[offset].set(value);
}
0x4000..=0xFFFF => {
unimplemented!("Tried to write to PPU address ${:04X}", addr);
}
}
}
fn copy_oam_dma(&self, page: u8) {
let target_addr_start = self.ppu.oam_addr.get() as u16;
let mut oam = self.ppu.oam.get();
for index in 0x00..=0xFF {
let source_addr = ((page as u16) << 8) | index;
let byte = self.read_u8(source_addr);
let target_addr = (target_addr_start + index) as usize % oam.len();
oam[target_addr] = byte;
}
self.ppu.oam.set(oam);
}
pub fn run(&'a self) -> impl Generator<Yield = NesStep, Return = !> + 'a {
let mut run_cpu = Cpu::run(&self);
let mut run_ppu = Ppu::run(&self);
move || loop {
// TODO: Clean this up
loop {
match Pin::new(&mut run_cpu).resume(()) {
GeneratorState::Yielded(cpu_step @ CpuStep::Cycle) => {
yield NesStep::Cpu(cpu_step);
break;
}
GeneratorState::Yielded(cpu_step) => {
yield NesStep::Cpu(cpu_step);
}
}
}
for _ in 0u8..3 {
loop {
match Pin::new(&mut run_ppu).resume(()) {
GeneratorState::Yielded(ppu_step @ PpuStep::Cycle) => {
yield NesStep::Ppu(ppu_step);
break;
}
GeneratorState::Yielded(ppu_step) => {
yield NesStep::Ppu(ppu_step);
}
}
}
}
}
}
}
pub enum NesStep {
Cpu(CpuStep),
Ppu(PpuStep),
}
// A trait that encapsulates NES I/O traits (`Video` and `Input`), allowing
// code that uses `Nes` to only take or return a single generic parameter.
pub trait NesIo {
type Video: Video;
type Input: Input;
fn video(&self) -> &Self::Video;
fn input(&self) -> &Self::Input;
}
pub struct NesIoWith<V, I>
where
V: Video,
I: Input,
{
pub video: V,
pub input: I,
}
impl<V, I> NesIo for NesIoWith<V, I>
where
V: Video,
I: Input,
{
type Video = V;
type Input = I;
fn video(&self) -> &Self::Video {
&self.video
}
fn input(&self) -> &Self::Input {
&self.input
}
}
impl<'a, I> NesIo for &'a I
where
I: NesIo,
{
type Video = I::Video;
type Input = I::Input;
fn video(&self) -> &Self::Video {
(*self).video()
}
fn input(&self) -> &Self::Input {
(*self).input()
}
}
#[derive(Clone)]
struct InputReader<I>
where
I: Input,
{
input: I,
strobe: Cell<InputStrobe>,
}
impl<I> InputReader<I>
where
I: Input,
{
fn new(input: I) -> Self {
let strobe = Cell::new(InputStrobe::Live);
InputReader { input, strobe }
}
fn start_strobe(&self) {
self.strobe.set(InputStrobe::Live);
}
fn stop_strobe(&self) {
let state = self.input.input_state();
self.strobe.set(InputStrobe::Strobed {
state,
read_port_1: 0,
read_port_2: 0,
});
}
fn read_port_1_data(&self) -> bool {
match self.strobe.get() {
InputStrobe::Live => {
let current_state = self.input.input_state();
current_state.joypad_1.a
}
InputStrobe::Strobed {
state,
read_port_1,
read_port_2,
} => {
let data = match read_port_1 {
0 => state.joypad_1.a,
1 => state.joypad_1.b,
2 => state.joypad_1.select,
3 => state.joypad_1.start,
4 => state.joypad_1.up,
5 => state.joypad_1.down,
6 => state.joypad_1.left,
7 => state.joypad_1.right,
_ => true,
};
self.strobe.set(InputStrobe::Strobed {
state,
read_port_1: read_port_1.saturating_add(1),
read_port_2,
});
data
}
}
}
}
#[derive(Clone, Copy)]
enum InputStrobe {
Live,
Strobed {
state: InputState,
read_port_1: u8,
read_port_2: u8,
},
}
|
use std::time::Duration;
use log::error;
use redis::aio::Connection;
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::error::{Error, Result};
use redis::RedisResult;
use crate::service::ICacheService;
use async_trait::async_trait;
///缓存服务
pub struct RedisService {
pub client: redis::Client,
}
impl RedisService {
pub fn new(url: &str) -> Self {
let client = redis::Client::open(url).unwrap();
println!("[abs_admin] conncect redis success!");
Self { client }
}
pub async fn get_conn(&self) -> Result<Connection> {
let conn = self.client.get_async_connection().await;
if conn.is_err() {
let err = format!("RedisService connect fail:{}", conn.err().unwrap());
error!("{}", err);
return Err(crate::error::Error::from(err));
}
return Ok(conn.unwrap());
}
}
#[async_trait]
impl ICacheService for RedisService {
async fn set_json<T>(&self, k: &str, v: &T) -> Result<String> where T: Serialize+Sync,
{
let data = serde_json::to_string(v);
if data.is_err() {
return Err(crate::error::Error::from(format!(
"RedisService set_json fail:{}",
data.err().unwrap()
)));
}
let data = self.set_string(k, data.unwrap().as_str()).await?;
Ok(data)
}
async fn get_json<T>(&self, k: &str) -> Result<T>
where
T: DeserializeOwned,
{
let mut r = self.get_string(k).await?;
if r.is_empty() {
r = "null".to_string();
}
let data: serde_json::Result<T> = serde_json::from_str(r.as_str());
if data.is_err() {
return Err(crate::error::Error::from(format!(
"RedisService get_json fail:{}",
data.err().unwrap()
)));
}
Ok(data.unwrap())
}
async fn set_string(&self, k: &str, v: &str) -> Result<String> {
return self.set_string_ex(k, v, None).await;
}
async fn get_string(&self, k: &str) -> Result<String> {
let mut conn = self.get_conn().await?;
let result: RedisResult<Option<String>> =
redis::cmd("GET").arg(&[k]).query_async(&mut conn).await;
match result {
Ok(v) => {
return Ok(v.unwrap_or(String::new()));
}
Err(e) => {
return Err(Error::from(format!(
"RedisService get_string({}) fail:{}",
k,
e.to_string()
)));
}
}
}
///set_string 自动过期
async fn set_string_ex(&self, k: &str, v: &str, ex: Option<Duration>) -> Result<String> {
let mut conn = self.get_conn().await?;
if ex.is_none() {
return match redis::cmd("SET").arg(&[k, v]).query_async(&mut conn).await {
Ok(v) => Ok(v),
Err(e) => Err(Error::from(format!(
"RedisService set_string_ex fail:{}",
e.to_string()
))),
};
} else {
return match redis::cmd("SET")
.arg(&[k, v, "EX", &ex.unwrap().as_secs().to_string()])
.query_async(&mut conn)
.await
{
Ok(v) => Ok(v),
Err(e) => Err(Error::from(format!(
"RedisService set_string_ex fail:{}",
e.to_string()
))),
};
}
}
///set_string 自动过期
async fn ttl(&self, k: &str) -> Result<i64> {
let mut conn = self.get_conn().await?;
return match redis::cmd("TTL").arg(&[k]).query_async(&mut conn).await {
Ok(v) => Ok(v),
Err(e) => Err(Error::from(format!(
"RedisService ttl fail:{}",
e.to_string()
))),
};
}
}
|
use solana_sdk_bpf_utils::info;
#[derive(Debug)]
pub enum ProgramError {
CannotPayoutToLosers,
CannotPayoutToSubset,
InvalidInput,
InvalidCommand,
InvalidTallyKey,
InvalidPayoutOrder,
MaxPollCapacity,
MaxTallyCapacity,
MissingSigner,
PollAlreadyCreated,
PollAlreadyFinished,
PollNotFinished,
PollHasNoFunds,
PollCannotBeEven,
}
pub type ProgramResult<T> = core::result::Result<T, ProgramError>;
impl ProgramError {
pub fn print(&self) {
match self {
ProgramError::CannotPayoutToLosers => info!("Error: CannotPayoutToLosers"),
ProgramError::CannotPayoutToSubset => info!("Error: CannotPayoutToSubset"),
ProgramError::InvalidInput => info!("Error: InvalidInput"),
ProgramError::InvalidCommand => info!("Error: InvalidCommand"),
ProgramError::InvalidTallyKey => info!("Error: InvalidTallyKey"),
ProgramError::InvalidPayoutOrder => info!("Error: InvalidPayoutOrder"),
ProgramError::MaxPollCapacity => info!("Error: MaxPollCapacity"),
ProgramError::MaxTallyCapacity => info!("Error: MaxTallyCapacity"),
ProgramError::MissingSigner => info!("Error: MissingSigner"),
ProgramError::PollAlreadyCreated => info!("Error: PollAlreadyCreated"),
ProgramError::PollAlreadyFinished => info!("Error: PollAlreadyFinished"),
ProgramError::PollNotFinished => info!("Error: PollNotFinished"),
ProgramError::PollHasNoFunds => info!("Error: PollHasNoFunds"),
ProgramError::PollCannotBeEven => info!("Error: PollCannotBeEven"),
}
}
}
|
use crate::block::Block;
use crate::chunk::ChunkGridCoordinate;
use crate::chunk::{Chunk, CHUNK_DEPTH, CHUNK_WIDTH};
use crate::world::generation::HeightMap;
use crate::world::generation::WorldSeed;
use math::geometry::Rect;
use math::vector::Vector2;
use math::random::noise::{CombinedNoise, LayeredNoiseOptions};
use math::random::Prng;
pub fn generate_chunk(coords: ChunkGridCoordinate, seed: WorldSeed) -> Chunk {
let generator = WorldGenerator::new(seed);
generator.generate_chunk(coords)
}
const BASE_BLOCK: Block = Block { id: 7 };
const STONE_BLOCK: Block = Block { id: 1 };
const DIRT_BLOCK: Block = Block { id: 3 };
const GRASS_BLOCK: Block = Block { id: 2 };
const LOG_BLOCK: Block = Block { id: 17 };
const LEAVES_BLOCK: Block = Block { id: 18 };
const TALL_GRASS_BLOCK: Block = Block { id: 31 };
const BASE_THICKNESS: usize = 5;
const BASE_FILL_DECREASE: f32 = 0.2;
const MIN_DIRT_THICKNESS: usize = 3;
const MAX_DIRT_THICKNESS: usize = 5;
pub struct WorldGenerator {
seed: WorldSeed,
}
impl WorldGenerator {
pub fn new(seed: WorldSeed) -> Self {
Self { seed }
}
fn generate_base(&self, chunk: &mut Chunk, prng: &mut Prng) {
let mut value = 1.0;
for y in 0..BASE_THICKNESS {
for x in 0..CHUNK_WIDTH {
for z in 0..CHUNK_DEPTH {
if prng.next_f32() <= value {
chunk.set_block(x, y, z, BASE_BLOCK);
} else {
chunk.set_block(x, y, z, STONE_BLOCK);
}
}
}
value -= BASE_FILL_DECREASE;
}
}
fn generate_strata(&self, chunk: &mut Chunk, prng: &mut Prng, height_map: &HeightMap) {
for x in 0..CHUNK_WIDTH {
for z in 0..CHUNK_DEPTH {
let height = height_map.height(x as u8, z as u8) as usize;
let dirt_thickness = prng.next_in_range(MIN_DIRT_THICKNESS..MAX_DIRT_THICKNESS + 1);
let dirt_height = height - dirt_thickness;
for y in BASE_THICKNESS..dirt_height {
chunk.set_block(x, y, z, STONE_BLOCK);
}
for y in dirt_height..height {
chunk.set_block(x, y, z, DIRT_BLOCK);
}
if height < 62 {
chunk.set_block(x, height, z, Block { id: 12 });
} else {
chunk.set_block(x, height, z, GRASS_BLOCK);
}
}
}
}
pub fn generate_tree(&self, x: usize, y: usize, z: usize, chunk: &mut Chunk, prng: &mut Prng) {
let height = prng.next_in_range(4..7);
chunk.set_block(x, y + height + 1, z, LEAVES_BLOCK);
chunk.set_block(x + 1, y + height + 1, z, LEAVES_BLOCK);
chunk.set_block(x - 1, y + height + 1, z, LEAVES_BLOCK);
chunk.set_block(x, y + height + 1, z + 1, LEAVES_BLOCK);
chunk.set_block(x, y + height + 1, z - 1, LEAVES_BLOCK);
for i in x - 1..=x + 1 {
for j in z - 1..=z + 1 {
chunk.set_block(i, y + height, j, LEAVES_BLOCK);
}
}
for i in x - 2..=x + 2 {
for j in z - 2..=z + 2 {
for k in y + height - 2..=y + height - 1 {
chunk.set_block(i, k, j, LEAVES_BLOCK);
}
}
}
for i in y..y + height {
chunk.set_block(x, i, z, LOG_BLOCK);
}
}
pub fn generate_chunk(&self, coords: ChunkGridCoordinate) -> Chunk {
let chunk_seed = self.seed.to_chunk_seed(coords);
let origin = Vector2::new(
(coords.x * CHUNK_WIDTH as i64) as f32,
(coords.z * CHUNK_DEPTH as i64) as f32,
);
let rect = Rect::new(origin, CHUNK_WIDTH as f32, CHUNK_DEPTH as f32);
let mut prng = Prng::new(chunk_seed.0);
let noise = CombinedNoise::new(
LayeredNoiseOptions::new(4, 100.0, 0.50, 2.0, self.seed.0),
LayeredNoiseOptions::new(6, 60.0, 0.50, 1.9, self.seed.0),
10.0,
);
//let height_map = HeightMap::new(rect, 40..200, noise);
let height_map = HeightMap::new(rect, 40..80, noise);
let mut chunk = Chunk::new(coords);
self.generate_base(&mut chunk, &mut prng);
self.generate_strata(&mut chunk, &mut prng, &height_map);
// TODO: remove this draft
for x in 2..CHUNK_WIDTH - 2 {
for z in 2..CHUNK_DEPTH - 2 {
let y = height_map.height(x as u8, z as u8) + 1;
if y <= 63 {
continue;
}
if prng.next_f32() > 0.96 {
self.generate_tree(x, y as usize, z, &mut chunk, &mut prng);
} else if prng.next_f32() > 0.96 {
chunk.set_block(x, y as usize, z, TALL_GRASS_BLOCK);
} else if prng.next_f32() > 0.99 {
chunk.set_block(x, y as usize, z, Block { id: 38 });
} else if prng.next_f32() > 0.99 {
chunk.set_block(x, y as usize, z, Block { id: 37 });
}
}
}
for x in 0..CHUNK_WIDTH {
for z in 0..CHUNK_DEPTH {
let y = height_map.height(x as u8, z as u8) + 1;
for i in y..63 {
chunk.set_block(x, i as usize, z, Block { id: 9 });
}
}
}
chunk
}
}
|
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_possible_wrap)]
use std::sync::mpsc;
use intcode;
// This code just serves as an interface between the Intcode computer and the user - it makes
// no effort to automatically play the game, sorry. Not interested in doing a bunch of dull
// text parsing plus yet more maze solving!
fn main() {
let program = intcode::load_program("day25/input.txt").unwrap_or_else(|err| {
println!("Could not load input file!\n{:?}", err);
std::process::exit(1);
});
let (in_send, in_recv) = mpsc::channel();
let (out_send, out_recv) = mpsc::channel();
let mut computer = intcode::ChannelIOComputer::new(&program, in_recv, out_send);
std::thread::spawn(move || { computer.run(); });
loop {
let mut display = String::new();
loop {
let c = out_recv.recv().unwrap() as u8 as char;
if c == '\n' {
println!("{}", display);
if display.eq("Command?") { break; }
display.clear();
} else {
display.push(c);
}
}
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Did not enter a string");
// Bloody Windows and its CRLF line endings
if let Some('\n') = input.chars().next_back() {
input.pop();
}
if let Some('\r') = input.chars().next_back() {
input.pop();
}
input.push('\n');
for c in input.chars() {
in_send.send(c as i64).unwrap();
}
}
}
|
use std::str;
fn main() {
let test_cases = [("Spenglerium", "Ee"), ("Zeddemorium", "Zr"),
("Venkmine", "Kn"), ("Stantzon", "Zt"), ("Melintzum", "Nn"), ("Tullium", "Ty")];
for test_case in test_cases.iter(){
if check(test_case.0, test_case.1) == true{
println!("The symbol {} works for {}", test_case.1, test_case.0);
} else{
println!("The symbol {} does not work for {}", test_case.1, test_case.0);
}
}
}
fn check(element: &str, symbol: &str) -> bool{
let first_letter = symbol.chars().nth(0).unwrap().to_lowercase().nth(0).unwrap();
let second_letter = symbol.chars().nth(1).unwrap().to_lowercase().nth(0).unwrap();
let mut result: bool = false;
for letter in element.char_indices(){
if letter.1.to_lowercase().nth(0).unwrap() == first_letter{
let new_strs = element.split_at(letter.0 + 1);
//Will not work for non-one byte strings, I will try to implement this
for character in new_strs.1.chars(){
if character == second_letter{
result = true;
}
}
}
}
return result;
}
|
use color_eyre::eyre::{Result, WrapErr};
use futures::future;
use tokio::sync::mpsc;
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::task::JoinHandle;
use crate::messages::{Command, CommandResult};
use reqwest::Client;
use std::time::Duration;
pub async fn dispatcher(
mut command_source: Receiver<Command>,
result_sink: Sender<CommandResult>,
) -> Result<()> {
// Block is to control lifetime of drain_tx
let drain_handle = {
let (drain_tx, drain_rx) = mpsc::channel::<JoinHandle<Result<()>>>(32);
let drain_handle = tokio::spawn(drain_requests(drain_rx));
let http_client: Client = Client::builder()
.timeout(Duration::from_secs(5))
.build()
.wrap_err("Unable to build HTTP client")?;
while let Some(command) = command_source.recv().await {
let requests = command
.urls
.iter()
.map(|url| tokio::spawn(request_url(http_client.clone(), url.clone(), result_sink.clone())))
.collect();
let request_handle = tokio::spawn(run_requests(requests));
drain_tx
.send(request_handle)
.await
.wrap_err("Error sending request to drain")?;
}
drain_handle
};
println!("Done dispatching!");
drain_handle.await.wrap_err("Error draining requests")??;
println!("Done draining!");
Ok(())
}
async fn drain_requests(mut requests_rx: Receiver<JoinHandle<Result<()>>>) -> Result<()> {
while let Some(join_handle) = requests_rx.recv().await {
join_handle.await.wrap_err("Request returned error")??;
}
println!("Done waiting on all requests!");
Ok(())
}
async fn request_url(http_client: Client, url: String, result_tx: Sender<CommandResult>) -> Result<()> {
let request = http_client.get(&url)
.build()
.wrap_err("Unable to build GET request")?;
let response = http_client.execute(request).await;
let command_result = match response {
Ok(result) => {
let status = result.status().as_str().to_string();
let mut start_of_response: String = result
.text()
.await
.unwrap_or("<error getting body>".to_string())
.chars()
.take(60)
.collect();
if start_of_response.len() == 60 {
start_of_response.push_str("...");
}
CommandResult {
url,
output: format!("{} {}", status, start_of_response),
}
}
Err(e) => CommandResult {
url,
output: format!(
"{} {}",
e.status()
.map(|status| status.as_str().to_string())
.unwrap_or("<none>".to_string()),
e.to_string()
),
},
};
result_tx
.send(command_result)
.await
.wrap_err("Error sending CommandResult")
}
async fn run_requests(requests: Vec<JoinHandle<Result<()>>>) -> Result<()> {
future::try_join_all(requests).await?;
Ok(())
}
|
#[doc = "Register `DCR2` reader"]
pub type R = crate::R<DCR2_SPEC>;
#[doc = "Register `DCR2` writer"]
pub type W = crate::W<DCR2_SPEC>;
#[doc = "Field `PRESCALER` reader - Clock prescaler"]
pub type PRESCALER_R = crate::FieldReader;
#[doc = "Field `PRESCALER` writer - Clock prescaler"]
pub type PRESCALER_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 8, O>;
#[doc = "Field `WRAPSIZE` reader - Wrap size"]
pub type WRAPSIZE_R = crate::FieldReader<WRAPSIZE_A>;
#[doc = "Wrap size\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum WRAPSIZE_A {
#[doc = "0: Wrapped reads are not supported by the memory"]
NoWrappingSupport = 0,
#[doc = "2: External memory supports wrap size of 16 bytes"]
WrappingSize16 = 2,
#[doc = "3: External memory supports wrap size of 16 bytes"]
WrappingSize32 = 3,
#[doc = "4: External memory supports wrap size of 16 bytes"]
WrappingSize64 = 4,
#[doc = "5: External memory supports wrap size of 16 bytes"]
WrappingSize128 = 5,
}
impl From<WRAPSIZE_A> for u8 {
#[inline(always)]
fn from(variant: WRAPSIZE_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for WRAPSIZE_A {
type Ux = u8;
}
impl WRAPSIZE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<WRAPSIZE_A> {
match self.bits {
0 => Some(WRAPSIZE_A::NoWrappingSupport),
2 => Some(WRAPSIZE_A::WrappingSize16),
3 => Some(WRAPSIZE_A::WrappingSize32),
4 => Some(WRAPSIZE_A::WrappingSize64),
5 => Some(WRAPSIZE_A::WrappingSize128),
_ => None,
}
}
#[doc = "Wrapped reads are not supported by the memory"]
#[inline(always)]
pub fn is_no_wrapping_support(&self) -> bool {
*self == WRAPSIZE_A::NoWrappingSupport
}
#[doc = "External memory supports wrap size of 16 bytes"]
#[inline(always)]
pub fn is_wrapping_size16(&self) -> bool {
*self == WRAPSIZE_A::WrappingSize16
}
#[doc = "External memory supports wrap size of 16 bytes"]
#[inline(always)]
pub fn is_wrapping_size32(&self) -> bool {
*self == WRAPSIZE_A::WrappingSize32
}
#[doc = "External memory supports wrap size of 16 bytes"]
#[inline(always)]
pub fn is_wrapping_size64(&self) -> bool {
*self == WRAPSIZE_A::WrappingSize64
}
#[doc = "External memory supports wrap size of 16 bytes"]
#[inline(always)]
pub fn is_wrapping_size128(&self) -> bool {
*self == WRAPSIZE_A::WrappingSize128
}
}
#[doc = "Field `WRAPSIZE` writer - Wrap size"]
pub type WRAPSIZE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O, WRAPSIZE_A>;
impl<'a, REG, const O: u8> WRAPSIZE_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Wrapped reads are not supported by the memory"]
#[inline(always)]
pub fn no_wrapping_support(self) -> &'a mut crate::W<REG> {
self.variant(WRAPSIZE_A::NoWrappingSupport)
}
#[doc = "External memory supports wrap size of 16 bytes"]
#[inline(always)]
pub fn wrapping_size16(self) -> &'a mut crate::W<REG> {
self.variant(WRAPSIZE_A::WrappingSize16)
}
#[doc = "External memory supports wrap size of 16 bytes"]
#[inline(always)]
pub fn wrapping_size32(self) -> &'a mut crate::W<REG> {
self.variant(WRAPSIZE_A::WrappingSize32)
}
#[doc = "External memory supports wrap size of 16 bytes"]
#[inline(always)]
pub fn wrapping_size64(self) -> &'a mut crate::W<REG> {
self.variant(WRAPSIZE_A::WrappingSize64)
}
#[doc = "External memory supports wrap size of 16 bytes"]
#[inline(always)]
pub fn wrapping_size128(self) -> &'a mut crate::W<REG> {
self.variant(WRAPSIZE_A::WrappingSize128)
}
}
impl R {
#[doc = "Bits 0:7 - Clock prescaler"]
#[inline(always)]
pub fn prescaler(&self) -> PRESCALER_R {
PRESCALER_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 16:18 - Wrap size"]
#[inline(always)]
pub fn wrapsize(&self) -> WRAPSIZE_R {
WRAPSIZE_R::new(((self.bits >> 16) & 7) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - Clock prescaler"]
#[inline(always)]
#[must_use]
pub fn prescaler(&mut self) -> PRESCALER_W<DCR2_SPEC, 0> {
PRESCALER_W::new(self)
}
#[doc = "Bits 16:18 - Wrap size"]
#[inline(always)]
#[must_use]
pub fn wrapsize(&mut self) -> WRAPSIZE_W<DCR2_SPEC, 16> {
WRAPSIZE_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 = "device configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dcr2::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 [`dcr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DCR2_SPEC;
impl crate::RegisterSpec for DCR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`dcr2::R`](R) reader structure"]
impl crate::Readable for DCR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`dcr2::W`](W) writer structure"]
impl crate::Writable for DCR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DCR2 to value 0"]
impl crate::Resettable for DCR2_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
pub type __time_t = ::std::os::raw::c_long;
pub type __suseconds_t = ::std::os::raw::c_long;
pub type __u32 = ::std::os::raw::c_uint;
pub type __s32 = ::std::os::raw::c_int;
pub type __s16 = ::std::os::raw::c_short;
pub type __u16 = ::std::os::raw::c_ushort;
#[repr(C)]
pub struct uinput_user_dev {
pub name: [::std::os::raw::c_char; 80usize],
pub id: input_id,
pub ff_effects_max: __u32,
pub absmax: [__s32; 64usize],
pub absmin: [__s32; 64usize],
pub absfuzz: [__s32; 64usize],
pub absflat: [__s32; 64usize],
}
#[repr(C)]
pub struct input_id {
pub bustype: __u16,
pub vendor: __u16,
pub product: __u16,
pub version: __u16,
}
#[repr(C)]
pub struct input_event {
pub time: timeval,
pub kind: __u16,
pub code: __u16,
pub value: __s32,
}
#[repr(C)]
pub struct timeval {
pub tv_sec: __time_t,
pub tv_usec: __suseconds_t,
}
|
// Problem 40 - Champernowne's constant
//
// An irrational decimal fraction is created by concatenating the positive
// integers:
//
// 0.12345678910[1]112131415161718192021...
//
// It can be seen that the 12th digit of the fractional part is 1.
//
// If d(n) represents the n-th digit of the fractional part, find the value of the
// following expression.
//
// d(1) × d(10) × d(100) × d(1000) × d(10000) × d(100000) × d(1000000)
fn main() {
println!("{}", solution());
}
fn solution() -> usize {
let indices = vec![1, 10, 100, 1_000, 10_000, 100_000, 1_000_000];
let max_idx = *indices.last().unwrap();
let fstr = (1..max_idx).map(|n| n.to_string())
.collect::<String>();
let fbytes = fstr.as_bytes();
let zero = '0' as u8;
let mut product: usize = 1;
for idx in indices {
product *= (fbytes[idx - 1] - zero) as usize;
}
product
}
|
//
// Copyright (C) 2020 Abstract Horizon
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Apache License v2.0
// which accompanies this distribution, and is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// Contributors:
// Daniel Sendula - initial API and implementation
//
#[allow(non_snake_case)]
pub fn SIMPLE_DIFFERENCE(x: f64, y: f64) -> f64 { x - y }
pub struct PID {
pub set_point: f64,
pub p: f64,
pub i: f64,
pub d: f64,
pub kp: f64,
pub ki: f64,
pub kd: f64,
pub kg: f64,
pub i_gain_scale: f64,
pub d_gain_scale: f64,
pub dead_band: f64,
pub last_error: f64,
pub last_time: f64,
pub last_output: f64,
pub last_delta: f64,
first: bool,
difference: fn(f64, f64) -> f64,
}
impl PID {
pub fn new(
p_gain: f64, i_gain: f64, d_gain: f64, gain: f64,
dead_band: f64, i_gain_scale: f64, d_gain_scale: f64,
difference: fn(f64, f64) -> f64) -> PID {
PID {
set_point: 0.0,
p: 0.0, i: 0.0, d: 0.0,
kp: p_gain, ki: i_gain, kd: d_gain, kg: gain,
i_gain_scale, d_gain_scale,
dead_band,
last_error: 0.0,
last_time: 0.0,
last_output: 0.0,
last_delta: 0.0,
first: true,
difference
}
}
pub fn process(&mut self, time:f64, set_point: f64, current: f64) -> f64 {
let mut error = (self.difference)(set_point, current);
if error.abs() <= self.dead_band {
error = 0.0;
}
if self.first {
self.first = false;
self.set_point = set_point;
self.last_error = error;
self.last_time = time;
0.0
} else {
let delta_time = time - self.last_time;
self.p = error;
if (self.last_error < 0.0 && 0.0 < error) || (self.last_error > 0.0 && 0.0 > error) {
self.i = 0.0
} else if error.abs() <= 0.01 {
self.i = 0.0;
} else {
self.i += error * delta_time * self.i_gain_scale
}
if delta_time > 0.0 {
self.d = (error - self.last_error) / (delta_time * self.d_gain_scale);
}
let mut output = self.p * self.kp + self.i * self.ki + self.d * self.kd;
output *= self.kg;
self.set_point = set_point;
self.last_output = output;
self.last_error = error;
self.last_time = time;
self.last_delta = delta_time;
output
}
}
}
|
#[macro_use]
mod obsmodule;
obs_declare_module!("obs-module-rust", "Rust OBS module example");
obs_module_author!("Stéphane Lepin");
#[no_mangle]
pub extern fn obs_module_load() -> bool
{
println!("Rust module loaded!");
true
}
#[no_mangle]
pub extern fn obs_module_unload() -> ()
{
println!("Rust module unloaded!");
} |
use std::collections::HashMap;
mod matrix_keyboard;
mod matrix_mice;
mod razer_report;
mod soft_keyboard;
pub use self::razer_report::Color;
use errors::{Error, ErrorKind, Result};
use hidapi::{HidApi, HidDevice};
use log::Level;
use std::ffi::CString;
use std::thread;
use std::time;
use self::matrix_keyboard::MatrixKeyboardFactory;
use self::matrix_mice::MatrixMiceFactory;
use self::razer_report::{RazerReport, RazerStatus};
use self::soft_keyboard::SoftKeyboardFactory;
const RAZER_VENDOR: u16 = 0x1532;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct DeviceId {
vendor_id: u16,
product_id: u16,
interface_number: i32,
}
pub trait DeviceFactory: Sync {
fn name(&self) -> &'static str;
fn open(&self, hid_device: HidDevice) -> Box<Device>;
}
pub trait Device {
fn name(&self) -> &'static str;
fn hid_device<'a>(&'a self) -> &'a HidDevice;
fn get_brightness(&self) -> Result<u8>;
fn set_brightness(&self, brightness: u8) -> Result<()>;
fn set_color(&self, color: Color) -> Result<()>;
fn get_manufacturer(&self) -> Result<Option<String>> {
Ok(self.hid_device().get_manufacturer_string()?)
}
fn get_product(&self) -> Result<Option<String>> {
Ok(self.hid_device().get_product_string()?)
}
fn send_report(&self, mut request: RazerReport) -> Result<RazerReport> {
let mut result: RazerReport = Default::default();
request.calculate_crc();
let mut last_error: Error = ErrorKind::NotSuccessful.into();
for retry in 0..3 {
if log_enabled!(Level::Debug) {
debug!("Sending >>>: {:?}", request);
}
match self.hid_device().send_feature_report(request.as_raw()) {
Ok(_) => (),
Err(error) => {
last_error = error.into();
continue;
}
}
if retry == 0 {
thread::sleep(time::Duration::from_micros(800));
} else {
thread::sleep(time::Duration::from_micros(8000));
}
match self.hid_device().get_feature_report(result.as_mut_raw()) {
Ok(_) => (),
Err(error) => {
last_error = error.into();
continue;
}
}
if log_enabled!(Level::Debug) {
debug!("Received <<<: {:?}", result);
}
if result.status == RazerStatus::NotSupported as u8 {
return Err(ErrorKind::NotSupported.into());
} else if result.status == RazerStatus::Successful as u8 {
return Ok(result);
}
}
Err(last_error)
}
fn get_serial(&self) -> Result<CString> {
let result = self.send_report(RazerReport::standard_get_serial())?;
let mut size = result.data_size as usize;
size = result
.arguments
.iter()
.take(size)
.position(|c| *c == 0x0)
.unwrap_or(size);
Ok(CString::new(&result.arguments[0..size])?)
}
}
impl DeviceId {
pub fn new(vendor_id: u16, product_id: u16, interface_number: i32) -> DeviceId {
DeviceId {
vendor_id,
product_id,
interface_number,
}
}
}
lazy_static! {
static ref known_devices: HashMap<DeviceId, Box<DeviceFactory>> = {
let mut map = HashMap::<DeviceId, Box<DeviceFactory>>::new();
map.insert(
DeviceId::new(RAZER_VENDOR, 0x0060, 0),
MatrixMiceFactory::new("Razer Lancehead TE", &[1, 4, 16, 17]),
);
map.insert(
DeviceId::new(RAZER_VENDOR, 0x0226, 0),
SoftKeyboardFactory::new("Razer Huntsman Elite"),
);
map.insert(
DeviceId::new(RAZER_VENDOR, 0x0221, 0),
MatrixKeyboardFactory::new("Razer BlackWidow Chroma V2", &[5]),
);
map
};
}
pub fn list_devices() -> Result<Vec<Box<Device>>> {
let api = HidApi::new()?;
let mut devices: Vec<Box<Device>> = Vec::new();
for hid_device_info in api.devices() {
if let Some(device_factory) = known_devices.get(&DeviceId::new(
hid_device_info.vendor_id,
hid_device_info.product_id,
hid_device_info.interface_number,
)) {
let hid_device = hid_device_info.open_device(&api)?;
devices.push(device_factory.open(hid_device));
}
}
Ok(devices)
}
|
/*
chapter 4
syntax and semantics
*/
fn main() {
let mut a = 5; {
let b = &mut a; // -+ &mut borrow starts here
*b += 1; // |
} // -+ ... and ends here
println!("{}", a); // <- try to borrow x here
}
// output should be:
/*
*/
|
pub mod commit_txs_scanner;
pub mod entry;
pub(crate) mod container;
pub(crate) mod orphan;
pub(crate) mod pending;
pub(crate) mod proposed;
pub use self::entry::{DefectEntry, TxEntry};
const DEFAULT_BYTES_PER_CYCLES: f64 = 0.000_17f64;
/// Virtual bytes(aka vbytes) is a concept to unify the size and cycles of a transaction,
/// tx_pool use vbytes to estimate transaction fee rate.
pub(crate) fn get_transaction_virtual_bytes(tx_size: usize, cycles: u64) -> u64 {
std::cmp::max(
tx_size as u64,
(cycles as f64 * DEFAULT_BYTES_PER_CYCLES) as u64,
)
}
|
use std::io;
fn main() {
loop {
println!("Qual'è la posizione nella serie di fibonacci del numero che stai cercando?");
let mut x = String::new();
io::stdin().read_line(&mut x)
.expect("Failed to read file");
// Parse user input
let x: u8 = match x.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
// That's too much, man
if x > 93 {
println!("gfy");
break
}
println!("Il numero è {}", fibonacci(x));
};
}
fn fibonacci(x: u8) -> u64 {
let mut curr = 1;
let mut prev = 1;
let mut tmp;
for _i in 3..(x+1) {
tmp = curr;
curr = curr + prev;
prev = tmp;
}
curr
}
|
use std::path::PathBuf;
use clap::Clap;
// use minmarkdown;
// mingen new <content_path> - creates a new content file in contents/<content_path>
// mingen new site <sitename> - creates a new site
// mingen server - launches server that shows live updates
#[derive(Clap, Debug)]
enum Args {
/// generate new mingen content
New {
#[clap(short, long)]
site: bool,
/// name of the content
#[clap(parse(from_os_str))]
name: PathBuf
},
Gen
}
fn main() {
let args = Args::parse();
match args {
Args::New {
site, name
} => {
if site {
// generate a new site project
match mingen::gen_new_site(&name) {
Ok(_) => println!("New site created!"),
Err(e) => {
println!("Application error: {}", e);
std::process::exit(1);
}
}
} else {
// generate new content
}
},
Args::Gen => {
match mingen::gen_site() {
Err(e) => {
println!("Application error: {}", e);
}
_ => ()
}
}
}
// reading test input file
/*let mut file = File::open("input-long.md").expect("Unable to open file.");
let mut input = String::new();
file.read_to_string(&mut input).expect("Unable to read input file.");
let input = input; // make immutable
let output = minmarkdown::to_html(&input);
let mut output_file = File::create("output.html").expect("Unable to create output file.");
output_file.write(output.as_bytes()).expect("Unable to write to output file.");
println!("done");*/
} |
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)]
pub struct AddPodcast {
name: String,
url: String,
}
fn add_podcast_info_db(conn: &SqliteConnection, podcast: AddPodcast) -> Result<String, String> {
return Ok("hello".to_string())
} |
#[cfg(feature = "sled-storage")]
use gluesql::{parse, Glue, Payload::*, Row, Value};
use std::fs::File;
use std::io::prelude::*;
use std::rc::Rc;
use crate::applic_folder::compileargs::*;
use crate::applic_folder::get_storage::get_storage;
pub fn dump_sql(my_input: &TheInput, seen: &Seen) -> std::io::Result<()> {
let sql = format!(
"select * from {};",
my_input.tablename.as_ref().expect("Missing tablename")
);
let db_name = my_input
.db_name
.as_ref()
.expect("Missing dbname")
.to_string();
let how = Rc::new(HowToOpenStorage::OldStorage(db_name));
let storage = get_storage(how);
let mut glue = Glue::new(storage);
let the_file_name = my_input.sql_filename.as_ref().unwrap();
let mut file = File::create(the_file_name)?;
for query in parse(&sql).unwrap() {
match &glue.execute(&query).unwrap() {
Select { labels, rows } => {
/*********************************************************/
let build_create_table = || {
format!(
r#"DROP TABLE IF EXISTS {tablename};
CREATE TABLE S ({allcolls});
"#,
tablename = my_input.tablename.as_ref().unwrap(),
allcolls = labels
.iter()
.map(|acol| format!("{} text", acol))
.collect::<Vec<String>>()
.join(",")
)
};
/*********************************************************/
let built_insert_into = format!(
"INSERT INTO {} ",
my_input.tablename.as_ref().expect("Missing tablename")
);
/*********************************************************/
let build_insert_cols = || {
labels
.iter()
.map(|acol| format!("{}", acol))
.collect::<Vec<String>>()
.join(",")
};
/*********************************************************/
if seen.droptable {
write!(file, "{}", build_create_table())?;
}
write!(
file,
"{}({}) VALUES
",
built_insert_into,
build_insert_cols()
)
.unwrap();
let mut first_row_seen: bool = false;
for arow in rows {
let Row(values) = arow;
let one_row: Vec<String> = values
.iter()
.map(|acolumn| {
let a_print_col = match acolumn {
Value::Str(ref s) => format!("\"{}\"", s.to_string()),
Value::F64(ref f) => format!("{:?}", f),
Value::I64(ref i) => format!("{:?}", i),
Value::Empty => "null".to_string(),
_ => "notyet".to_string(),
};
a_print_col
})
.collect::<Vec<String>>();
if first_row_seen {
write!(file, "{}\n", ",")?;
} // list separator on prev row
first_row_seen = true;
write!(file, "({})", one_row.join(","))?;
}
write!(file, "{}\n", ";")?; // fina;
file.flush()?;
}
_ => {}
}
}
Ok(())
}
|
extern crate reducto;
use reducto::deflate::Deflate;
use reducto::lz77::LZ77;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
fn main() {
// example from https://www.researchgate.net/figure/An-example-of-LZ77-encoding_fig4_322296027
let test_sample = "aacaacabcabaaac";
let mut deflate = Deflate::new(4, 6);
let compressed = deflate.compress(test_sample);
let decoded = deflate.decompress(&compressed);
assert_eq!(test_sample, decoded);
let test_sample = "LZ77 présente certains défauts, en particulier";
let mut deflate = Deflate::new(4, 6);
let compressed = deflate.compress(test_sample);
let decoded = deflate.decompress(&compressed);
assert_eq!(test_sample, decoded);
let path = Path::new("resources/small_lorem.txt");
let file = match File::open(path) {
Ok(f) => f,
Err(e) => panic!("{}", e),
};
let mut test_sample = String::new();
let mut reader = BufReader::new(file);
if let Err(e) = reader.read_to_string(&mut test_sample) {
panic!("{}", e)
}
let mut deflate = Deflate::new(16, 32);
let compressed = deflate.compress(&test_sample);
let decoded = deflate.decompress(&compressed);
assert_eq!(test_sample, decoded);
// test with utf code
let test_sample = "網站有中、英文版本,也有繁、簡體版,可通過每頁左上角的連結隨時調整。";
let mut deflate = Deflate::new(8, 16);
let compressed = deflate.compress(test_sample);
let decoded = deflate.decompress(&compressed);
assert_eq!(test_sample, decoded);
let path = Path::new("resources/lorem.txt");
let file = match File::open(path) {
Ok(f) => f,
Err(e) => panic!("{}", e),
};
let mut test_sample = String::new();
let mut reader = BufReader::new(file);
if let Err(e) = reader.read_to_string(&mut test_sample) {
panic!("{}", e)
}
let mut deflate = Deflate::new(16, 32);
let compressed = deflate.compress(&test_sample);
let decoded = deflate.decompress(&compressed);
assert_eq!(test_sample, decoded);
}
|
pub mod fun;
use fun::Fun;
pub mod local;
use local::Local;
pub mod property;
use property::Property;
pub mod modules;
// use modules::Module;
use core::pos::BiPos;
#[derive(Debug, Clone)]
pub struct Statement{
pub kind: StatementKind,
pub pos: BiPos,
}
#[derive(Debug, Clone)]
pub enum StatementKind{
Property(Property),
Fun(Fun),
Local(Local),
}
|
use std::future::Future;
use std::path::Path;
use std::process::Stdio;
use futures::sink::SinkExt;
use futures::stream;
use futures::stream::{Stream, StreamExt};
use heim::process::Process;
use tokio::fs::OpenOptions;
use tokio::process::Command;
use tokio::sync::broadcast;
use tokio_util::codec::{FramedRead, FramedWrite, LinesCodec};
use persist_core::error::Error;
use persist_core::protocol::{ProcessSpec, ProcessStatus};
use crate::server::codec::LogDecoder;
pub struct ProcessHandle {
pub(crate) spec: ProcessSpec,
pub(crate) process: Option<Process>,
pub(crate) stdout: broadcast::Sender<String>,
pub(crate) stderr: broadcast::Sender<String>,
}
impl ProcessHandle {
/// Creates a new process handle (but does not spawn the process).
pub fn new(spec: ProcessSpec) -> Self {
let (stdout, _) = broadcast::channel(15);
let (stderr, _) = broadcast::channel(15);
Self {
spec,
stdout,
stderr,
process: None,
}
}
pub fn name(&self) -> &str {
self.spec.name.as_str()
}
pub fn spec(&self) -> &ProcessSpec {
&self.spec
}
pub fn status(&self) -> ProcessStatus {
self.process
.as_ref()
.map_or(ProcessStatus::Stopped, |_| ProcessStatus::Running)
}
pub fn pid(&self) -> Option<usize> {
self.process.as_ref().map(|handle| handle.pid() as usize)
}
pub fn pid_file(&self) -> &Path {
self.spec.pid_path.as_path()
}
pub fn stdout_file(&self) -> &Path {
self.spec.stdout_path.as_path()
}
pub fn stderr_file(&self) -> &Path {
self.spec.stderr_path.as_path()
}
pub fn stdout(&self) -> impl Stream<Item = String> {
stream::unfold(self.stdout.subscribe(), |mut stdout| async move {
loop {
match stdout.recv().await {
Ok(item) => return Some((item, stdout)),
Err(broadcast::RecvError::Closed) => return None,
Err(broadcast::RecvError::Lagged(_)) => continue,
}
}
})
}
pub fn stderr(&self) -> impl Stream<Item = String> {
stream::unfold(self.stderr.subscribe(), |mut stderr| async move {
loop {
match stderr.recv().await {
Ok(item) => return Some((item, stderr)),
Err(broadcast::RecvError::Closed) => return None,
Err(broadcast::RecvError::Lagged(_)) => continue,
}
}
})
}
pub async fn start(&mut self) -> Result<impl Future<Output = ()>, Error> {
let stdout_sink = OpenOptions::new()
.create(true)
.append(true)
.open(&self.spec.stdout_path)
.await?;
let mut stdout_sink = FramedWrite::new(stdout_sink, LinesCodec::new());
let stderr_sink = OpenOptions::new()
.create(true)
.append(true)
.open(&self.spec.stderr_path)
.await?;
let mut stderr_sink = FramedWrite::new(stderr_sink, LinesCodec::new());
let (cmd, args) = self.spec.cmd.split_first().expect("empty command");
let mut child = Command::new(cmd)
.args(args)
.env_clear()
.envs(self.spec.env.iter())
.current_dir(self.spec.cwd.as_path())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let pid = child.id();
let handle = heim::process::get(pid as i32).await?;
tokio::fs::write(self.spec.pid_path.clone(), pid.to_string()).await?;
let stdout = child.stdout.take().expect("failed to capture stdout");
let stderr = child.stderr.take().expect("failed to capture stderr");
let mut stdout = FramedRead::new(stdout, LogDecoder::new());
let mut stderr = FramedRead::new(stderr, LogDecoder::new());
let sender = self.stdout.clone();
tokio::spawn(async move {
while let Some(item) = stdout.next().await {
if let Ok(item) = item {
let _ = stdout_sink.send(item.clone()).await;
let _ = sender.send(item);
}
}
});
let sender = self.stderr.clone();
tokio::spawn(async move {
while let Some(item) = stderr.next().await {
if let Ok(item) = item {
let _ = stderr_sink.send(item.clone()).await;
let _ = sender.send(item);
}
}
});
self.process.replace(handle);
let future = async move {
let _ = child.await;
};
Ok(future)
}
pub async fn stop(&mut self) -> Result<(), Error> {
if let Some(child) = self.process.take() {
let _ = child.terminate().await;
}
Ok(())
}
pub async fn restart(&mut self) -> Result<impl Future<Output = ()>, Error> {
self.stop().await?;
self.start().await
}
pub async fn restart_with_spec(
&mut self,
spec: ProcessSpec,
) -> Result<impl Future<Output = ()>, Error> {
self.spec = spec;
self.restart().await
}
pub async fn with_process<'a, F, Fut, T>(&'a self, func: F) -> Option<T>
where
F: FnOnce(&'a Process) -> Fut,
Fut: Future<Output = T> + 'a,
{
if let Some(process) = self.process.as_ref() {
Some(func(process).await)
} else {
None
}
}
}
|
use crate::api::routes::run_server;
use crate::db::db::Database;
use std::env;
mod api;
mod db;
#[tokio::main]
async fn main() {
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be specified");
let listen_address = env::var("LISTEN").expect("LISTEN must be specified");
let database = Database::new(database_url.as_str()).await;
run_server(listen_address.as_str(), database).await;
} |
use std::ops;
pub trait Vector<T>
where
T: ops::Add<Output = T>
+ ops::Sub<Output = T>
+ ops::Mul<Output = T>
+ ops::Div<Output = T>
+ Copy
+ Clone,
{
const DIMS: usize;
fn zero() -> Self;
fn get(&self, i: usize) -> T;
fn set(&mut self, i: usize, value: T);
fn len_sqr(&self) -> T {
let mut sum = self.get(0) * self.get(0);
for i in 1..Self::DIMS {
sum = sum + self.get(i) * self.get(i);
}
sum
}
fn add(&self, other: &Self) -> Self
where
Self: std::marker::Sized,
{
let mut new = Self::zero();
for i in 0..Self::DIMS {
new.set(i, self.get(i) + other.get(i));
}
new
}
fn sub(&self, other: &Self) -> Self
where
Self: std::marker::Sized,
{
let mut new = Self::zero();
for i in 0..Self::DIMS {
new.set(i, self.get(i) - other.get(i));
}
new
}
fn mul(&self, other: &Self) -> Self
where
Self: std::marker::Sized,
{
let mut new = Self::zero();
for i in 0..Self::DIMS {
new.set(i, self.get(i) * other.get(i));
}
new
}
fn div(&self, other: &Self) -> Self
where
Self: std::marker::Sized,
{
let mut new = Self::zero();
for i in 0..Self::DIMS {
new.set(i, self.get(i) / other.get(i));
}
new
}
fn sum(&self) -> T {
let mut sum = self.get(0);
for i in 1..Self::DIMS {
sum = sum + self.get(i)
}
sum
}
fn dot(&self, other: &Self) -> T
where
Self: std::marker::Sized,
{
self.add(other).sum()
}
fn scal(&self, scal: T) -> Self
where
Self: std::marker::Sized,
{
let mut new = Self::zero();
for i in 0..Self::DIMS {
new.set(i, self.get(i) * scal);
}
new
}
}
pub trait Zeroable {
const ZERO: Self;
}
#[derive(Debug)]
pub struct Vec3<T>(pub T, pub T, pub T)
where
T: ops::Add<Output = T>
+ ops::Sub<Output = T>
+ ops::Mul<Output = T>
+ ops::Div<Output = T>
+ Copy
+ Clone
+ Zeroable;
impl<T> Vector<T> for Vec3<T>
where
T: ops::Add<Output = T>
+ ops::Sub<Output = T>
+ ops::Mul<Output = T>
+ ops::Div<Output = T>
+ Copy
+ Clone
+ Zeroable,
{
const DIMS: usize = 3;
fn zero() -> Self {
Vec3(T::ZERO, T::ZERO, T::ZERO)
}
fn get(&self, i: usize) -> T {
match i {
0 => self.0,
1 => self.1,
2 => self.2,
_ => panic!("Illegal index"),
}
}
fn set(&mut self, i: usize, value: T) {
match i {
0 => self.0 = value,
1 => self.1 = value,
2 => self.2 = value,
_ => panic!("Illegal index"),
};
}
}
#[derive(Debug)]
pub struct Vec2<T>(pub T, pub T)
where
T: ops::Add<Output = T>
+ ops::Sub<Output = T>
+ ops::Mul<Output = T>
+ ops::Div<Output = T>
+ Copy
+ Clone
+ Zeroable;
impl<T> Vec2<T>
where
T: ops::Add<Output = T>
+ ops::Sub<Output = T>
+ ops::Mul<Output = T>
+ ops::Div<Output = T>
+ Copy
+ Clone
+ Zeroable,
{
pub fn cross(&self, other: &Self) -> T {
self.0 * other.1 - self.1 * other.0
}
}
impl<T> Vector<T> for Vec2<T>
where
T: ops::Add<Output = T>
+ ops::Sub<Output = T>
+ ops::Mul<Output = T>
+ ops::Div<Output = T>
+ Copy
+ Clone
+ Zeroable,
{
const DIMS: usize = 2;
fn zero() -> Self {
Vec2(T::ZERO, T::ZERO)
}
fn get(&self, i: usize) -> T {
match i {
0 => self.0,
1 => self.1,
_ => panic!("Illegal index"),
}
}
fn set(&mut self, i: usize, value: T) {
match i {
0 => self.0 = value,
1 => self.1 = value,
_ => panic!("Illegal index"),
};
}
}
impl Zeroable for f32 {
const ZERO: f32 = 0.0;
}
pub type Vec3f = Vec3<f32>;
pub type Vec2f = Vec2<f32>;
impl Zeroable for i32 {
const ZERO: i32 = 0;
}
pub type Vec3i = Vec3<i32>;
pub type Vec2i = Vec2<i32>;
|
use super::*;
use std::convert::Into;
use dataview::Pod;
use log::debug;
use memflow::*;
use memflow_derive::*;
const SIZE_4KB: u64 = size::kb(4) as u64;
#[repr(C)]
#[derive(Copy, Clone, ByteSwap)]
pub struct PhysicalMemoryRun<T: Pod + ByteSwap> {
pub base_page: T,
pub page_count: T,
}
#[repr(C)]
#[derive(Copy, Clone, ByteSwap)]
pub struct PhysicalMemoryDescriptor<T: Pod + ByteSwap> {
pub number_of_runs: u32,
pub number_of_pages: T,
pub runs: [PhysicalMemoryRun<T>; PHYSICAL_MEMORY_MAX_RUNS],
}
pub fn parse_full_dump<T: Pod + ByteSwap + Copy + Into<u64>>(
descriptor: PhysicalMemoryDescriptor<T>,
header_size: usize,
) -> Result<MemoryMap<(Address, usize)>> {
let number_of_runs = descriptor.number_of_runs.into();
if number_of_runs > PHYSICAL_MEMORY_MAX_RUNS as u64 {
return Err(Error::Connector(
"too many memory segments in crash dump file",
));
}
let mut mem_map = MemoryMap::new();
// start runs from right after header size (x86: 0x1000 / x64: 0x2000)
let mut real_base = header_size as u64;
for i in 0..number_of_runs {
let base = descriptor.runs[i as usize].base_page.into() * SIZE_4KB;
let size = descriptor.runs[i as usize].page_count.into() * SIZE_4KB;
debug!(
"adding memory mapping: base={:x} size={:x} real_base={:x}",
base, size, real_base
);
mem_map.push_remap(base.into(), size as usize, real_base.into());
real_base += size;
}
Ok(mem_map)
}
|
#![allow(dead_code)]
use cli_integration_test::IntegrationTestEnvironment;
use short::BIN_NAME;
fn cmd_help() {
let e = IntegrationTestEnvironment::new("cmd_help");
let mut command = e.command(BIN_NAME).unwrap();
let r = command.assert();
r.stderr(
r#" short 0.0.2
Vincent Herlemont <vincentherl@leszeros.com>
USAGE:
short [FLAGS] [OPTIONS] [SUBCOMMAND]
FLAGS:
--dry-run Disable all executions
-h, --help Prints help information
-V, --version Prints version information
OPTIONS:
-s, --setup <setup> Set up name
-e, --env <environment> Environment name
SUBCOMMANDS:
init Create an empty "short.yaml" configuration file
env Manage environment
deploy Deploy your set up
show Show your current set up
use Switch of current setup or/and environment
ls List set up and environments
help Prints this message or the help of the given subcommand(s)
"#,
);
}
fn cmd_help_env() {
let e = IntegrationTestEnvironment::new("cmd_help");
let mut command = e.command(BIN_NAME).unwrap();
let r = command.arg("env").assert();
r.stderr(
r#"short-env
Manage environment
USAGE:
short env [FLAGS] [OPTIONS] <SUBCOMMAND>
FLAGS:
--dry-run Disable all executions
-h, --help Prints help information
OPTIONS:
-s, --setup <setup> Set up name
-e, --env <environment> Environment name
SUBCOMMANDS:
new Add new environment
dir Change env directory
pdir Add or change private env directory
help Prints this message or the help of the given subcommand(s)
"#,
);
}
|
use crate::models::{ComicId, ComicIdInvalidity, Token};
use crate::util::{ensure_is_authorized, ensure_is_valid};
use actix_web::{error, web, HttpResponse, Result};
use actix_web_grants::permissions::AuthDetails;
use anyhow::anyhow;
use database::models::{Comic as DatabaseComic, Item as DatabaseItem, LogEntry, Occurrence};
use database::DbPool;
use parse_display::Display;
use semval::{context::Context as ValidationContext, Validate};
use serde::Deserialize;
use shared::token_permissions;
#[allow(clippy::too_many_lines)]
pub(crate) async fn add_item(
pool: web::Data<DbPool>,
request: web::Json<AddItemToComicBody>,
auth: AuthDetails,
) -> Result<HttpResponse> {
const CREATE_NEW_ITEM_ID: i16 = -1;
ensure_is_authorized(&auth, token_permissions::CAN_ADD_ITEM_TO_COMIC)
.map_err(error::ErrorForbidden)?;
ensure_is_valid(&*request).map_err(error::ErrorBadRequest)?;
let mut transaction = pool
.begin()
.await
.map_err(error::ErrorInternalServerError)?;
DatabaseComic::ensure_exists_by_id(&mut *transaction, request.comic_id.into_inner())
.await
.map_err(error::ErrorInternalServerError)?;
let item = if request.item_id == CREATE_NEW_ITEM_ID {
let new_item_name = request.new_item_name.as_ref().ok_or_else(|| {
error::ErrorBadRequest(anyhow!(
"New Item request without providing newItemName value"
))
})?;
let new_item_type = request.new_item_type.as_ref().ok_or_else(|| {
error::ErrorBadRequest(anyhow!(
"New Item request without providing newItemType value"
))
})?;
let result = DatabaseItem::create(
&mut *transaction,
new_item_name,
new_item_name,
AsRef::<str>::as_ref(new_item_type)
.try_into()
.map_err(|e| error::ErrorBadRequest(anyhow!("Invalid item type: {}", e)))?,
)
.await
.map_err(error::ErrorInternalServerError)?;
let new_item_id = result.last_insert_id() as u16;
LogEntry::log_action(
&mut *transaction,
request.token.to_string(),
format!(
"Created {} #{} ({})",
new_item_type, new_item_id, new_item_name
),
)
.await
.map_err(error::ErrorInternalServerError)?;
DatabaseItem {
id: new_item_id,
name: new_item_name.clone(),
short_name: new_item_name.clone(),
r#type: new_item_type.clone(),
color_blue: 127,
color_green: 127,
color_red: 127,
}
} else {
let item_id = request.item_id as u16;
let item = DatabaseItem::by_id(&mut *transaction, item_id)
.await
.map_err(error::ErrorInternalServerError)?
.ok_or_else(|| error::ErrorBadRequest(anyhow!("Item does not exist")))?;
let occurrence_exists = Occurrence::occurrence_by_item_id_and_comic_id(
&mut *transaction,
item_id,
request.comic_id.into_inner(),
)
.await
.map_err(error::ErrorInternalServerError)?;
if occurrence_exists {
return Err(error::ErrorBadRequest(anyhow!(
"Item is already added to comic"
)));
}
item
};
Occurrence::create(&mut *transaction, item.id, request.comic_id.into_inner())
.await
.map_err(error::ErrorInternalServerError)?;
LogEntry::log_action(
&mut *transaction,
request.token.to_string(),
format!(
"Added {} #{} ({}) to comic #{}",
item.r#type, item.id, item.name, request.comic_id
),
)
.await
.map_err(error::ErrorInternalServerError)?;
transaction
.commit()
.await
.map_err(error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().body("Item added to comic"))
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AddItemToComicBody {
token: Token,
comic_id: ComicId,
item_id: i16,
#[serde(default)]
new_item_name: Option<String>,
#[serde(default)]
new_item_type: Option<String>,
}
impl Validate for AddItemToComicBody {
type Invalidity = AddItemToComicBodyInvalidity;
fn validate(&self) -> semval::ValidationResult<Self::Invalidity> {
ValidationContext::new()
.validate_with(&self.comic_id, AddItemToComicBodyInvalidity::ComicId)
.invalidate_if(
self.item_id < 1 && self.item_id != -1,
AddItemToComicBodyInvalidity::ItemIdInvalid,
)
.invalidate_if(
self.item_id >= 1 && self.new_item_name.is_some(),
AddItemToComicBodyInvalidity::NewItemNameUsedWithoutCreateNewItemId,
)
.invalidate_if(
self.item_id == -1 && self.new_item_name.is_none(),
AddItemToComicBodyInvalidity::NewItemNameMissingWithCreateNewItemId,
)
.invalidate_if(
self.item_id >= 1 && self.new_item_type.is_some(),
AddItemToComicBodyInvalidity::NewItemTypeUsedWithoutCreateNewItemId,
)
.invalidate_if(
self.item_id == -1 && self.new_item_type.is_none(),
AddItemToComicBodyInvalidity::NewItemTypeMissingWithCreateNewItemId,
)
.into()
}
}
#[derive(Copy, Clone, Debug, Display, Eq, PartialEq)]
pub(crate) enum AddItemToComicBodyInvalidity {
#[display("{0}")]
ComicId(ComicIdInvalidity),
#[display(
"itemId must be either -1 (for a new item) or a value larger than 0 (for an existing item)"
)]
ItemIdInvalid,
#[display("newItemName value given when itemId was not -1")]
NewItemNameUsedWithoutCreateNewItemId,
#[display("newItemName value not given when itemId was -1")]
NewItemNameMissingWithCreateNewItemId,
#[display("newItemType value given when itemId was not -1")]
NewItemTypeUsedWithoutCreateNewItemId,
#[display("newItemType value not given when itemId was -1")]
NewItemTypeMissingWithCreateNewItemId,
}
|
mod bin_gen;
mod memory;
pub use {bin_gen::*, memory::*};
|
//! Type definitions for the queues used in this crate.
use heapless::Vec;
use heapless::{
consts,
spsc::{Consumer, Producer, Queue},
ArrayLength,
};
pub use crate::error::InternalError;
pub use crate::Command;
// Queue item types
pub type ComItem = Command;
pub type ResItem<BufLen> = Result<Vec<u8, BufLen>, InternalError>;
pub type UrcItem<BufLen> = Vec<u8, BufLen>;
pub type ResCapacity = consts::U1;
pub type ComCapacity = consts::U3;
// Consumers
pub type ComConsumer = Consumer<'static, ComItem, ComCapacity, u8>;
pub type ResConsumer<BufLen> = Consumer<'static, ResItem<BufLen>, ResCapacity, u8>;
pub type UrcConsumer<BufLen, UrcCapacity> = Consumer<'static, UrcItem<BufLen>, UrcCapacity, u8>;
// Producers
pub type ComProducer = Producer<'static, ComItem, ComCapacity, u8>;
pub type ResProducer<BufLen> = Producer<'static, ResItem<BufLen>, ResCapacity, u8>;
pub type UrcProducer<BufLen, UrcCapacity> = Producer<'static, UrcItem<BufLen>, UrcCapacity, u8>;
// Queues
pub type ComQueue = Queue<ComItem, ComCapacity, u8>;
pub type ResQueue<BufLen> = Queue<ResItem<BufLen>, ResCapacity, u8>;
pub type UrcQueue<BufLen, UrcCapacity> = Queue<UrcItem<BufLen>, UrcCapacity, u8>;
pub struct Queues<BufLen, UrcCapacity>
where
BufLen: ArrayLength<u8>,
UrcCapacity: ArrayLength<UrcItem<BufLen>>,
{
pub res_queue: (ResProducer<BufLen>, ResConsumer<BufLen>),
pub urc_queue: (
UrcProducer<BufLen, UrcCapacity>,
UrcConsumer<BufLen, UrcCapacity>,
),
pub com_queue: (ComProducer, ComConsumer),
}
|
pub enum UpdateType {
Add,
Change
}
impl UpdateType {
pub fn as_str(&self) -> &'static str {
match self {
UpdateType::Add => "A",
UpdateType::Change => "C"
}
}
}
|
use text_unit::TextUnit;
use text_unit::TextRange;
pub struct ParseError {
pub location: Location,
pub error_kind: ParseErrorKind,
}
pub enum Location {
Offset(TextUnit),
Range(TextRange),
}
pub enum ParseErrorKind {
} |
use cosmwasm_std::{
log, to_binary, Api, CanonicalAddr, CosmosMsg, Decimal, Env, Extern, HandleResponse,
HandleResult, HumanAddr, Order, Querier, QueryRequest, StdError, StdResult, Storage, Uint128,
WasmMsg, WasmQuery,
};
use crate::state::{
pool_info_read, pool_info_store, read_config, read_state, rewards_read, rewards_store,
state_store, Config, PoolInfo, RewardInfo, State,
};
use cw20::Cw20HandleMsg;
use crate::querier::{query_mirror_pool_balance, query_mirror_reward_info};
use mirror_protocol::gov::{
HandleMsg as MirrorGovHandleMsg, QueryMsg as MirrorGovQueryMsg,
StakerResponse as MirrorStakerResponse,
};
use mirror_protocol::staking::{
Cw20HookMsg as MirrorCw20HookMsg, HandleMsg as MirrorStakingHandleMsg,
};
use spectrum_protocol::gov::{
BalanceResponse as SpecBalanceResponse, HandleMsg as SpecHandleMsg, QueryMsg as SpecQueryMsg,
};
use spectrum_protocol::math::UDec128;
use spectrum_protocol::mirror_farm::{RewardInfoResponse, RewardInfoResponseItem};
use std::collections::HashMap;
pub fn try_bond<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
sender_addr: HumanAddr,
asset_token: HumanAddr,
amount: Uint128,
compound_rate: Option<Decimal>,
) -> HandleResult {
let asset_token_raw = deps.api.canonical_address(&asset_token)?;
let sender_addr_raw = deps.api.canonical_address(&sender_addr)?;
let mut pool_info = pool_info_read(&deps.storage).load(asset_token_raw.as_slice())?;
// only staking token contract can execute this message
if pool_info.staking_token != deps.api.canonical_address(&env.message.sender)? {
return Err(StdError::unauthorized());
}
let mut state = read_state(&deps.storage)?;
let config = read_config(&deps.storage)?;
let lp_balance = query_mirror_pool_balance(
deps,
&config.mirror_staking,
&asset_token_raw,
&state.contract_addr,
)?;
// update reward index; before changing share
if !pool_info.total_auto_bond_share.is_zero() || !pool_info.total_stake_bond_share.is_zero() {
deposit_spec_reward(deps, &mut state, &config, env.block.height, false)?;
spec_reward_to_pool(&state, &mut pool_info, lp_balance)?;
}
// withdraw reward to pending reward; before changing share
let mut reward_info = rewards_read(&deps.storage, &sender_addr_raw)
.may_load(asset_token_raw.as_slice())?
.unwrap_or_else(|| RewardInfo {
farm_share_index: pool_info.farm_share_index,
auto_spec_share_index: pool_info.auto_spec_share_index,
stake_spec_share_index: pool_info.stake_spec_share_index,
auto_bond_share: Uint128::zero(),
stake_bond_share: Uint128::zero(),
spec_share: Uint128::zero(),
accum_spec_share: Uint128::zero(),
farm_share: Uint128::zero(),
});
before_share_change(&pool_info, &mut reward_info)?;
// increase bond_amount
increase_bond_amount(
&mut pool_info,
&mut reward_info,
&config,
amount,
compound_rate,
lp_balance,
)?;
rewards_store(&mut deps.storage, &sender_addr_raw)
.save(&asset_token_raw.as_slice(), &reward_info)?;
pool_info_store(&mut deps.storage).save(asset_token_raw.as_slice(), &pool_info)?;
state_store(&mut deps.storage).save(&state)?;
stake_token(
&deps.api,
&config.mirror_staking,
&pool_info.staking_token,
&asset_token_raw,
amount,
)
}
pub fn deposit_farm_share<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
config: &Config,
pool_pairs: Vec<(HumanAddr, Uint128)>, // array of (pool address, new MIR amount)
) -> StdResult<()> {
let mut state = read_state(&deps.storage)?;
let staked: MirrorStakerResponse =
deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: deps.api.human_address(&config.mirror_gov)?,
msg: to_binary(&MirrorGovQueryMsg::Staker {
address: deps.api.human_address(&state.contract_addr)?,
})?,
}))?;
let mut new_total_share = Uint128::zero();
for (asset_token, amount) in pool_pairs {
let asset_token_raw = deps.api.canonical_address(&asset_token)?;
let key = asset_token_raw.as_slice();
let mut pool_info = pool_info_read(&deps.storage).load(key)?;
if pool_info.total_stake_bond_share.is_zero() {
continue;
}
let new_share = state.calc_farm_share(amount, staked.balance);
let share_per_bond = Decimal::from_ratio(new_share, pool_info.total_stake_bond_share);
pool_info.farm_share_index = pool_info.farm_share_index + share_per_bond;
pool_info.farm_share += new_share;
new_total_share += new_share;
pool_info_store(&mut deps.storage).save(key, &pool_info)?;
}
state.total_farm_share += new_total_share;
state_store(&mut deps.storage).save(&state)?;
Ok(())
}
pub fn deposit_spec_reward<S: Storage, A: Api, Q: Querier>(
deps: &Extern<S, A, Q>,
state: &mut State,
config: &Config,
height: u64,
query: bool,
) -> StdResult<SpecBalanceResponse> {
if state.total_weight == 0 {
return Ok(SpecBalanceResponse {
share: Uint128::zero(),
balance: Uint128::zero(),
locked_balance: vec![],
});
}
let staked: SpecBalanceResponse =
deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: deps.api.human_address(&config.spectrum_gov)?,
msg: to_binary(&SpecQueryMsg::balance {
address: deps.api.human_address(&state.contract_addr)?,
height: Some(height),
})?,
}))?;
let diff = staked.share - state.previous_spec_share;
let deposit_share = if query {
diff.unwrap_or(Uint128::zero())
} else {
diff?
};
let share_per_weight = Decimal::from_ratio(deposit_share, state.total_weight);
state.spec_share_index = state.spec_share_index + share_per_weight;
state.previous_spec_share = staked.share;
Ok(staked)
}
fn spec_reward_to_pool(
state: &State,
pool_info: &mut PoolInfo,
lp_balance: Uint128,
) -> StdResult<()> {
if lp_balance.is_zero() {
return Ok(());
}
let share = (UDec128::from(state.spec_share_index) - pool_info.state_spec_share_index.into())
* Uint128::from(pool_info.weight as u128);
// pool_info.total_stake_bond_amount / lp_balance = ratio for auto-stake
// now stake_share is additional SPEC rewards for auto-stake
let stake_share = share * pool_info.total_stake_bond_amount / lp_balance;
if !stake_share.is_zero() {
let stake_share_per_bond = stake_share / pool_info.total_stake_bond_share;
pool_info.stake_spec_share_index =
pool_info.stake_spec_share_index + stake_share_per_bond.into();
}
// auto_share is additional SPEC rewards for auto-compound
let auto_share = share - stake_share;
if !auto_share.is_zero() {
let auto_share_per_bond = auto_share / pool_info.total_auto_bond_share;
pool_info.auto_spec_share_index =
pool_info.auto_spec_share_index + auto_share_per_bond.into();
}
pool_info.state_spec_share_index = state.spec_share_index;
Ok(())
}
// withdraw reward to pending reward
fn before_share_change(pool_info: &PoolInfo, reward_info: &mut RewardInfo) -> StdResult<()> {
let farm_share = (pool_info.farm_share_index - reward_info.farm_share_index.into())
* reward_info.stake_bond_share;
reward_info.farm_share += farm_share;
reward_info.farm_share_index = pool_info.farm_share_index;
let stake_spec_share = reward_info.stake_bond_share
* (pool_info.stake_spec_share_index - reward_info.stake_spec_share_index.into());
let auto_spec_share = reward_info.auto_bond_share
* (pool_info.auto_spec_share_index - reward_info.auto_spec_share_index.into());
let spec_share = stake_spec_share + auto_spec_share;
reward_info.spec_share += spec_share;
reward_info.accum_spec_share += spec_share;
reward_info.stake_spec_share_index = pool_info.stake_spec_share_index;
reward_info.auto_spec_share_index = pool_info.auto_spec_share_index;
Ok(())
}
// increase share amount in pool and reward info
fn increase_bond_amount(
pool_info: &mut PoolInfo,
reward_info: &mut RewardInfo,
config: &Config,
amount: Uint128,
compound_rate: Option<Decimal>,
lp_balance: Uint128,
) -> StdResult<()> {
// calculate target state
let compound_rate = compound_rate.unwrap_or(Decimal::zero());
let amount_to_auto = amount * compound_rate;
let amount_to_stake = (amount - amount_to_auto)?;
let new_balance = lp_balance + amount;
let new_auto_bond_amount =
(new_balance - (pool_info.total_stake_bond_amount + amount_to_stake))?;
// calculate deposit fee; split based on auto balance & stake balance
let deposit_fee = amount * config.deposit_fee;
let auto_bond_fee = deposit_fee.multiply_ratio(new_auto_bond_amount, new_balance);
let stake_bond_fee = (deposit_fee - auto_bond_fee)?;
// calculate amount after fee
let remaining_amount = (amount - deposit_fee)?;
let auto_bond_amount = remaining_amount * compound_rate;
let stake_bond_amount = (remaining_amount - auto_bond_amount)?;
// convert amount to share & update
let auto_bond_share = pool_info.calc_auto_bond_share(auto_bond_amount, lp_balance);
let stake_bond_share = pool_info.calc_stake_bond_share(stake_bond_amount);
pool_info.total_auto_bond_share += auto_bond_share;
pool_info.total_stake_bond_amount += stake_bond_amount + stake_bond_fee;
pool_info.total_stake_bond_share += stake_bond_share;
reward_info.auto_bond_share += auto_bond_share;
reward_info.stake_bond_share += stake_bond_share;
Ok(())
}
// stake LP token to Mirror Staking
fn stake_token<A: Api>(
api: &A,
mirror_staking: &CanonicalAddr,
staking_token: &CanonicalAddr,
asset_token: &CanonicalAddr,
amount: Uint128,
) -> HandleResult {
let asset_token = api.human_address(asset_token)?;
let mirror_staking = api.human_address(mirror_staking)?;
let staking_token = api.human_address(staking_token)?;
let response = HandleResponse {
messages: vec![CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: staking_token.clone(),
send: vec![],
msg: to_binary(&Cw20HandleMsg::Send {
contract: mirror_staking,
amount,
msg: Some(to_binary(&MirrorCw20HookMsg::Bond {
asset_token: asset_token.clone(),
})?),
})?,
})],
log: vec![
log("action", "bond"),
log("staking_token", staking_token.as_str()),
log("asset_token", asset_token.as_str()),
log("amount", amount.to_string()),
],
data: None,
};
Ok(response)
}
pub fn unbond<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
asset_token: HumanAddr,
amount: Uint128,
) -> HandleResult {
let staker_addr_raw = deps.api.canonical_address(&env.message.sender)?;
let asset_token_raw = deps.api.canonical_address(&asset_token)?;
let config = read_config(&deps.storage)?;
let mut state = read_state(&deps.storage)?;
let mut pool_info = pool_info_read(&deps.storage).load(asset_token_raw.as_slice())?;
let mut reward_info =
rewards_read(&deps.storage, &staker_addr_raw).load(asset_token_raw.as_slice())?;
let lp_balance = query_mirror_pool_balance(
deps,
&config.mirror_staking,
&asset_token_raw,
&state.contract_addr,
)?;
let user_auto_balance =
pool_info.calc_user_auto_balance(lp_balance, reward_info.auto_bond_share);
let user_stake_balance = pool_info.calc_user_stake_balance(reward_info.stake_bond_share);
let user_balance = user_auto_balance + user_stake_balance;
if user_balance < amount {
return Err(StdError::generic_err("Cannot unbond more than bond amount"));
}
// distribute reward to pending reward; before changing share
let config = read_config(&deps.storage)?;
deposit_spec_reward(deps, &mut state, &config, env.block.height, false)?;
spec_reward_to_pool(&state, &mut pool_info, lp_balance)?;
before_share_change(&pool_info, &mut reward_info)?;
// decrease bond amount
let auto_bond_amount = if reward_info.stake_bond_share.is_zero() {
amount
} else {
amount.multiply_ratio(user_auto_balance, user_balance)
};
let stake_bond_amount = (amount - auto_bond_amount)?;
let auto_bond_share = pool_info.calc_auto_bond_share(auto_bond_amount, lp_balance);
let stake_bond_share = pool_info.calc_stake_bond_share(stake_bond_amount);
pool_info.total_auto_bond_share = (pool_info.total_auto_bond_share - auto_bond_share)?;
pool_info.total_stake_bond_amount = (pool_info.total_stake_bond_amount - stake_bond_amount)?;
pool_info.total_stake_bond_share = (pool_info.total_stake_bond_share - stake_bond_share)?;
reward_info.auto_bond_share = (reward_info.auto_bond_share - auto_bond_share)?;
reward_info.stake_bond_share = (reward_info.stake_bond_share - stake_bond_share)?;
// update rewards info
if reward_info.spec_share.is_zero()
&& reward_info.farm_share.is_zero()
&& reward_info.auto_bond_share.is_zero()
&& reward_info.stake_bond_share.is_zero()
{
rewards_store(&mut deps.storage, &staker_addr_raw).remove(asset_token_raw.as_slice());
} else {
rewards_store(&mut deps.storage, &staker_addr_raw)
.save(asset_token_raw.as_slice(), &reward_info)?;
}
// update pool info
pool_info_store(&mut deps.storage).save(asset_token_raw.as_slice(), &pool_info)?;
state_store(&mut deps.storage).save(&state)?;
Ok(HandleResponse {
messages: vec![
CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: deps.api.human_address(&config.mirror_staking)?,
send: vec![],
msg: to_binary(&MirrorStakingHandleMsg::Unbond {
asset_token: asset_token.clone(),
amount,
})?,
}),
CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: deps.api.human_address(&pool_info.staking_token)?,
msg: to_binary(&Cw20HandleMsg::Transfer {
recipient: env.message.sender.clone(),
amount,
})?,
send: vec![],
}),
],
log: vec![
log("action", "unbond"),
log("staker_addr", env.message.sender.as_str()),
log("asset_token", asset_token.as_str()),
log("amount", amount.to_string()),
],
data: None,
})
}
pub fn withdraw<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
asset_token: Option<HumanAddr>,
) -> HandleResult {
let staker_addr = deps.api.canonical_address(&env.message.sender)?;
let asset_token = asset_token.map(|a| deps.api.canonical_address(&a).unwrap());
let mut state = read_state(&deps.storage)?;
// update pending reward; before withdraw
let config = read_config(&deps.storage)?;
let spec_staked = deposit_spec_reward(deps, &mut state, &config, env.block.height, false)?;
let (spec_amount, spec_share, farm_amount, farm_share) = withdraw_reward(
deps,
&config,
env.block.height,
&mut state,
&staker_addr,
&asset_token,
&spec_staked,
)?;
state.previous_spec_share = (state.previous_spec_share - spec_share)?;
state.total_farm_share = (state.total_farm_share - farm_share)?;
state_store(&mut deps.storage).save(&state)?;
let mut messages: Vec<CosmosMsg> = vec![];
if !spec_amount.is_zero() {
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: deps.api.human_address(&config.spectrum_gov)?,
msg: to_binary(&SpecHandleMsg::withdraw {
amount: Some(spec_amount),
})?,
send: vec![],
}));
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: deps.api.human_address(&config.spectrum_token)?,
msg: to_binary(&Cw20HandleMsg::Transfer {
recipient: env.message.sender.clone(),
amount: spec_amount,
})?,
send: vec![],
}));
}
if !farm_amount.is_zero() {
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: deps.api.human_address(&config.mirror_gov)?,
msg: to_binary(&MirrorGovHandleMsg::WithdrawVotingTokens {
amount: Some(farm_amount),
})?,
send: vec![],
}));
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: deps.api.human_address(&config.mirror_token)?,
msg: to_binary(&Cw20HandleMsg::Transfer {
recipient: env.message.sender.clone(),
amount: farm_amount,
})?,
send: vec![],
}));
}
Ok(HandleResponse {
messages,
log: vec![
log("action", "withdraw"),
log("farm_amount", farm_amount.to_string()),
log("spec_amount", spec_amount.to_string()),
],
data: None,
})
}
fn withdraw_reward<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
config: &Config,
height: u64,
state: &State,
staker_addr: &CanonicalAddr,
asset_token: &Option<CanonicalAddr>,
spec_staked: &SpecBalanceResponse,
) -> StdResult<(Uint128, Uint128, Uint128, Uint128)> {
let rewards_bucket = rewards_read(&deps.storage, &staker_addr);
// single reward withdraw; or all rewards
let reward_pairs: Vec<(CanonicalAddr, RewardInfo)>;
if let Some(asset_token) = asset_token {
let key = asset_token.as_slice();
let reward_info = rewards_bucket.may_load(key)?;
reward_pairs = if let Some(reward_info) = reward_info {
vec![(asset_token.clone(), reward_info)]
} else {
vec![]
};
} else {
reward_pairs = rewards_bucket
.range(None, None, Order::Ascending)
.map(|item| {
let (k, v) = item?;
Ok((CanonicalAddr::from(k), v))
})
.collect::<StdResult<Vec<(CanonicalAddr, RewardInfo)>>>()?;
}
let farm_staked: MirrorStakerResponse =
deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: deps.api.human_address(&config.mirror_gov)?,
msg: to_binary(&MirrorGovQueryMsg::Staker {
address: deps.api.human_address(&state.contract_addr)?,
})?,
}))?;
let mirror_reward_infos = query_mirror_reward_info(
deps,
&deps.api.human_address(&config.mirror_staking)?,
&deps.api.human_address(&state.contract_addr)?,
)?;
let mirror_map: HashMap<_, _> = mirror_reward_infos
.reward_infos
.into_iter()
.map(|it| (it.asset_token, it.bond_amount))
.collect();
let mut spec_amount = Uint128::zero();
let mut spec_share = Uint128::zero();
let mut farm_amount = Uint128::zero();
let mut farm_share = Uint128::zero();
for reward_pair in reward_pairs {
let (asset_token_raw, mut reward_info) = reward_pair;
// withdraw reward to pending reward
let key = asset_token_raw.as_slice();
let mut pool_info = pool_info_read(&deps.storage).load(key)?;
let asset_token = &deps.api.human_address(&asset_token_raw)?;
let lp_balance = *mirror_map.get(asset_token).unwrap_or(&Uint128::zero());
spec_reward_to_pool(state, &mut pool_info, lp_balance)?;
before_share_change(&pool_info, &mut reward_info)?;
// update withdraw
farm_share += reward_info.farm_share;
farm_amount += calc_farm_balance(
reward_info.farm_share,
farm_staked.balance,
state.total_farm_share,
);
let locked_share = config.calc_locked_reward(reward_info.accum_spec_share, height);
let withdraw_share = if locked_share >= reward_info.spec_share {
Uint128::zero()
} else {
(reward_info.spec_share - locked_share)?
};
spec_share += withdraw_share;
spec_amount += calc_spec_balance(withdraw_share, spec_staked);
pool_info.farm_share = (pool_info.farm_share - reward_info.farm_share)?;
reward_info.farm_share = Uint128::zero();
reward_info.spec_share = locked_share;
// update rewards info
pool_info_store(&mut deps.storage).save(key, &pool_info)?;
if reward_info.spec_share.is_zero()
&& reward_info.farm_share.is_zero()
&& reward_info.auto_bond_share.is_zero()
&& reward_info.stake_bond_share.is_zero()
{
rewards_store(&mut deps.storage, &staker_addr).remove(key);
} else {
rewards_store(&mut deps.storage, &staker_addr).save(key, &reward_info)?;
}
}
Ok((spec_amount, spec_share, farm_amount, farm_share))
}
fn calc_farm_balance(share: Uint128, total_balance: Uint128, total_farm_share: Uint128) -> Uint128 {
if total_farm_share.is_zero() {
Uint128::zero()
} else {
total_balance.multiply_ratio(share, total_farm_share)
}
}
fn calc_spec_balance(share: Uint128, staked: &SpecBalanceResponse) -> Uint128 {
if staked.share.is_zero() {
Uint128::zero()
} else {
share.multiply_ratio(staked.balance, staked.share)
}
}
pub fn query_reward_info<S: Storage, A: Api, Q: Querier>(
deps: &Extern<S, A, Q>,
staker_addr: HumanAddr,
asset_token: Option<HumanAddr>,
height: u64,
) -> StdResult<RewardInfoResponse> {
let staker_addr_raw = deps.api.canonical_address(&staker_addr)?;
let mut state = read_state(&deps.storage)?;
let config = read_config(&deps.storage)?;
let spec_staked = deposit_spec_reward(deps, &mut state, &config, height, true)?;
let reward_infos = read_reward_infos(
deps,
&config,
height,
&state,
&staker_addr_raw,
&asset_token,
&spec_staked,
)?;
Ok(RewardInfoResponse {
staker_addr,
reward_infos,
})
}
fn read_reward_infos<S: Storage, A: Api, Q: Querier>(
deps: &Extern<S, A, Q>,
config: &Config,
height: u64,
state: &State,
staker_addr: &CanonicalAddr,
asset_token: &Option<HumanAddr>,
spec_staked: &SpecBalanceResponse,
) -> StdResult<Vec<RewardInfoResponseItem>> {
let rewards_bucket = rewards_read(&deps.storage, &staker_addr);
// single reward; or all rewards
let reward_pairs: Vec<(CanonicalAddr, RewardInfo)>;
if let Some(asset_token) = asset_token {
let asset_token_raw = deps.api.canonical_address(&asset_token)?;
let key = asset_token_raw.as_slice();
let reward_info = rewards_bucket.may_load(key)?;
reward_pairs = if let Some(reward_info) = reward_info {
vec![(asset_token_raw.clone(), reward_info)]
} else {
vec![]
};
} else {
reward_pairs = rewards_bucket
.range(None, None, Order::Ascending)
.map(|item| {
let (k, v) = item?;
Ok((CanonicalAddr::from(k), v))
})
.collect::<StdResult<Vec<(CanonicalAddr, RewardInfo)>>>()?;
}
let farm_staked: MirrorStakerResponse =
deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: deps.api.human_address(&config.mirror_gov)?,
msg: to_binary(&MirrorGovQueryMsg::Staker {
address: deps.api.human_address(&state.contract_addr)?,
})?,
}))?;
let mirror_reward_infos = query_mirror_reward_info(
deps,
&deps.api.human_address(&config.mirror_staking)?,
&deps.api.human_address(&state.contract_addr)?,
)?;
let mirror_map: HashMap<_, _> = mirror_reward_infos
.reward_infos
.into_iter()
.map(|it| (it.asset_token, it.bond_amount))
.collect();
let bucket = pool_info_read(&deps.storage);
let reward_infos: Vec<RewardInfoResponseItem> = reward_pairs
.into_iter()
.map(|(asset_token_raw, reward_info)| {
let mut pool_info = bucket.load(asset_token_raw.as_slice())?;
let asset_token = &deps.api.human_address(&asset_token_raw)?;
// update pending rewards
let mut reward_info = reward_info;
let lp_balance = *mirror_map.get(asset_token).unwrap_or(&Uint128::zero());
let farm_share_index = reward_info.farm_share_index;
let auto_spec_index = reward_info.auto_spec_share_index;
let stake_spec_index = reward_info.stake_spec_share_index;
spec_reward_to_pool(state, &mut pool_info, lp_balance)?;
before_share_change(&pool_info, &mut reward_info)?;
let auto_bond_amount =
pool_info.calc_user_auto_balance(lp_balance, reward_info.auto_bond_share);
let stake_bond_amount = pool_info.calc_user_stake_balance(reward_info.stake_bond_share);
let locked_spec_share = config.calc_locked_reward(reward_info.accum_spec_share, height);
Ok(RewardInfoResponseItem {
asset_token: asset_token.clone(),
farm_share_index,
auto_spec_share_index: auto_spec_index,
stake_spec_share_index: stake_spec_index,
bond_amount: auto_bond_amount + stake_bond_amount,
auto_bond_amount,
stake_bond_amount,
farm_share: reward_info.farm_share,
auto_bond_share: reward_info.auto_bond_share,
stake_bond_share: reward_info.stake_bond_share,
spec_share: reward_info.spec_share,
pending_spec_reward: calc_spec_balance(reward_info.spec_share, spec_staked),
pending_farm_reward: calc_farm_balance(
reward_info.farm_share,
farm_staked.balance,
state.total_farm_share,
),
accum_spec_share: reward_info.accum_spec_share,
locked_spec_share,
locked_spec_reward: calc_spec_balance(locked_spec_share, spec_staked),
})
})
.collect::<StdResult<Vec<RewardInfoResponseItem>>>()?;
Ok(reward_infos)
}
|
//!
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::fmt::Write;
use super::pattern::Pattern;
pub enum BinaryOperator {
Plus,
Minus,
Times,
Divided,
Power,
Mod,
}
pub enum UnaryOp {
Log,
Exp,
Sin,
Cos,
Tan,
Sqrt,
}
pub enum Reserved {
Pi,
}
#[derive(Clone, Debug, PartialEq)]
pub enum AlgebraicExpression {
Float(f64),
// TODO
// Reserved(Reserved),
// Variable(String),
// BinOp(Box<AlgebraicExpression>, BinaryOperator, Box<AlgebraicExpression>),
// UnOp(UnaryOp, AlgebraicExpression),
// Max(AlgebraicExpression, AlgebraicExpression),
// Min(AlgebraicExpression, AlgebraicExpression),
// Conditional(AlgebraicExpression, AlgebraicExpression, AlgebraicExpression)
Occurrences(Pattern),
}
impl Display for AlgebraicExpression {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
match self {
AlgebraicExpression::Float(value) => value.fmt(f),
AlgebraicExpression::Occurrences(pattern) => {
f.write_char('|').and(pattern.fmt(f)).and(f.write_char('|'))
}
}
}
}
|
use std::iter;
use std::mem;
use crate::data::*;
use crate::solver::*;
pub struct GridSolver {
grid: Grid,
clues: Clues,
stats: GridSolverStats,
changed_rows: Vec <bool>,
changed_cols: Vec <bool>,
line_solver: LineSolver,
state: State,
vertical: bool,
index: LineSize,
index_changed: bool,
}
enum State {
Scanning,
Solving (LineSize),
Complete,
}
#[ derive (Clone, Copy, Debug) ]
pub struct GridSolverStats {
pub grid_iterations: usize,
pub line_iterations: usize,
}
#[ derive (Debug) ]
pub enum GridSolverEvent {
StartRow (LineSize),
StartCol (LineSize),
SolvedCell (LineSize, LineSize),
SolvedRow (LineSize),
SolvedCol (LineSize),
SolvedGrid,
}
impl GridSolver {
pub fn new (
grid: Grid,
clues: Clues,
) -> GridSolver {
let changed_rows = iter::repeat (true).take (
grid.num_rows () as usize,
).collect ();
let changed_cols = iter::repeat (true).take (
grid.num_cols () as usize,
).collect ();
GridSolver {
grid: grid,
clues: clues,
stats: GridSolverStats::new (),
changed_rows: changed_rows,
changed_cols: changed_cols,
line_solver: Default::default (),
vertical: false,
index: 0,
index_changed: true,
state: State::Scanning,
}
}
pub fn release (self) -> (Clues, Grid) {
(self.clues, self.grid)
}
pub fn clues (& self) -> & Clues {
& self.clues
}
pub fn grid (& self) -> & Grid {
& self.grid
}
pub fn stats (& self) -> & GridSolverStats {
& self.stats
}
fn advance (& mut self) {
let max_index = if ! self.vertical {
self.grid.num_rows ()
} else {
self.grid.num_cols ()
};
if ! self.vertical {
self.changed_rows [self.index as usize] = false;
} else {
self.changed_cols [self.index as usize] = false;
}
self.index += 1;
if self.index == max_index {
if self.vertical {
self.stats.grid_iterations += 1;
}
self.vertical = ! self.vertical;
self.index = 0;
}
self.index_changed = true;
}
fn get_line_changed (& self) -> bool {
if ! self.vertical {
self.changed_rows [self.index as usize]
} else {
self.changed_cols [self.index as usize]
}
}
fn unset_line_changed (& mut self) {
if ! self.vertical {
self.changed_rows [self.index as usize] = false
} else {
self.changed_cols [self.index as usize] = false
}
}
fn get_clues (& self) -> & CluesLine {
if ! self.vertical {
self.clues.row (self.index)
} else {
self.clues.col (self.index)
}
}
fn get_line <'a> (
& 'a self,
) -> GridIter <'a> {
if ! self.vertical {
self.grid.row (self.index)
} else {
self.grid.col (self.index)
}
}
fn get_cell (& mut self, cell_index: LineSize) -> Cell {
if ! self.vertical {
self.grid [(self.index, cell_index)]
} else {
self.grid [(cell_index, self.index)]
}
}
fn set_cell (& mut self, cell_index: LineSize, cell: Cell) {
if ! self.vertical {
self.grid [(self.index, cell_index)] = cell;
self.changed_cols [cell_index as usize] = true
} else {
self.grid [(cell_index, self.index)] = cell;
self.changed_rows [cell_index as usize] = true;
}
}
fn is_complete (& self) -> bool {
match self.state {
State::Complete => true,
_ => false,
}
}
fn is_solving (& self) -> bool {
match self.state {
State::Solving (..) => true,
_ => false,
}
}
fn next_cell (& mut self) -> Option <(LineSize, Cell)> {
match self.state {
State::Solving (ref mut cell_index) => {
if let Some (cell) = self.line_solver.next () {
let result = (* cell_index, cell);
* cell_index += 1;
Some (result)
} else {
None
}
},
_ => panic! (),
}
}
pub fn next (
& mut self,
) -> Option <GridSolverEvent> {
if self.is_complete () {
return None;
}
loop {
if self.is_solving () {
if let Some ((cell_index, cell)) = self.next_cell () {
if cell == self.get_cell (cell_index) {
continue;
}
self.set_cell (cell_index, cell);
return Some (
if ! self.vertical {
GridSolverEvent::SolvedCell (self.index, cell_index)
} else {
GridSolverEvent::SolvedCell (cell_index, self.index)
}
);
}
self.state = State::Scanning;
self.unset_line_changed ();
self.stats.line_iterations += 1;
continue;
}
if self.grid.is_solved () {
self.stats.grid_iterations += 1;
self.state = State::Complete;
return Some (GridSolverEvent::SolvedGrid);
}
while ! self.get_line_changed ()
|| self.get_line ().all (Cell::is_solved) {
self.advance ();
}
if self.index_changed {
self.index_changed = false;
return Some (
if ! self.vertical {
GridSolverEvent::StartRow (self.index)
} else {
GridSolverEvent::StartCol (self.index)
}
);
}
self.state = State::Solving (0);
let mut line_solver = Default::default ();
mem::swap (& mut line_solver, & mut self.line_solver);
self.line_solver = match line_solver.into_new (
self.get_line (),
self.get_clues (),
) {
Ok (val) => val,
Err (_) => panic! (),
};
}
}
pub fn end (self) -> (Grid, GridSolverStats) {
(self.grid, self.stats)
}
}
impl GridSolverStats {
pub fn new () -> GridSolverStats {
GridSolverStats {
grid_iterations: 0,
line_iterations: 0,
}
}
}
|
use self::error;
use console::style;
use log::*;
use std::path::PathBuf;
use std::process;
use structopt::{
clap::crate_authors, clap::crate_description, clap::crate_version, clap::AppSettings, StructOpt,
};
use uvm_cli::{options::ColorOption, set_colors_enabled, set_loglevel};
use uvm_core::unity::Component;
use uvm_core::unity::Version;
const SETTINGS: &'static [AppSettings] = &[
AppSettings::ColoredHelp,
AppSettings::DontCollapseArgsInUsage,
];
#[derive(StructOpt, Debug)]
#[structopt(version = crate_version!(), author = crate_authors!(), about = crate_description!(), settings = SETTINGS)]
struct Opts {
/// Module to install
///
/// A support module to install. You can list all awailable
/// modules for a given version using `uvm-modules`
#[structopt(short, long = "module", number_of_values = 1)]
modules: Option<Vec<Component>>,
/// Install also synced modules
///
/// Synced modules are optional dependencies of some Unity modules.
/// e.g. Android SDK for the android module.
#[structopt(long = "with-sync")]
sync: bool,
/// The unity version to install in the form of `2018.1.0f3`
version: Version,
/// A directory to install the requested version to
destination: Option<PathBuf>,
/// print debug output
#[structopt(short, long)]
debug: bool,
/// print more output
#[structopt(short, long, parse(from_occurrences))]
verbose: i32,
/// Color:.
#[structopt(short, long, possible_values = &ColorOption::variants(), case_insensitive = true, default_value)]
color: ColorOption,
}
fn main() {
let opt = Opts::from_args();
set_colors_enabled(&opt.color);
set_loglevel(opt.debug.then(|| 2).unwrap_or(opt.verbose));
let version = opt.version;
let modules = opt.modules;
let install_sync = opt.sync;
let destination = opt.destination;
uvm_install2::install(version, modules.as_ref(), install_sync, destination).unwrap_or_else(
|err| {
error!("Failure during installation");
error!("{}", &err);
for e in err.iter().skip(1) {
debug!("{}", &format!("caused by: {}", style(&e).red()));
}
if let Some(backtrace) = err.backtrace() {
debug!("backtrace: {:?}", backtrace);
}
process::exit(1);
},
);
eprintln!("{}", style("Finish").green().bold())
}
|
use crate::{f32s, f64s, sparse::SparseMatrix};
use simd_aligned::{MatrixD, Rows};
/// Represents one class of the SVM model.
#[derive(Clone, Debug)]
#[doc(hidden)]
pub(crate) struct Class<M32> {
/// The label of this class
pub(crate) label: i32,
// /// The number of support vectors in this class
// pub(crate) num_support_vectors: usize,
/// Coefficients between this class and n-1 other classes.
pub(crate) coefficients: MatrixD<f64s, Rows>,
/// All support vectors in this class.
pub(crate) support_vectors: M32,
}
impl Class<MatrixD<f32s, Rows>> {
/// Creates a new class with the given parameters.
pub fn with_parameters(classes: usize, support_vectors: usize, attributes: usize, label: i32) -> Self {
Self {
label,
coefficients: MatrixD::with_dimension(classes - 1, support_vectors),
support_vectors: MatrixD::with_dimension(support_vectors, attributes),
}
}
}
impl Class<SparseMatrix<f32>> {
/// Creates a new class with the given parameters.
pub fn with_parameters(classes: usize, support_vectors: usize, _attributes: usize, label: i32) -> Self {
Self {
label,
coefficients: MatrixD::with_dimension(classes - 1, support_vectors),
support_vectors: SparseMatrix::with(support_vectors),
}
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 0x04],
#[doc = "0x04 - OctoSPI IO Manager Port 1 Configuration Register"]
pub p1cr: P1CR,
#[doc = "0x08 - OctoSPI IO Manager Port 2 Configuration Register"]
pub p2cr: P2CR,
}
#[doc = "P1CR (rw) register accessor: OctoSPI IO Manager Port 1 Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`p1cr::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 [`p1cr::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 [`p1cr`]
module"]
pub type P1CR = crate::Reg<p1cr::P1CR_SPEC>;
#[doc = "OctoSPI IO Manager Port 1 Configuration Register"]
pub mod p1cr;
#[doc = "P2CR (rw) register accessor: OctoSPI IO Manager Port 2 Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`p2cr::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 [`p2cr::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 [`p2cr`]
module"]
pub type P2CR = crate::Reg<p2cr::P2CR_SPEC>;
#[doc = "OctoSPI IO Manager Port 2 Configuration Register"]
pub mod p2cr;
|
struct Node {
pub bits: [bool; 24]
}
impl Node {
pub fn new(string: String) -> Node {
let mut collector = [true; 24];
for (i, character) in string.split(' ').into_iter().enumerate() {
collector[i] = character == "1";
}
Node{bits: collector}
}
fn get_hamming_distance(&self, other: Node) -> u8 {
let mut dist = 0;
for (i, character) in self.bits.iter().enumerate() {
if *character != other.bits[i] {
dist += 1
}
}
dist
}
fn generate_within_distance(&self, distance: u8) -> Vec<[bool; 24]> {
let mut result : Vec<[bool; 24]> = Vec::new();
for (i, value) in self.bits.iter().enumerate() {
let mut mutation = [true; 24];
mutation.copy_from_slice(&self.bits[..]);
mutation[i] = !mutation[i];
result.push(mutation)
}
result
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn hamming_dist_0() {
let node_1 = Node::new(String::from("0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1"));
let node_2 = Node::new(String::from("0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1"));
assert_eq!(node_1.get_hamming_distance(node_2), 0)
}
#[test]
fn hamming_dist_3() {
let node_1 = Node::new(String::from("0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1"));
let node_2 = Node::new(String::from("0 1 0 0 0 1 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 0 1"));
assert_eq!(node_1.get_hamming_distance(node_2), 3)
}
#[test]
fn generate_within_distance_1() {
let node = Node::new(String::from("0 0 0 0"));
let within_1 = node.generate_within_distance(1);
let result : Vec<[bool; 24]> = Vec::new();
assert_eq!(within_1, result)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.