text stringlengths 8 4.13M |
|---|
use wasm_bindgen::prelude::*;
use web_sys::{OffscreenCanvas, WebGlRenderingContext};
use crate::simulations::{Boid, FallingSand, Flock, GoL, Simulation};
// use crate::simulations::GoL;
type GL = web_sys::WebGlRenderingContext;
mod common_funcs;
mod gl_setup;
mod quadtree;
mod rendering;
mod shaders;
mod simulations;
mod utils;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
pub fn log(s: &str);
}
#[wasm_bindgen]
pub struct FolioClient {
gl: WebGlRenderingContext,
flock: Flock,
fallingsim: FallingSand,
golsim: GoL,
n: u16,
}
#[wasm_bindgen]
impl FolioClient {
#[wasm_bindgen(constructor)]
pub fn new(gl: WebGlRenderingContext, n: u16) -> Self {
console_error_panic_hook::set_once();
let width = gl.drawing_buffer_width();
let height = gl.drawing_buffer_height();
let gol = GoL::new(&gl, width as u32 / 10, height as u32 / 10);
let fs = FallingSand::new(&gl, width as u32 / 10, height as u32 / 10);
//*****let flock = Flock::new(&gl, canvas.width() / 10, canvas.height() / 10);
let flock = Flock::new(&gl, width as u32, height as u32);
Self {
gl,
flock: flock,
fallingsim: fs,
golsim: gol,
n,
}
}
pub fn update(&mut self) -> Result<(), JsValue> {
match self.n {
0 => self.flock.update(
self.gl.drawing_buffer_width(),
self.gl.drawing_buffer_height(),
),
1 => self.fallingsim.update(),
2 => self.golsim.update(
self.gl.drawing_buffer_width(),
self.gl.drawing_buffer_height(),
),
_ => println!("err"),
}
Ok(())
}
pub fn render(&self) {
self.gl.viewport(
0,
0,
self.gl.drawing_buffer_width(),
self.gl.drawing_buffer_height(),
);
self.gl.clear(GL::COLOR_BUFFER_BIT | GL::DEPTH_BUFFER_BIT);
match self.n {
0 => self.flock.render(&self.gl),
1 => self.fallingsim.render(&self.gl),
2 => self.golsim.render(&self.gl),
_ => println!("err"),
}
//self.sim.render(&self.gl);
}
}
|
use std::sync::Arc;
use eyre::Report;
use rosu_pp::{
Beatmap as Map, CatchPP, CatchStars, ManiaPP, OsuPP, PerformanceAttributes, TaikoPP,
};
use rosu_v2::prelude::{Beatmap, GameMode, GameMods, OsuError, Score, User};
use twilight_model::{
application::interaction::{application_command::CommandOptionValue, ApplicationCommand},
channel::message::MessageType,
id::{marker::UserMarker, Id},
};
use crate::{
commands::{check_user_mention, parse_discord, DoubleResultCow, MyCommand},
database::OsuData,
embeds::{EmbedData, FixScoreEmbed},
error::{Error, PpError},
tracking::process_osu_tracking,
util::{
constants::{
common_literals::{DISCORD, MAP, MAP_PARSE_FAIL, MODS, MODS_PARSE_FAIL, NAME},
GENERAL_ISSUE, OSU_API_ISSUE,
},
matcher,
osu::{
map_id_from_history, map_id_from_msg, prepare_beatmap_file, MapIdType, ModSelection,
},
ApplicationCommandExt, InteractionExt, MessageExt,
},
Args, BotResult, CommandData, Context,
};
use super::{
get_beatmap_user_score, get_user, option_discord, option_map, option_mods, option_name,
UserArgs,
};
#[command]
#[short_desc("Display a user's pp after unchoking their score on a map")]
#[long_desc(
"Display a user's pp after unchoking their score on a map. \n\
If no map is given, I will choose the last map \
I can find in the embeds of this channel.\n\
Mods can be specified but only if there already is a score \
on the map with those mods."
)]
#[aliases("fixscore")]
#[usage("[username] [map url / map id] [+mods]")]
#[example(
"badewanne3",
"badewanne3 2240404 +hdhr",
"https://osu.ppy.sh/beatmapsets/902425#osu/2240404"
)]
async fn fix(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
match data {
CommandData::Message { msg, mut args, num } => {
match FixArgs::args(&ctx, &mut args, msg.author.id).await {
Ok(Ok(mut fix_args)) => {
let reply = msg
.referenced_message
.as_ref()
.filter(|_| msg.kind == MessageType::Reply);
if let Some(id) = reply.and_then(|msg| map_id_from_msg(msg)) {
fix_args.id = Some(MapOrScore::Map(id));
} else if let Some((mode, id)) =
reply.and_then(|msg| matcher::get_osu_score_id(&msg.content))
{
fix_args.id = Some(MapOrScore::Score { id, mode });
}
_fix(ctx, CommandData::Message { msg, args, num }, fix_args).await
}
Ok(Err(content)) => msg.error(&ctx, content).await,
Err(why) => {
let _ = msg.error(&ctx, GENERAL_ISSUE).await;
Err(why)
}
}
}
CommandData::Interaction { command } => slash_fix(ctx, *command).await,
}
}
async fn _fix(ctx: Arc<Context>, data: CommandData<'_>, args: FixArgs) -> BotResult<()> {
let FixArgs { osu, id, mods } = args;
let name = match osu.map(OsuData::into_username) {
Some(name) => name,
None => return super::require_link(&ctx, &data).await,
};
let mods = match mods {
None | Some(ModSelection::Exclude(_)) => None,
Some(ModSelection::Exact(mods)) | Some(ModSelection::Include(mods)) => Some(mods),
};
let data_result = match id {
Some(MapOrScore::Score { id, mode }) => {
request_by_score(&ctx, &data, id, mode, name.as_str()).await
}
Some(MapOrScore::Map(MapIdType::Map(id))) => {
request_by_map(&ctx, &data, id, name.as_str(), mods).await
}
Some(MapOrScore::Map(MapIdType::Set(_))) => {
let content = "Looks like you gave me a mapset id, I need a map id though";
return data.error(&ctx, content).await;
}
None => {
let msgs = match ctx.retrieve_channel_history(data.channel_id()).await {
Ok(msgs) => msgs,
Err(why) => {
let _ = data.error(&ctx, GENERAL_ISSUE).await;
return Err(why);
}
};
match map_id_from_history(&msgs) {
Some(MapIdType::Map(id)) => {
request_by_map(&ctx, &data, id, name.as_str(), mods).await
}
Some(MapIdType::Set(_)) => {
let content = "I found a mapset in the channel history but I need a map. \
Try specifying a map either by url to the map, or just by map id.";
return data.error(&ctx, content).await;
}
None => {
let content = "No beatmap specified and none found in recent channel history. \
Try specifying a map either by url to the map, or just by map id.";
return data.error(&ctx, content).await;
}
}
}
};
let ScoreData {
user,
map,
mut scores,
} = match data_result {
ScoreResult::Data(data) => data,
ScoreResult::Done => return Ok(()),
ScoreResult::Error(err) => return Err(err),
};
if map.mode == GameMode::MNA {
return data.error(&ctx, "Can't fix mania scores \\:(").await;
}
let unchoked_pp = match scores {
Some((ref mut score, _)) => {
if score.pp.is_some() && !needs_unchoking(score, &map) {
None
} else {
match unchoke_pp(&ctx, score, &map).await {
Ok(pp) => pp,
Err(why) => {
let _ = data.error(&ctx, GENERAL_ISSUE).await;
return Err(why);
}
}
}
}
None => None,
};
// Process tracking
if let Some((_, best)) = scores.as_mut() {
process_osu_tracking(&ctx, best, Some(&user)).await;
}
let gb = ctx.map_garbage_collector(&map);
let embed_data = FixScoreEmbed::new(user, map, scores, unchoked_pp, mods);
let builder = embed_data.into_builder().build().into();
data.create_message(&ctx, builder).await?;
// Set map on garbage collection list if unranked
gb.execute(&ctx);
Ok(())
}
#[allow(clippy::large_enum_variant)]
enum ScoreResult {
Data(ScoreData),
Done,
Error(Error),
}
struct ScoreData {
user: User,
map: Beatmap,
scores: Option<(Score, Vec<Score>)>,
}
// Retrieve user's score on the map, the user itself, and the map including mapset
async fn request_by_map(
ctx: &Context,
data: &CommandData<'_>,
map_id: u32,
name: &str,
mods: Option<GameMods>,
) -> ScoreResult {
let user_args = UserArgs::new(name, GameMode::STD);
match get_beatmap_user_score(ctx.osu(), map_id, &user_args, mods).await {
Ok(mut score) => match super::prepare_score(ctx, &mut score.score).await {
Ok(_) => {
let mut map = score.score.map.take().unwrap();
// First try to just get the mapset from the DB
let mapset_fut = ctx.psql().get_beatmapset(map.mapset_id);
let user_fut = ctx.osu().user(score.score.user_id).mode(score.score.mode);
let best_fut = ctx
.osu()
.user_scores(score.score.user_id)
.mode(score.score.mode)
.limit(100)
.best();
let (user, best) = match tokio::join!(mapset_fut, user_fut, best_fut) {
(_, Err(why), _) | (_, _, Err(why)) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return ScoreResult::Error(why.into());
}
(Ok(mapset), Ok(user), Ok(best)) => {
map.mapset = Some(mapset);
(user, best)
}
(Err(_), Ok(user), Ok(best)) => {
let mapset = match ctx.osu().beatmapset(map.mapset_id).await {
Ok(mapset) => mapset,
Err(why) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return ScoreResult::Error(why.into());
}
};
map.mapset = Some(mapset);
(user, best)
}
};
let data = ScoreData {
user,
map,
scores: Some((score.score, best)),
};
ScoreResult::Data(data)
}
Err(why) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
ScoreResult::Error(why.into())
}
},
// Either the user, map, or user score on the map don't exist
Err(OsuError::NotFound) => {
let map = match ctx.psql().get_beatmap(map_id, true).await {
Ok(map) => map,
Err(_) => match ctx.osu().beatmap().map_id(map_id).await {
Ok(map) => {
if let Err(err) = ctx.psql().insert_beatmap(&map).await {
warn!("{:?}", Report::new(err));
}
map
}
Err(OsuError::NotFound) => {
let content = format!("There is no map with id {map_id}");
return match data.error(ctx, content).await {
Ok(_) => ScoreResult::Done,
Err(err) => ScoreResult::Error(err),
};
}
Err(why) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return ScoreResult::Error(why.into());
}
},
};
let user_args = UserArgs::new(name, map.mode);
let user = match get_user(ctx, &user_args).await {
Ok(user) => user,
Err(OsuError::NotFound) => {
let content = format!("Could not find user `{name}`");
return match data.error(ctx, content).await {
Ok(_) => ScoreResult::Done,
Err(err) => ScoreResult::Error(err),
};
}
Err(why) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return ScoreResult::Error(why.into());
}
};
let data = ScoreData {
user,
map,
scores: None,
};
ScoreResult::Data(data)
}
Err(why) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
ScoreResult::Error(why.into())
}
}
}
async fn request_by_score(
ctx: &Context,
data: &CommandData<'_>,
score_id: u64,
mode: GameMode,
name: &str,
) -> ScoreResult {
let score_fut = ctx.osu().score(score_id, mode);
let user_fut = ctx.osu().user(name).mode(mode);
let (user, mut score) = match tokio::try_join!(user_fut, score_fut) {
Ok((user, score)) => (user, score),
Err(err) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return ScoreResult::Error(err.into());
}
};
let mut map = score.map.take().unwrap();
// First try to just get the mapset from the DB
let mapset_fut = ctx.psql().get_beatmapset(map.mapset_id);
let best_fut = ctx
.osu()
.user_scores(score.user_id)
.mode(score.mode)
.limit(100)
.best();
let best = match tokio::join!(mapset_fut, best_fut) {
(_, Err(why)) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return ScoreResult::Error(why.into());
}
(Ok(mapset), Ok(best)) => {
map.mapset = Some(mapset);
best
}
(Err(_), Ok(best)) => {
let mapset = match ctx.osu().beatmapset(map.mapset_id).await {
Ok(mapset) => mapset,
Err(why) => {
let _ = data.error(ctx, OSU_API_ISSUE).await;
return ScoreResult::Error(why.into());
}
};
map.mapset = Some(mapset);
best
}
};
let data = ScoreData {
user,
map,
scores: Some((score, best)),
};
ScoreResult::Data(data)
}
/// Returns unchoked pp and sets score pp if not available already
pub(super) async fn unchoke_pp(
ctx: &Context,
score: &mut Score,
map: &Beatmap,
) -> BotResult<Option<f32>> {
let map_path = prepare_beatmap_file(ctx, map.map_id).await?;
let rosu_map = Map::from_path(map_path).await.map_err(PpError::from)?;
let mods = score.mods.bits();
let attributes = if score.pp.is_some() {
None
} else {
let pp_result: PerformanceAttributes = match map.mode {
GameMode::STD => OsuPP::new(&rosu_map)
.mods(mods)
.combo(score.max_combo as usize)
.n300(score.statistics.count_300 as usize)
.n100(score.statistics.count_100 as usize)
.n50(score.statistics.count_50 as usize)
.misses(score.statistics.count_miss as usize)
.calculate()
.into(),
GameMode::MNA => ManiaPP::new(&rosu_map)
.mods(mods)
.score(score.score)
.calculate()
.into(),
GameMode::CTB => CatchPP::new(&rosu_map)
.mods(mods)
.combo(score.max_combo as usize)
.fruits(score.statistics.count_300 as usize)
.droplets(score.statistics.count_100 as usize)
.misses(score.statistics.count_miss as usize)
.accuracy(score.accuracy as f64)
.calculate()
.into(),
GameMode::TKO => TaikoPP::new(&rosu_map)
.combo(score.max_combo as usize)
.mods(mods)
.misses(score.statistics.count_miss as usize)
.accuracy(score.accuracy as f64)
.calculate()
.into(),
};
score.pp.replace(pp_result.pp() as f32);
if !needs_unchoking(score, map) {
return Ok(None);
}
Some(pp_result)
};
let unchoked_pp = match map.mode {
GameMode::STD => {
let total_objects = map.count_objects() as usize;
let mut count300 = score.statistics.count_300 as usize;
let count_hits = total_objects - score.statistics.count_miss as usize;
let ratio = 1.0 - (count300 as f32 / count_hits as f32);
let new100s = (ratio * score.statistics.count_miss as f32).ceil() as u32;
count300 += score.statistics.count_miss.saturating_sub(new100s) as usize;
let count100 = (score.statistics.count_100 + new100s) as usize;
let count50 = score.statistics.count_50 as usize;
let mut calculator = OsuPP::new(&rosu_map);
if let Some(attributes) = attributes {
calculator = calculator.attributes(attributes);
}
calculator
.mods(mods)
.n300(count300)
.n100(count100)
.n50(count50)
.calculate()
.pp
}
GameMode::CTB => {
let attributes = match attributes {
Some(PerformanceAttributes::Catch(attrs)) => attrs.difficulty,
Some(_) => panic!("no ctb attributes after calculating stars for ctb map"),
None => CatchStars::new(&rosu_map).mods(mods).calculate(),
};
let total_objects = attributes.max_combo();
let passed_objects = (score.statistics.count_300
+ score.statistics.count_100
+ score.statistics.count_miss) as usize;
let missing = total_objects.saturating_sub(passed_objects);
let missing_fruits = missing.saturating_sub(
attributes
.n_droplets
.saturating_sub(score.statistics.count_100 as usize),
);
let missing_droplets = missing - missing_fruits;
let n_fruits = score.statistics.count_300 as usize + missing_fruits;
let n_droplets = score.statistics.count_100 as usize + missing_droplets;
let n_tiny_droplet_misses = score.statistics.count_katu as usize;
let n_tiny_droplets = score.statistics.count_50 as usize;
CatchPP::new(&rosu_map)
.attributes(attributes)
.mods(mods)
.fruits(n_fruits)
.droplets(n_droplets)
.tiny_droplets(n_tiny_droplets)
.tiny_droplet_misses(n_tiny_droplet_misses)
.calculate()
.pp
}
GameMode::TKO => {
let total_objects = map.count_circles as usize;
let passed_objects = score.total_hits() as usize;
let mut count300 =
score.statistics.count_300 as usize + total_objects.saturating_sub(passed_objects);
let count_hits = total_objects - score.statistics.count_miss as usize;
let ratio = 1.0 - (count300 as f32 / count_hits as f32);
let new100s = (ratio * score.statistics.count_miss as f32).ceil() as u32;
count300 += score.statistics.count_miss.saturating_sub(new100s) as usize;
let count100 = (score.statistics.count_100 + new100s) as usize;
let acc = 100.0 * (2 * count300 + count100) as f32 / (2 * total_objects) as f32;
let mut calculator = TaikoPP::new(&rosu_map);
if let Some(attributes) = attributes {
calculator = calculator.attributes(attributes);
}
calculator.mods(mods).accuracy(acc as f64).calculate().pp
}
GameMode::MNA => panic!("can not unchoke mania scores"),
};
Ok(Some(unchoked_pp as f32))
}
fn needs_unchoking(score: &Score, map: &Beatmap) -> bool {
match map.mode {
GameMode::STD => {
score.statistics.count_miss > 0
|| score.max_combo < map.max_combo.map_or(0, |c| c.saturating_sub(5))
}
GameMode::TKO => score.statistics.count_miss > 0,
GameMode::CTB => score.max_combo != map.max_combo.unwrap_or(0),
GameMode::MNA => panic!("can not unchoke mania scores"),
}
}
enum MapOrScore {
Map(MapIdType),
Score { id: u64, mode: GameMode },
}
struct FixArgs {
osu: Option<OsuData>,
id: Option<MapOrScore>,
mods: Option<ModSelection>,
}
impl FixArgs {
async fn args(
ctx: &Context,
args: &mut Args<'_>,
author_id: Id<UserMarker>,
) -> DoubleResultCow<Self> {
let mut osu = ctx.psql().get_user_osu(author_id).await?;
let mut id = None;
let mut mods = None;
for arg in args.take(3) {
if let Some(id_) =
matcher::get_osu_map_id(arg).or_else(|| matcher::get_osu_mapset_id(arg))
{
id = Some(MapOrScore::Map(id_));
} else if let Some((mode, id_)) = matcher::get_osu_score_id(arg) {
id = Some(MapOrScore::Score { mode, id: id_ })
} else if let Some(mods_) = matcher::get_mods(arg) {
mods = Some(mods_);
} else {
match check_user_mention(ctx, arg).await? {
Ok(osu_) => osu = Some(osu_),
Err(content) => return Ok(Err(content)),
}
}
}
Ok(Ok(Self { osu, id, mods }))
}
async fn slash(ctx: &Context, command: &mut ApplicationCommand) -> DoubleResultCow<Self> {
let mut osu = ctx.psql().get_user_osu(command.user_id()?).await?;
let mut id = None;
let mut mods = None;
for option in command.yoink_options() {
match option.value {
CommandOptionValue::String(value) => match option.name.as_str() {
NAME => osu = Some(value.into()),
MAP => match matcher::get_osu_map_id(&value)
.or_else(|| matcher::get_osu_mapset_id(&value))
{
Some(id_) => id = Some(MapOrScore::Map(id_)),
None => match matcher::get_osu_score_id(&value) {
Some((mode, id_)) => id = Some(MapOrScore::Score { mode, id: id_ }),
None => return Ok(Err(MAP_PARSE_FAIL.into())),
},
},
MODS => match matcher::get_mods(&value) {
Some(mods_) => mods = Some(mods_),
None => match value.parse() {
Ok(mods_) => mods = Some(ModSelection::Exact(mods_)),
Err(_) => return Ok(Err(MODS_PARSE_FAIL.into())),
},
},
_ => return Err(Error::InvalidCommandOptions),
},
CommandOptionValue::User(value) => match option.name.as_str() {
DISCORD => match parse_discord(ctx, value).await? {
Ok(osu_) => osu = Some(osu_),
Err(content) => return Ok(Err(content)),
},
_ => return Err(Error::InvalidCommandOptions),
},
_ => return Err(Error::InvalidCommandOptions),
}
}
Ok(Ok(Self { osu, id, mods }))
}
}
pub async fn slash_fix(ctx: Arc<Context>, mut command: ApplicationCommand) -> BotResult<()> {
match FixArgs::slash(&ctx, &mut command).await? {
Ok(args) => _fix(ctx, command.into(), args).await,
Err(content) => command.error(&ctx, content).await,
}
}
pub fn define_fix() -> MyCommand {
let name = option_name();
let map = option_map();
let mods = option_mods(false);
let discord = option_discord();
let description = "Display a user's pp after unchoking their score on a map";
MyCommand::new("fix", description).options(vec![name, map, mods, discord])
}
|
use crate::codec::*;
use crate::error::*;
use crate::*;
use crate::{SocketType, ZmqResult};
use async_trait::async_trait;
use crossbeam::atomic::AtomicCell;
use crossbeam::queue::SegQueue;
use dashmap::DashMap;
use futures::lock::Mutex;
use futures::stream::FuturesUnordered;
use futures_util::sink::SinkExt;
use std::sync::Arc;
use std::time::Duration;
use tokio::stream::StreamExt;
struct ReqSocketBackend {
pub(crate) peers: DashMap<PeerIdentity, Peer>,
pub(crate) round_robin: SegQueue<PeerIdentity>,
pub(crate) current_request_peer_id: Mutex<Option<PeerIdentity>>,
}
pub struct ReqSocket {
backend: Arc<ReqSocketBackend>,
_accept_close_handle: Option<oneshot::Sender<bool>>,
current_request: Option<PeerIdentity>,
}
#[async_trait]
impl BlockingSend for ReqSocket {
async fn send(&mut self, message: ZmqMessage) -> ZmqResult<()> {
if self.current_request.is_some() {
return Err(ZmqError::Socket(
"Unable to send message. Request already in progress",
));
}
// In normal scenario this will always be only 1 iteration
// There can be special case when peer has disconnected and his id is still in RR queue
// This happens because SegQueue don't have an api to delete items from queue.
// So in such case we'll just pop item and skip it if we don't have a matching peer in peers map
loop {
let next_peer_id = match self.backend.round_robin.pop() {
Ok(peer) => peer,
Err(_) => {
return Err(ZmqError::Other(
"Not connected to peers. Unable to send messages",
))
}
};
match self.backend.peers.get_mut(&next_peer_id) {
Some(mut peer) => {
self.backend.round_robin.push(next_peer_id.clone());
let frames = vec![
"".into(), // delimiter frame
message,
];
peer.send_queue
.send(Message::MultipartMessage(frames))
.await?;
self.backend
.current_request_peer_id
.lock()
.await
.replace(next_peer_id.clone());
self.current_request = Some(next_peer_id);
return Ok(());
}
None => continue,
}
}
}
}
#[async_trait]
impl BlockingRecv for ReqSocket {
async fn recv(&mut self) -> ZmqResult<ZmqMessage> {
match self.current_request.take() {
Some(peer_id) => {
if let Some(recv_queue) = self
.backend
.peers
.get(&peer_id)
.map(|p| p.recv_queue.clone())
{
let message = recv_queue.lock().await.next().await;
match message {
Some(Message::MultipartMessage(mut message)) => {
assert!(message.len() == 2);
assert!(message[0].data.is_empty()); // Ensure that we have delimeter as first part
Ok(message.pop().unwrap())
}
Some(_) => Err(ZmqError::Other("Wrong message type received")),
None => Err(ZmqError::NoMessage),
}
} else {
Err(ZmqError::Other("Server disconnected"))
}
}
None => Err(ZmqError::Other("Unable to recv. No request in progress")),
}
}
}
#[async_trait]
impl SocketFrontend for ReqSocket {
fn new() -> Self {
Self {
backend: Arc::new(ReqSocketBackend {
peers: DashMap::new(),
round_robin: SegQueue::new(),
current_request_peer_id: Mutex::new(None),
}),
_accept_close_handle: None,
current_request: None,
}
}
async fn bind(&mut self, endpoint: &str) -> ZmqResult<()> {
if self._accept_close_handle.is_some() {
return Err(ZmqError::Other(
"Socket server already started. Currently only one server is supported",
));
}
let stop_handle = util::start_accepting_connections(endpoint, self.backend.clone()).await?;
self._accept_close_handle = Some(stop_handle);
Ok(())
}
async fn connect(&mut self, endpoint: &str) -> ZmqResult<()> {
let addr = endpoint.parse::<SocketAddr>()?;
let raw_socket = tokio::net::TcpStream::connect(addr).await?;
util::peer_connected(raw_socket, self.backend.clone()).await;
Ok(())
}
}
impl MultiPeer for ReqSocketBackend {
fn peer_connected(
&self,
peer_id: &PeerIdentity,
) -> (mpsc::Receiver<Message>, oneshot::Receiver<bool>) {
let default_queue_size = 1;
let (out_queue, out_queue_receiver) = mpsc::channel(default_queue_size);
let (in_queue, in_queue_receiver) = mpsc::channel(default_queue_size);
let (stop_handle, stop_callback) = oneshot::channel::<bool>();
self.peers.insert(
peer_id.clone(),
Peer {
identity: peer_id.clone(),
send_queue: out_queue,
recv_queue: Arc::new(Mutex::new(in_queue_receiver)),
recv_queue_in: in_queue,
_io_close_handle: stop_handle,
},
);
self.round_robin.push(peer_id.clone());
(out_queue_receiver, stop_callback)
}
fn peer_disconnected(&self, peer_id: &PeerIdentity) {
self.peers.remove(peer_id);
}
}
#[async_trait]
impl SocketBackend for ReqSocketBackend {
async fn message_received(&self, peer_id: &PeerIdentity, message: Message) {
// This is needed to ensure that we only store messages that we are expecting to get
// Other messages are silently discarded according to spec
let mut curr_req_lock = self.current_request_peer_id.lock().await;
match curr_req_lock.take() {
Some(id) => {
if &id != peer_id {
curr_req_lock.replace(id);
return;
}
}
None => return,
}
drop(curr_req_lock);
// We've got reply that we were waiting for
self.peers
.get_mut(peer_id)
.expect("Not found peer by id")
.recv_queue_in
.send(message)
.await
.expect("Failed to send");
}
fn socket_type(&self) -> SocketType {
SocketType::REQ
}
fn shutdown(&self) {
self.peers.clear();
}
}
struct RepSocketBackend {
pub(crate) peers: Arc<DashMap<PeerIdentity, Peer>>,
}
pub struct RepSocket {
backend: Arc<RepSocketBackend>,
_accept_close_handle: Option<oneshot::Sender<bool>>,
current_request: Option<PeerIdentity>,
}
#[async_trait]
impl SocketFrontend for RepSocket {
fn new() -> Self {
Self {
backend: Arc::new(RepSocketBackend {
peers: Arc::new(DashMap::new()),
}),
_accept_close_handle: None,
current_request: None,
}
}
async fn bind(&mut self, endpoint: &str) -> ZmqResult<()> {
let stop_handle = util::start_accepting_connections(endpoint, self.backend.clone()).await?;
self._accept_close_handle = Some(stop_handle);
Ok(())
}
async fn connect(&mut self, endpoint: &str) -> ZmqResult<()> {
unimplemented!()
}
}
impl MultiPeer for RepSocketBackend {
fn peer_connected(
&self,
peer_id: &PeerIdentity,
) -> (mpsc::Receiver<Message>, oneshot::Receiver<bool>) {
let default_queue_size = 100;
let (out_queue, out_queue_receiver) = mpsc::channel(default_queue_size);
let (in_queue, in_queue_receiver) = mpsc::channel(default_queue_size);
let (stop_handle, stop_callback) = oneshot::channel::<bool>();
self.peers.insert(
peer_id.clone(),
Peer {
identity: peer_id.clone(),
send_queue: out_queue,
recv_queue: Arc::new(Mutex::new(in_queue_receiver)),
recv_queue_in: in_queue,
_io_close_handle: stop_handle,
},
);
(out_queue_receiver, stop_callback)
}
fn peer_disconnected(&self, peer_id: &PeerIdentity) {
self.peers.remove(peer_id);
}
}
#[async_trait]
impl SocketBackend for RepSocketBackend {
async fn message_received(&self, peer_id: &PeerIdentity, message: Message) {
self.peers
.get_mut(peer_id)
.expect("Not found peer by id")
.recv_queue_in
.send(message)
.await
.expect("Failed to send");
}
fn socket_type(&self) -> SocketType {
SocketType::REP
}
fn shutdown(&self) {
self.peers.clear();
}
}
#[async_trait]
impl BlockingSend for RepSocket {
async fn send(&mut self, message: ZmqMessage) -> ZmqResult<()> {
match self.current_request.take() {
Some(peer_id) => {
if let Some(mut peer) = self.backend.peers.get_mut(&peer_id) {
let frames = vec![
"".into(), // delimiter frame
message,
];
peer.send_queue
.send(Message::MultipartMessage(frames))
.await?;
Ok(())
} else {
Err(ZmqError::Other("Client disconnected"))
}
}
None => Err(ZmqError::Other(
"Unable to send reply. No request in progress",
)),
}
}
}
#[async_trait]
impl BlockingRecv for RepSocket {
async fn recv(&mut self) -> ZmqResult<ZmqMessage> {
let mut messages = FuturesUnordered::new();
loop {
for peer in self.backend.peers.iter() {
let peer_id = peer.identity.clone();
let recv_queue = peer.recv_queue.clone();
messages.push(async move { (peer_id, recv_queue.lock().await.next().await) });
}
if messages.is_empty() {
// TODO this is super stupid way of waiting for new connections
// Needs to be refactored
tokio::time::delay_for(Duration::from_millis(100)).await;
continue;
} else {
break;
}
}
loop {
match messages.next().await {
Some((peer_id, Some(Message::MultipartMessage(mut messages)))) => {
assert!(messages.len() == 2);
assert!(messages[0].data.is_empty()); // Ensure that we have delimeter as first part
self.current_request = Some(peer_id);
return Ok(messages.pop().unwrap());
}
Some((peer_id, None)) => {
println!("Peer disconnected {:?}", peer_id);
self.backend.peers.remove(&peer_id);
}
Some((_peer_id, _)) => todo!(),
None => continue,
};
}
}
}
|
#[macro_use]
mod utils;
pub mod dl_cache;
pub mod dynamic;
pub mod elf;
pub mod error;
pub mod header;
pub mod ld_so_cache;
pub mod ldd;
pub mod section;
pub mod segment;
pub mod strtab;
pub mod types;
pub use dynamic::{Dynamic, DynamicContent};
pub use elf::Elf;
pub use error::Error;
pub use header::Header;
pub use section::{Section, SectionContent, SectionHeader};
pub use segment::SegmentHeader;
pub use strtab::Strtab;
|
// Import hacspec and all needed definitions.
use hacspec_lib::*;
// Import chacha20 and poly1305
use hacspec_chacha20::*;
use hacspec_poly1305::*;
#[derive(Debug)]
pub enum Error {
InvalidTag,
}
pub type ChaChaPolyKey = ChaChaKey;
pub type ChaChaPolyIV = ChaChaIV;
pub type ByteSeqResult = Result<ByteSeq, Error>;
pub fn init(key: ChaChaPolyKey, iv: ChaChaPolyIV) -> PolyState {
let key_block0 = chacha20_key_block0(key, iv);
let poly_key = PolyKey::from_slice(&key_block0, 0, 32);
poly1305_init(poly_key)
}
pub fn poly1305_update_padded(m: &ByteSeq, st: PolyState) -> PolyState {
let st = poly1305_update_blocks(m, st);
let last = m.get_remainder_chunk(16);
poly1305_update_last(16, &last, st)
}
pub fn finish(aad_len: usize, cipher_len: usize, st: PolyState) -> Poly1305Tag {
let mut last_block = PolyBlock::new();
last_block = last_block.update(0, &U64_to_le_bytes(U64(aad_len as u64)));
last_block = last_block.update(8, &U64_to_le_bytes(U64(cipher_len as u64)));
let st = poly1305_update_block(&last_block, st);
poly1305_finish(st)
}
pub fn chacha20_poly1305_encrypt(
key: ChaChaPolyKey,
iv: ChaChaPolyIV,
aad: &ByteSeq,
msg: &ByteSeq,
) -> (ByteSeq, Poly1305Tag) {
let cipher_text = chacha20(key, iv, 1u32, msg);
let mut poly_st = init(key, iv);
poly_st = poly1305_update_padded(aad, poly_st);
poly_st = poly1305_update_padded(&cipher_text, poly_st);
let tag = finish(aad.len(), cipher_text.len(), poly_st);
(cipher_text, tag)
}
pub fn chacha20_poly1305_decrypt(
key: ChaChaPolyKey,
iv: ChaChaPolyIV,
aad: &ByteSeq,
cipher_text: &ByteSeq,
tag: Poly1305Tag,
) -> ByteSeqResult {
let mut poly_st = init(key, iv);
poly_st = poly1305_update_padded(aad, poly_st);
poly_st = poly1305_update_padded(cipher_text, poly_st);
let my_tag = finish(aad.len(), cipher_text.len(), poly_st);
if my_tag.declassify_eq(&tag) {
ByteSeqResult::Ok(chacha20(key, iv, 1u32, cipher_text))
} else {
ByteSeqResult::Err(Error::InvalidTag)
}
}
|
use super::*;
pub struct TimTicketQueue {
pub ticket_queue: Arc<Mutex<Vec<Ticket>>>,
}
pub struct TimScheduler {
pub should_run: Arc<Mutex<Option<Uuid>>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum SchedulerCommand {
Start,
Stop,
}
pub trait TicketQueue {
fn add(&mut self) -> (PathBuf, uuid::Uuid);
fn get_position(&mut self, id: &uuid::Uuid) -> usize;
fn remove(&mut self, id: &uuid::Uuid);
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Ticket {
pub id: uuid::Uuid,
pub temp_path: PathBuf,
pub date: DateTime<Utc>,
}
impl TicketQueue for Arc<Mutex<Vec<Ticket>>> {
fn add(&mut self) -> (PathBuf, uuid::Uuid) {
let (temp_path, id) = get_new_temp_path();
self.lock().expect("Should unlock").push(Ticket {
id: id.clone(),
temp_path: temp_path.clone(),
date: chrono::Utc::now(),
});
(temp_path, id)
}
fn get_position(&mut self, id: &uuid::Uuid) -> usize {
match self
.lock()
.expect("Should unlock")
.iter()
.position(|x| x.id == *id)
{
Some(index) => index,
None => 0,
}
}
fn remove(&mut self, id: &uuid::Uuid) {
let mut unlocked = self.lock().expect("Should unlock");
match unlocked.iter().position(|x| x.id == *id) {
Some(index) => {
std::fs::remove_dir_all(&unlocked[index].temp_path)
.expect("Should remove temp dir");
unlocked.remove(index);
}
None => {}
};
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum FolderType {
#[serde(rename = "analysis")]
Analysis,
#[serde(rename = "data")]
Data,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum LanguageType {
#[serde(rename = "r")]
R,
#[serde(rename = "stata")]
Stata,
}
impl<'r> FromParam<'r> for FolderType {
type Error = &'r str;
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
let json_str = format!("\"{}\"", ¶m);
match serde_json::from_str::<FolderType>(&json_str) {
Ok(ft) => Ok(ft),
Err(_) => Err(param),
}
}
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NewAnalysis {
pub name: String,
pub language: LanguageType,
pub topic: String,
pub tags: Vec<String>,
pub scheduled: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AnalysisPackage {
pub id: String,
pub metadata: AnalysisMetaData,
pub code: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AnalysisSummary {
pub id: String,
pub metadata: AnalysisMetaData,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AnalysisSummaryWithSchedulerOrder {
pub id: String,
pub metadata: AnalysisMetaData,
pub order: usize,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AnalysisMetaData {
pub name: String,
pub language: LanguageType,
pub inputs: Vec<InputFile>,
pub outputs: Vec<OutputFile>,
pub topic: String,
pub tags: Vec<String>,
//
#[serde(rename = "createdAt")]
pub created_at: DateTime<Utc>,
#[serde(rename = "createdBy")]
pub created_by: String,
//
#[serde(rename = "lastRunAt")]
pub last_run_at: DateTime<Utc>,
#[serde(rename = "lastRunBy")]
pub last_run_by: String,
//
#[serde(rename = "lastModifiedAt")]
pub last_modified_at: DateTime<Utc>,
#[serde(rename = "lastModifiedBy")]
pub last_modified_by: String,
//
pub scheduled: bool,
#[serde(rename = "lastStatus")]
pub last_status: StageResult,
}
impl AnalysisMetaData {
pub fn new(
name: &String,
language: &LanguageType,
topic: &String,
tags: &Vec<String>,
scheduled: bool,
creator: &String,
) -> AnalysisMetaData {
AnalysisMetaData {
name: name.clone(),
language: language.clone(),
inputs: Vec::new(),
outputs: Vec::new(),
topic: topic.clone(),
tags: tags.clone(),
created_at: chrono::Utc::now(),
created_by: creator.clone(),
last_run_at: chrono::Utc::now(),
last_run_by: "".to_string(),
last_modified_at: chrono::Utc::now(),
last_modified_by: "".to_string(),
scheduled,
last_status: StageResult::NA,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct InputFile {
#[serde(rename = "folderType")]
pub folder_type: FolderType,
#[serde(rename = "analysisId")]
pub analysis_id: String,
#[serde(rename = "fileName")]
pub file_name: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct OutputFile {
#[serde(rename = "fileName")]
pub file_name: String,
pub public: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DataFile {
#[serde(rename = "fileName")]
pub file_name: String,
pub date: String,
pub size: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CheckFileResponse {
pub exists: bool,
pub date: String,
pub size: u64,
pub public: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RealTimeMessage {
#[serde(rename = "msgType")]
pub msg_type: MessageType,
pub stage: Option<Stage>,
#[serde(rename = "stageResult")]
pub stage_result: Option<StageResult>,
pub log: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum MessageType {
Heartbeat,
Waiting,
Stage,
LogOut,
LogErr,
EndSuccess,
EndFailure,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum Stage {
InitializeAnalysis,
ImportInputFiles,
CleanRun,
OutputFiles,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum StageResult {
NA,
Pending,
Success,
Failure,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Topic {
pub id: String,
pub label: String,
}
|
#![warn(
clippy::all,
clippy::nursery,
clippy::pedantic,
missing_copy_implementations,
missing_debug_implementations,
rust_2018_idioms,
unused_qualifications
)]
#![allow(
clippy::doc_markdown,
clippy::enum_glob_use,
clippy::module_name_repetitions,
clippy::must_use_candidate,
clippy::similar_names,
clippy::single_match_else,
clippy::wildcard_imports,
dead_code,
elided_lifetimes_in_paths
)]
#![feature(format_args_capture, box_syntax, once_cell)]
pub mod builtins;
pub mod diagnostic;
pub mod hir;
pub mod scopes;
pub mod ty;
pub(crate) use walrus_syntax as syntax;
|
// error-pattern: mismatched types
enum a { A(int), }
enum b { B(int), }
fn main() { let x: a = A(0); alt x { B(y) { } } }
|
use color_eyre::Report;
use reqwest::Client;
use tracing::info;
use tracing_subscriber::EnvFilter;
pub const URL_1: &str = "https://fasterthanli.me/articles/whats-in-the-box";
pub const URL_2: &str = "https://fasterthanli.me/series/advent-of-code-2020/part-13";
#[tokio::main]
async fn main() -> Result<(), Report> {
setup()?;
let client = Client::new();
let fut1 = fetch_thing(&client, URL_1);
let fut2 = fetch_thing(&client, URL_2);
fut1.await?;
fut2.await?;
Ok(())
}
fn setup() -> Result<(), Report> {
if std::env::var("RUST_LIB_BACKTRACE").is_err() {
std::env::set_var("RUST_LIB_BACKTRACE", "1");
}
color_eyre::install()?;
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::fmt()
.with_env_filter(EnvFilter::from_default_env())
.init();
Ok(())
}
async fn fetch_thing(client: &Client, url: &str) -> Result<(), Report> {
let res = client.get(url).send().await?.error_for_status()?;
let content_type = res.headers().get("content-type");
info!(%url, ?content_type, "Got a response!");
Ok(())
}
|
fn main(){
let a = "hi";
let b = a.to_string();
println!("{}", b);
} |
// Copyright 2021 The MWC Developers
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Test an integrity output creation. Check if we can sing this commit.
//! At mwc-walllet there is a test for validation. It will use printed results form this test
//!
#[macro_use]
extern crate log;
extern crate grin_wallet_controller as wallet;
extern crate grin_wallet_impls as impls;
use grin_wallet_util::grin_core as core;
use grin_wallet_util::grin_core::global;
use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self, LocalWalletClient};
use std::thread;
use std::time::Duration;
use grin_wallet_util::grin_util as util;
use libp2p::PeerId;
#[macro_use]
mod common;
use common::{clean_output_dir, create_wallet_proxy, setup};
use grin_wallet_libwallet::internal::updater;
use grin_wallet_libwallet::{owner, TxLogEntryType};
use grin_wallet_util::grin_core::core::hash::Hash;
use grin_wallet_util::grin_core::core::{KernelFeatures, TxKernel};
use grin_wallet_util::grin_core::libtx::aggsig;
use grin_wallet_util::grin_p2p::libp2p_connection;
use grin_wallet_util::grin_util::secp;
use grin_wallet_util::grin_util::secp::pedersen::Commitment;
use grin_wallet_util::grin_util::secp::Message;
use libp2p::identity::Keypair;
use std::collections::HashMap;
/// self send impl
fn integrity_kernel_impl(test_dir: &'static str) -> Result<(), wallet::Error> {
// Create a new proxy to simulate server and wallet responses
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
let mut wallet_proxy = create_wallet_proxy(test_dir);
let chain = wallet_proxy.chain.clone();
// Create a new wallet test client, and set its queues to communicate with the
// proxy
create_wallet_and_add!(
client1,
wallet1,
mask1_i,
test_dir,
"wallet1",
None,
&mut wallet_proxy,
true
);
let mask1 = (&mask1_i).as_ref();
// Set the wallet proxy listener running
thread::spawn(move || {
global::set_local_chain_type(global::ChainTypes::AutomatedTesting);
if let Err(e) = wallet_proxy.run() {
error!("Wallet Proxy error: {}", e);
}
});
// few values to keep things shorter
let reward = core::consensus::MWC_FIRST_GROUP_REWARD;
// 4 is a lock height for coinbase. We want 2 mining rewards to spend.
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false);
let _ = owner::perform_refresh_from_node(wallet1.clone(), mask1, &None)?;
// Check wallet 1 contents are as expected
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let (_wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?;
debug!(
"Wallet 1 Info Pre-Transaction, after {} blocks: {:?}",
wallet1_info.last_confirmed_height,
wallet1_info // assert_eq!(wallet1_info.total, 1);
);
assert_eq!(wallet1_info.total, 5 * reward);
Ok(())
})?;
// Nothing expected at the beginning
let (account, outputs, _height, integral_balance) =
libwallet::owner_libp2p::get_integral_balance(wallet1.clone(), mask1)?;
assert!(account.is_none());
assert!(outputs.is_empty());
assert!(integral_balance.is_empty());
// Creating the integral balance.
let integral_balance = libwallet::owner_libp2p::create_integral_balance(
wallet1.clone(),
mask1,
1_000_000_000,
&vec![30_000_000],
&Some("default".to_string()),
)?;
assert_eq!(integral_balance.len(), 1);
assert_eq!(integral_balance[0].0.is_some(), true);
assert_eq!(integral_balance[0].0.clone().unwrap().fee, 30_000_000);
assert_eq!(integral_balance[0].1, false);
assert_eq!(
integral_balance[0].0.clone().unwrap().expiration_height,
1445 + 3
);
let (account, outputs, _height, integral_balance) =
libwallet::owner_libp2p::get_integral_balance(wallet1.clone(), mask1)?;
assert!(account.is_some());
assert_eq!(outputs.len(), 1);
assert_eq!(integral_balance.len(), 1);
assert_eq!(integral_balance[0].0.fee, 30_000_000);
assert_eq!(integral_balance[0].1, false);
assert_eq!(integral_balance[0].0.expiration_height, 1445 + 3);
// Retry should do nothing because first transaction is not mined yet
let integral_balance = libwallet::owner_libp2p::create_integral_balance(
wallet1.clone(),
mask1,
1_000_000_000,
&vec![30_000_000, 35_000_000],
&Some("default".to_string()),
)?;
assert_eq!(integral_balance.len(), 2);
assert_eq!(integral_balance[1].0.is_some(), true);
assert_eq!(integral_balance[1].0.clone().unwrap().fee, 30_000_000);
assert_eq!(integral_balance[1].1, false);
assert_eq!(
integral_balance[1].0.clone().unwrap().expiration_height,
1445 + 3
);
assert_eq!(integral_balance[0].0.is_some(), false);
assert_eq!(integral_balance[0].1, false);
// Mine a block, the transaction should be confirmed
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 1, false);
let _ = owner::perform_refresh_from_node(wallet1.clone(), mask1, &None)?;
let (account, outputs, _height, integral_balance) =
libwallet::owner_libp2p::get_integral_balance(wallet1.clone(), mask1)?;
assert!(account.is_some());
assert_eq!(outputs.len(), 1); // Should see available output
assert_eq!(integral_balance.len(), 1);
assert_eq!(integral_balance[0].0.fee, 30_000_000);
assert_eq!(integral_balance[0].1, false); // Now should be confirmed...
assert_eq!(integral_balance[0].0.expiration_height, 1446 + 3);
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false);
let _ = owner::perform_refresh_from_node(wallet1.clone(), mask1, &None)?;
let (account, outputs, _height, integral_balance) =
libwallet::owner_libp2p::get_integral_balance(wallet1.clone(), mask1)?;
assert!(account.is_some());
assert_eq!(outputs.len(), 1); // Should see available output
assert_eq!(integral_balance.len(), 1);
assert_eq!(integral_balance[0].0.fee, 30_000_000);
assert_eq!(integral_balance[0].1, true); // Now should be confirmed...
// Now create second one should succeed
let integral_balance = libwallet::owner_libp2p::create_integral_balance(
wallet1.clone(),
mask1,
1_000_000_000,
&vec![30_000_000, 35_000_000],
&Some("default".to_string()),
)?;
assert_eq!(integral_balance.len(), 2);
assert_eq!(integral_balance[1].0.clone().unwrap().fee, 30_000_000);
assert_eq!(integral_balance[1].1, true);
assert_eq!(
integral_balance[1].0.clone().unwrap().expiration_height,
1446 + 3
);
assert_eq!(integral_balance[0].0.clone().unwrap().fee, 35_000_000);
assert_eq!(integral_balance[0].1, false);
assert_eq!(
integral_balance[0].0.clone().unwrap().expiration_height,
1449 + 3
);
// Mine a block, the second transaction should be confirmed
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
let _ = owner::perform_refresh_from_node(wallet1.clone(), mask1, &None)?;
let (account, outputs, _height, integral_balance) =
libwallet::owner_libp2p::get_integral_balance(wallet1.clone(), mask1)?;
assert!(account.is_some());
assert_eq!(outputs.len(), 1);
assert_eq!(integral_balance.len(), 2);
assert_eq!(integral_balance[0].0.fee, 30_000_000);
assert_eq!(integral_balance[0].1, true);
assert_eq!(integral_balance[0].0.expiration_height, 1446 + 3);
assert_eq!(integral_balance[1].0.fee, 35_000_000);
assert_eq!(integral_balance[1].1, true);
assert_eq!(integral_balance[1].0.expiration_height, 1450 + 3); // +1 because post in test environment mining another block.
// Let's verify if Integrity context match the Tx Kernels.
let txs = {
wallet_inst!(wallet1, w);
let mut txs = updater::retrieve_txs(&mut **w, mask1, None, None, None, false, None, None)?;
txs.retain(|t| t.tx_type == TxLogEntryType::TxSent);
txs
};
assert_eq!(txs.len(), 2);
assert!(txs[0].kernel_excess.is_some());
assert!(txs[1].kernel_excess.is_some());
assert_eq!(txs[0].fee, Some(30_000_000));
assert_eq!(txs[1].fee, Some(35_000_000));
let kernel1 = txs[0].kernel_excess.unwrap();
let kernel2 = txs[1].kernel_excess.unwrap();
let integrity_context1 = integral_balance[0].0.clone();
let integrity_context2 = integral_balance[1].0.clone();
// Let's check if excess values matching integrity_contexts
let secp = secp::Secp256k1::new();
// Let's check if all signaatures are unique. It is expected
let mut signatures: Vec<secp::Signature> = Vec::new();
let peer_keys = Keypair::generate_ed25519();
let peer_id = PeerId::from_public_key(peer_keys.public());
let peer_pk = peer_id.as_dalek_pubkey().unwrap();
let peer_id_message =
Message::from_slice(Hash::from_vec(peer_pk.as_bytes()).as_bytes()).unwrap();
// Let't verify the we can generate multiple valid signatures for the commits
for _i in 0..20 {
let (excess1, signature1) = integrity_context1.calc_kernel_excess(&secp, &peer_pk)?;
assert_eq!(excess1, kernel1);
let pk1 = excess1.to_pubkey().unwrap();
// Validating the message
assert_eq!(signatures.contains(&signature1), false);
signatures.push(signature1.clone());
aggsig::verify_completed_sig(&secp, &signature1, &pk1, Some(&pk1), &peer_id_message)
.expect("Signature1 validation is failed");
let (excess2, signature2) = integrity_context2.calc_kernel_excess(&secp, &peer_pk)?;
assert_eq!(excess2, kernel2);
let pk2 = excess2.to_pubkey().unwrap();
// Validating the message
assert_eq!(signatures.contains(&signature2), false);
signatures.push(signature2.clone());
aggsig::verify_completed_sig(&secp, &signature2, &pk2, Some(&pk2), &peer_id_message)
.expect("Signature2 validation is failed");
}
// Testing for libp2p routine
println!("peer_id data: {}", util::to_hex(&peer_id.to_bytes()));
let (kernel_excess, signature) = integrity_context1.calc_kernel_excess(&secp, &peer_pk)?;
let message: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
println!("kernel_excess: {}", util::to_hex(&kernel_excess.0));
println!(
"signature: {}",
util::to_hex(&signature.serialize_compact())
);
// Build message for p2p network
let libp2p_message =
libp2p_connection::build_integrity_message(&kernel_excess, &peer_pk, &signature, &message)
.unwrap();
let output_validation_fn = |_kernel: &Commitment| {
Ok(Some(TxKernel::with_features(KernelFeatures::Plain {
fee: 100_000_000,
})))
};
let output_validation_fn = std::sync::Arc::new(output_validation_fn);
let validate_ok = libp2p_connection::validate_integrity_message(
&peer_id,
&libp2p_message,
output_validation_fn.clone(),
&mut HashMap::new(),
1_000_000,
);
// PeerId can be anyting. because of forward it can change
let validate_ok2 = libp2p_connection::validate_integrity_message(
&PeerId::random(),
&libp2p_message,
output_validation_fn.clone(),
&mut HashMap::new(),
1_000_000,
);
assert!(validate_ok.is_ok());
assert_eq!(validate_ok.unwrap().0, 100_000_000);
assert!(validate_ok2.is_ok());
assert_eq!(validate_ok2.unwrap().0, 100_000_000);
// add some accounts to check if lowest indexes will be used.
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let acc_id1 = api.create_account_path(m, "second")?;
let acc_id2 = api.create_account_path(m, "third")?;
assert_eq!(acc_id1.to_bip_32_string(), "m/1/0");
assert_eq!(acc_id2.to_bip_32_string(), "m/2/0");
Ok(())
})?;
// let logging finish
thread::sleep(Duration::from_millis(200));
Ok(())
}
#[test]
fn wallet_integrity_kernel() {
let test_dir = "test_output/integrity_kernel";
setup(test_dir);
if let Err(e) = integrity_kernel_impl(test_dir) {
panic!("Libwallet Error: {} - {}", e, e.backtrace().unwrap());
}
clean_output_dir(test_dir);
}
|
use crate::config::ApiList;
use crate::equity::Equity;
use serde_json::Value;
use std::collections::HashMap;
use std::error;
use std::io;
// Stores a HashMap of all the platforms and their JSON API pairings.
// Fetcher is the object to interact with external API interfaces.
#[derive(Debug)]
pub struct Fetcher {
// Designates the current platform. eg. Alpha Vantage, IEX Cloud, Yahoo Finance
pub current: String,
// Stores a HashMap of all the platforms and their JSON API pairings.
pub platforms: HashMap<String, HashMap<String, String>>,
// Stores a list of all API's and their URL
pub apilist: ApiList,
// Stores a HashMap pairing of all global quotes from AlphaVantage for parsing
pub global_quote: Vec<(String, String)>,
// Private key for accessing external API
api_key: String,
}
impl Fetcher {
pub fn new(provider: String, api_key: String) -> Self {
let global_quote: Vec<(String, String)> = vec![
("01. symbol".to_string(), "ticker".to_string()),
("02. open".to_string(), "open".to_string()),
("03. high".to_string(), "high".to_string()),
("04. low".to_string(), "low".to_string()),
("05. price".to_string(), "price".to_string()),
("06. volume".to_string(), "volume".to_string()),
("07. latest trading day".to_string(), "ltd".to_string()),
(
"08. previous close".to_string(),
"previous close".to_string(),
),
("09. change".to_string(), "change".to_string()),
(
"10. change percent".to_string(),
"change percent".to_string(),
),
];
let overview_title: Vec<(String, String)> = vec![
("Description".to_string(), "description".to_string()),
("Country".to_string(), "country".to_string()),
("Sector".to_string(), "sector".to_string()),
("Industry".to_string(), "industry".to_string()),
("EBITDA".to_string(), "ebitda".to_string()),
("EPS".to_string(), "eps".to_string()),
("MarketCapitalization".to_string(), "market_cap".to_string()),
("BookValue".to_string(), "book_value".to_string()),
];
let mut endpoints: HashMap<String, String> = HashMap::new();
endpoints.insert("quote".to_string(), "GLOBAL_QUOTE&".to_string());
let mut plats: HashMap<String, HashMap<String, String>> = HashMap::new();
plats.insert("alpha_vantage".to_string(), endpoints);
Fetcher {
current: provider,
platforms: plats,
apilist: ApiList::new(),
global_quote,
api_key,
}
}
pub async fn fetch_equity(ticker: String) -> Result<(), Error> {
let url = format!("https://alphavantage.co/query?function={}", 5);
let res = reqwest::get(url).await?;
println!("Status:{}", res.status());
let body = res.text().await?;
let data = &body[..];
let v: Value = serde_json::from_str(data)?;
println!("Body:\n\n{}", body);
Ok(())
}
pub async fn fetch_equity_price(&self, equity: &Equity) -> Result<(), Error> {
let url = format!(
"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={}&apikey={}",
&equity.ticker, &self.api_key
);
let resp = reqwest::get(url).await?.json::<serde_json::Value>().await?;
println!("{:?}", resp);
Ok(())
}
pub async fn search_equity(&self, ticker: String) -> Result<(), Error> {
let url = format!(
"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={}&apikey={}",
ticker, &self.api_key
);
let resp = reqwest::get(url).await?.json::<serde_json::Value>().await?;
let quotes = resp.get("Global Quote").unwrap();
for x in &self.global_quote {
let value = quotes.get(&x.0).unwrap();
let title = &x.1;
println!("{}: {}", title, value);
}
println!("");
Ok(())
}
pub async fn equity_overview(&self, ticker: String) -> Result<(), Error> {
let url = format!(
"https://www.alphavantage.co/query?function=OVERVIEW&symbol={}&apikey={}",
ticker, &self.api_key
);
let resp = reqwest::get(url).await?.json::<serde_json::Value>().await?;
// println!("{:?}", resp);
let desc = resp.get("Description").unwrap();
println!("{}", desc);
Ok(())
}
// Searches an equity by ticker and outputs a list of global quote information
// Example:
// Ticker: IBM
// Open: 150.4300
// High: 151.8450
// Low: 150.3700
// Price: 150.2800
// Volume: 3421395
// Latest Trading Day: 2021-06-11
// Previous Close: 150.5400
// Change: 0.700
// Change Percent: 0.4916%
pub async fn search_equity_demo(&self, ticker: String) -> Result<(), Error> {
let url = format!(
"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM&apikey=demo",
);
let resp = reqwest::get(url).await?.json::<serde_json::Value>().await?;
let quotes = resp.get("Global Quote").unwrap();
for x in &self.global_quote {
let value = quotes.get(&x.0).unwrap();
let title = &x.1;
println!("{}: {}", title, value);
}
println!("");
Ok(())
}
}
// Derives custom errors using thiserror crate
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
CrosstermError(#[from] crossterm::ErrorKind),
#[error(transparent)]
IoError(#[from] io::Error),
#[error(transparent)]
ReqwestError(#[from] reqwest::Error),
#[error(transparent)]
SerdeError(#[from] serde_json::Error),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fetch_price() {}
}
|
trait LiveBeing
{
fn create(name: &'static str) -> Self;
fn name(&self) -> &'static str;
fn talk(&self)
{
println!("{} can not talk", self.name())
}
}
#[derive(Debug)]
struct Cat
{
name: &'static str,
}
impl LiveBeing for Cat {
fn create(name: &'static str) -> Cat
{
Cat{name: name}
}
fn name(&self) -> &'static str {
self.name
}
}
#[derive(Debug)]
struct Human
{
name: &'static str,
}
impl LiveBeing for Human {
fn create(name: &'static str) -> Human
{
Human{name: name}
}
fn name(&self) -> &'static str {
self.name
}
fn talk(&self) {
println!("{} says hello!", self.name)
}
}
// Extend built-in with a trait.
trait Summary<T>
{
fn sum(&self) -> T;
}
impl Summary<i32> for Vec<i32>
{
fn sum(&self) -> i32
{
let mut res = 0;
for x in self
{
res += x
}
res
}
}
fn main() {
let person = Human{ name: "Jose" };
let cat = Cat{ name: "Boris" };
let another_cat = Cat::create("John");
let another_human: Human = LiveBeing::create("John");
println!("{:#?}", person);
println!("{:#?}", cat);
println!("{:#?}", another_cat);
println!("{:#?}", another_human);
person.talk();
cat.talk();
let v = vec![1,2,3];
println!("sum of elements in vector {:?} is {}", v, v.sum());
}
|
use deadpool_postgres::Client;
pub async fn db_query<F>(client: &Client, mut read: F)
where
F: FnMut(&str),
{
// http://blog.cleverelephant.ca/2019/03/geojson.html
let stmt = client
.prepare(
&"SELECT rowjsonb_to_geojson(to_jsonb(ne.admin_0_countries.*), 'wkb_geometry') \
FROM ne.admin_0_countries",
)
.await
.unwrap();
for row in client.query(&stmt, &[]).await.unwrap() {
read(row.get::<_, &str>(0));
}
// Using RowStream
// use futures::{StreamExt, TryStreamExt};
// use std::io;
// let fut = client.query_raw(&stmt, &[]);
// let mut items = vec![];
// Box::pin(async move {
// let mut stream = fut
// .await
// .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e))).unwrap();
// while let Some(row) = stream.next().await {
// let row = row.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{:?}", e))).unwrap();
// items.push(row.get::<_, i32>(0));
// }
// });
}
|
use futures::executor::block_on;
use rocket_contrib::json::Json;
use rocket::{Route, State};
use crate::libs::database_client::DatabaseClient;
use crate::libs::models::Podcast;
use crate::libs::repositories::{insert_podcast, podcast_list, find_podcast_by_id};
use crate::libs::guards::AuthorizationGuard;
#[get("/podcasts")]
pub fn podcasts_list(database_client: State<DatabaseClient>) -> Json<Vec<Podcast>> {
let podcast_list = block_on(podcast_list(&database_client)).expect("Fail to get the list of podcast from the database");
Json(podcast_list)
}
#[get("/podcasts/<id>")]
pub fn get_podcast(database_client: State<DatabaseClient>, id: String) -> Json<Podcast> {
let podcast = block_on(find_podcast_by_id(&database_client, &id)).expect("Fail to find the podcast by id");
Json(podcast)
}
#[post("/podcasts", format = "json", data = "<new_podcast>")]
pub fn create_podcast(_guard: AuthorizationGuard, database_client: State<DatabaseClient>, new_podcast: Json<Podcast>) -> Json<Podcast> {
let podcast = new_podcast.into_inner();
let new_podcast = block_on(insert_podcast(&database_client, &podcast)).expect("Fail to find the podcast by id");
Json(new_podcast)
}
pub fn initialize_routes() -> Vec<Route> {
routes![podcasts_list, create_podcast, get_podcast]
}
|
extern crate rustc_serialize;
extern crate csv;
extern crate clap;
use clap::App;
use clap::Arg;
use csv::Writer;
use rustc_serialize::json::Json;
use std::fs::File;
use std::cmp::Ordering::*;
mod colony;
use colony::Colony;
type ColonySet = std::collections::HashMap<u32, Colony>;
fn main() {
let matches = App::new("colony_merge")
.author("Sam Crow")
.version("0.1.0")
.about("Converts colony data from JSON into CSV")
.arg(Arg::with_name("input").help("An input JSON file to read").short("i").long("input").takes_value(true).required(true).min_values(1))
.arg(Arg::with_name("output").short("o").long("output").takes_value(true).help("An output CSV file to write").required(true))
.get_matches();
let json_paths = matches.values_of("input").unwrap();
let csv_path = matches.value_of("output").unwrap();
// Read and merge
let mut colonies = ColonySet::new();
for path in json_paths {
match read_from_json(path) {
Ok(json_colonies) => {
colonies = merge_sets(colonies, json_colonies);
},
Err(message) => println!("Could not read colonies from {}: {}", path, message),
}
}
match write_to_csv(csv_path, colonies) {
Ok(()) => {},
Err(message) => println!("Could not write colonies: {}", message),
}
}
fn read_from_json<P>(path: P) -> Result<ColonySet, String> where P : AsRef<std::path::Path> {
match File::open(path) {
Ok(mut file) => {
match Json::from_reader(&mut file) {
Ok(json) => {
match json {
Json::Object(json_obj) => {
match json_obj.get("colonies") {
Some(colonies) => {
match *colonies {
Json::Array(ref colonies_array) => {
let mut map = ColonySet::new();
for ref colony_item in colonies_array {
let colony_result = Colony::from_json((*colony_item).clone());
match colony_result {
Ok(colony) => {
map.insert(colony.id, colony);
},
Err(message) => println!("Failed to read colony: {}", message),
}
}
Ok(map)
},
_ => Err("Colonies item not an array".to_string()),
}
},
_ => Err("No colonies item".to_string()),
}
},
_ => Err("JSON root is not an object".to_string()),
}
}
Err(_) => Err("Could not parse JSON".to_string()),
}
},
Err(_) => Err("Could not open file".to_string()),
}
}
fn write_to_csv<P>(path: P, colonies: ColonySet) -> Result<(), String> where P : AsRef<std::path::Path> {
match File::create(path) {
Ok(file) => {
let mut writer = Writer::from_writer(file);
for (_, colony) in colonies {
let active_str = match colony.visited {
false => "",
true => match colony.active {
true => "A",
false => "NA",
}
};
let _ = writer.encode((colony.id, colony.x, colony.y, active_str));
}
Ok(())
},
Err(_) => Err("Could not open file".to_string()),
}
}
fn merge_sets(set1: ColonySet, set2: ColonySet) -> ColonySet {
// Procedure:
// Copy all colonies from set1 to out
// For each colony in set2, add to out
// If a colony also exists in out, choose one and replace it
let mut out = set1.clone();
for (_, colony2) in set2 {
if out.contains_key(&colony2.id) {
let colony1 = *out.get(&colony2.id).unwrap();
let chosen = choose_colony(colony1, colony2);
out.insert(chosen.id, chosen);
}
else {
out.insert(colony2.id, colony2);
}
}
out
}
fn choose_colony(c1: Colony, c2: Colony) -> Colony {
assert!(c1.id == c2.id);
// Choose the more recently updated colony
match c1.updated.cmp(&c2.updated) {
Less => c2,
Greater => c1,
Equal => {
// If one is active, choose it
match (c1.active, c2.active) {
(true, false) => c1,
(false, true) => c2,
_ => {
// Choose one arbitrarily
c1
}
}
}
}
}
|
mod audio_loading;
mod info;
mod websocket;
mod utils;
use actix_web::web;
pub(super) fn config(cfg: &mut web::ServiceConfig) {
audio_loading::scoped_config(cfg);
info::scoped_config(cfg);
websocket::scoped_config(cfg);
}
|
//! Utility items
use regex::Regex;
use rocket::http::Status;
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
use rocket_contrib::json::Json;
use serde::Serialize;
use std::fmt;
/// Rgex pattern for converting special characters to spaces
const TO_SPACE_REGEX: &str = r"(\.|-| )+";
/// A template to respond to requests with, includes status code and message,
/// along with an optional `body` key that may contain anything (but should
/// ideally be as standard as possible)
#[derive(Debug, Serialize)]
pub struct ResponseModel<T: Serialize> {
pub status: u16,
pub msg: String,
pub body: Option<T>,
}
impl<T: Serialize> ResponseModel<T> {
/// Creates a new [ResponseModel] with all values filled out
pub fn new(status: u16, msg: impl fmt::Display, body: T) -> Self {
Self {
status,
msg: format!("{}", msg),
body: Some(body),
}
}
/// Creates a basic response without the `body` field
pub fn basic(status: u16, msg: impl fmt::Display) -> Self {
Self {
status,
msg: format!("{}", msg),
body: None,
}
}
}
impl<'r, T: Serialize> Responder<'r> for ResponseModel<T> {
fn respond_to(self, req: &Request) -> response::Result<'r> {
Response::build_from(Json(&self).respond_to(req)?)
.status(Status::from_code(self.status).unwrap())
.ok()
}
}
/// Attempts to capture `filename` used and `ext` used from a given `file_path`
/// by splitting
pub fn cap_filename_ext(file_path: impl AsRef<str>) -> (String, Option<String>) {
let split: Vec<&str> = file_path.as_ref().split('.').collect();
(
split[..split.len() - 1].join(".").to_string(),
if split.len() > 1 {
Some(format!(".{}", split.last().unwrap()))
} else {
None
},
)
}
/// Formats name by elimintating non alphanumeric characters with the use of
/// regex and replacing characters with spaces
pub fn format_name(name: impl AsRef<str>) -> String {
Regex::new(TO_SPACE_REGEX)
.unwrap()
.replace_all(name.as_ref(), " ")
.as_ref().trim().to_string()
}
|
/*
* 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
*/
/// UsageCustomReportsPage : The object containing page total count.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageCustomReportsPage {
/// Total page count.
#[serde(rename = "total_count", skip_serializing_if = "Option::is_none")]
pub total_count: Option<i64>,
}
impl UsageCustomReportsPage {
/// The object containing page total count.
pub fn new() -> UsageCustomReportsPage {
UsageCustomReportsPage {
total_count: None,
}
}
}
|
use super::physics_collider::PhysicsCollider;
use ptgui::prelude::*;
pub trait PhysicsBody: PhysicsCollider {
fn try_fall<T>(&mut self, others: &[T])
where
T: PhysicsCollider;
fn try_move<T>(&mut self, deltas: Point, others: &[T])
where
T: PhysicsCollider;
fn move_pos(&mut self, deltas: Point);
fn set_pos(&mut self, position: Point);
}
|
fn make_bins(limits: &Vec<usize>, data: &Vec<usize>) -> Vec<Vec<usize>> {
let mut bins: Vec<Vec<usize>> = Vec::with_capacity(limits.len() + 1);
for _ in 0..=limits.len() {bins.push(Vec::new());}
limits.iter().enumerate().for_each(|(idx, limit)| {
data.iter().for_each(|elem| {
if idx == 0 && elem < limit { bins[0].push(*elem); } // smaller than the smallest limit
else if idx == limits.len()-1 && elem >= limit { bins[limits.len()].push(*elem); } // larger than the largest limit
else if elem < limit && elem >= &limits[idx-1] { bins[idx].push(*elem); } // otherwise
});
});
bins
}
fn print_bins(limits: &Vec<usize>, bins: &Vec<Vec<usize>>) {
for (idx, bin) in bins.iter().enumerate() {
if idx == 0 {
println!(" < {:3} := {:3}", limits[idx], bin.len());
} else if idx == limits.len() {
println!(">= {:3} := {:3}", limits[idx-1], bin.len());
}else {
println!(">= {:3} .. < {:3} := {:3}", limits[idx-1], limits[idx], bin.len());
}
};
}
fn main() {
let limits1 = vec![23, 37, 43, 53, 67, 83];
let data1 = vec![95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55];
let limits2 = vec![14, 18, 249, 312, 389, 392, 513, 591, 634, 720];
let data2 = vec![
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749
];
// Why are we calling it RC anyways???
println!("RC FIRST EXAMPLE");
let bins1 = make_bins(&limits1, &data1);
print_bins(&limits1, &bins1);
println!("\nRC SECOND EXAMPLE");
let bins2 = make_bins(&limits2, &data2);
print_bins(&limits2, &bins2);
} |
#[doc = "Register `RF%sR` reader"]
pub type R = crate::R<RFR_SPEC>;
#[doc = "Register `RF%sR` writer"]
pub type W = crate::W<RFR_SPEC>;
#[doc = "Field `FMP` reader - FMP0"]
pub type FMP_R = crate::FieldReader;
#[doc = "Field `FULL` reader - FULL0"]
pub type FULL_R = crate::BitReader;
#[doc = "Field `FULL` writer - FULL0"]
pub type FULL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FOVR` reader - FOVR0"]
pub type FOVR_R = crate::BitReader;
#[doc = "Field `FOVR` writer - FOVR0"]
pub type FOVR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RFOM` reader - RFOM0"]
pub type RFOM_R = crate::BitReader;
#[doc = "Field `RFOM` writer - RFOM0"]
pub type RFOM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bits 0:1 - FMP0"]
#[inline(always)]
pub fn fmp(&self) -> FMP_R {
FMP_R::new((self.bits & 3) as u8)
}
#[doc = "Bit 3 - FULL0"]
#[inline(always)]
pub fn full(&self) -> FULL_R {
FULL_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - FOVR0"]
#[inline(always)]
pub fn fovr(&self) -> FOVR_R {
FOVR_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - RFOM0"]
#[inline(always)]
pub fn rfom(&self) -> RFOM_R {
RFOM_R::new(((self.bits >> 5) & 1) != 0)
}
}
impl W {
#[doc = "Bit 3 - FULL0"]
#[inline(always)]
#[must_use]
pub fn full(&mut self) -> FULL_W<RFR_SPEC, 3> {
FULL_W::new(self)
}
#[doc = "Bit 4 - FOVR0"]
#[inline(always)]
#[must_use]
pub fn fovr(&mut self) -> FOVR_W<RFR_SPEC, 4> {
FOVR_W::new(self)
}
#[doc = "Bit 5 - RFOM0"]
#[inline(always)]
#[must_use]
pub fn rfom(&mut self) -> RFOM_W<RFR_SPEC, 5> {
RFOM_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 = "receive FIFO %s register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rfr::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 [`rfr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RFR_SPEC;
impl crate::RegisterSpec for RFR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rfr::R`](R) reader structure"]
impl crate::Readable for RFR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rfr::W`](W) writer structure"]
impl crate::Writable for RFR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RF%sR to value 0"]
impl crate::Resettable for RFR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use quix::node::{NodeConfig, NodeController, Connect};
use actix::{SystemService, Message, Actor, Handler, Running};
use std::time::Duration;
use quix::{Process};
use std::thread::JoinHandle;
use quix::global::{Global, Set};
use quix::util::RpcMethod;
use bytes::{Buf, BufMut};
use quix::process::DispatchError;
use quix::proto::*;
use quix::memkv::{MemKv, GlobalFind};
#[derive(prost::Message)]
pub struct M {
#[prost(int32, tag = "1")]
v: i32
}
impl Message for M {
type Result = i32;
}
impl RpcMethod for M {
const NAME: &'static str = "M";
const ID: u32 = 42;
fn read(_b: impl Buf) -> Result<Self, DispatchError> {
unimplemented!()
}
fn write(&self, _b: &mut impl BufMut) -> Result<(), DispatchError> {
unimplemented!()
}
fn read_result(_b: impl Buf) -> Self::Result {
unimplemented!()
}
fn write_result(_r: &Self::Result, _b: &mut impl BufMut) -> Result<(), DispatchError> {
unimplemented!()
}
}
#[derive(quix::DynHandler)]
#[dispatch(M)]
pub struct Act {}
impl Actor for Act {
type Context = Process<Self>;
fn stopping(&mut self, _: &mut Self::Context) -> Running {
log::warn!("Stopping actor");
Running::Stop
}
}
impl Handler<M> for Act {
type Result = i32;
fn handle(&mut self, _msg: M, _ctx: &mut Process<Self>) -> Self::Result {
unimplemented!()
}
}
fn make_node(i: i32) -> JoinHandle<()> {
std::thread::spawn(move || {
actix::run(async move {
//MemKv::from_registry().send(GlobalFind { key: vec![]}).await;
tokio::time::delay_for(Duration::from_millis((i * 100) as u64)).await;
let config = NodeConfig {
listen: format!("127.0.0.1:900{}", i).parse().unwrap(),
..Default::default()
};
Global::<NodeConfig>::from_registry().send(Set(config)).await.unwrap();
if i > 0 {
let _ = NodeController::from_registry().send(Connect {
addr: format!("127.0.0.1:900{}", i - 1).parse().unwrap()
}).await.unwrap();
}
let _ = Process::start(Act {});
// m2 should be deleted after the end of the block
{
let _ = Process::start(Act {});
tokio::time::delay_for(Duration::from_secs(1)).await;
}
tokio::time::delay_for(Duration::from_secs(10)).await;
}).unwrap();
})
}
#[test]
fn test_e2e() {
std::env::set_var("RUST_LOG", "info");
env_logger::init();
let n0 = make_node(0);
let n1 = make_node(1);
let n2 = make_node(2);
n0.join().unwrap();
n1.join().unwrap();
n2.join().unwrap();
} |
use azure_core::headers::CommonStorageResponseHeaders;
use bytes::Bytes;
use http::Response;
use serde::de::DeserializeOwned;
use std::convert::{TryFrom, TryInto};
#[derive(Debug, Clone)]
pub struct GetEntityResponse<E>
where
E: DeserializeOwned,
{
pub common_storage_response_headers: CommonStorageResponseHeaders,
pub metadata: String,
pub entity: E,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
struct GetEntityResponseInternal<E> {
#[serde(rename = "odata.metadata")]
pub metadata: String,
#[serde(flatten)]
pub value: E,
}
impl<E> TryFrom<&Response<Bytes>> for GetEntityResponse<E>
where
E: DeserializeOwned,
{
type Error = crate::Error;
fn try_from(response: &Response<Bytes>) -> Result<Self, Self::Error> {
debug!("{}", std::str::from_utf8(response.body())?);
debug!("headers == {:#?}", response.headers());
let get_entity_response_internal: GetEntityResponseInternal<E> =
serde_json::from_slice(response.body())?;
Ok(GetEntityResponse {
common_storage_response_headers: response.headers().try_into()?,
metadata: get_entity_response_internal.metadata,
entity: get_entity_response_internal.value,
})
}
}
|
use std::collections::HashMap;
use std::io::BufRead;
fn parse_guard(line: &String, start: usize) -> i32 {
let start = start + 1;
let mut end = start;
for (i, c) in line[start + 1..].chars().enumerate() {
if !c.is_digit(10) {
end = start + i + 1;
break;
}
}
line[start..end]
.to_string()
.parse::<i32>()
.expect("problem parsing guard number")
}
fn parse_minute(line: &String) -> i32 {
let left_bracket = line.find("]").unwrap();
line[left_bracket - 2..left_bracket]
.to_string()
.parse::<i32>()
.expect("problem parsing minute")
}
fn sort_bufread<I>(buf: I) -> Vec<String>
where
I: BufRead,
{
let mut lines_vec = Vec::new();
for line in buf.lines() {
lines_vec.push(line.unwrap());
}
lines_vec.sort_unstable();
lines_vec
}
fn extract_guard_sleep<'a>(
sorted_lines: &'a Vec<String>,
) -> impl Iterator<Item = (i32, Vec<i32>)> + 'a {
let mut cur_guard: i32 = -1; // XXX: this -1 business is nonsense
let mut slept_from: i32 = -1; // XXX
sorted_lines.iter().filter_map(move |line| {
if let Some(id_start) = line.find("#") {
cur_guard = parse_guard(line, id_start);
None
} else if let Some(_) = line.find("falls asleep") {
slept_from = parse_minute(line);
None
} else if let Some(_) = line.find("wakes up") {
let awoke = parse_minute(line);
let mut sleep_mins = Vec::<i32>::new();
for i in slept_from..awoke {
sleep_mins.push(i);
}
Some((cur_guard, sleep_mins))
} else {
panic!("we're screwed");
}
})
}
pub fn four_a<I>(buf: I) -> i32
where
I: BufRead,
{
let lines_vec = sort_bufread(buf);
let sleep_counts = extract_guard_sleep(&lines_vec);
let mut agg_counts = HashMap::<i32, Vec<i32>>::new();
for (guard, minutes) in sleep_counts {
let sleep_mins = agg_counts.entry(guard).or_insert(Vec::<i32>::new());
sleep_mins.append(&mut minutes.clone());
}
let mut sorted_guards: Vec<_> = agg_counts.iter().collect();
sorted_guards.sort_by(|a, b| b.1.len().cmp(&a.1.len()));
let minutes = sorted_guards[0].1.to_owned();
let mut minute_counts = HashMap::new();
for m in minutes.iter() {
*minute_counts.entry(m).or_insert(0) += 1;
}
let mut sorted_minutes: Vec<_> = minute_counts.iter().collect();
sorted_minutes.sort_by(|a, b| b.1.cmp(a.1));
sorted_guards[0].0 * **sorted_minutes[0].0
}
pub fn four_b<I>(buf: I) -> i32
where
I: BufRead,
{
let lines_vec = sort_bufread(buf);
let guards_to_minutes = extract_guard_sleep(&lines_vec);
let mut agg_counts = HashMap::new();
for (guard, minutes) in guards_to_minutes {
let guard_table = agg_counts
.entry(guard.clone())
.or_insert(HashMap::<i32, i32>::new());
for m in minutes.iter() {
*guard_table.entry(m.clone()).or_insert(0) += 1;
}
}
let mut top_minute = (-1, -1, -1); // count, minute, guard;
for (guard, guard_table) in agg_counts {
let mut sorted_minutes: Vec<_> = guard_table.iter().collect();
sorted_minutes.sort_by(|a, b| b.1.cmp(a.1));
if sorted_minutes[0].1 > &top_minute.0 {
top_minute = (*sorted_minutes[0].1, *sorted_minutes[0].0, guard);
}
}
top_minute.1 * top_minute.2
}
#[cfg(test)]
mod tests {
use super::*;
static INPUT: &[u8; 569] = b"[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up";
#[test]
fn test_four_a() {
assert_eq!(240, four_a(&INPUT[..]));
}
#[test]
fn test_four_b() {
assert_eq!(4455, four_b(&INPUT[..]));
}
}
|
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unused, clippy::no_effect, clippy::unnecessary_operation)]
#![warn(clippy::mut_mut)]
fn fun(x: &mut &mut u32) -> bool {
**x > 0
}
fn less_fun(x: *mut *mut u32) {
let y = x;
}
macro_rules! mut_ptr {
($p:expr) => {
&mut $p
};
}
#[allow(unused_mut, unused_variables)]
fn main() {
let mut x = &mut &mut 1u32;
{
let mut y = &mut x;
}
if fun(x) {
let y: &mut &mut u32 = &mut &mut 2;
**y + **x;
}
if fun(x) {
let y: &mut &mut &mut u32 = &mut &mut &mut 2;
***y + **x;
}
let mut z = mut_ptr!(&mut 3u32);
}
fn issue939() {
let array = [5, 6, 7, 8, 9];
let mut args = array.iter().skip(2);
for &arg in &mut args {
println!("{}", arg);
}
let args = &mut args;
for arg in args {
println!(":{}", arg);
}
}
|
use cpu::Cpu;
pub struct TermGfx { }
impl TermGfx {
pub fn new() -> TermGfx {
TermGfx { }
}
pub fn composite(&self, buffer: Vec<u8>) {
for row in buffer.chunks(64) {
println!("{}", "");
for byte in row.iter() {
match *byte {
0x0 => { print!("{}", " ") },
_ => { print!("{}", "X") }
}
}
}
print!("{}[2J", 27 as char);
}
}
|
mod parser;
mod generator;
pub use parser::SpecFieldType as FieldType;
pub use generator::Generator as SerdeBuilder;
|
mod sprite;
mod player;
mod directions;
use tetra::graphics::{self, Color, DrawParams, Texture};
use tetra::{Context, ContextBuilder, State, input};
use tetra::input::Key;
use tetra::math::Vec2;
use crate::sprite::SpriteSheet;
use crate::player::Player;
use crate::directions::{MoveDirection, TrunDirection};
struct GameState {
player: Player,
}
impl GameState {
fn new(ctx: &mut Context) -> tetra::Result<GameState> {
let (width, height) = (1280.0, 720.0);
Ok(GameState {
player: Player::new(SpriteSheet::new(Vec2::new(64, 64), Texture::new(ctx, "./assets/textures/Player.png")?), Vec2::new(width / 2.0, height / 1.3), 200.0, 6.0, 4.0)
})
}
}
impl State for GameState {
fn update(&mut self, ctx: &mut Context) -> tetra::Result {
if input::is_key_down(ctx, Key::P) { println!("{}", self.player) }
if input::is_key_down(ctx, Key::W) {
self.player.movement = MoveDirection::Forward
}
if input::is_key_down(ctx, Key::S) ||(input::is_key_up(ctx, Key::W) && input::is_key_up(ctx, Key::D)) {
self.player.movement = MoveDirection::Break
}
if self.player.speed > 0.0{
if input::is_key_up(ctx, Key::A) && input::is_key_up(ctx, Key::D){
self.player.turn = TrunDirection::None
}
if input::is_key_down(ctx, Key::A) {
self.player.turn = TrunDirection::Left
}
if input::is_key_down(ctx, Key::D) {
self.player.turn = TrunDirection::Right
}
}
self.player.update_player();
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> tetra::Result {
// Cornflower blue, as is tradition
graphics::clear(ctx, Color::rgb(0.392, 0.584, 0.929));
render_player(&self.player, ctx);
Ok(())
}
}
fn render_player(player: &Player, ctx: &mut Context) {
player.sprite_sheet.texture.draw_region(
ctx,
player.sprite_sheet.frames[player.get_player_frame()],
DrawParams::new().position(player.position).scale(Vec2::new(3.0, 3.0)).origin(Vec2::new(32.0, 32.0)),
);
}
fn main() -> tetra::Result {
ContextBuilder::new("Hello, world!", 1280, 720)
.quit_on_escape(true)
.build()?
.run(GameState::new)
} |
use std::process;
use what_time::*;
fn main() {
// get command line args:
let CmdLineArgs {
config_path_or_url,
name,
} = get_cmd_line_args();
// read and parse config file:
let config = get_config(&config_path_or_url).unwrap_or_else(|err| {
println!("{}: {:?}", err, err);
process::exit(1);
});
let zones = parse_config(&config);
// convert current time to friend's timezone, and print:
let local_time = get_local_time(&name, zones).unwrap_or_else(|err| {
println!("{}: {:?}", err, err);
process::exit(1);
});
println!("{}", local_time);
}
|
use gotham::state::State;
use hyper::server::Response;
use hyper::StatusCode;
use hyper::Uri;
use hyper::header::Location;
use state::AppConfig;
use oauth;
use errors::*;
use gotham::middleware::session::SessionData;
use gotham::state::FromState;
pub fn handler(mut state: State) -> (State, Response) {
let token_res = {
let uri = state.take();
get_oauth_stuff(&mut state, &uri)
};
match token_res {
Ok(()) => (
state,
Response::new()
.with_status(StatusCode::Found)
.with_header(Location::new("/")),
),
Err(e) => (
state,
Response::new()
.with_status(StatusCode::NotFound)
.with_body(format!(
"Something went wrong getting the code and state: {}\n",
e
)),
),
}
}
fn get_oauth_stuff(state: &mut State, uri: &Uri) -> Result<()> {
let token = {
let cfg = state
.try_borrow::<AppConfig>()
.ok_or(format_err!("No app config in state?"))?;
oauth::extract_token(cfg, uri)?
};
let session = SessionData::<super::D2Session>::borrow_mut_from(state);
session.acquire_token(token);
Ok(())
}
|
// q0169_majority_element
struct Solution;
use std::collections::HashMap;
impl Solution {
pub fn majority_element(nums: Vec<i32>) -> i32 {
let mut map = HashMap::new();
let cpr = |c| {
if nums.len() % 2 == 0 {
c >= nums.len() / 2
} else {
c > nums.len() / 2
}
};
for i in nums.iter() {
if let Some(c) = map.get_mut(i) {
*c += 1;
if cpr(*c) {
return *i;
}
} else {
map.insert(*i, 1);
if cpr(1) {
return *i;
}
}
}
panic!(1234567890);
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn it_works() {
assert_eq!(3, Solution::majority_element(vec![3, 2, 3]));
assert_eq!(2, Solution::majority_element(vec![2, 2, 1, 1, 1, 2, 2]));
}
}
|
//use super::*;
//use cgmath::Vector2;
//use std::f64::INFINITY;
//
//type Subject = ImageWriter;
//
//mod write {
// use super::*;
//
// #[test]
// fn it_writes_the_image_to_a_file() {
// let resolution = Vector2::new(20, 20);
//
// let image = Image::new(resolution);
// let name = Name::new("test-file");
//
// Subject::write((&image, &name));
// }
//}
//
//mod byte {
// use super::*;
//
// #[test]
// fn it_normalizes_the_f64_to_the_0_to_255_range() {
// assert_eq!(Subject::byte(0.2), 51);
// assert_eq!(Subject::byte(0.5), 128);
// assert_eq!(Subject::byte(0.7), 179);
// }
//
// #[test]
// fn it_clamps_negative_values_to_zero() {
// assert_eq!(Subject::byte(-0.1), 0);
// assert_eq!(Subject::byte(-100.0), 0);
// assert_eq!(Subject::byte(-INFINITY), 0);
// }
//
// #[test]
// fn it_clamps_positive_values_to_255() {
// println!("{}", INFINITY as i32);
//
// assert_eq!(Subject::byte(1.1), 255);
// assert_eq!(Subject::byte(100.0), 255);
// assert_eq!(Subject::byte(INFINITY), 255);
// }
//}
|
use crate::Pred;
use num_integer::Integer;
std_prelude!();
#[derive(Clone, Copy, Debug, Default)]
/// Accepts even integers.
pub struct Even;
#[derive(Clone, Copy, Debug, Default)]
/// Accepts odd integers.
pub struct Odd;
impl<T: Integer> Pred<T> for Even {
fn accept(t: &T) -> bool {
t.is_even()
}
}
impl<T: Integer> Pred<T> for Odd {
fn accept(t: &T) -> bool {
t.is_odd()
}
}
|
use std::fmt::Debug;
#[cfg(test)]
pub fn assert_sorted_vec_eq<T>(a: &Vec<T>, b: &Vec<T>)
where
T: PartialEq + Ord + Clone + Debug,
{
let mut a: Vec<T> = (*a).clone();
let mut b: Vec<T> = (*b).clone();
a.sort();
b.sort();
assert_eq!(a, b)
}
|
use std::fs;
use std::io::Write;
#[allow(dead_code)]
pub fn write_text_to_file(path: String, text: &[u8]) -> std::io::Result<()> {
let mut file = fs::File::create(path)?;
file.write_all(text)?;
Ok(())
}
|
#[doc = "Reader of register FREQA"]
pub type R = crate::R<u32, super::FREQA>;
#[doc = "Writer for register FREQA"]
pub type W = crate::W<u32, super::FREQA>;
#[doc = "Register FREQA `reset()`'s with value 0"]
impl crate::ResetValue for super::FREQA {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Set to 0x9696 to apply the settings\\n Any other value in this field will set all drive strengths to 0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u16)]
pub enum PASSWD_A {
#[doc = "38550: `1001011010010110`"]
PASS = 38550,
}
impl From<PASSWD_A> for u16 {
#[inline(always)]
fn from(variant: PASSWD_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `PASSWD`"]
pub type PASSWD_R = crate::R<u16, PASSWD_A>;
impl PASSWD_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u16, PASSWD_A> {
use crate::Variant::*;
match self.bits {
38550 => Val(PASSWD_A::PASS),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PASS`"]
#[inline(always)]
pub fn is_pass(&self) -> bool {
*self == PASSWD_A::PASS
}
}
#[doc = "Write proxy for field `PASSWD`"]
pub struct PASSWD_W<'a> {
w: &'a mut W,
}
impl<'a> PASSWD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PASSWD_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "`1001011010010110`"]
#[inline(always)]
pub fn pass(self) -> &'a mut W {
self.variant(PASSWD_A::PASS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xffff << 16)) | (((value as u32) & 0xffff) << 16);
self.w
}
}
#[doc = "Reader of field `DS3`"]
pub type DS3_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DS3`"]
pub struct DS3_W<'a> {
w: &'a mut W,
}
impl<'a> DS3_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 << 12)) | (((value as u32) & 0x07) << 12);
self.w
}
}
#[doc = "Reader of field `DS2`"]
pub type DS2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DS2`"]
pub struct DS2_W<'a> {
w: &'a mut W,
}
impl<'a> DS2_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 << 8)) | (((value as u32) & 0x07) << 8);
self.w
}
}
#[doc = "Reader of field `DS1`"]
pub type DS1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DS1`"]
pub struct DS1_W<'a> {
w: &'a mut W,
}
impl<'a> DS1_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 << 4)) | (((value as u32) & 0x07) << 4);
self.w
}
}
#[doc = "Reader of field `DS0`"]
pub type DS0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `DS0`"]
pub struct DS0_W<'a> {
w: &'a mut W,
}
impl<'a> DS0_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) | ((value as u32) & 0x07);
self.w
}
}
impl R {
#[doc = "Bits 16:31 - Set to 0x9696 to apply the settings\\n Any other value in this field will set all drive strengths to 0"]
#[inline(always)]
pub fn passwd(&self) -> PASSWD_R {
PASSWD_R::new(((self.bits >> 16) & 0xffff) as u16)
}
#[doc = "Bits 12:14 - Stage 3 drive strength"]
#[inline(always)]
pub fn ds3(&self) -> DS3_R {
DS3_R::new(((self.bits >> 12) & 0x07) as u8)
}
#[doc = "Bits 8:10 - Stage 2 drive strength"]
#[inline(always)]
pub fn ds2(&self) -> DS2_R {
DS2_R::new(((self.bits >> 8) & 0x07) as u8)
}
#[doc = "Bits 4:6 - Stage 1 drive strength"]
#[inline(always)]
pub fn ds1(&self) -> DS1_R {
DS1_R::new(((self.bits >> 4) & 0x07) as u8)
}
#[doc = "Bits 0:2 - Stage 0 drive strength"]
#[inline(always)]
pub fn ds0(&self) -> DS0_R {
DS0_R::new((self.bits & 0x07) as u8)
}
}
impl W {
#[doc = "Bits 16:31 - Set to 0x9696 to apply the settings\\n Any other value in this field will set all drive strengths to 0"]
#[inline(always)]
pub fn passwd(&mut self) -> PASSWD_W {
PASSWD_W { w: self }
}
#[doc = "Bits 12:14 - Stage 3 drive strength"]
#[inline(always)]
pub fn ds3(&mut self) -> DS3_W {
DS3_W { w: self }
}
#[doc = "Bits 8:10 - Stage 2 drive strength"]
#[inline(always)]
pub fn ds2(&mut self) -> DS2_W {
DS2_W { w: self }
}
#[doc = "Bits 4:6 - Stage 1 drive strength"]
#[inline(always)]
pub fn ds1(&mut self) -> DS1_W {
DS1_W { w: self }
}
#[doc = "Bits 0:2 - Stage 0 drive strength"]
#[inline(always)]
pub fn ds0(&mut self) -> DS0_W {
DS0_W { w: self }
}
}
|
use super::prelude::*;
use glib::clone;
use super::super::ui;
fn connect_signals(state: &ui::State) {
let about_menu_item: gtk::MenuItem = state.get_about_menu_item();
let about_dialog: gtk::AboutDialog = state.get_about_dialog();
about_menu_item.connect_activate(move |_| {
about_dialog.run();
about_dialog.hide();
});
let quit_menu_item: gtk::MenuItem = state.get_quit_menu_item();
quit_menu_item.connect_activate(
clone!(@weak state.app as app => move |_| {
app.quit();
}),
);
}
pub fn setup(state: &ui::State) {
connect_signals(state);
}
|
use super::libs::tex_table::TexTable;
use super::libs::webgl::WebGlRenderingContext;
use crate::libs::random_id::U128Id;
pub struct Idmap {
depth_buffer: web_sys::WebGlRenderbuffer,
screen_tex: (web_sys::WebGlTexture, U128Id),
frame_buffer: web_sys::WebGlFramebuffer,
}
impl Idmap {
pub fn new(
gl: &WebGlRenderingContext,
width: i32,
height: i32,
tex_table: &mut TexTable,
) -> Self {
let depth_buffer = gl.create_renderbuffer().unwrap();
super::resize_depthbuffer(&gl, &depth_buffer, width, height);
let screen_tex = super::create_screen_texture(&gl, tex_table, width, height, None);
let frame_buffer = gl.create_framebuffer().unwrap();
gl.bind_framebuffer(
web_sys::WebGlRenderingContext::FRAMEBUFFER,
Some(&frame_buffer),
);
gl.framebuffer_renderbuffer(
web_sys::WebGlRenderingContext::FRAMEBUFFER,
web_sys::WebGlRenderingContext::DEPTH_ATTACHMENT,
web_sys::WebGlRenderingContext::RENDERBUFFER,
Some(&depth_buffer),
);
gl.framebuffer_texture_2d(
web_sys::WebGlRenderingContext::FRAMEBUFFER,
web_sys::WebGlRenderingContext::COLOR_ATTACHMENT0,
web_sys::WebGlRenderingContext::TEXTURE_2D,
Some(&screen_tex.0),
0,
);
Self {
depth_buffer,
screen_tex,
frame_buffer,
}
}
pub fn reset_size(
&self,
gl: &WebGlRenderingContext,
width: i32,
height: i32,
tex_table: &mut TexTable,
) {
super::resize_depthbuffer(&gl, &self.depth_buffer, width, height);
super::resize_texturebuffer(
&gl,
&self.screen_tex.0,
&self.screen_tex.1,
tex_table,
width,
height,
);
}
pub fn bind_self(&self, gl: &WebGlRenderingContext) {
gl.bind_framebuffer(
web_sys::WebGlRenderingContext::FRAMEBUFFER,
Some(&self.frame_buffer),
);
}
pub fn begin_to_render(&self, gl: &WebGlRenderingContext, tex_table: &TexTable) {
if let Some((_, tex_flag)) = tex_table.try_use_custom(&self.screen_tex.1) {
gl.active_texture(tex_flag);
gl.bind_texture(web_sys::WebGlRenderingContext::TEXTURE_2D, None);
}
}
pub fn screen_tex(&self) -> &(web_sys::WebGlTexture, U128Id) {
&self.screen_tex
}
}
|
#[doc = "Register `SECCFGR1` reader"]
pub type R = crate::R<SECCFGR1_SPEC>;
#[doc = "Register `SECCFGR1` writer"]
pub type W = crate::W<SECCFGR1_SPEC>;
#[doc = "Field `TIM2SEC` reader - secure access mode for TIM2"]
pub type TIM2SEC_R = crate::BitReader;
#[doc = "Field `TIM2SEC` writer - secure access mode for TIM2"]
pub type TIM2SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM3SEC` reader - secure access mode for TIM3"]
pub type TIM3SEC_R = crate::BitReader;
#[doc = "Field `TIM3SEC` writer - secure access mode for TIM3"]
pub type TIM3SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM4SEC` reader - secure access mode for TIM4"]
pub type TIM4SEC_R = crate::BitReader;
#[doc = "Field `TIM4SEC` writer - secure access mode for TIM4"]
pub type TIM4SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM5SEC` reader - secure access mode for TIM5"]
pub type TIM5SEC_R = crate::BitReader;
#[doc = "Field `TIM5SEC` writer - secure access mode for TIM5"]
pub type TIM5SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM6SEC` reader - secure access mode for TIM6"]
pub type TIM6SEC_R = crate::BitReader;
#[doc = "Field `TIM6SEC` writer - secure access mode for TIM6"]
pub type TIM6SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM7SEC` reader - secure access mode for TIM7"]
pub type TIM7SEC_R = crate::BitReader;
#[doc = "Field `TIM7SEC` writer - secure access mode for TIM7"]
pub type TIM7SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM12SEC` reader - secure access mode for TIM12"]
pub type TIM12SEC_R = crate::BitReader;
#[doc = "Field `TIM12SEC` writer - secure access mode for TIM12"]
pub type TIM12SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM13SEC` reader - secure access mode for TIM13"]
pub type TIM13SEC_R = crate::BitReader;
#[doc = "Field `TIM13SEC` writer - secure access mode for TIM13"]
pub type TIM13SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM14SEC` reader - secure access mode for TIM14"]
pub type TIM14SEC_R = crate::BitReader;
#[doc = "Field `TIM14SEC` writer - secure access mode for TIM14"]
pub type TIM14SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WWDGSEC` reader - secure access mode for WWDG"]
pub type WWDGSEC_R = crate::BitReader;
#[doc = "Field `WWDGSEC` writer - secure access mode for WWDG"]
pub type WWDGSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IWDGSEC` reader - secure access mode for IWDG"]
pub type IWDGSEC_R = crate::BitReader;
#[doc = "Field `IWDGSEC` writer - secure access mode for IWDG"]
pub type IWDGSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI2SEC` reader - secure access mode for SPI2"]
pub type SPI2SEC_R = crate::BitReader;
#[doc = "Field `SPI2SEC` writer - secure access mode for SPI2"]
pub type SPI2SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI3SEC` reader - secure access mode for SPI3"]
pub type SPI3SEC_R = crate::BitReader;
#[doc = "Field `SPI3SEC` writer - secure access mode for SPI3"]
pub type SPI3SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART2SEC` reader - secure access mode for USART2"]
pub type USART2SEC_R = crate::BitReader;
#[doc = "Field `USART2SEC` writer - secure access mode for USART2"]
pub type USART2SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART3SEC` reader - secure access mode for USART3"]
pub type USART3SEC_R = crate::BitReader;
#[doc = "Field `USART3SEC` writer - secure access mode for USART3"]
pub type USART3SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART4SEC` reader - secure access mode for UART4"]
pub type UART4SEC_R = crate::BitReader;
#[doc = "Field `UART4SEC` writer - secure access mode for UART4"]
pub type UART4SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART5SEC` reader - secure access mode for UART5"]
pub type UART5SEC_R = crate::BitReader;
#[doc = "Field `UART5SEC` writer - secure access mode for UART5"]
pub type UART5SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C1SEC` reader - secure access mode for I2C1"]
pub type I2C1SEC_R = crate::BitReader;
#[doc = "Field `I2C1SEC` writer - secure access mode for I2C1"]
pub type I2C1SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C2SEC` reader - secure access mode for I2C2"]
pub type I2C2SEC_R = crate::BitReader;
#[doc = "Field `I2C2SEC` writer - secure access mode for I2C2"]
pub type I2C2SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I3C1SEC` reader - secure access mode for I3C1"]
pub type I3C1SEC_R = crate::BitReader;
#[doc = "Field `I3C1SEC` writer - secure access mode for I3C1"]
pub type I3C1SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRSSEC` reader - secure access mode for CRS"]
pub type CRSSEC_R = crate::BitReader;
#[doc = "Field `CRSSEC` writer - secure access mode for CRS"]
pub type CRSSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART6SEC` reader - secure access mode for USART6"]
pub type USART6SEC_R = crate::BitReader;
#[doc = "Field `USART6SEC` writer - secure access mode for USART6"]
pub type USART6SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART10SEC` reader - secure access mode for USART10"]
pub type USART10SEC_R = crate::BitReader;
#[doc = "Field `USART10SEC` writer - secure access mode for USART10"]
pub type USART10SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART11SEC` reader - secure access mode for USART11"]
pub type USART11SEC_R = crate::BitReader;
#[doc = "Field `USART11SEC` writer - secure access mode for USART11"]
pub type USART11SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `HDMICECSEC` reader - secure access mode for HDMICEC"]
pub type HDMICECSEC_R = crate::BitReader;
#[doc = "Field `HDMICECSEC` writer - secure access mode for HDMICEC"]
pub type HDMICECSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DAC1SEC` reader - secure access mode for DAC1"]
pub type DAC1SEC_R = crate::BitReader;
#[doc = "Field `DAC1SEC` writer - secure access mode for DAC1"]
pub type DAC1SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART7SEC` reader - secure access mode for UART7"]
pub type UART7SEC_R = crate::BitReader;
#[doc = "Field `UART7SEC` writer - secure access mode for UART7"]
pub type UART7SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART8SEC` reader - secure access mode for UART8"]
pub type UART8SEC_R = crate::BitReader;
#[doc = "Field `UART8SEC` writer - secure access mode for UART8"]
pub type UART8SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART9SEC` reader - secure access mode for UART9"]
pub type UART9SEC_R = crate::BitReader;
#[doc = "Field `UART9SEC` writer - secure access mode for UART9"]
pub type UART9SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `UART12SEC` reader - secure access mode for UART12"]
pub type UART12SEC_R = crate::BitReader;
#[doc = "Field `UART12SEC` writer - secure access mode for UART12"]
pub type UART12SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DTSSEC` reader - secure access mode for DTS"]
pub type DTSSEC_R = crate::BitReader;
#[doc = "Field `DTSSEC` writer - secure access mode for DTS"]
pub type DTSSEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LPTIM2SEC` reader - secure access mode for LPTIM2"]
pub type LPTIM2SEC_R = crate::BitReader;
#[doc = "Field `LPTIM2SEC` writer - secure access mode for LPTIM2"]
pub type LPTIM2SEC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - secure access mode for TIM2"]
#[inline(always)]
pub fn tim2sec(&self) -> TIM2SEC_R {
TIM2SEC_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - secure access mode for TIM3"]
#[inline(always)]
pub fn tim3sec(&self) -> TIM3SEC_R {
TIM3SEC_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - secure access mode for TIM4"]
#[inline(always)]
pub fn tim4sec(&self) -> TIM4SEC_R {
TIM4SEC_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - secure access mode for TIM5"]
#[inline(always)]
pub fn tim5sec(&self) -> TIM5SEC_R {
TIM5SEC_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - secure access mode for TIM6"]
#[inline(always)]
pub fn tim6sec(&self) -> TIM6SEC_R {
TIM6SEC_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - secure access mode for TIM7"]
#[inline(always)]
pub fn tim7sec(&self) -> TIM7SEC_R {
TIM7SEC_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - secure access mode for TIM12"]
#[inline(always)]
pub fn tim12sec(&self) -> TIM12SEC_R {
TIM12SEC_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - secure access mode for TIM13"]
#[inline(always)]
pub fn tim13sec(&self) -> TIM13SEC_R {
TIM13SEC_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - secure access mode for TIM14"]
#[inline(always)]
pub fn tim14sec(&self) -> TIM14SEC_R {
TIM14SEC_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - secure access mode for WWDG"]
#[inline(always)]
pub fn wwdgsec(&self) -> WWDGSEC_R {
WWDGSEC_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - secure access mode for IWDG"]
#[inline(always)]
pub fn iwdgsec(&self) -> IWDGSEC_R {
IWDGSEC_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - secure access mode for SPI2"]
#[inline(always)]
pub fn spi2sec(&self) -> SPI2SEC_R {
SPI2SEC_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - secure access mode for SPI3"]
#[inline(always)]
pub fn spi3sec(&self) -> SPI3SEC_R {
SPI3SEC_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - secure access mode for USART2"]
#[inline(always)]
pub fn usart2sec(&self) -> USART2SEC_R {
USART2SEC_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - secure access mode for USART3"]
#[inline(always)]
pub fn usart3sec(&self) -> USART3SEC_R {
USART3SEC_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - secure access mode for UART4"]
#[inline(always)]
pub fn uart4sec(&self) -> UART4SEC_R {
UART4SEC_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - secure access mode for UART5"]
#[inline(always)]
pub fn uart5sec(&self) -> UART5SEC_R {
UART5SEC_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - secure access mode for I2C1"]
#[inline(always)]
pub fn i2c1sec(&self) -> I2C1SEC_R {
I2C1SEC_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - secure access mode for I2C2"]
#[inline(always)]
pub fn i2c2sec(&self) -> I2C2SEC_R {
I2C2SEC_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - secure access mode for I3C1"]
#[inline(always)]
pub fn i3c1sec(&self) -> I3C1SEC_R {
I3C1SEC_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - secure access mode for CRS"]
#[inline(always)]
pub fn crssec(&self) -> CRSSEC_R {
CRSSEC_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - secure access mode for USART6"]
#[inline(always)]
pub fn usart6sec(&self) -> USART6SEC_R {
USART6SEC_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 22 - secure access mode for USART10"]
#[inline(always)]
pub fn usart10sec(&self) -> USART10SEC_R {
USART10SEC_R::new(((self.bits >> 22) & 1) != 0)
}
#[doc = "Bit 23 - secure access mode for USART11"]
#[inline(always)]
pub fn usart11sec(&self) -> USART11SEC_R {
USART11SEC_R::new(((self.bits >> 23) & 1) != 0)
}
#[doc = "Bit 24 - secure access mode for HDMICEC"]
#[inline(always)]
pub fn hdmicecsec(&self) -> HDMICECSEC_R {
HDMICECSEC_R::new(((self.bits >> 24) & 1) != 0)
}
#[doc = "Bit 25 - secure access mode for DAC1"]
#[inline(always)]
pub fn dac1sec(&self) -> DAC1SEC_R {
DAC1SEC_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 26 - secure access mode for UART7"]
#[inline(always)]
pub fn uart7sec(&self) -> UART7SEC_R {
UART7SEC_R::new(((self.bits >> 26) & 1) != 0)
}
#[doc = "Bit 27 - secure access mode for UART8"]
#[inline(always)]
pub fn uart8sec(&self) -> UART8SEC_R {
UART8SEC_R::new(((self.bits >> 27) & 1) != 0)
}
#[doc = "Bit 28 - secure access mode for UART9"]
#[inline(always)]
pub fn uart9sec(&self) -> UART9SEC_R {
UART9SEC_R::new(((self.bits >> 28) & 1) != 0)
}
#[doc = "Bit 29 - secure access mode for UART12"]
#[inline(always)]
pub fn uart12sec(&self) -> UART12SEC_R {
UART12SEC_R::new(((self.bits >> 29) & 1) != 0)
}
#[doc = "Bit 30 - secure access mode for DTS"]
#[inline(always)]
pub fn dtssec(&self) -> DTSSEC_R {
DTSSEC_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - secure access mode for LPTIM2"]
#[inline(always)]
pub fn lptim2sec(&self) -> LPTIM2SEC_R {
LPTIM2SEC_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - secure access mode for TIM2"]
#[inline(always)]
#[must_use]
pub fn tim2sec(&mut self) -> TIM2SEC_W<SECCFGR1_SPEC, 0> {
TIM2SEC_W::new(self)
}
#[doc = "Bit 1 - secure access mode for TIM3"]
#[inline(always)]
#[must_use]
pub fn tim3sec(&mut self) -> TIM3SEC_W<SECCFGR1_SPEC, 1> {
TIM3SEC_W::new(self)
}
#[doc = "Bit 2 - secure access mode for TIM4"]
#[inline(always)]
#[must_use]
pub fn tim4sec(&mut self) -> TIM4SEC_W<SECCFGR1_SPEC, 2> {
TIM4SEC_W::new(self)
}
#[doc = "Bit 3 - secure access mode for TIM5"]
#[inline(always)]
#[must_use]
pub fn tim5sec(&mut self) -> TIM5SEC_W<SECCFGR1_SPEC, 3> {
TIM5SEC_W::new(self)
}
#[doc = "Bit 4 - secure access mode for TIM6"]
#[inline(always)]
#[must_use]
pub fn tim6sec(&mut self) -> TIM6SEC_W<SECCFGR1_SPEC, 4> {
TIM6SEC_W::new(self)
}
#[doc = "Bit 5 - secure access mode for TIM7"]
#[inline(always)]
#[must_use]
pub fn tim7sec(&mut self) -> TIM7SEC_W<SECCFGR1_SPEC, 5> {
TIM7SEC_W::new(self)
}
#[doc = "Bit 6 - secure access mode for TIM12"]
#[inline(always)]
#[must_use]
pub fn tim12sec(&mut self) -> TIM12SEC_W<SECCFGR1_SPEC, 6> {
TIM12SEC_W::new(self)
}
#[doc = "Bit 7 - secure access mode for TIM13"]
#[inline(always)]
#[must_use]
pub fn tim13sec(&mut self) -> TIM13SEC_W<SECCFGR1_SPEC, 7> {
TIM13SEC_W::new(self)
}
#[doc = "Bit 8 - secure access mode for TIM14"]
#[inline(always)]
#[must_use]
pub fn tim14sec(&mut self) -> TIM14SEC_W<SECCFGR1_SPEC, 8> {
TIM14SEC_W::new(self)
}
#[doc = "Bit 9 - secure access mode for WWDG"]
#[inline(always)]
#[must_use]
pub fn wwdgsec(&mut self) -> WWDGSEC_W<SECCFGR1_SPEC, 9> {
WWDGSEC_W::new(self)
}
#[doc = "Bit 10 - secure access mode for IWDG"]
#[inline(always)]
#[must_use]
pub fn iwdgsec(&mut self) -> IWDGSEC_W<SECCFGR1_SPEC, 10> {
IWDGSEC_W::new(self)
}
#[doc = "Bit 11 - secure access mode for SPI2"]
#[inline(always)]
#[must_use]
pub fn spi2sec(&mut self) -> SPI2SEC_W<SECCFGR1_SPEC, 11> {
SPI2SEC_W::new(self)
}
#[doc = "Bit 12 - secure access mode for SPI3"]
#[inline(always)]
#[must_use]
pub fn spi3sec(&mut self) -> SPI3SEC_W<SECCFGR1_SPEC, 12> {
SPI3SEC_W::new(self)
}
#[doc = "Bit 13 - secure access mode for USART2"]
#[inline(always)]
#[must_use]
pub fn usart2sec(&mut self) -> USART2SEC_W<SECCFGR1_SPEC, 13> {
USART2SEC_W::new(self)
}
#[doc = "Bit 14 - secure access mode for USART3"]
#[inline(always)]
#[must_use]
pub fn usart3sec(&mut self) -> USART3SEC_W<SECCFGR1_SPEC, 14> {
USART3SEC_W::new(self)
}
#[doc = "Bit 15 - secure access mode for UART4"]
#[inline(always)]
#[must_use]
pub fn uart4sec(&mut self) -> UART4SEC_W<SECCFGR1_SPEC, 15> {
UART4SEC_W::new(self)
}
#[doc = "Bit 16 - secure access mode for UART5"]
#[inline(always)]
#[must_use]
pub fn uart5sec(&mut self) -> UART5SEC_W<SECCFGR1_SPEC, 16> {
UART5SEC_W::new(self)
}
#[doc = "Bit 17 - secure access mode for I2C1"]
#[inline(always)]
#[must_use]
pub fn i2c1sec(&mut self) -> I2C1SEC_W<SECCFGR1_SPEC, 17> {
I2C1SEC_W::new(self)
}
#[doc = "Bit 18 - secure access mode for I2C2"]
#[inline(always)]
#[must_use]
pub fn i2c2sec(&mut self) -> I2C2SEC_W<SECCFGR1_SPEC, 18> {
I2C2SEC_W::new(self)
}
#[doc = "Bit 19 - secure access mode for I3C1"]
#[inline(always)]
#[must_use]
pub fn i3c1sec(&mut self) -> I3C1SEC_W<SECCFGR1_SPEC, 19> {
I3C1SEC_W::new(self)
}
#[doc = "Bit 20 - secure access mode for CRS"]
#[inline(always)]
#[must_use]
pub fn crssec(&mut self) -> CRSSEC_W<SECCFGR1_SPEC, 20> {
CRSSEC_W::new(self)
}
#[doc = "Bit 21 - secure access mode for USART6"]
#[inline(always)]
#[must_use]
pub fn usart6sec(&mut self) -> USART6SEC_W<SECCFGR1_SPEC, 21> {
USART6SEC_W::new(self)
}
#[doc = "Bit 22 - secure access mode for USART10"]
#[inline(always)]
#[must_use]
pub fn usart10sec(&mut self) -> USART10SEC_W<SECCFGR1_SPEC, 22> {
USART10SEC_W::new(self)
}
#[doc = "Bit 23 - secure access mode for USART11"]
#[inline(always)]
#[must_use]
pub fn usart11sec(&mut self) -> USART11SEC_W<SECCFGR1_SPEC, 23> {
USART11SEC_W::new(self)
}
#[doc = "Bit 24 - secure access mode for HDMICEC"]
#[inline(always)]
#[must_use]
pub fn hdmicecsec(&mut self) -> HDMICECSEC_W<SECCFGR1_SPEC, 24> {
HDMICECSEC_W::new(self)
}
#[doc = "Bit 25 - secure access mode for DAC1"]
#[inline(always)]
#[must_use]
pub fn dac1sec(&mut self) -> DAC1SEC_W<SECCFGR1_SPEC, 25> {
DAC1SEC_W::new(self)
}
#[doc = "Bit 26 - secure access mode for UART7"]
#[inline(always)]
#[must_use]
pub fn uart7sec(&mut self) -> UART7SEC_W<SECCFGR1_SPEC, 26> {
UART7SEC_W::new(self)
}
#[doc = "Bit 27 - secure access mode for UART8"]
#[inline(always)]
#[must_use]
pub fn uart8sec(&mut self) -> UART8SEC_W<SECCFGR1_SPEC, 27> {
UART8SEC_W::new(self)
}
#[doc = "Bit 28 - secure access mode for UART9"]
#[inline(always)]
#[must_use]
pub fn uart9sec(&mut self) -> UART9SEC_W<SECCFGR1_SPEC, 28> {
UART9SEC_W::new(self)
}
#[doc = "Bit 29 - secure access mode for UART12"]
#[inline(always)]
#[must_use]
pub fn uart12sec(&mut self) -> UART12SEC_W<SECCFGR1_SPEC, 29> {
UART12SEC_W::new(self)
}
#[doc = "Bit 30 - secure access mode for DTS"]
#[inline(always)]
#[must_use]
pub fn dtssec(&mut self) -> DTSSEC_W<SECCFGR1_SPEC, 30> {
DTSSEC_W::new(self)
}
#[doc = "Bit 31 - secure access mode for LPTIM2"]
#[inline(always)]
#[must_use]
pub fn lptim2sec(&mut self) -> LPTIM2SEC_W<SECCFGR1_SPEC, 31> {
LPTIM2SEC_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 = "GTZC1 TZSC secure configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`seccfgr1::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 [`seccfgr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SECCFGR1_SPEC;
impl crate::RegisterSpec for SECCFGR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`seccfgr1::R`](R) reader structure"]
impl crate::Readable for SECCFGR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`seccfgr1::W`](W) writer structure"]
impl crate::Writable for SECCFGR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SECCFGR1 to value 0"]
impl crate::Resettable for SECCFGR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - IPCC Processor 1 control register"]
pub ipcc_c1cr: IPCC_C1CR,
#[doc = "0x04 - IPCC Processor 1 mask register"]
pub ipcc_c1mr: IPCC_C1MR,
#[doc = "0x08 - Reading this register will always return 0x0000 0000."]
pub ipcc_c1scr: IPCC_C1SCR,
#[doc = "0x0c - IPCC processor 1 to processor 2 status register"]
pub ipcc_c1toc2sr: IPCC_C1TOC2SR,
#[doc = "0x10 - IPCC Processor 2 control register"]
pub ipcc_c2cr: IPCC_C2CR,
#[doc = "0x14 - IPCC Processor 2 mask register"]
pub ipcc_c2mr: IPCC_C2MR,
#[doc = "0x18 - Reading this register will always return 0x0000 0000."]
pub ipcc_c2scr: IPCC_C2SCR,
#[doc = "0x1c - IPCC processor 2 to processor 1 status register"]
pub ipcc_c2toc1sr: IPCC_C2TOC1SR,
_reserved8: [u8; 0x03d0],
#[doc = "0x3f0 - IPCC Hardware configuration register"]
pub ipcc_hwcfgr: IPCC_HWCFGR,
#[doc = "0x3f4 - IPCC IP Version register"]
pub ipcc_ver: IPCC_VER,
#[doc = "0x3f8 - IPCC IP Identification register"]
pub ipcc_id: IPCC_ID,
#[doc = "0x3fc - IPCC Size ID register"]
pub ipcc_sid: IPCC_SID,
}
#[doc = "IPCC_C1CR (rw) register accessor: IPCC Processor 1 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c1cr::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 [`ipcc_c1cr::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 [`ipcc_c1cr`]
module"]
pub type IPCC_C1CR = crate::Reg<ipcc_c1cr::IPCC_C1CR_SPEC>;
#[doc = "IPCC Processor 1 control register"]
pub mod ipcc_c1cr;
#[doc = "IPCC_C1MR (rw) register accessor: IPCC Processor 1 mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c1mr::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 [`ipcc_c1mr::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 [`ipcc_c1mr`]
module"]
pub type IPCC_C1MR = crate::Reg<ipcc_c1mr::IPCC_C1MR_SPEC>;
#[doc = "IPCC Processor 1 mask register"]
pub mod ipcc_c1mr;
#[doc = "IPCC_C1SCR (rw) register accessor: Reading this register will always return 0x0000 0000.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c1scr::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 [`ipcc_c1scr::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 [`ipcc_c1scr`]
module"]
pub type IPCC_C1SCR = crate::Reg<ipcc_c1scr::IPCC_C1SCR_SPEC>;
#[doc = "Reading this register will always return 0x0000 0000."]
pub mod ipcc_c1scr;
#[doc = "IPCC_C1TOC2SR (r) register accessor: IPCC processor 1 to processor 2 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c1toc2sr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ipcc_c1toc2sr`]
module"]
pub type IPCC_C1TOC2SR = crate::Reg<ipcc_c1toc2sr::IPCC_C1TOC2SR_SPEC>;
#[doc = "IPCC processor 1 to processor 2 status register"]
pub mod ipcc_c1toc2sr;
#[doc = "IPCC_C2CR (rw) register accessor: IPCC Processor 2 control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c2cr::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 [`ipcc_c2cr::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 [`ipcc_c2cr`]
module"]
pub type IPCC_C2CR = crate::Reg<ipcc_c2cr::IPCC_C2CR_SPEC>;
#[doc = "IPCC Processor 2 control register"]
pub mod ipcc_c2cr;
#[doc = "IPCC_C2MR (rw) register accessor: IPCC Processor 2 mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c2mr::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 [`ipcc_c2mr::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 [`ipcc_c2mr`]
module"]
pub type IPCC_C2MR = crate::Reg<ipcc_c2mr::IPCC_C2MR_SPEC>;
#[doc = "IPCC Processor 2 mask register"]
pub mod ipcc_c2mr;
#[doc = "IPCC_C2SCR (rw) register accessor: Reading this register will always return 0x0000 0000.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c2scr::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 [`ipcc_c2scr::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 [`ipcc_c2scr`]
module"]
pub type IPCC_C2SCR = crate::Reg<ipcc_c2scr::IPCC_C2SCR_SPEC>;
#[doc = "Reading this register will always return 0x0000 0000."]
pub mod ipcc_c2scr;
#[doc = "IPCC_C2TOC1SR (r) register accessor: IPCC processor 2 to processor 1 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c2toc1sr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ipcc_c2toc1sr`]
module"]
pub type IPCC_C2TOC1SR = crate::Reg<ipcc_c2toc1sr::IPCC_C2TOC1SR_SPEC>;
#[doc = "IPCC processor 2 to processor 1 status register"]
pub mod ipcc_c2toc1sr;
#[doc = "IPCC_HWCFGR (r) register accessor: IPCC Hardware configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_hwcfgr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ipcc_hwcfgr`]
module"]
pub type IPCC_HWCFGR = crate::Reg<ipcc_hwcfgr::IPCC_HWCFGR_SPEC>;
#[doc = "IPCC Hardware configuration register"]
pub mod ipcc_hwcfgr;
#[doc = "IPCC_VER (r) register accessor: IPCC IP Version register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_ver::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ipcc_ver`]
module"]
pub type IPCC_VER = crate::Reg<ipcc_ver::IPCC_VER_SPEC>;
#[doc = "IPCC IP Version register"]
pub mod ipcc_ver;
#[doc = "IPCC_ID (r) register accessor: IPCC IP Identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_id::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ipcc_id`]
module"]
pub type IPCC_ID = crate::Reg<ipcc_id::IPCC_ID_SPEC>;
#[doc = "IPCC IP Identification register"]
pub mod ipcc_id;
#[doc = "IPCC_SID (r) register accessor: IPCC Size ID register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_sid::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ipcc_sid`]
module"]
pub type IPCC_SID = crate::Reg<ipcc_sid::IPCC_SID_SPEC>;
#[doc = "IPCC Size ID register"]
pub mod ipcc_sid;
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Ethernet MMC control register"]
pub mmccr: MMCCR,
#[doc = "0x04 - Ethernet MMC receive interrupt register"]
pub mmcrir: MMCRIR,
#[doc = "0x08 - Ethernet MMC transmit interrupt register"]
pub mmctir: MMCTIR,
#[doc = "0x0c - Ethernet MMC receive interrupt mask register"]
pub mmcrimr: MMCRIMR,
#[doc = "0x10 - Ethernet MMC transmit interrupt mask register"]
pub mmctimr: MMCTIMR,
_reserved5: [u8; 0x38],
#[doc = "0x4c - Ethernet MMC transmitted good frames after a single collision counter"]
pub mmctgfsccr: MMCTGFSCCR,
#[doc = "0x50 - Ethernet MMC transmitted good frames after more than a single collision"]
pub mmctgfmsccr: MMCTGFMSCCR,
_reserved7: [u8; 0x14],
#[doc = "0x68 - Ethernet MMC transmitted good frames counter register"]
pub mmctgfcr: MMCTGFCR,
_reserved8: [u8; 0x28],
#[doc = "0x94 - Ethernet MMC received frames with CRC error counter register"]
pub mmcrfcecr: MMCRFCECR,
#[doc = "0x98 - Ethernet MMC received frames with alignment error counter register"]
pub mmcrfaecr: MMCRFAECR,
_reserved10: [u8; 0x28],
#[doc = "0xc4 - MMC received good unicast frames counter register"]
pub mmcrgufcr: MMCRGUFCR,
}
#[doc = "MMCCR (rw) register accessor: Ethernet MMC control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmccr::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 [`mmccr::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 [`mmccr`]
module"]
pub type MMCCR = crate::Reg<mmccr::MMCCR_SPEC>;
#[doc = "Ethernet MMC control register"]
pub mod mmccr;
#[doc = "MMCRIR (rw) register accessor: Ethernet MMC receive interrupt register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmcrir::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 [`mmcrir::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 [`mmcrir`]
module"]
pub type MMCRIR = crate::Reg<mmcrir::MMCRIR_SPEC>;
#[doc = "Ethernet MMC receive interrupt register"]
pub mod mmcrir;
#[doc = "MMCTIR (rw) register accessor: Ethernet MMC transmit interrupt register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmctir::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 [`mmctir::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 [`mmctir`]
module"]
pub type MMCTIR = crate::Reg<mmctir::MMCTIR_SPEC>;
#[doc = "Ethernet MMC transmit interrupt register"]
pub mod mmctir;
#[doc = "MMCRIMR (rw) register accessor: Ethernet MMC receive interrupt mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmcrimr::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 [`mmcrimr::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 [`mmcrimr`]
module"]
pub type MMCRIMR = crate::Reg<mmcrimr::MMCRIMR_SPEC>;
#[doc = "Ethernet MMC receive interrupt mask register"]
pub mod mmcrimr;
#[doc = "MMCTIMR (rw) register accessor: Ethernet MMC transmit interrupt mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmctimr::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 [`mmctimr::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 [`mmctimr`]
module"]
pub type MMCTIMR = crate::Reg<mmctimr::MMCTIMR_SPEC>;
#[doc = "Ethernet MMC transmit interrupt mask register"]
pub mod mmctimr;
#[doc = "MMCTGFSCCR (r) register accessor: Ethernet MMC transmitted good frames after a single collision counter\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmctgfsccr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mmctgfsccr`]
module"]
pub type MMCTGFSCCR = crate::Reg<mmctgfsccr::MMCTGFSCCR_SPEC>;
#[doc = "Ethernet MMC transmitted good frames after a single collision counter"]
pub mod mmctgfsccr;
#[doc = "MMCTGFMSCCR (r) register accessor: Ethernet MMC transmitted good frames after more than a single collision\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmctgfmsccr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mmctgfmsccr`]
module"]
pub type MMCTGFMSCCR = crate::Reg<mmctgfmsccr::MMCTGFMSCCR_SPEC>;
#[doc = "Ethernet MMC transmitted good frames after more than a single collision"]
pub mod mmctgfmsccr;
#[doc = "MMCTGFCR (r) register accessor: Ethernet MMC transmitted good frames counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmctgfcr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mmctgfcr`]
module"]
pub type MMCTGFCR = crate::Reg<mmctgfcr::MMCTGFCR_SPEC>;
#[doc = "Ethernet MMC transmitted good frames counter register"]
pub mod mmctgfcr;
#[doc = "MMCRFCECR (r) register accessor: Ethernet MMC received frames with CRC error counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmcrfcecr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mmcrfcecr`]
module"]
pub type MMCRFCECR = crate::Reg<mmcrfcecr::MMCRFCECR_SPEC>;
#[doc = "Ethernet MMC received frames with CRC error counter register"]
pub mod mmcrfcecr;
#[doc = "MMCRFAECR (r) register accessor: Ethernet MMC received frames with alignment error counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmcrfaecr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mmcrfaecr`]
module"]
pub type MMCRFAECR = crate::Reg<mmcrfaecr::MMCRFAECR_SPEC>;
#[doc = "Ethernet MMC received frames with alignment error counter register"]
pub mod mmcrfaecr;
#[doc = "MMCRGUFCR (r) register accessor: MMC received good unicast frames counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mmcrgufcr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`mmcrgufcr`]
module"]
pub type MMCRGUFCR = crate::Reg<mmcrgufcr::MMCRGUFCR_SPEC>;
#[doc = "MMC received good unicast frames counter register"]
pub mod mmcrgufcr;
|
//! Utilities for pinning
#![no_std]
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
#[macro_use]
mod stack_pin;
#[macro_use]
mod projection;
// Not public API.
#[doc(hidden)]
pub mod __private {
pub use core::pin::Pin;
}
|
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
// atomic duration in milli seconds
#[derive(Debug)]
pub struct AtomicDuration(AtomicUsize);
impl AtomicDuration {
pub fn new(dur: Option<Duration>) -> Self {
let dur = match dur {
None => 0,
Some(d) => dur_to_ms(d) as usize,
};
AtomicDuration(AtomicUsize::new(dur))
}
#[inline]
#[cfg(feature = "io_timeout")]
pub fn get(&self) -> Option<Duration> {
match self.0.load(Ordering::Relaxed) {
0 => None,
d => Some(Duration::from_millis(d as u64)),
}
}
#[inline]
pub fn store(&self, dur: Option<Duration>) {
let timeout = match dur {
None => 0,
Some(d) => dur_to_ms(d) as usize,
};
self.0.store(timeout, Ordering::Relaxed);
}
#[inline]
pub fn take(&self) -> Option<Duration> {
match self.0.swap(0, Ordering::Relaxed) {
0 => None,
d => Some(Duration::from_millis(d as u64)),
}
}
}
fn dur_to_ms(dur: Duration) -> u64 {
// Note that a duration is a (u64, u32) (seconds, nanoseconds) pair
const MS_PER_SEC: u64 = 1_000;
const NANOS_PER_MILLI: u64 = 1_000_000;
let ns = u64::from(dur.subsec_nanos());
let ms = (ns + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI;
dur.as_secs().saturating_mul(MS_PER_SEC).saturating_add(ms)
}
|
#![allow(dead_code)]
mod controls;
mod generator;
mod render;
use render::State;
use winit::{
event,
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
use iced_wgpu::{window::SwapChain, Primitive, Renderer, Settings, Target};
use iced_winit::{Cache, Clipboard, MouseCursor, Size, UserInterface};
const MSAA_SAMPLES: u32 = 4;
const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb;
pub fn run() {
let event_loop = EventLoop::new();
let window = WindowBuilder::new().with_title("Polyhedrator").build(&event_loop).unwrap();
let mut size = window.inner_size();
let mut logical_size = size.to_logical(window.scale_factor());
let mut modifiers = event::ModifiersState::default();
let surface = wgpu::Surface::create(&window);
let adapter = wgpu::Adapter::request(&Default::default()).unwrap();
let (mut device, mut queue) = adapter.request_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
limits: Default::default(),
});
let mut ui_swap = SwapChain::new(&device, &surface, TEXTURE_FORMAT, size.width, size.height);
let mut ui_swap_desc = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
format: TEXTURE_FORMAT,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Vsync,
};
let mut resized = false;
// Initialize iced
let mut events = Vec::new();
let mut cache = Some(Cache::default());
let mut renderer = Renderer::new(&mut device, Settings::default());
let mut output = (Primitive::None, MouseCursor::OutOfBounds);
let clipboard = Clipboard::new(&window);
let mut controls = controls::Controls::new();
// let mut ui_framebuffer = create_multisampled_framebuffer(&device, &ui_swap_desc, MSAA_SAMPLES);
let mesh = gen_polyhedron();
let mut state = State::new(&device, &mut queue, &ui_swap_desc, mesh);
controls.update(controls::Message::UpdatePressed, &mut state, &device);
event_loop.run(move |event, _, control_flow| {
*control_flow = if cfg!(feature = "metal-auto-capture") {
ControlFlow::Exit
} else {
ControlFlow::Wait
};
match event {
event::Event::WindowEvent { event, .. } => {
match event {
event::WindowEvent::ModifiersChanged(new_modifiers) => {
modifiers = new_modifiers;
}
// Recreate swapchain when window is resized.
event::WindowEvent::Resized(new_size) => {
if new_size.width == 0 || new_size.height == 0 {
return;
}
size = new_size;
logical_size = size.to_logical(window.scale_factor());
resized = true;
/*
ui_framebuffer =
create_multisampled_framebuffer(&device, &ui_swap_desc, MSAA_SAMPLES);
state.resize(&device, &ui_swap_desc);
*/
}
// Close on request or on Escape.
event::WindowEvent::KeyboardInput {
input:
event::KeyboardInput {
virtual_keycode: Some(event::VirtualKeyCode::Escape),
state: event::ElementState::Pressed,
..
},
..
}
| event::WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit;
}
_ => {}
}
// Map window event to iced event
if let Some(event) =
iced_winit::conversion::window_event(&event, window.scale_factor(), modifiers)
{
events.push(event);
}
}
event::Event::MainEventsCleared => {
// If no relevant events happened, we can simply skip this
if events.is_empty() {
return;
}
// We need to:
// 1. Process events of our user interface.
// 2. Update state as a result of any interaction.
// 3. Generate a new output for our renderer.
// First, we build our user interface.
let mut user_interface = UserInterface::build(
controls.view(),
Size::new(logical_size.width, logical_size.height),
cache.take().unwrap(),
&mut renderer,
);
// Then, we process the events, obtaining messages in return.
let messages = user_interface.update(
events.drain(..),
clipboard.as_ref().map(|c| c as _),
&renderer,
);
let user_interface = if messages.is_empty() {
// If there are no messages, no interactions we care about have
// happened. We can simply leave our user interface as it is.
user_interface
} else {
// If there are messages, we need to update our state
// accordingly and rebuild our user interface.
// We can only do this if we drop our user interface first
// by turning it into its cache.
cache = Some(user_interface.into_cache());
// In this example, `Controls` is the only part that cares
// about messages, so updating our state is pretty
// straightforward.
for message in messages {
controls.update(message, &mut state, &device);
}
// Once the state has been changed, we rebuild our updated
// user interface.
UserInterface::build(
controls.view(),
Size::new(logical_size.width, logical_size.height),
cache.take().unwrap(),
&mut renderer,
)
};
// Finally, we just need to draw a new output for our renderer,
output = user_interface.draw(&mut renderer);
// update our cache,
cache = Some(user_interface.into_cache());
// and request a redraw
window.request_redraw();
}
event::Event::RedrawRequested(_) => {
if resized {
let size = window.inner_size();
ui_swap =
SwapChain::new(&device, &surface, TEXTURE_FORMAT, size.width, size.height);
ui_swap_desc = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
format: TEXTURE_FORMAT,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Vsync,
};
state.apply_update(&device, render::Update {
swap_desc: Some(&ui_swap_desc),
.. Default::default()
});
resized = false;
}
let (frame, viewport) = ui_swap.next_frame();
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
state.update(&mut encoder, &device);
state.render(&frame.view, None, &mut encoder);
// And then iced on top
let mouse_cursor = renderer.draw(
&mut device,
&mut encoder,
Target {
texture: &frame.view,
viewport,
},
&output,
window.scale_factor(),
&[""],
);
queue.submit(&[encoder.finish()]);
// And update the mouse cursor
window.set_cursor_icon(iced_winit::conversion::mouse_cursor(mouse_cursor));
}
_ => (),
}
});
}
fn create_multisampled_framebuffer(
device: &wgpu::Device,
sc_desc: &wgpu::SwapChainDescriptor,
sample_count: u32,
) -> wgpu::TextureView {
let multisampled_texture_extent = wgpu::Extent3d {
width: sc_desc.width,
height: sc_desc.height,
depth: 1,
};
let multisampled_frame_descriptor = &wgpu::TextureDescriptor {
size: multisampled_texture_extent,
array_layer_count: 1,
mip_level_count: 1,
sample_count,
dimension: wgpu::TextureDimension::D2,
format: sc_desc.format,
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
};
device
.create_texture(multisampled_frame_descriptor)
.create_default_view()
}
fn gen_polyhedron() -> render::Mesh {
use super::seeds::Platonic;
use generator::Generator;
type MeshVertex = render::Vertex;
let seed = Platonic::dodecahedron(2.0);
let generator = Generator::seed(seed);
generator.to_mesh()
}
|
use crate::day9::{intcode_computer, parse_program};
use std::collections::HashMap;
#[aoc_generator(day11, part1)]
fn p1_generator(input: &str) -> Vec<i64> {
parse_program(input)
}
#[derive(Debug)]
pub enum Direction {
Up,
Down,
Left,
Right,
}
impl Direction {
pub fn rotate_right(&self) -> Self {
match *self {
Direction::Up => Direction::Right,
Direction::Right => Direction::Down,
Direction::Down => Direction::Left,
Direction::Left => Direction::Up,
}
}
pub fn rotate_left(&self) -> Self {
match *self {
Direction::Up => Direction::Left,
Direction::Left => Direction::Down,
Direction::Down => Direction::Right,
Direction::Right => Direction::Up,
}
}
pub fn dx(&self) -> i64 {
match *self {
Direction::Up => 0,
Direction::Left => -1,
Direction::Down => 0,
Direction::Right => 1,
}
}
pub fn dy(&self) -> i64 {
match *self {
Direction::Up => -1,
Direction::Left => 0,
Direction::Down => 1,
Direction::Right => 0,
}
}
}
#[derive(Debug, Clone, Copy)]
enum Color {
Black,
White,
}
impl Into<i64> for Color {
fn into(self) -> i64 {
match self {
Color::Black => 0,
Color::White => 1,
}
}
}
impl From<i64> for Color {
fn from(num: i64) -> Self {
match num {
0 => Color::Black,
1 => Color::White,
e => panic!("Unrecognized color {:?}", e),
}
}
}
#[aoc(day11, part1)]
fn solve_p1(tape: &[i64]) -> usize {
let mut robot_x = 0i64;
let mut robot_y = 0i64;
let mut robot_dir = Direction::Up;
let mut panels: HashMap<(i64, i64), Color> = HashMap::new();
let mut tape = tape.to_owned();
let mut i = 0;
let mut relative_base = 0;
loop {
let paint = intcode_computer(&mut tape, &mut i, &mut relative_base, || {
(*panels.get(&(robot_x, robot_y)).unwrap_or(&Color::Black)).into()
});
if paint == -1 {
break;
}
panels.insert((robot_x, robot_y), paint.into());
let dir = intcode_computer(&mut tape, &mut i, &mut relative_base, || 0);
match dir {
0 => robot_dir = robot_dir.rotate_left(),
1 => robot_dir = robot_dir.rotate_right(),
e => panic!("Unknown direction to turn: {:?}", e),
}
robot_x += robot_dir.dx();
robot_y += robot_dir.dy();
}
panels.len()
}
#[aoc_generator(day11, part2)]
fn p2_generator(input: &str) -> Vec<i64> {
parse_program(input)
}
#[aoc(day11, part2)]
fn solve_p2(tape: &[i64]) -> usize {
let mut robot_x = 0i64;
let mut robot_y = 0i64;
let mut robot_dir = Direction::Up;
let mut panels: HashMap<(i64, i64), Color> = HashMap::new();
panels.insert((robot_x, robot_y), Color::White);
let mut tape = tape.to_owned();
let mut i = 0;
let mut relative_base = 0;
loop {
let paint = intcode_computer(&mut tape, &mut i, &mut relative_base, || {
(*panels.get(&(robot_x, robot_y)).unwrap_or(&Color::Black)).into()
});
if paint == -1 {
break;
}
panels.insert((robot_x, robot_y), paint.into());
let dir = intcode_computer(&mut tape, &mut i, &mut relative_base, || 1);
match dir {
0 => robot_dir = robot_dir.rotate_left(),
1 => robot_dir = robot_dir.rotate_right(),
e => panic!("Unknown direction to turn: {:?}", e),
}
robot_x += robot_dir.dx();
robot_y += robot_dir.dy();
}
for y in 0..10 {
for x in 0..50 {
let color = *panels.get(&(x, y)).unwrap_or(&Color::Black);
print!(
"{}",
match color {
Color::White => "■",
Color::Black => " ",
}
)
}
println!();
}
0
}
|
impl Solution {
pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
for i in 0..nums.len() {
if nums[i] >= target {
return i as i32;
}
}
nums.len() as i32
}
}
|
use crate::compiler::InterpreterCompiler;
use cranelift::prelude::*;
pub struct AddStub;
impl AddStub {
pub fn generate(
ic: &mut InterpreterCompiler<'_>,
frame: Value,
left: Value,
right: Value,
) -> Value {
let left_not_int = ic.create_block();
let right_not_int = ic.create_block();
let finish = ic.create_block();
let slowpath = ic.create_block();
let right_is_double = ic.create_block();
let right_was_integer = ic.create_block();
let fop = ic.create_block();
ic.append_block_param(right_was_integer, types::F64);
ic.append_block_param(right_was_integer, types::F64);
ic.append_block_param(right_is_double, types::F64);
ic.append_block_param(right_is_double, types::I64);
ic.append_block_param(slowpath, types::I64);
ic.append_block_param(slowpath, types::I64);
ic.append_block_param(slowpath, types::I64);
ic.append_block_param(finish, types::I64);
ic.append_block_param(left_not_int, types::I64);
ic.append_block_param(left_not_int, types::I64);
ic.append_block_param(right_not_int, types::I64);
ic.append_block_param(right_not_int, types::I64);
ic.append_block_param(fop, types::F64);
ic.append_block_param(fop, types::F64);
let is_i = ic.is_int32(left);
ic.ins().brz(is_i, left_not_int, &[left, right]);
let next = ic.create_block();
ic.ins().jump(next, &[]);
ic.switch_to_block(next);
let is_i = ic.is_int32(right);
ic.ins().brz(is_i, right_not_int, &[left, right]);
let next = ic.create_block();
ic.ins().jump(next, &[]);
ic.switch_to_block(next);
let ileft = ic.as_int32(left);
let iright = ic.as_int32(right);
let (result, flags) = ic.ins().iadd_ifcout(ileft, iright);
ic.ins()
.brif(IntCC::Overflow, flags, slowpath, &[frame, left, right]);
ic.fall(&[types::I32], &[result]);
let bb = ic.current_block().unwrap();
let p = ic.block_params(bb)[0];
let res = ic.new_int(p);
ic.ins().jump(finish, &[res]);
ic.switch_to_block(left_not_int);
{
let left = ic.block_params(left_not_int)[0];
let right = ic.block_params(left_not_int)[1];
let left_not_number = ic.is_number(left);
let right_not_number = ic.is_number(right);
ic.ins()
.brz(left_not_number, slowpath, &[frame, left, right]);
let next = ic.create_block();
ic.ins().jump(next, &[]);
ic.switch_to_block(next);
ic.ins()
.brz(right_not_number, slowpath, &[frame, left, right]);
let next = ic.create_block();
ic.ins().jump(next, &[]);
ic.switch_to_block(next);
let res = ic.as_double(left);
let is_int32 = ic.is_int32(right);
ic.ins().brz(is_int32, right_is_double, &[res, right]);
let next = ic.create_block();
ic.ins().jump(next, &[]);
ic.switch_to_block(next);
let as_i = ic.ins().ireduce(types::I32, right);
let as_d = ic.ins().fcvt_from_sint(types::F64, as_i);
ic.ins().jump(right_was_integer, &[res, as_d]);
ic.switch_to_block(right_not_int);
let left = ic.block_params(right_not_int)[0];
let right = ic.block_params(right_not_int)[1];
let right_not_number = ic.is_number(right);
ic.ins()
.brz(right_not_number, slowpath, &[frame, left, right]);
let next = ic.create_block();
ic.ins().jump(next, &[]);
ic.switch_to_block(next);
let as_i = ic.ins().ireduce(types::I32, left);
let as_d = ic.ins().fcvt_from_sint(types::F64, as_i);
ic.ins().jump(right_is_double, &[as_d, right]);
ic.switch_to_block(right_is_double);
let left = ic.block_params(right_is_double)[0];
let right = ic.block_params(right_is_double)[1];
let as_d = ic.as_double(right);
ic.ins().jump(fop, &[left, as_d]);
}
ic.switch_to_block(right_was_integer);
let left = ic.block_params(right_was_integer)[0];
let right = ic.block_params(right_was_integer)[1];
ic.ins().jump(fop, &[left, right]);
ic.switch_to_block(fop);
let left = ic.block_params(fop)[0];
let right = ic.block_params(fop)[1];
let res = ic.ins().fadd(left, right);
let boxed = ic.new_double(res);
ic.ins().jump(finish, &[boxed]);
ic.switch_to_block(slowpath);
let v = ic.undefined_value();
ic.ins().jump(finish, &[v]);
ic.switch_to_block(finish);
let res = ic.block_params(finish)[0];
res
}
}
|
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Stateless CSRF protection middleware based on a chacha20-poly1305 encrypted
//! and signed token
use std::time::SystemTime;
use async_trait::async_trait;
use chacha20poly1305::{
aead::{generic_array::GenericArray, Aead, NewAead},
ChaCha20Poly1305,
};
use chrono::{DateTime, Duration, Utc};
use data_encoding::BASE64URL_NOPAD;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, TimestampSeconds};
use tide::http::{
cookies::{CookieBuilder, SameSite},
Cookie,
};
#[serde_as]
#[derive(Serialize, Deserialize)]
pub struct UnencryptedToken {
#[serde_as(as = "TimestampSeconds<i64>")]
expiration: DateTime<Utc>,
token: [u8; 32],
}
impl UnencryptedToken {
/// Create a new token from a defined value valid for a specified duration
fn new(token: [u8; 32], ttl: Duration) -> Self {
let expiration = Utc::now() + ttl;
Self { expiration, token }
}
/// Generate a new random token valid for a specified duration
fn generate(ttl: Duration) -> Self {
let token = rand::random();
Self::new(token, ttl)
}
/// Generate a new token with the same value but an up to date expiration
fn refresh(self, ttl: Duration) -> Self {
Self::new(self.token, ttl)
}
/// Encrypt the token with the given chacha20-poly1305 key
fn encrypt(&self, key: &[u8; 32]) -> anyhow::Result<EncryptedToken> {
let key = GenericArray::from_slice(key);
let aead = ChaCha20Poly1305::new(key);
// Serialize the token
let message = bincode::serialize(self)?;
// Generate a nonce
let nonce: [u8; 12] = rand::random();
// And encrypt everything
let ciphertext = aead.encrypt(GenericArray::from_slice(&nonce[..]), &message[..])?;
// Return the encrypted token + nonce
Ok(EncryptedToken { nonce, ciphertext })
}
/// Get the value to include in HTML forms
pub fn form_value(&self) -> String {
BASE64URL_NOPAD.encode(&self.token[..])
}
/// Verifies that the value got from an HTML form matches this token
pub fn verify_form_value(&self, form_value: &str) -> anyhow::Result<()> {
let form_value = BASE64URL_NOPAD.decode(form_value.as_bytes())?;
if self.token[..] == form_value {
Ok(())
} else {
Err(anyhow::anyhow!("CSRF token mismatch"))
}
}
fn verify_expiration(self) -> anyhow::Result<Self> {
if Utc::now() < self.expiration {
Ok(self)
} else {
Err(anyhow::anyhow!("CSRF token expired"))
}
}
fn to_cookie_builder<'c, 'n: 'c>(
&self,
name: &'n str,
key: &[u8; 32],
) -> anyhow::Result<CookieBuilder<'c>> {
let value = self.encrypt(key)?.to_cookie_value()?;
// Converting expiration time from `chrono` to `time` via native `SystemTime`
let expires: SystemTime = self.expiration.into();
Ok(Cookie::build(name, value)
.expires(expires.into())
.http_only(true)
.same_site(SameSite::Strict))
}
fn from_cookie(cookie: &Cookie, key: &[u8; 32]) -> anyhow::Result<Self> {
let encrypted = EncryptedToken::from_cookie_value(cookie.value())?;
let token = encrypted.decrypt(key)?;
Ok(token)
}
}
#[derive(Serialize, Deserialize)]
struct EncryptedToken {
nonce: [u8; 12],
ciphertext: Vec<u8>,
}
impl EncryptedToken {
/// Decrypt the content of the token from a given key
fn decrypt(&self, key: &[u8; 32]) -> anyhow::Result<UnencryptedToken> {
let key = GenericArray::from_slice(key);
let aead = ChaCha20Poly1305::new(key);
let message = aead.decrypt(
GenericArray::from_slice(&self.nonce[..]),
&self.ciphertext[..],
)?;
let token = bincode::deserialize(&message)?;
Ok(token)
}
/// Encode the token to be then saved as a cookie
fn to_cookie_value(&self) -> anyhow::Result<String> {
let raw = bincode::serialize(self)?;
Ok(BASE64URL_NOPAD.encode(&raw))
}
/// Extract the encrypted token from a cookie
fn from_cookie_value(value: &str) -> anyhow::Result<Self> {
let raw = BASE64URL_NOPAD.decode(value.as_bytes())?;
let content = bincode::deserialize(&raw)?;
Ok(content)
}
}
#[derive(Debug, Clone)]
pub struct Middleware {
key: [u8; 32],
ttl: Duration,
cookie_name: String,
}
impl Middleware {
/// Create a new CSRF protection middleware from a key, cookie name and TTL
pub fn new(key: [u8; 32], cookie_name: String, ttl: Duration) -> Self {
Self {
key,
ttl,
cookie_name,
}
}
}
#[async_trait]
impl<State> tide::Middleware<State> for Middleware
where
State: Clone + Send + Sync + 'static,
{
async fn handle(
&self,
mut request: tide::Request<State>,
next: tide::Next<'_, State>,
) -> tide::Result {
let csrf_token = request
// Get the CSRF cookie
.cookie(&self.cookie_name)
// Try decrypting it
.map(|cookie| UnencryptedToken::from_cookie(&cookie, &self.key))
// If there was an error decrypting it, bail out here
.transpose()?
// Verify it's TTL (but do not hard-error if it expired)
.and_then(|token| token.verify_expiration().ok())
.map_or_else(
// Generate a new token if no valid one were found
|| UnencryptedToken::generate(self.ttl),
// Else, refresh the expiration of the cookie
|token| token.refresh(self.ttl),
);
// Build the cookie before calling the next stage since the owned csrf_token has
// to be passed as a request extension
let cookie = csrf_token
.to_cookie_builder(&self.cookie_name, &self.key)?
.finish()
.into_owned();
request.set_ext(csrf_token);
let mut response = next.run(request).await;
response.insert_cookie(cookie);
Ok(response)
}
}
|
use bevy::prelude::{Handle, Texture, TextureAtlas, Vec2};
use bevy::sprite::Rect;
pub fn from_grid_with_offset(
texture: Handle<Texture>,
tile_size: Vec2,
offset: Vec2,
rows: usize,
columns: usize,
) -> TextureAtlas {
let mut sprites = Vec::new();
for y in 0..columns {
for x in 0..rows {
let rect_min = Vec2::new(
offset.x + tile_size.x * x as f32,
offset.y + tile_size.y * y as f32,
);
sprites.push(Rect {
min: rect_min,
max: Vec2::new(rect_min.x + tile_size.x, rect_min.y + tile_size.y),
})
}
}
TextureAtlas {
size: Vec2::new(512.0, 512.0),
textures: sprites,
texture,
texture_handles: None,
}
}
pub fn from_tiles(
texture: Handle<Texture>,
tile_size: Vec2,
tiles_x0y0: Vec<Vec2>,
) -> TextureAtlas {
let mut sprites = Vec::new();
for x0y0 in tiles_x0y0 {
sprites.push(Rect {
min: x0y0,
max: Vec2::new(x0y0.x + tile_size.x, x0y0.y + tile_size.y),
})
}
TextureAtlas {
size: Vec2::new(512.0, 512.0),
textures: sprites,
texture,
texture_handles: None,
}
}
|
#[derive(Debug, Copy, Clone)]
pub struct Point {
pub x: i64,
pub y: i64,
pub z: i64,
}
impl Point {
pub fn new(x: i64, y: i64, z: i64) -> Point {
Point{x, y, z}
}
}
|
extern crate sdl2;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn run(mut render: &sdl2::render::Renderer, mut event_pump: sdl2::EventPump)
{
println!("Game is running!");
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {
break 'running;
},
_ => {}
}
}
// game logic
}
}
|
use std::sync::Arc;
use eyre::Report;
use prometheus::core::Collector;
use twilight_model::application::interaction::ApplicationCommand;
use crate::{
commands::MyCommand,
embeds::{CommandCounterEmbed, EmbedData},
pagination::{CommandCountPagination, Pagination},
util::{numbers, MessageExt},
BotResult, CommandData, Context,
};
#[command]
#[short_desc("List of popular commands")]
#[long_desc("Let me show you my most popular commands since my last reboot")]
async fn commands(ctx: Arc<Context>, data: CommandData) -> BotResult<()> {
let owner = data.author()?.id;
let mut cmds: Vec<_> = ctx.stats.command_counts.message_commands.collect()[0]
.get_metric()
.iter()
.map(|metric| {
let name = metric.get_label()[0].get_value();
let count = metric.get_counter().get_value();
(name.to_owned(), count as u32)
})
.collect();
cmds.sort_unstable_by(|&(_, a), &(_, b)| b.cmp(&a));
// Prepare embed data
let boot_time = ctx.stats.start_time;
let sub_vec = cmds
.iter()
.take(15)
.map(|(name, amount)| (name, *amount))
.collect();
let pages = numbers::div_euclid(15, cmds.len());
// Creating the embed
let embed_data = CommandCounterEmbed::new(sub_vec, &boot_time, 1, (1, pages));
let builder = embed_data.into_builder().build().into();
let response = data.create_message(&ctx, builder).await?.model().await?;
// Pagination
let pagination = CommandCountPagination::new(&ctx, response, cmds);
tokio::spawn(async move {
if let Err(err) = pagination.start(&ctx, owner, 90).await {
warn!("{:?}", Report::new(err));
}
});
Ok(())
}
pub async fn slash_commands(ctx: Arc<Context>, command: ApplicationCommand) -> BotResult<()> {
commands(ctx, command.into()).await
}
pub fn define_commands() -> MyCommand {
MyCommand::new("commands", "Display a list of popular commands")
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::FIFOPTR {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct FIFO1REMR {
bits: u8,
}
impl FIFO1REMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct FIFO1SIZR {
bits: u8,
}
impl FIFO1SIZR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct FIFO0REMR {
bits: u8,
}
impl FIFO0REMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct FIFO0SIZR {
bits: u8,
}
impl FIFO0SIZR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _FIFO1REMW<'a> {
w: &'a mut W,
}
impl<'a> _FIFO1REMW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 24;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FIFO1SIZW<'a> {
w: &'a mut W,
}
impl<'a> _FIFO1SIZW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FIFO0REMW<'a> {
w: &'a mut W,
}
impl<'a> _FIFO0REMW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FIFO0SIZW<'a> {
w: &'a mut W,
}
impl<'a> _FIFO0SIZW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 24:31 - The number of remaining data bytes slots currently in FIFO 1 (written by interface, read by MCU)"]
#[inline]
pub fn fifo1rem(&self) -> FIFO1REMR {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 24;
((self.bits >> OFFSET) & MASK as u32) as u8
};
FIFO1REMR { bits }
}
#[doc = "Bits 16:23 - The number of valid data bytes currently in FIFO 1 (written by interface, read by MCU)"]
#[inline]
pub fn fifo1siz(&self) -> FIFO1SIZR {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) as u8
};
FIFO1SIZR { bits }
}
#[doc = "Bits 8:15 - The number of remaining data bytes slots currently in FIFO 0 (written by MCU, read by interface)"]
#[inline]
pub fn fifo0rem(&self) -> FIFO0REMR {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
};
FIFO0REMR { bits }
}
#[doc = "Bits 0:7 - The number of valid data bytes currently in the FIFO 0 (written by MCU, read by interface)"]
#[inline]
pub fn fifo0siz(&self) -> FIFO0SIZR {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
FIFO0SIZR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 24:31 - The number of remaining data bytes slots currently in FIFO 1 (written by interface, read by MCU)"]
#[inline]
pub fn fifo1rem(&mut self) -> _FIFO1REMW {
_FIFO1REMW { w: self }
}
#[doc = "Bits 16:23 - The number of valid data bytes currently in FIFO 1 (written by interface, read by MCU)"]
#[inline]
pub fn fifo1siz(&mut self) -> _FIFO1SIZW {
_FIFO1SIZW { w: self }
}
#[doc = "Bits 8:15 - The number of remaining data bytes slots currently in FIFO 0 (written by MCU, read by interface)"]
#[inline]
pub fn fifo0rem(&mut self) -> _FIFO0REMW {
_FIFO0REMW { w: self }
}
#[doc = "Bits 0:7 - The number of valid data bytes currently in the FIFO 0 (written by MCU, read by interface)"]
#[inline]
pub fn fifo0siz(&mut self) -> _FIFO0SIZW {
_FIFO0SIZW { w: self }
}
}
|
use {DocumentId, DocumentPath, Error, IntoDatabasePath, Revision, serde, std};
use document::WriteDocumentResponse;
use transport::{JsonResponse, JsonResponseDecoder, Request, StatusCode, Transport};
pub struct CreateDocument<'a, T, P, C>
where
C: serde::Serialize + 'a,
P: IntoDatabasePath,
T: Transport + 'a,
{
transport: &'a T,
db_path: Option<P>,
content: &'a C,
doc_id: Option<DocumentId>,
}
impl<'a, C, P, T> CreateDocument<'a, T, P, C>
where
C: serde::Serialize + 'a,
P: IntoDatabasePath,
T: Transport + 'a,
{
#[doc(hidden)]
pub fn new(transport: &'a T, db_path: P, content: &'a C) -> Self {
CreateDocument {
transport: transport,
db_path: Some(db_path),
content: content,
doc_id: None,
}
}
pub fn with_document_id<D>(mut self, doc_id: D) -> Self
where
D: Into<DocumentId>,
{
self.doc_id = Some(doc_id.into());
self
}
pub fn run(mut self) -> Result<(DocumentId, Revision), Error> {
self.transport.send(
try!(self.make_request()),
JsonResponseDecoder::new(handle_response),
)
}
fn make_request(&mut self) -> Result<Request, Error> {
let db_path = try!(
std::mem::replace(&mut self.db_path, None)
.unwrap()
.into_database_path()
);
let request = try!(
match self.doc_id {
None => self.transport.post(db_path.iter()),
Some(ref doc_id) => {
let doc_path = DocumentPath::from((db_path, doc_id.clone()));
self.transport.put(doc_path.iter())
}
}.with_accept_json()
.with_json_content(self.content)
);
Ok(request)
}
}
fn handle_response(response: JsonResponse) -> Result<(DocumentId, Revision), Error> {
match response.status_code() {
StatusCode::Created => {
let content: WriteDocumentResponse = try!(response.decode_content());
Ok((content.doc_id, content.revision))
}
StatusCode::Conflict => Err(Error::document_conflict(&response)),
StatusCode::Unauthorized => Err(Error::unauthorized(&response)),
_ => Err(Error::server_response(&response)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use {DocumentId, Error, Revision, serde_json};
use transport::{JsonResponseBuilder, MockTransport, StatusCode, Transport};
#[test]
fn make_request_default() {
let doc_content = serde_json::builder::ObjectBuilder::new()
.insert("field", 42)
.build();
let transport = MockTransport::new();
let expected = transport
.post(vec!["foo"])
.with_accept_json()
.with_json_content(&doc_content)
.unwrap();
let got = {
let mut action = CreateDocument::new(&transport, "/foo", &doc_content);
action.make_request().unwrap()
};
assert_eq!(expected, got);
}
#[test]
fn make_request_with_document_id() {
let doc_content = serde_json::builder::ObjectBuilder::new()
.insert("field", 42)
.build();
let transport = MockTransport::new();
let expected = transport
.put(vec!["foo", "bar"])
.with_accept_json()
.with_json_content(&doc_content)
.unwrap();
let got = {
let mut action = CreateDocument::new(&transport, "/foo", &doc_content).with_document_id("bar");
action.make_request().unwrap()
};
assert_eq!(expected, got);
}
#[test]
fn handle_response_created() {
let response = JsonResponseBuilder::new(StatusCode::Created)
.with_json_content_raw(
r#"{"ok":true, "id": "foo", "rev": "1-1234567890abcdef1234567890abcdef"}"#,
)
.unwrap();
let expected = (
DocumentId::from("foo"),
Revision::parse("1-1234567890abcdef1234567890abcdef").unwrap(),
);
let got = super::handle_response(response).unwrap();
assert_eq!(expected, got);
}
#[test]
fn take_response_conflict() {
let response = JsonResponseBuilder::new(StatusCode::Conflict)
.with_json_content_raw(
r#"{"error":"conflict","reason":"Document update conflict."}"#,
)
.unwrap();
match super::handle_response(response) {
Err(Error::DocumentConflict(ref error_response))
if error_response.error() == "conflict" && error_response.reason() == "Document update conflict." => (),
x @ _ => unexpected_result!(x),
}
}
#[test]
fn take_response_unauthorized() {
let response = JsonResponseBuilder::new(StatusCode::Unauthorized)
.with_json_content_raw(
r#"{"error":"unauthorized","reason":"Authentication required."}"#,
)
.unwrap();
match super::handle_response(response) {
Err(Error::Unauthorized(ref error_response))
if error_response.error() == "unauthorized" && error_response.reason() == "Authentication required." =>
(),
x @ _ => unexpected_result!(x),
}
}
}
|
/// CreateLabelOption options for creating a label
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CreateLabelOption {
pub color: String,
pub description: Option<String>,
pub name: String,
}
impl CreateLabelOption {
/// Create a builder for this object.
#[inline]
pub fn builder() -> CreateLabelOptionBuilder<crate::generics::MissingColor, crate::generics::MissingName> {
CreateLabelOptionBuilder {
body: Default::default(),
_color: core::marker::PhantomData,
_name: core::marker::PhantomData,
}
}
#[inline]
pub fn org_create_label() -> CreateLabelOptionPostBuilder<crate::generics::MissingOrg, crate::generics::MissingColor, crate::generics::MissingName> {
CreateLabelOptionPostBuilder {
inner: Default::default(),
_param_org: core::marker::PhantomData,
_color: core::marker::PhantomData,
_name: core::marker::PhantomData,
}
}
#[inline]
pub fn issue_create_label() -> CreateLabelOptionPostBuilder1<crate::generics::MissingOwner, crate::generics::MissingRepo, crate::generics::MissingColor, crate::generics::MissingName> {
CreateLabelOptionPostBuilder1 {
inner: Default::default(),
_param_owner: core::marker::PhantomData,
_param_repo: core::marker::PhantomData,
_color: core::marker::PhantomData,
_name: core::marker::PhantomData,
}
}
}
impl Into<CreateLabelOption> for CreateLabelOptionBuilder<crate::generics::ColorExists, crate::generics::NameExists> {
fn into(self) -> CreateLabelOption {
self.body
}
}
impl Into<CreateLabelOption> for CreateLabelOptionPostBuilder<crate::generics::OrgExists, crate::generics::ColorExists, crate::generics::NameExists> {
fn into(self) -> CreateLabelOption {
self.inner.body
}
}
impl Into<CreateLabelOption> for CreateLabelOptionPostBuilder1<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ColorExists, crate::generics::NameExists> {
fn into(self) -> CreateLabelOption {
self.inner.body
}
}
/// Builder for [`CreateLabelOption`](./struct.CreateLabelOption.html) object.
#[derive(Debug, Clone)]
pub struct CreateLabelOptionBuilder<Color, Name> {
body: self::CreateLabelOption,
_color: core::marker::PhantomData<Color>,
_name: core::marker::PhantomData<Name>,
}
impl<Color, Name> CreateLabelOptionBuilder<Color, Name> {
#[inline]
pub fn color(mut self, value: impl Into<String>) -> CreateLabelOptionBuilder<crate::generics::ColorExists, Name> {
self.body.color = value.into();
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn description(mut self, value: impl Into<String>) -> Self {
self.body.description = Some(value.into());
self
}
#[inline]
pub fn name(mut self, value: impl Into<String>) -> CreateLabelOptionBuilder<Color, crate::generics::NameExists> {
self.body.name = value.into();
unsafe { std::mem::transmute(self) }
}
}
/// Builder created by [`CreateLabelOption::org_create_label`](./struct.CreateLabelOption.html#method.org_create_label) method for a `POST` operation associated with `CreateLabelOption`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct CreateLabelOptionPostBuilder<Org, Color, Name> {
inner: CreateLabelOptionPostBuilderContainer,
_param_org: core::marker::PhantomData<Org>,
_color: core::marker::PhantomData<Color>,
_name: core::marker::PhantomData<Name>,
}
#[derive(Debug, Default, Clone)]
struct CreateLabelOptionPostBuilderContainer {
body: self::CreateLabelOption,
param_org: Option<String>,
}
impl<Org, Color, Name> CreateLabelOptionPostBuilder<Org, Color, Name> {
/// name of the organization
#[inline]
pub fn org(mut self, value: impl Into<String>) -> CreateLabelOptionPostBuilder<crate::generics::OrgExists, Color, Name> {
self.inner.param_org = Some(value.into());
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn color(mut self, value: impl Into<String>) -> CreateLabelOptionPostBuilder<Org, crate::generics::ColorExists, Name> {
self.inner.body.color = value.into();
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn description(mut self, value: impl Into<String>) -> Self {
self.inner.body.description = Some(value.into());
self
}
#[inline]
pub fn name(mut self, value: impl Into<String>) -> CreateLabelOptionPostBuilder<Org, Color, crate::generics::NameExists> {
self.inner.body.name = value.into();
unsafe { std::mem::transmute(self) }
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreateLabelOptionPostBuilder<crate::generics::OrgExists, crate::generics::ColorExists, crate::generics::NameExists> {
type Output = crate::label::Label;
const METHOD: http::Method = http::Method::POST;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/orgs/{org}/labels", org=self.inner.param_org.as_ref().expect("missing parameter org?")).into()
}
fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> {
use crate::client::Request;
Ok(req
.json(&self.inner.body))
}
}
impl crate::client::ResponseWrapper<crate::label::Label, CreateLabelOptionPostBuilder<crate::generics::OrgExists, crate::generics::ColorExists, crate::generics::NameExists>> {
#[inline]
pub fn message(&self) -> Option<String> {
self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
#[inline]
pub fn url(&self) -> Option<String> {
self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
}
/// Builder created by [`CreateLabelOption::issue_create_label`](./struct.CreateLabelOption.html#method.issue_create_label) method for a `POST` operation associated with `CreateLabelOption`.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct CreateLabelOptionPostBuilder1<Owner, Repo, Color, Name> {
inner: CreateLabelOptionPostBuilder1Container,
_param_owner: core::marker::PhantomData<Owner>,
_param_repo: core::marker::PhantomData<Repo>,
_color: core::marker::PhantomData<Color>,
_name: core::marker::PhantomData<Name>,
}
#[derive(Debug, Default, Clone)]
struct CreateLabelOptionPostBuilder1Container {
body: self::CreateLabelOption,
param_owner: Option<String>,
param_repo: Option<String>,
}
impl<Owner, Repo, Color, Name> CreateLabelOptionPostBuilder1<Owner, Repo, Color, Name> {
/// owner of the repo
#[inline]
pub fn owner(mut self, value: impl Into<String>) -> CreateLabelOptionPostBuilder1<crate::generics::OwnerExists, Repo, Color, Name> {
self.inner.param_owner = Some(value.into());
unsafe { std::mem::transmute(self) }
}
/// name of the repo
#[inline]
pub fn repo(mut self, value: impl Into<String>) -> CreateLabelOptionPostBuilder1<Owner, crate::generics::RepoExists, Color, Name> {
self.inner.param_repo = Some(value.into());
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn color(mut self, value: impl Into<String>) -> CreateLabelOptionPostBuilder1<Owner, Repo, crate::generics::ColorExists, Name> {
self.inner.body.color = value.into();
unsafe { std::mem::transmute(self) }
}
#[inline]
pub fn description(mut self, value: impl Into<String>) -> Self {
self.inner.body.description = Some(value.into());
self
}
#[inline]
pub fn name(mut self, value: impl Into<String>) -> CreateLabelOptionPostBuilder1<Owner, Repo, Color, crate::generics::NameExists> {
self.inner.body.name = value.into();
unsafe { std::mem::transmute(self) }
}
}
impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreateLabelOptionPostBuilder1<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ColorExists, crate::generics::NameExists> {
type Output = crate::label::Label;
const METHOD: http::Method = http::Method::POST;
fn rel_path(&self) -> std::borrow::Cow<'static, str> {
format!("/repos/{owner}/{repo}/labels", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?")).into()
}
fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> {
use crate::client::Request;
Ok(req
.json(&self.inner.body))
}
}
impl crate::client::ResponseWrapper<crate::label::Label, CreateLabelOptionPostBuilder1<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ColorExists, crate::generics::NameExists>> {
#[inline]
pub fn message(&self) -> Option<String> {
self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
#[inline]
pub fn url(&self) -> Option<String> {
self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok())
}
}
|
use super::{chunk_type::*, *};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::fmt;
///chunkHeader represents a SCTP Chunk header, defined in https://tools.ietf.org/html/rfc4960#section-3.2
///The figure below illustrates the field format for the chunks to be
///transmitted in the SCTP packet. Each chunk is formatted with a Chunk
///Type field, a chunk-specific Flag field, a Chunk Length field, and a
///Value field.
///
/// 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
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| Chunk Type | Chunk Flags | Chunk Length |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///| |
///| Chunk Value |
///| |
///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#[derive(Debug, Clone)]
pub(crate) struct ChunkHeader {
pub(crate) typ: ChunkType,
pub(crate) flags: u8,
pub(crate) value_length: u16,
}
pub(crate) const CHUNK_HEADER_SIZE: usize = 4;
/// makes ChunkHeader printable
impl fmt::Display for ChunkHeader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.typ)
}
}
impl Chunk for ChunkHeader {
fn header(&self) -> ChunkHeader {
self.clone()
}
fn unmarshal(raw: &Bytes) -> Result<Self, Error> {
if raw.len() < CHUNK_HEADER_SIZE {
return Err(Error::ErrChunkHeaderTooSmall);
}
let reader = &mut raw.clone();
let typ = ChunkType(reader.get_u8());
let flags = reader.get_u8();
let length = reader.get_u16();
if length < CHUNK_HEADER_SIZE as u16 {
return Err(Error::ErrChunkHeaderInvalidLength);
}
// Length includes Chunk header
let value_length = length as isize - CHUNK_HEADER_SIZE as isize;
let length_after_value = raw.len() as isize - length as isize;
if length_after_value < 0 {
return Err(Error::ErrChunkHeaderNotEnoughSpace);
} else if length_after_value < 4 {
// https://tools.ietf.org/html/rfc4960#section-3.2
// The Chunk Length field does not count any chunk PADDING.
// Chunks (including Type, Length, and Value fields) are padded out
// by the sender with all zero bytes to be a multiple of 4 bytes
// long. This PADDING MUST NOT be more than 3 bytes in total. The
// Chunk Length value does not include terminating PADDING of the
// chunk. However, it does include PADDING of any variable-length
// parameter except the last parameter in the chunk. The receiver
// MUST ignore the PADDING.
for i in (1..=length_after_value).rev() {
let padding_offset = CHUNK_HEADER_SIZE + (value_length + i - 1) as usize;
if raw[padding_offset] != 0 {
return Err(Error::ErrChunkHeaderPaddingNonZero);
}
}
}
Ok(ChunkHeader {
typ,
flags,
value_length: length - CHUNK_HEADER_SIZE as u16,
})
}
fn marshal_to(&self, writer: &mut BytesMut) -> Result<usize, Error> {
writer.put_u8(self.typ.0);
writer.put_u8(self.flags);
writer.put_u16(self.value_length + CHUNK_HEADER_SIZE as u16);
Ok(writer.len())
}
fn check(&self) -> Result<(), Error> {
Ok(())
}
fn value_length(&self) -> usize {
self.value_length as usize
}
fn as_any(&self) -> &(dyn Any + Send + Sync) {
self
}
}
|
extern crate rand;
use rand::Rng;
use std::io;
struct Hand {
name: String,
cards: Vec<u8>
}
impl Hand {
fn new(name: String) -> Hand {
let mut cards: Vec<u8> = Vec::new();
for _ in 0..2 {
cards.push(rand::thread_rng().gen_range(2, 10));
}
Hand { name, cards }
}
fn count(&self) -> u8 {
let mut card_count = 0;
for card in self.cards.iter() {
card_count += card;
}
card_count
}
fn show(&self) -> () {
println!("{}'s cards:", self.name);
for card in self.cards.iter() {
print!("{} ", card);
}
println!();
println!("Count is {}", self.count());
}
fn draw(&mut self){
self.cards.push(rand::thread_rng().gen_range(2, 10));
}
fn check_lost(&self) -> bool {
self.count() > 21
}
fn draw_until(&mut self, until: u8) {
while self.count() < until {
self.draw();
}
}
}
fn main() {
let mut players_hand = Hand::new("Player".to_string());
let mut dealers_hand = Hand::new("Dealer".to_string());
players_hand.show();
loop {
println!("You can (s)tart or (d)raw more cards, what is your move?");
let mut choice = String::new();
io::stdin().read_line(&mut choice)
.expect("Failed to read your command!");
let choice = choice.trim();
match choice {
"s" => {
dealers_hand.draw_until(17);
let difference: i8 = players_hand.count() as i8 - dealers_hand.count() as i8;
dealers_hand.show();
if (difference > 0 || dealers_hand.check_lost()) && !players_hand.check_lost() {
println!("You won!!");
} else if difference == 0 {
println!("Its a draw!!");
} else {
println!("You lost!!");
}
break;
},
"d" => {
players_hand.draw();
if players_hand.check_lost() {
println!("You went over 21, you lost!!");
break;
}
players_hand.show();
},
_ => println!()
}
}
}
|
use std::collections::HashMap;
use rocket::response::status;
use rocket_contrib::Json;
use db::project::{Project, ProjectWithStaff};
use db::session::Session;
use db::staff::{NewStaff, Staff};
use db::student::Student;
pub type ErrorResponse = status::Custom<Json<GenericMessage>>;
pub type V1Response<T> = Result<Json<T>, ErrorResponse>;
#[derive(Serialize, Debug)]
pub struct GenericMessage {
pub message: String,
}
#[derive(Deserialize, Debug)]
pub struct LoginMessage {
pub username: String,
pub password: String,
}
#[derive(Serialize, Debug)]
pub struct WhoAmIMessage {
pub email: String,
pub name: String,
pub user_type: String,
}
#[derive(Serialize, Debug)]
pub struct SessionEntry {
pub session: Session,
pub is_current: bool,
}
#[derive(Serialize, Debug)]
pub struct SessionFullList {
pub sessions: Vec<SessionEntry>,
pub projects: Vec<ProjectWithStaff>,
}
#[derive(Serialize, Debug)]
pub struct ProjectList {
pub projects: Vec<ProjectWithStaff>,
}
#[derive(Serialize, Debug)]
pub struct StaffList {
pub staff: Vec<Staff>,
}
#[derive(Deserialize, Debug)]
pub struct NewStaffList {
pub staff: Vec<NewStaff>,
}
#[derive(Serialize, Debug)]
pub struct StudentList {
pub students: Vec<Student>,
}
#[derive(Deserialize, Debug)]
pub struct NewStudentList {
pub students: Vec<NewStudentEntry>,
}
#[derive(Deserialize, Debug)]
pub struct NewStudentEntry {
pub email: String,
pub full_name: String,
}
#[derive(Deserialize, Debug)]
pub struct MarkMessage {
pub id: i32,
}
#[derive(Serialize, Debug)]
pub struct MarkList {
pub projects: Vec<i32>,
}
#[derive(Deserialize, Debug)]
pub struct SelectionList {
pub selections: Vec<SelectionEntry>,
}
#[derive(Deserialize, Debug)]
pub struct SelectionEntry {
pub project: i32,
pub weight: f64,
}
#[derive(Deserialize, Debug)]
pub struct CommentMessage {
pub comment: Option<String>,
}
/// Version of the Project structure with excess material trimmed to save memory and bandwidth when generating reports.
#[derive(Serialize, Debug)]
pub struct ProjectStripped {
pub id: i32,
pub name: String,
pub supervisor_name: String,
pub supervisor_email: String,
}
impl From<Project> for ProjectStripped {
fn from(proj: Project) -> Self {
ProjectStripped {
id: proj.id,
name: proj.name,
supervisor_name: proj.supervisor_name,
supervisor_email: proj.supervisor_email,
}
}
}
#[derive(Serialize, Debug)]
pub struct SessionReport {
pub session: Session,
pub by_student: Vec<SessionReportByStudent>,
pub by_project: Vec<SessionReportByProject>,
pub students: Vec<Student>,
pub projects: Vec<ProjectStripped>,
pub comments: HashMap<i32, String>,
}
#[derive(Serialize, Debug)]
pub struct SessionReportByStudent {
pub student: i32,
/// Array of project IDs, ordered from best to worst.
pub choices: Vec<i32>,
/// Array of bools between each pair of choices - true if equal priority, false otherwise.
/// e.g. `choices = [1, 2, 3]`, `is_eq = [false, true]` for `1 > 2 == 3`
pub is_eq: Vec<bool>,
}
#[derive(Serialize, Debug)]
pub struct SessionReportByProject {
pub project: i32,
/// Map of choice (e.g. 1, 2, 3) -> students with that priority.
pub selections: Vec<Vec<i32>>,
/// Map of choice -> array specifying if the matching student marked this selection equal to another.
pub is_eq: Vec<Vec<bool>>,
}
|
pub struct RailFence {
rails: u32
}
impl RailFence {
pub fn generate_zig_zag(n: u32, length: u32) -> Vec<(u32, u32)> {
let mut col_down = (0..n).collect::<Vec<u32>>();
let mut col_up = (1..n-1).collect::<Vec<u32>>();
let mut counter = 0;
let mut output: Vec<(u32, u32)> = Vec::new();
col_up.reverse();
col_down.extend(col_up);
let mut citer_row = col_down.iter().cycle();
while counter < length {
output.push((*citer_row.next().unwrap(), counter));
counter += 1;
}
output
}
pub fn new(rails: u32) -> RailFence {
RailFence {
rails: rails
}
}
pub fn encode(&self, text: &str) -> String {
let cipher_chars: Vec<char> = text.chars().collect();
let height = self.rails;
let string_length = cipher_chars.len() as usize;
let matrix = RailFence::generate_zig_zag(height, string_length as u32);
let mut matrix_sorted = matrix.clone();
let mut output: Vec<Vec<char>> = Vec::new();
let mut encoded_string: String = String::new();
matrix_sorted.sort_by_key(|x| x.0);
for _x in 0..height {
output.push(vec!['-'; string_length as usize]);
}
for (_index, item) in matrix.iter().enumerate() {
output[item.0 as usize][item.1 as usize] = cipher_chars[_index];
}
for (_index, item) in matrix_sorted.iter().enumerate() {
encoded_string.push(output[item.0 as usize][item.1 as usize]);
}
encoded_string
}
pub fn decode(&self, cipher: &str) -> String {
let cipher_chars: Vec<char> = cipher.chars().collect();
let height = self.rails;
let string_length = cipher_chars.len() as usize;
let matrix = RailFence::generate_zig_zag(height, string_length as u32);
let mut matrix_sorted = matrix.clone();
let mut output: Vec<Vec<char>> = Vec::new();
let mut decoded_string: String = String::new();
matrix_sorted.sort_by_key(|x| x.0);
for _x in 0..height {
output.push(vec!['-'; string_length as usize]);
}
for (index, item) in matrix_sorted.iter().enumerate() {
output[item.0 as usize][item.1 as usize] = cipher_chars[index];
}
for (_index, item) in matrix.iter().enumerate() {
decoded_string.push(output[item.0 as usize][item.1 as usize]);
}
decoded_string
}
}
|
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Macro for creating the tests for the module.
#![cfg(test)]
#[derive(Debug)]
pub struct CallWithDispatchInfo;
impl sp_runtime::traits::Dispatchable for CallWithDispatchInfo {
type Origin = ();
type Trait = ();
type Info = frame_support::weights::DispatchInfo;
type PostInfo = frame_support::weights::PostDispatchInfo;
fn dispatch(self, _origin: Self::Origin) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> {
panic!("Do not use dummy implementation for dispatch.");
}
}
#[macro_export]
macro_rules! decl_tests {
($test:ty, $ext_builder:ty, $existential_deposit:expr) => {
use crate::*;
use sp_runtime::{FixedPointNumber, traits::{SignedExtension, BadOrigin}};
use frame_support::{
assert_noop, assert_ok, assert_err,
traits::{
LockableCurrency, LockIdentifier, WithdrawReason, WithdrawReasons,
Currency, ReservableCurrency, ExistenceRequirement::AllowDeath, StoredMap
}
};
use pallet_transaction_payment::{ChargeTransactionPayment, Multiplier};
use frame_system::RawOrigin;
const ID_1: LockIdentifier = *b"1 ";
const ID_2: LockIdentifier = *b"2 ";
pub type System = frame_system::Module<$test>;
pub type Balances = Module<$test>;
pub const CALL: &<$test as frame_system::Trait>::Call = &$crate::tests::CallWithDispatchInfo;
/// create a transaction info struct from weight. Handy to avoid building the whole struct.
pub fn info_from_weight(w: Weight) -> DispatchInfo {
DispatchInfo { weight: w, ..Default::default() }
}
fn events() -> Vec<Event> {
let evt = System::events().into_iter().map(|evt| evt.event).collect::<Vec<_>>();
System::reset_events();
evt
}
fn last_event() -> Event {
system::Module::<Test>::events().pop().expect("Event expected").event
}
#[test]
fn basic_locking_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
assert_eq!(Balances::free_balance(1), 10);
Balances::set_lock(ID_1, &1, 9, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 5, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
});
}
#[test]
fn account_should_be_reaped() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
assert_eq!(Balances::free_balance(1), 10);
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 10, AllowDeath));
assert!(!<<Test as Trait>::AccountStore as StoredMap<u64, AccountData<u64>>>::is_explicit(&1));
});
}
#[test]
fn partial_locking_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 5, WithdrawReasons::all());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath));
});
}
#[test]
fn lock_removal_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, u64::max_value(), WithdrawReasons::all());
Balances::remove_lock(ID_1, &1);
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath));
});
}
#[test]
fn lock_replacement_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, u64::max_value(), WithdrawReasons::all());
Balances::set_lock(ID_1, &1, 5, WithdrawReasons::all());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath));
});
}
#[test]
fn double_locking_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 5, WithdrawReasons::all());
Balances::set_lock(ID_2, &1, 5, WithdrawReasons::all());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath));
});
}
#[test]
fn combination_locking_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, u64::max_value(), WithdrawReasons::none());
Balances::set_lock(ID_2, &1, 0, WithdrawReasons::all());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath));
});
}
#[test]
fn lock_value_extension_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 5, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
Balances::extend_lock(ID_1, &1, 2, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
Balances::extend_lock(ID_1, &1, 8, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 3, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
});
}
#[test]
fn lock_reasons_should_work() {
<$ext_builder>::default()
.existential_deposit(1)
.monied(true)
.build()
.execute_with(|| {
pallet_transaction_payment::NextFeeMultiplier::put(Multiplier::saturating_from_integer(1));
Balances::set_lock(ID_1, &1, 10, WithdrawReason::Reserve.into());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
assert_noop!(
<Balances as ReservableCurrency<_>>::reserve(&1, 1),
Error::<$test, _>::LiquidityRestrictions,
);
assert!(<ChargeTransactionPayment<$test> as SignedExtension>::pre_dispatch(
ChargeTransactionPayment::from(1),
&1,
CALL,
&info_from_weight(1),
1,
).is_err());
assert!(<ChargeTransactionPayment<$test> as SignedExtension>::pre_dispatch(
ChargeTransactionPayment::from(0),
&1,
CALL,
&info_from_weight(1),
1,
).is_ok());
Balances::set_lock(ID_1, &1, 10, WithdrawReason::TransactionPayment.into());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath));
assert_ok!(<Balances as ReservableCurrency<_>>::reserve(&1, 1));
assert!(<ChargeTransactionPayment<$test> as SignedExtension>::pre_dispatch(
ChargeTransactionPayment::from(1),
&1,
CALL,
&info_from_weight(1),
1,
).is_err());
assert!(<ChargeTransactionPayment<$test> as SignedExtension>::pre_dispatch(
ChargeTransactionPayment::from(0),
&1,
CALL,
&info_from_weight(1),
1,
).is_err());
});
}
#[test]
fn lock_block_number_extension_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 10, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
Balances::extend_lock(ID_1, &1, 10, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
System::set_block_number(2);
Balances::extend_lock(ID_1, &1, 10, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 3, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
});
}
#[test]
fn lock_reasons_extension_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 10, WithdrawReason::Transfer.into());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
Balances::extend_lock(ID_1, &1, 10, WithdrawReasons::none());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
Balances::extend_lock(ID_1, &1, 10, WithdrawReason::Reserve.into());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
});
}
#[test]
fn default_indexing_on_new_accounts_should_not_work2() {
<$ext_builder>::default()
.existential_deposit(10)
.monied(true)
.build()
.execute_with(|| {
assert_eq!(Balances::is_dead_account(&5), true);
// account 5 should not exist
// ext_deposit is 10, value is 9, not satisfies for ext_deposit
assert_noop!(
Balances::transfer(Some(1).into(), 5, 9),
Error::<$test, _>::ExistentialDeposit,
);
assert_eq!(Balances::is_dead_account(&5), true); // account 5 should not exist
assert_eq!(Balances::free_balance(1), 100);
});
}
#[test]
fn reserved_balance_should_prevent_reclaim_count() {
<$ext_builder>::default()
.existential_deposit(256 * 1)
.monied(true)
.build()
.execute_with(|| {
System::inc_account_nonce(&2);
assert_eq!(Balances::is_dead_account(&2), false);
assert_eq!(Balances::is_dead_account(&5), true);
assert_eq!(Balances::total_balance(&2), 256 * 20);
assert_ok!(Balances::reserve(&2, 256 * 19 + 1)); // account 2 becomes mostly reserved
assert_eq!(Balances::free_balance(2), 255); // "free" account deleted."
assert_eq!(Balances::total_balance(&2), 256 * 20); // reserve still exists.
assert_eq!(Balances::is_dead_account(&2), false);
assert_eq!(System::account_nonce(&2), 1);
// account 4 tries to take index 1 for account 5.
assert_ok!(Balances::transfer(Some(4).into(), 5, 256 * 1 + 0x69));
assert_eq!(Balances::total_balance(&5), 256 * 1 + 0x69);
assert_eq!(Balances::is_dead_account(&5), false);
assert!(Balances::slash(&2, 256 * 19 + 2).1.is_zero()); // account 2 gets slashed
// "reserve" account reduced to 255 (below ED) so account deleted
assert_eq!(Balances::total_balance(&2), 0);
assert_eq!(System::account_nonce(&2), 0); // nonce zero
assert_eq!(Balances::is_dead_account(&2), true);
// account 4 tries to take index 1 again for account 6.
assert_ok!(Balances::transfer(Some(4).into(), 6, 256 * 1 + 0x69));
assert_eq!(Balances::total_balance(&6), 256 * 1 + 0x69);
assert_eq!(Balances::is_dead_account(&6), false);
});
}
#[test]
fn reward_should_work() {
<$ext_builder>::default().monied(true).build().execute_with(|| {
assert_eq!(Balances::total_balance(&1), 10);
assert_ok!(Balances::deposit_into_existing(&1, 10).map(drop));
assert_eq!(Balances::total_balance(&1), 20);
assert_eq!(<TotalIssuance<$test>>::get(), 120);
});
}
#[test]
fn dust_account_removal_should_work() {
<$ext_builder>::default()
.existential_deposit(100)
.monied(true)
.build()
.execute_with(|| {
System::inc_account_nonce(&2);
assert_eq!(System::account_nonce(&2), 1);
assert_eq!(Balances::total_balance(&2), 2000);
// index 1 (account 2) becomes zombie
assert_ok!(Balances::transfer(Some(2).into(), 5, 1901));
assert_eq!(Balances::total_balance(&2), 0);
assert_eq!(Balances::total_balance(&5), 1901);
assert_eq!(System::account_nonce(&2), 0);
});
}
#[test]
fn balance_works() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 42);
assert_eq!(Balances::free_balance(1), 42);
assert_eq!(Balances::reserved_balance(1), 0);
assert_eq!(Balances::total_balance(&1), 42);
assert_eq!(Balances::free_balance(2), 0);
assert_eq!(Balances::reserved_balance(2), 0);
assert_eq!(Balances::total_balance(&2), 0);
});
}
#[test]
fn balance_transfer_works() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::transfer(Some(1).into(), 2, 69));
assert_eq!(Balances::total_balance(&1), 42);
assert_eq!(Balances::total_balance(&2), 69);
});
}
#[test]
fn force_transfer_works() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_noop!(
Balances::force_transfer(Some(2).into(), 1, 2, 69),
BadOrigin,
);
assert_ok!(Balances::force_transfer(RawOrigin::Root.into(), 1, 2, 69));
assert_eq!(Balances::total_balance(&1), 42);
assert_eq!(Balances::total_balance(&2), 69);
});
}
#[test]
fn reserving_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_eq!(Balances::total_balance(&1), 111);
assert_eq!(Balances::free_balance(1), 111);
assert_eq!(Balances::reserved_balance(1), 0);
assert_ok!(Balances::reserve(&1, 69));
assert_eq!(Balances::total_balance(&1), 111);
assert_eq!(Balances::free_balance(1), 42);
assert_eq!(Balances::reserved_balance(1), 69);
});
}
#[test]
fn balance_transfer_when_reserved_should_not_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 69));
assert_noop!(
Balances::transfer(Some(1).into(), 2, 69),
Error::<$test, _>::InsufficientBalance,
);
});
}
#[test]
fn deducting_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 69));
assert_eq!(Balances::free_balance(1), 42);
});
}
#[test]
fn refunding_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 42);
Balances::mutate_account(&1, |a| a.reserved = 69);
Balances::unreserve(&1, 69);
assert_eq!(Balances::free_balance(1), 111);
assert_eq!(Balances::reserved_balance(1), 0);
});
}
#[test]
fn slashing_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 69));
assert!(Balances::slash(&1, 69).1.is_zero());
assert_eq!(Balances::free_balance(1), 0);
assert_eq!(Balances::reserved_balance(1), 42);
assert_eq!(<TotalIssuance<$test>>::get(), 42);
});
}
#[test]
fn slashing_incomplete_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 42);
assert_ok!(Balances::reserve(&1, 21));
assert_eq!(Balances::slash(&1, 69).1, 27);
assert_eq!(Balances::free_balance(1), 0);
assert_eq!(Balances::reserved_balance(1), 0);
assert_eq!(<TotalIssuance<$test>>::get(), 0);
});
}
#[test]
fn unreserving_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 111));
Balances::unreserve(&1, 42);
assert_eq!(Balances::reserved_balance(1), 69);
assert_eq!(Balances::free_balance(1), 42);
});
}
#[test]
fn slashing_reserved_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 111));
assert_eq!(Balances::slash_reserved(&1, 42).1, 0);
assert_eq!(Balances::reserved_balance(1), 69);
assert_eq!(Balances::free_balance(1), 0);
assert_eq!(<TotalIssuance<$test>>::get(), 69);
});
}
#[test]
fn slashing_incomplete_reserved_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 42));
assert_eq!(Balances::slash_reserved(&1, 69).1, 27);
assert_eq!(Balances::free_balance(1), 69);
assert_eq!(Balances::reserved_balance(1), 0);
assert_eq!(<TotalIssuance<$test>>::get(), 69);
});
}
#[test]
fn repatriating_reserved_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 110);
let _ = Balances::deposit_creating(&2, 1);
assert_ok!(Balances::reserve(&1, 110));
assert_ok!(Balances::repatriate_reserved(&1, &2, 41, Status::Free), 0);
assert_eq!(
last_event(),
Event::balances(RawEvent::ReserveRepatriated(1, 2, 41, Status::Free)),
);
assert_eq!(Balances::reserved_balance(1), 69);
assert_eq!(Balances::free_balance(1), 0);
assert_eq!(Balances::reserved_balance(2), 0);
assert_eq!(Balances::free_balance(2), 42);
});
}
#[test]
fn transferring_reserved_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 110);
let _ = Balances::deposit_creating(&2, 1);
assert_ok!(Balances::reserve(&1, 110));
assert_ok!(Balances::repatriate_reserved(&1, &2, 41, Status::Reserved), 0);
assert_eq!(Balances::reserved_balance(1), 69);
assert_eq!(Balances::free_balance(1), 0);
assert_eq!(Balances::reserved_balance(2), 41);
assert_eq!(Balances::free_balance(2), 1);
});
}
#[test]
fn transferring_reserved_balance_to_nonexistent_should_fail() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 111));
assert_noop!(Balances::repatriate_reserved(&1, &2, 42, Status::Free), Error::<$test, _>::DeadAccount);
});
}
#[test]
fn transferring_incomplete_reserved_balance_should_work() {
<$ext_builder>::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 110);
let _ = Balances::deposit_creating(&2, 1);
assert_ok!(Balances::reserve(&1, 41));
assert_ok!(Balances::repatriate_reserved(&1, &2, 69, Status::Free), 28);
assert_eq!(Balances::reserved_balance(1), 0);
assert_eq!(Balances::free_balance(1), 69);
assert_eq!(Balances::reserved_balance(2), 0);
assert_eq!(Balances::free_balance(2), 42);
});
}
#[test]
fn transferring_too_high_value_should_not_panic() {
<$ext_builder>::default().build().execute_with(|| {
Balances::make_free_balance_be(&1, u64::max_value());
Balances::make_free_balance_be(&2, 1);
assert_err!(
Balances::transfer(Some(1).into(), 2, u64::max_value()),
Error::<$test, _>::Overflow,
);
assert_eq!(Balances::free_balance(1), u64::max_value());
assert_eq!(Balances::free_balance(2), 1);
});
}
#[test]
fn account_create_on_free_too_low_with_other() {
<$ext_builder>::default().existential_deposit(100).build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 100);
assert_eq!(<TotalIssuance<$test>>::get(), 100);
// No-op.
let _ = Balances::deposit_creating(&2, 50);
assert_eq!(Balances::free_balance(2), 0);
assert_eq!(<TotalIssuance<$test>>::get(), 100);
})
}
#[test]
fn account_create_on_free_too_low() {
<$ext_builder>::default().existential_deposit(100).build().execute_with(|| {
// No-op.
let _ = Balances::deposit_creating(&2, 50);
assert_eq!(Balances::free_balance(2), 0);
assert_eq!(<TotalIssuance<$test>>::get(), 0);
})
}
#[test]
fn account_removal_on_free_too_low() {
<$ext_builder>::default().existential_deposit(100).build().execute_with(|| {
assert_eq!(<TotalIssuance<$test>>::get(), 0);
// Setup two accounts with free balance above the existential threshold.
let _ = Balances::deposit_creating(&1, 110);
let _ = Balances::deposit_creating(&2, 110);
assert_eq!(Balances::free_balance(1), 110);
assert_eq!(Balances::free_balance(2), 110);
assert_eq!(<TotalIssuance<$test>>::get(), 220);
// Transfer funds from account 1 of such amount that after this transfer
// the balance of account 1 will be below the existential threshold.
// This should lead to the removal of all balance of this account.
assert_ok!(Balances::transfer(Some(1).into(), 2, 20));
// Verify free balance removal of account 1.
assert_eq!(Balances::free_balance(1), 0);
assert_eq!(Balances::free_balance(2), 130);
// Verify that TotalIssuance tracks balance removal when free balance is too low.
assert_eq!(<TotalIssuance<$test>>::get(), 130);
});
}
#[test]
fn burn_must_work() {
<$ext_builder>::default().monied(true).build().execute_with(|| {
let init_total_issuance = Balances::total_issuance();
let imbalance = Balances::burn(10);
assert_eq!(Balances::total_issuance(), init_total_issuance - 10);
drop(imbalance);
assert_eq!(Balances::total_issuance(), init_total_issuance);
});
}
#[test]
fn transfer_keep_alive_works() {
<$ext_builder>::default().existential_deposit(1).build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 100);
assert_noop!(
Balances::transfer_keep_alive(Some(1).into(), 2, 100),
Error::<$test, _>::KeepAlive
);
assert_eq!(Balances::is_dead_account(&1), false);
assert_eq!(Balances::total_balance(&1), 100);
assert_eq!(Balances::total_balance(&2), 0);
});
}
#[test]
#[should_panic = "the balance of any account should always be more than existential deposit."]
fn cannot_set_genesis_value_below_ed() {
($existential_deposit).with(|v| *v.borrow_mut() = 11);
let mut t = frame_system::GenesisConfig::default().build_storage::<$test>().unwrap();
let _ = GenesisConfig::<$test> {
balances: vec![(1, 10)],
}.assimilate_storage(&mut t).unwrap();
}
#[test]
fn dust_moves_between_free_and_reserved() {
<$ext_builder>::default()
.existential_deposit(100)
.build()
.execute_with(|| {
// Set balance to free and reserved at the existential deposit
assert_ok!(Balances::set_balance(RawOrigin::Root.into(), 1, 100, 0));
// Check balance
assert_eq!(Balances::free_balance(1), 100);
assert_eq!(Balances::reserved_balance(1), 0);
// Reserve some free balance
assert_ok!(Balances::reserve(&1, 50));
// Check balance, the account should be ok.
assert_eq!(Balances::free_balance(1), 50);
assert_eq!(Balances::reserved_balance(1), 50);
// Reserve the rest of the free balance
assert_ok!(Balances::reserve(&1, 50));
// Check balance, the account should be ok.
assert_eq!(Balances::free_balance(1), 0);
assert_eq!(Balances::reserved_balance(1), 100);
// Unreserve everything
Balances::unreserve(&1, 100);
// Check balance, all 100 should move to free_balance
assert_eq!(Balances::free_balance(1), 100);
assert_eq!(Balances::reserved_balance(1), 0);
});
}
#[test]
fn account_deleted_when_just_dust() {
<$ext_builder>::default()
.existential_deposit(100)
.build()
.execute_with(|| {
// Set balance to free and reserved at the existential deposit
assert_ok!(Balances::set_balance(RawOrigin::Root.into(), 1, 50, 50));
// Check balance
assert_eq!(Balances::free_balance(1), 50);
assert_eq!(Balances::reserved_balance(1), 50);
// Reserve some free balance
let _ = Balances::slash(&1, 1);
// The account should be dead.
assert!(Balances::is_dead_account(&1));
assert_eq!(Balances::free_balance(1), 0);
assert_eq!(Balances::reserved_balance(1), 0);
});
}
#[test]
fn emit_events_with_reserve_and_unreserve() {
<$ext_builder>::default()
.build()
.execute_with(|| {
let _ = Balances::deposit_creating(&1, 100);
System::set_block_number(2);
let _ = Balances::reserve(&1, 10);
assert_eq!(
last_event(),
Event::balances(RawEvent::Reserved(1, 10)),
);
System::set_block_number(3);
let _ = Balances::unreserve(&1, 5);
assert_eq!(
last_event(),
Event::balances(RawEvent::Unreserved(1, 5)),
);
System::set_block_number(4);
let _ = Balances::unreserve(&1, 6);
// should only unreserve 5
assert_eq!(
last_event(),
Event::balances(RawEvent::Unreserved(1, 5)),
);
});
}
#[test]
fn emit_events_with_existential_deposit() {
<$ext_builder>::default()
.existential_deposit(100)
.build()
.execute_with(|| {
assert_ok!(Balances::set_balance(RawOrigin::Root.into(), 1, 100, 0));
assert_eq!(
events(),
[
Event::system(system::RawEvent::NewAccount(1)),
Event::balances(RawEvent::Endowed(1, 100)),
Event::balances(RawEvent::BalanceSet(1, 100, 0)),
]
);
let _ = Balances::slash(&1, 1);
assert_eq!(
events(),
[
Event::balances(RawEvent::DustLost(1, 99)),
Event::system(system::RawEvent::KilledAccount(1))
]
);
});
}
#[test]
fn emit_events_with_no_existential_deposit_suicide() {
<$ext_builder>::default()
.existential_deposit(0)
.build()
.execute_with(|| {
assert_ok!(Balances::set_balance(RawOrigin::Root.into(), 1, 100, 0));
assert_eq!(
events(),
[
Event::system(system::RawEvent::NewAccount(1)),
Event::balances(RawEvent::Endowed(1, 100)),
Event::balances(RawEvent::BalanceSet(1, 100, 0)),
]
);
let _ = Balances::slash(&1, 100);
// no events
assert_eq!(events(), []);
assert_ok!(System::suicide(Origin::signed(1)));
assert_eq!(
events(),
[
Event::system(system::RawEvent::KilledAccount(1))
]
);
});
}
}
}
|
use anyhow::Result;
use sqlx::{mysql::MySqlPool, MySql};
pub type DbPool = sqlx::Pool<MySql>;
pub async fn new_pool(database_url: &str) -> Result<DbPool> {
let pool = MySqlPool::connect(database_url).await?;
Ok(pool)
}
#[cfg(feature = "db_test")]
#[cfg(test)]
mod test {
use super::*;
use crate::config::ENV_CONFIG;
#[tokio::test]
async fn test_db() -> Result<()> {
use crate::repository::SubmitRepository;
let pool = new_pool(&ENV_CONFIG.database_url).await?;
let result = pool.begin().await?.get_submits().await?;
dbg!(result);
Ok(())
}
#[tokio::test]
async fn test_db2() -> Result<()> {
use crate::repository::ProblemsRepository;
let pool = new_pool(&ENV_CONFIG.database_url).await?;
let result = pool.fetch_problem(1).await?;
dbg!(result);
Ok(())
}
#[tokio::test]
async fn test_db3() -> Result<()> {
use crate::repository::TestcasesRepository;
let pool = new_pool(&ENV_CONFIG.database_url).await?;
let result = pool.fetch_testcases(1).await?;
dbg!(result);
Ok(())
}
}
|
// Packages: A Cargo feature that lets you build, test, and share crates
// Crates: A tree of modules that produces a library or executable
// Modules and use: Let you control the organization, scope, and privacy of paths
// Paths: A way of naming an item, such as a struct, function, or module
// use将路径带入范围的关键字;以及将pub项目设为公开的关键字
// !!!!!! 本节示例查看: ../restaurant lib
fn main() {
println!("Hello, world!");
}
|
#![deny(warnings)]
extern crate extra;
use std::env;
use std::fs;
use std::io::{stderr, stdout, Write};
use extra::option::OptionalExt;
const MAN_PAGE: &'static str = /* @MANSTART{mv} */ r#"
NAME
mv - move files
SYNOPSIS
mv [ -h | --help ] SOURCE_FILE DESTINATION_FILE
DESCRIPTION
The mv utility renames the file named by the SOURCE_FILE operand to the destination path named by the DESTINATION_FILE operand.
OPTIONS
--help, -h
print this message
"#; /* @MANEND */
fn main() {
let stdout = stdout();
let mut stdout = stdout.lock();
let mut stderr = stderr();
if env::args().count() == 2 {
if let Some(arg) = env::args().nth(1) {
if arg == "--help" || arg == "-h" {
stdout.write_all(MAN_PAGE.as_bytes()).try(&mut stderr);
stdout.flush().try(&mut stderr);
return;
}
}
}
let ref src = env::args().nth(1).fail("No source argument. Use --help to see the usage.", &mut stderr);
let ref dst = env::args().nth(2).fail("No destination argument. Use --help to see the usage.", &mut stderr);
fs::rename(src, dst).try(&mut stderr);
}
|
use iced::{button, container, Background, Color, Vector};
const SURFACE: Color = Color::from_rgb(
0xF2 as f32 / 255.0,
0xF3 as f32 / 255.0,
0xF5 as f32 / 255.0,
);
const ACTIVE: Color = Color::from_rgb(
0x72 as f32 / 255.0,
0x89 as f32 / 255.0,
0xDA as f32 / 255.0,
);
const HOVERED: Color = Color::from_rgb(
0x67 as f32 / 255.0,
0x7B as f32 / 255.0,
0xC4 as f32 / 255.0,
);
pub enum Button {
Start,
Stop,
Post,
Primary,
Destructive,
}
impl button::StyleSheet for Button {
fn active(&self) -> button::Style {
let (background, text_color) = match self {
Button::Primary => (Some(ACTIVE), Color::WHITE),
Button::Destructive => (None, Color::from_rgb8(0xFF, 0x47, 0x47)),
_ => (None, Color::from_rgb8(0xFF, 0x47, 0x47)),
};
match self {
Button::Start => button::Style {
background: Some(Background::Color(Color::from_rgb(0.0, 0.8, 0.1))),
border_radius: 5.0,
text_color: Color::WHITE,
..button::Style::default()
},
Button::Stop => button::Style {
background: Some(Background::Color(Color::from_rgb(0.8, 0.2, 0.6))),
border_radius: 5.0,
text_color: Color::WHITE,
..button::Style::default()
},
Button::Post => button::Style {
background: Some(Background::Color(ACTIVE)), //Some(Background::Color(Color::from_rgb(0.1, 0.2, 0.8))),
border_radius: 5.0,
text_color: Color::WHITE,
..button::Style::default()
},
Button::Primary => button::Style {
text_color,
background: background.map(Background::Color),
border_radius: 5.0,
shadow_offset: Vector::new(0.0, 0.0),
..button::Style::default()
},
Button::Destructive => button::Style {
text_color,
background: background.map(Background::Color),
border_radius: 5.0,
shadow_offset: Vector::new(0.0, 0.0),
..button::Style::default()
},
}
}
fn hovered(&self) -> button::Style {
let active = self.active();
let background = match self {
Button::Primary => Some(HOVERED),
_ => Some(Color {
a: 0.1,
..active.text_color
})
};
button::Style {
text_color: match self {
Button::Start => Color::from_rgb(0.2, 0.2, 0.7),
_ => active.text_color,
},
shadow_offset: active.shadow_offset + Vector::new(0.0, 1.0),
background: background.map(Background::Color),
..active
}
}
}
pub struct TitleBar {
pub is_focused: bool,
}
impl container::StyleSheet for TitleBar {
fn style(&self) -> container::Style {
let pane = Pane {
is_focused: self.is_focused,
}
.style();
container::Style {
text_color: Some(Color::WHITE),
background: Some(pane.border_color.into()),
..Default::default()
}
}
}
pub struct Pane {
pub is_focused: bool,
}
impl container::StyleSheet for Pane {
fn style(&self) -> container::Style {
container::Style {
background: Some(Background::Color(SURFACE)),
border_width: 2.0,
border_color: if self.is_focused {
Color::from_rgb(0.0, 0.8, 0.8)
} else {
Color::from_rgb(0.8, 0.9, 0.9)
},
..Default::default()
}
}
}
|
use fancy_slice::FancySlice;
use crate::util;
use crate::resources;
use crate::chr0::*;
use crate::mdl0::*;
use crate::plt0::*;
pub(crate) fn bres(data: FancySlice) -> Bres {
let endian = data.u16_be(0x4);
let version = data.u16_be(0x6);
//let size = data.u32_be(0x8);
let root_offset = data.u16_be(0xc);
//let num_sections = data.u16_be(0xe);
let children = bres_group(data.relative_fancy_slice(root_offset as usize ..));
Bres { endian, version, children }
}
fn bres_group(data: FancySlice) -> Vec<BresChild> {
let mut children = vec!();
for resource in resources::resources(data.relative_fancy_slice(ROOT_HEADER_SIZE..)) {
let child_data = data.relative_fancy_slice(ROOT_HEADER_SIZE + resource.data_offset as usize ..);
let tag = util::parse_tag(child_data.relative_slice(..));
let child_data = match tag.as_ref() {
"CHR0" => BresChildData::Chr0 (chr0(child_data)),
"MDL0" => BresChildData::Mdl0 (mdl0(child_data)),
"PLT0" => BresChildData::Plt0 (plt0(child_data)),
"" => BresChildData::Bres (bres_group(data.relative_fancy_slice(resource.data_offset as usize ..))), // TODO: I suspect the match on "" is succeeding by accident
_ => BresChildData::Unknown (tag),
};
children.push(BresChild {
name: resource.string,
data: child_data,
});
}
children
}
// Brawlbox has this split into three structs: BRESHeader, BRESEntry and ROOTHeader
// BRESEntry is commented out, so that appears wrong
// BRESHeader and RootHeader are combined because without BRESEntry they appear to be sequential
const BRES_HEADER_SIZE: usize = 0x10;
#[derive(Clone, Debug)]
pub struct Bres {
pub endian: u16,
pub version: u16,
pub children: Vec<BresChild>
}
impl Bres {
pub fn compile(&self) -> Vec<u8> {
let mut output = vec!();
let mut root_output: Vec<u8> = vec!();
let root_size = ROOT_HEADER_SIZE
+ resources::RESOURCE_HEADER_SIZE
+ resources::RESOURCE_SIZE
+ self.children.iter().map(|x| x.bres_size()).sum::<usize>();
let bres_size_leafless = BRES_HEADER_SIZE + root_size;
let mut bres_size_leafless_buffered = bres_size_leafless;
while bres_size_leafless_buffered % 0x20 != 0 {
bres_size_leafless_buffered += 1; // TODO: arithmeticize the loop
}
// compile children
let mut leaf_children_output: Vec<Vec<u8>> = vec!();
let mut leaf_children_size = 0;
let mut to_process = vec!(&self.children);
while to_process.len() > 0 {
let children = to_process.remove(0);
let resource_header_offset = BRES_HEADER_SIZE + ROOT_HEADER_SIZE + root_output.len();
// create resources header
let resources_size = (children.len() + 1) * resources::RESOURCE_SIZE + resources::RESOURCE_HEADER_SIZE; // includes the dummy child
root_output.extend(&i32::to_be_bytes(resources_size as i32));
root_output.extend(&i32::to_be_bytes(children.len() as i32)); // num_children
// insert the dummy resource
let root_resource = 1;
root_output.extend(&[0xff, 0xff]); // id
root_output.extend(&u16::to_be_bytes(0)); // flag
root_output.extend(&u16::to_be_bytes(root_resource)); // left_index
root_output.extend(&u16::to_be_bytes(0)); // right_index
root_output.extend(&i32::to_be_bytes(0)); // string_offset
root_output.extend(&i32::to_be_bytes(0)); // data_offset
let mut data_offset_current = resources_size;
for (i, child) in children.iter().enumerate() {
let data_offset = match child.data {
BresChildData::Bres (_) => data_offset_current as i32,
_ =>
bres_size_leafless_buffered as i32
- resource_header_offset as i32
+ leaf_children_size,
};
match child.data {
BresChildData::Bres (ref children) => {
to_process.push(children);
data_offset_current += (children.len() + 1) * resources::RESOURCE_SIZE + resources::RESOURCE_HEADER_SIZE;
}
_ => {
// calculate offset to child
let mut child_offset = bres_size_leafless as i32;
while child_offset % 0x20 != 0 {
child_offset += 1; // TODO: arithmeticize the loop
}
child_offset += leaf_children_size;
let child_output = child.compile(-child_offset);
leaf_children_size = if let Some(result) = leaf_children_size.checked_add(child_output.len() as i32) {
result
} else {
panic!("BRES over 2 ^ 32 bytes"); // TODO: Make this an Err(_)
};
leaf_children_output.push(child_output);
}
}
let mut name = child.name.clone();
let index_component = (name.len() as u16 - 1) << 3;
let char_component = most_significant_different_bit(name.pop().unwrap() as u8, 0) as u16;
let id = index_component | char_component;
let left_index = (i + 1) as u16;
let right_index = (i + 1) as u16;
// create each resource
root_output.extend(&u16::to_be_bytes(id));
root_output.extend(&u16::to_be_bytes(0));
root_output.extend(&u16::to_be_bytes(left_index));
root_output.extend(&u16::to_be_bytes(right_index));
root_output.extend(&i32::to_be_bytes(0)); // TODO: string_offset
root_output.extend(&i32::to_be_bytes(data_offset));
}
}
let bres_size = bres_size_leafless as u32 + leaf_children_size as u32;
let leaf_count: usize = self.children.iter().map(|x| x.count_leaves()).sum();
// create bres header
output.extend("bres".chars().map(|x| x as u8));
output.extend(&u16::to_be_bytes(self.endian));
output.extend(&u16::to_be_bytes(self.version));
output.extend(&u32::to_be_bytes(bres_size as u32));
output.extend(&u16::to_be_bytes(0x10)); // root_offset
output.extend(&u16::to_be_bytes(leaf_count as u16 + 1)); // +1 for the root entry
// create bres root child header
output.extend("root".chars().map(|x| x as u8));
output.extend(&i32::to_be_bytes(root_size as i32));
// create bres root child contents
output.extend(root_output);
while output.len() % 0x20 != 0 {
output.push(0x00);
}
// create bres leaf children
let mut size: u32 = 0;
for child_output in leaf_children_output {
size = if let Some(result) = size.checked_add(child_output.len() as u32) {
result
} else {
panic!("BRES over 2 ^ 32 bytes"); // TODO: Make this an Err(_)
};
output.extend(child_output);
}
output
}
}
fn most_significant_different_bit(b0: u8, b1: u8) -> u8 {
for i in 0..8 {
let bit = 0x80 >> i;
if b0 & bit != b1 & bit {
return 7 - i;
}
}
0
}
impl BresChild {
pub fn compile(&self, bres_offset: i32) -> Vec<u8> {
match &self.data {
BresChildData::Bres (children) => {
let mut output = vec!();
for child in children {
output.extend(child.compile(bres_offset));
}
output
}
BresChildData::Mdl0 (child) => child.compile(bres_offset),
BresChildData::Plt0 (child) => child.compile(bres_offset),
_ => vec!(),
}
}
// Calculates the size taken up by non-leaf data
// Doesnt include the root data
fn bres_size(&self) -> usize {
resources::RESOURCE_SIZE + // the resource entry
match &self.data {
// its pointing to a group of children
BresChildData::Bres (children) =>
resources::RESOURCE_HEADER_SIZE
+ resources::RESOURCE_SIZE // dummy child
+ children.iter().map(|x| x.bres_size()).sum::<usize>(),
// its pointing to a leaf node
_ => 0,
}
}
fn count_leaves(&self) -> usize {
match &self.data {
BresChildData::Bres (children) => children.iter().map(|x| x.count_leaves()).sum::<usize>(),
_ => 1,
}
}
}
const ROOT_HEADER_SIZE: usize = 0x8;
#[derive(Clone, Debug)]
pub struct BresChild {
pub name: String,
pub data: BresChildData
}
#[derive(Clone, Debug)]
pub enum BresChildData {
Chr0 (Chr0),
Mdl0 (Mdl0),
Plt0 (Plt0),
Bres (Vec<BresChild>),
Unknown (String)
}
|
#![deny(unsafe_code)]
#![deny(rust_2018_idioms)]
// NOTE only these two modules can and do contain unsafe code.
#[allow(unsafe_code)]
mod high;
#[allow(unsafe_code)]
mod indexing_str;
#[forbid(unsafe_code)]
pub mod generate;
#[forbid(unsafe_code)]
pub mod grammar;
#[forbid(unsafe_code)]
pub mod proc_macro;
#[forbid(unsafe_code)]
pub mod runtime;
#[forbid(unsafe_code)]
pub mod scannerless;
#[forbid(unsafe_code)]
mod parse_grammar;
|
#[macro_use(try_f)]
extern crate susanoo;
extern crate r2d2;
extern crate r2d2_sqlite;
extern crate rusqlite;
use susanoo::{Context, Server, Response, AsyncResult};
use susanoo::contrib::hyper::{Get, StatusCode};
use susanoo::contrib::futures::{future, Future};
use susanoo::contrib::typemap::Key;
use std::ops::Deref;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::Connection as SqliteConnection;
// DB connection pool.
struct DBPool(Pool<SqliteConnectionManager>);
impl Deref for DBPool {
type Target = Pool<SqliteConnectionManager>;
fn deref(&self) -> &Pool<SqliteConnectionManager> {
&self.0
}
}
impl Key for DBPool {
type Value = Self;
}
// Model
#[derive(Debug)]
struct Person {
id: i32,
name: String,
data: Option<Vec<u8>>,
}
impl Person {
fn new(id: i32, name: &str) -> Self {
Person {
id,
name: name.to_owned(),
data: None,
}
}
fn from_row(row: &rusqlite::Row) -> Self {
Person {
id: row.get(0),
name: row.get(1),
data: row.get(2),
}
}
fn insert(&self, conn: &SqliteConnection) -> rusqlite::Result<i32> {
conn.execute(
"INSERT INTO persons (name, data) VALUES (?1, ?2)",
&[&self.name, &self.data],
)
}
fn create_table(conn: &SqliteConnection) -> rusqlite::Result<()> {
conn.execute(
r#"CREATE TABLE persons (
id INTEGER PRIMARY KEY
, name TEXT NOT NULL
, data BLOB
)"#,
&[],
).map(|_| ())
}
fn select(conn: &SqliteConnection) -> rusqlite::Result<Vec<Person>> {
let mut stmt = conn.prepare("SELECT id,name,data FROM persons")?;
let people = stmt.query_map(&[], Person::from_row)?
.collect::<Result<_, _>>()?;
Ok(people)
}
}
fn index(ctx: Context) -> AsyncResult {
let db = ctx.states.get::<DBPool>().unwrap();
let conn = try_f!(db.get());
let people = try_f!(Person::select(&*conn));
future::ok(
Response::new()
.with_status(StatusCode::Ok)
.with_body(format!("people: {:?}", people))
.into(),
).boxed()
}
fn init_db(path: &str) {
let _ = std::fs::remove_file(path);
let conn = SqliteConnection::open(path).unwrap();
Person::create_table(&conn).unwrap();
let me = Person::new(0, "Bob");
me.insert(&conn).unwrap();
}
fn main() {
init_db("app.sqlite");
// create DB connection pool
let manager = SqliteConnectionManager::new("app.sqlite");
let pool = r2d2::Pool::new(Default::default(), manager).unwrap();
let db = DBPool(pool);
let server = Server::new()
.with_route(Get, "/", index)
.with_state(db);
server.run("0.0.0.0:4000");
}
|
pub use environment::Environment;
pub use flappy::FlappyEnvironment;
pub use jump::JumpEnvironment;
mod environment;
mod flappy;
mod jump;
|
use std::env::Args;
use rustybox::Function;
pub fn binding() -> (&'static str, Function) {
("false", Box::new(false_fn))
}
fn false_fn(_: Args) -> i32 {
1
}
|
#[doc = "Reader of register TIMEOUT_CTL"]
pub type R = crate::R<u32, super::TIMEOUT_CTL>;
#[doc = "Writer for register TIMEOUT_CTL"]
pub type W = crate::W<u32, super::TIMEOUT_CTL>;
#[doc = "Register TIMEOUT_CTL `reset()`'s with value 0xffff"]
impl crate::ResetValue for super::TIMEOUT_CTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xffff
}
}
#[doc = "Reader of field `TIMEOUT`"]
pub type TIMEOUT_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `TIMEOUT`"]
pub struct TIMEOUT_W<'a> {
w: &'a mut W,
}
impl<'a> TIMEOUT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 0:15 - This field specifies a number of peripheral group (clk_group) clock cycles. If an AHB-Lite bus transfer takes more than the specified number of cycles (timeout detection), the bus transfer is terminated with an AHB-Lite bus error and a fault is generated (and possibly recorded in the fault report structure(s)). '0x0000'-'0xfffe': Number of peripheral group clock cycles. '0xffff': This value is the default/reset value and specifies that no timeout detection is performed: a bus transfer will never be terminated and a fault will never be generated."]
#[inline(always)]
pub fn timeout(&self) -> TIMEOUT_R {
TIMEOUT_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - This field specifies a number of peripheral group (clk_group) clock cycles. If an AHB-Lite bus transfer takes more than the specified number of cycles (timeout detection), the bus transfer is terminated with an AHB-Lite bus error and a fault is generated (and possibly recorded in the fault report structure(s)). '0x0000'-'0xfffe': Number of peripheral group clock cycles. '0xffff': This value is the default/reset value and specifies that no timeout detection is performed: a bus transfer will never be terminated and a fault will never be generated."]
#[inline(always)]
pub fn timeout(&mut self) -> TIMEOUT_W {
TIMEOUT_W { w: self }
}
}
|
use enumset::EnumSet;
use crate::{
args,
track::{Duration, Track},
};
fn command_line(line: &str) -> args::Command {
let arguments = shell_words
::split(line)
.expect("failed to shell parse test command line");
args
::parse(arguments)
.expect("failed to parse test command line")
}
#[test]
fn test_debug() {
let test = |args, level| {
let commands = [ // (command, track duration)
(format!("sdl 'Test - track' {}", args), None),
(format!("sdl {} 'Test - track'", args), None),
(format!("sdl -d 1:00 'Test - track' {}", args), Some(Duration::from_seconds(60))),
(format!("sdl -d 1:00 {} 'Test - track'", args), Some(Duration::from_seconds(60))),
(format!("sdl 'Test - track' -d 1:00 {}", args), Some(Duration::from_seconds(60))),
(format!("sdl 'Test - track' {} -d 1:00", args), Some(Duration::from_seconds(60))),
];
for (command, duration) in commands.iter() {
let mut track = Track
::new("Test - track")
.expect("invalid track");
track.duration = *duration;
assert_eq!(
command_line(command),
args::Command::Download(
args::Args {
log_level: level,
track,
metasources: EnumSet::all(),
tracksources: EnumSet::all(),
}
)
);
}
};
test("", log::Level::Info);
test("-v", log::Level::Debug);
test("-vv", log::Level::Trace);
test("-vvv", log::Level::Trace);
test("-vvvv", log::Level::Trace);
}
|
fn a(x: bool, y: bool) -> bool {
if x && y {
let a: bool = true;
y || a
} else {
x && false
}
}
fn b(x: bool, y: bool) -> i32 {
let a: bool = a(x, y || false);
let mut b: i32 = 0;
if a && y {
let a: bool = true;
if y || a {
b = b + 1;
};
} else {
if !(x && false) {
b = b - 1;
}
};
b + 3
}
fn c(x: bool, y: bool) -> i32 {
let mut b: i32 = 0;
let mut c: i32 = 1;
while (b < 10) {
c = c * 2;
}
c
} |
use packed_secret_sharing::*;
use packed_secret_sharing::packed::*;
use rand::{thread_rng, Rng};
use criterion::{black_box, Bencher};
pub fn share_bench(bench: &mut Bencher, _i: &()) {
let prime = 4610415792919412737u128;
let root2 = 1266473570726112470u128;
let root3 = 2230453091198852918u128;
let mut rng = thread_rng();
let degree = 511;
let num_secrets = rng.gen_range(1, 512);
let num_shares = rng.gen_range(512, 729);
let mut pss = PackedSecretSharing::new(prime, root2, root3, degree, num_secrets, num_shares);
let mut secrets = vec![0u128; num_secrets];
for i in 0..num_secrets {
secrets[i] = rng.gen_range(0, &prime);
}
bench.iter(|| black_box(
pss.share(black_box(&secrets))
));
}
pub fn reconstruct_bench(bench: &mut Bencher, _i: &()) {
let prime = 4610415792919412737u128;
let root2 = 1266473570726112470u128;
let root3 = 2230453091198852918u128;
let mut rng = thread_rng();
let degree = 511;
let num_secrets = 10; //rng.gen_range(1, 512);
let num_shares = rng.gen_range(512, 729);
let mut pss = PackedSecretSharing::new(prime, root2, root3, degree, num_secrets, num_shares);
let mut secrets = vec![0u128; num_secrets];
for i in 0..num_secrets {
secrets[i] = rng.gen_range(0, &prime);
}
let shares = pss.share(&secrets);
// ======================================================
let mut shares_point = pss.rootTable3.clone();
shares_point.split_off(512);
let mut shares_val = shares.clone();
shares_val.split_off(512);
bench.iter(|| black_box(
pss.reconstruct(black_box(&shares_point), black_box(&shares_val))
));
}
pub fn lagrange_interpolation_bench(bench: &mut Bencher, _i: &()) {
let prime = 4610415792919412737u128;
let degree = 511;
let num_roots = 100;
let mut shares_point = vec![0u128; degree + 1];
let mut shares_val = vec![0u128; degree + 1];
let mut rng = thread_rng();
for i in 0..degree + 1 {
shares_point[i] = rng.gen_range(0, &prime);
shares_val[i] = rng.gen_range(0, &prime);
}
let mut root = vec![0u128; num_roots];
for i in 0..num_roots {
root[i] = rng.gen_range(0, &prime);
}
bench.iter(|| black_box(
lagrange_interpolation(black_box(&shares_point), black_box(&shares_val),
black_box(&root), black_box(&prime))
));
} |
#![no_std]
#[allow(
non_camel_case_types,
non_snake_case,
non_upper_case_globals,
dead_code
)]
#[allow(clippy::all)]
mod binding {
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}
mod blake2b;
#[cfg(test)]
extern crate std;
pub use crate::blake2b::{blake2b, Blake2b, Blake2bBuilder};
|
mod table;
mod table_theme;
mod textstyle;
mod width_control;
pub use table::{Alignments, Table};
pub use table_theme::TableTheme;
pub use textstyle::{Alignment, StyledString, TextStyle};
|
use bytes::Bytes;
use rml_rtmp::sessions::StreamMetadata;
pub enum RtmpInput {
Media(Media),
Metadata(StreamMetadata),
}
pub struct Media {
pub media_type: MediaType,
pub data: Bytes,
pub timestamp: u32,
pub can_be_dropped: bool,
}
pub enum MediaType {
Video,
Audio,
}
|
#[macro_use]
extern crate text_io;
fn main() {
let (i, f): (i32, f64);
scan!("{}, {}", i, f);
let a: u32 = read!("{}\n");
println!("{} {} enter and {} here", i + 11, f - 20.0, a + 10);
}
|
use failure::Error;
use futures::prelude::*;
use futures::stream;
use slog::Logger;
use std::cell::Cell;
use std::rc::Rc;
use tokio_retry::{self, Retry, strategy::ExponentialBackoff};
use github::{GithubClient, PullRequest};
pub fn poll_notifications(
client: GithubClient,
logger: Logger,
) -> impl Stream<Item = (PullRequest, Logger), Error = Error> {
let batch_number = Rc::new(Cell::new(0));
let unfold_logger = logger.clone();
let unfold_bn = batch_number.clone();
stream::unfold(client, move |client| {
unfold_bn.set(unfold_bn.get() + 1);
let logger = unfold_logger.new(o!("batch_number" => unfold_bn.get()));
let mut retry_number = 0;
let retry_strategy = ExponentialBackoff::from_millis(10).take(5);
let retry = Retry::spawn(retry_strategy, move || {
retry_number += 1;
let logger = logger.new(o!("retry_number" => retry_number));
get_next_batch(&client, logger)
});
let future = retry.map_err(|err| match err {
tokio_retry::Error::OperationError(e) => e,
tokio_retry::Error::TimerError(e) => Error::from(e),
});
Some(future)
}).map(move |batch| {
let logger = logger.new(o!("batch_number" => batch_number.get()));
batch.map(move |item| (item, logger.clone()))
})
.flatten()
}
fn get_next_batch(
client: &GithubClient,
logger: Logger,
) -> impl Future<Item = (impl Stream<Item = PullRequest, Error = Error>, GithubClient), Error = Error> {
let next_review_requests = client.next_review_requests();
let stream_logger = logger.clone();
client
.wait_poll_interval()
.and_then(move |_| next_review_requests)
.map(move |(stream, next_client)| {
let stream = stream.inspect_err(move |err| {
error!(stream_logger, "Error in notification stream"; "error" => %err);
});
(stream, next_client)
})
.map_err(move |err| {
if is_http_incomplete(&err) {
debug!(logger, "Got early HTTP EOF"; "error" => ?err);
} else {
error!(logger, "Error while preparing stream"; "error" => ?err);
}
return err;
})
}
fn is_http_incomplete(err: &Error) -> bool {
match downcast_to_hyper_error(err) {
Some(::hyper::Error::Incomplete) => true,
_ => false,
}
}
fn downcast_to_hyper_error(err: &Error) -> Option<&::hyper::Error> {
let reqwest_error = err.downcast_ref::<::reqwest::Error>()?;
let error_ref = reqwest_error.get_ref()?;
error_ref.downcast_ref::<::hyper::Error>()
}
|
#[macro_use] extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate rmp_serde;
extern crate byteorder;
extern crate indy;
#[macro_use]
mod utils;
use indy::did::Did;
use indy::ErrorCode;
use std::sync::mpsc::channel;
use std::time::Duration;
use utils::b58::{FromBase58};
use utils::constants::{
DID_1,
SEED_1,
VERKEY_1,
METADATA,
VERKEY_ABV_1,
INVALID_HANDLE
};
use utils::setup::{Setup, SetupConfig};
use utils::wallet::Wallet;
const VALID_TIMEOUT: Duration = Duration::from_secs(5);
const INVALID_TIMEOUT: Duration = Duration::from_nanos(1);
#[inline]
fn assert_verkey_len(verkey: &str) {
assert_eq!(32, verkey.from_base58().unwrap().len());
}
#[cfg(test)]
mod create_new_did {
use super::*;
#[inline]
fn assert_did_length(did: &str) {
assert_eq!(16, did.from_base58().unwrap().len());
}
#[test]
fn create_did_with_empty_json() {
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
assert_did_length(&did);
assert_verkey_len(&verkey);
}
#[test]
fn create_did_with_seed() {
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
assert_eq!(DID_1, did);
assert_eq!(VERKEY_1, verkey);
}
#[test]
fn create_did_with_cid() {
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1,
"cid": true,
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
assert_eq!(VERKEY_1, did);
assert_eq!(VERKEY_1, verkey);
}
#[test]
fn create_did_with_did() {
let wallet = Wallet::new();
let config = json!({
"did": DID_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
assert_eq!(DID_1, did);
assert_ne!(VERKEY_1, verkey);
}
#[test]
fn create_did_with_crypto_type() {
let wallet = Wallet::new();
let config = json!({
"crypto_type": "ed25519"
}).to_string();
let result = Did::new(wallet.handle, &config);
assert!(result.is_ok());
}
#[test]
fn create_did_with_invalid_wallet_handle() {
let result = Did::new(INVALID_HANDLE, "{}");
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn create_wallet_empty_config() {
let wallet = Wallet::new();
let result = Did::new(wallet.handle, "");
assert!(result.is_err());
}
#[test]
fn create_did_async_no_config() {
let wallet = Wallet::new();
let (sender, receiver) = channel();
Did::new_async(
wallet.handle,
"{}",
move |ec, did, verkey| { sender.send((ec, did, verkey)).unwrap(); }
);
let (ec, did, verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_did_length(&did);
assert_verkey_len(&verkey);
}
#[test]
fn create_did_async_with_seed() {
let wallet = Wallet::new();
let (sender, receiver) = channel();
let config = json!({
"seed": SEED_1
}).to_string();
Did::new_async(
wallet.handle,
&config,
move |ec, did, key| { sender.send((ec, did, key)).unwrap(); }
);
let (ec, did, verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_eq!(DID_1, did);
assert_eq!(VERKEY_1, verkey);
}
#[test]
fn create_did_async_invalid_wallet() {
let (sender, receiver) = channel();
Did::new_async(
INVALID_HANDLE,
"{}",
move |ec, did, key| sender.send((ec, did, key)).unwrap()
);
let result = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
let expected = (ErrorCode::WalletInvalidHandle, String::new(), String::new());
assert_eq!(expected, result);
}
#[test]
fn create_did_timeout_no_config() {
let wallet = Wallet::new();
let (did, verkey) = Did::new_timeout(
wallet.handle,
"{}",
VALID_TIMEOUT
).unwrap();
assert_did_length(&did);
assert_verkey_len(&verkey);
}
#[test]
fn create_did_timeout_with_seed() {
let wallet = Wallet::new();
let config = json!({"seed": SEED_1}).to_string();
let (did, verkey) = Did::new_timeout(
wallet.handle,
&config,
VALID_TIMEOUT
).unwrap();
assert_eq!(DID_1, did);
assert_eq!(VERKEY_1, verkey);
}
#[test]
fn create_did_timeout_invalid_wallet() {
let result = Did::new_timeout(INVALID_HANDLE, "{}", VALID_TIMEOUT);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn create_did_timeout_timeouts() {
let wallet = Wallet::new();
let config = json!({"seed": SEED_1}).to_string();
let result = Did::new_timeout(
wallet.handle,
&config,
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod replace_keys_start {
use super::*;
#[test]
fn replace_keys_start() {
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
let new_verkey = Did::replace_keys_start(wallet.handle, &did, "{}").unwrap();
assert_verkey_len(&new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_start_invalid_wallet() {
let result = Did::replace_keys_start(INVALID_HANDLE, DID_1, "{}");
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn replace_keys_start_with_seed() {
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
let config = json!({"seed": SEED_1}).to_string();
let new_verkey = Did::replace_keys_start(wallet.handle, &did, &config).unwrap();
assert_eq!(VERKEY_1, new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_start_valid_crypto_type() {
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
let config = json!({"crypto_type": "ed25519"}).to_string();
let new_verkey = Did::replace_keys_start(wallet.handle, &did, &config).unwrap();
assert_verkey_len(&new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_start_invalid_crypto_type() {
let wallet = Wallet::new();
let (did, _verkey) = Did::new(wallet.handle, "{}").unwrap();
let config = json!({"crypto_type": "ed25518"}).to_string();
let result = Did::replace_keys_start(wallet.handle, &did, &config);
assert_eq!(ErrorCode::UnknownCryptoTypeError, result.unwrap_err());
}
#[test]
fn replace_keys_start_invalid_did() {
let wallet = Wallet::new();
let result = Did::replace_keys_start(wallet.handle, DID_1, "{}");
assert_eq!(ErrorCode::WalletItemNotFound, result.unwrap_err());
}
#[test]
fn replace_keys_start_async() {
let wallet = Wallet::new();
let (sender, receiver) = channel();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
Did::replace_keys_start_async(
wallet.handle,
&did,
"{}",
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, new_verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_verkey_len(&new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_start_async_invalid_wallet() {
let (sender, receiver) = channel();
Did::replace_keys_start_async(
INVALID_HANDLE,
DID_1,
"{}",
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, new_verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::WalletInvalidHandle, ec);
assert_eq!("", new_verkey);
}
#[test]
fn replace_keys_start_async_with_seed() {
let wallet = Wallet::new();
let (sender, receiver) = channel();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
let config = json!({"seed": SEED_1}).to_string();
Did::replace_keys_start_async(
wallet.handle,
&did,
&config,
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, new_verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_eq!(VERKEY_1, new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_start_timeout() {
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
let new_verkey = Did::replace_keys_start_timeout(
wallet.handle,
&did,
"{}",
VALID_TIMEOUT
).unwrap();
assert_verkey_len(&new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_start_timeout_with_seed() {
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
let config = json!({"seed": SEED_1}).to_string();
let new_verkey = Did::replace_keys_start_timeout(
wallet.handle,
&did,
&config,
VALID_TIMEOUT
).unwrap();
assert_eq!(VERKEY_1, new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_start_timeout_invalid_wallet() {
let result = Did::replace_keys_start_timeout(
INVALID_HANDLE,
DID_1,
"{}",
VALID_TIMEOUT
);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn replace_keys_start_timeout_timeouts() {
let wallet = Wallet::new();
let (did, _verkey) = Did::new(wallet.handle, "{}").unwrap();
let result = Did::replace_keys_start_timeout(
wallet.handle,
&did,
"{}",
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod replace_keys_apply {
use super::*;
fn setup() -> (Wallet, String, String) {
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
(wallet, did, verkey)
}
#[inline]
fn start_key_replacement(wallet: &Wallet, did: &str) {
let config = json!({"seed": SEED_1}).to_string();
Did::replace_keys_start(wallet.handle, did, &config).unwrap();
}
#[test]
fn replace_keys_apply() {
let (wallet, did, verkey) = setup();
start_key_replacement(&wallet, &did);
let result = Did::replace_keys_apply(wallet.handle, &did);
assert_eq!((), result.unwrap());
let new_verkey = Did::get_ver_key_local(wallet.handle, &did).unwrap();
assert_eq!(VERKEY_1, new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_apply_without_replace_keys_start() {
let (wallet, did, _) = setup();
let result = Did::replace_keys_apply(wallet.handle, &did);
assert_eq!(ErrorCode::WalletItemNotFound, result.unwrap_err());
}
#[test]
fn replace_keys_apply_invalid_did() {
let wallet = Wallet::new();
let result = Did::replace_keys_apply(wallet.handle, DID_1);
assert_eq!(ErrorCode::WalletItemNotFound, result.unwrap_err());
}
#[test]
fn replace_keys_apply_invalid_wallet() {
let result = Did::replace_keys_apply(INVALID_HANDLE, DID_1);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn replace_keys_apply_async() {
let (wallet, did, verkey) = setup();
let (sender, receiver) = channel();
start_key_replacement(&wallet, &did);
Did::replace_keys_apply_async(
wallet.handle,
&did,
move |ec| sender.send(ec).unwrap()
);
let ec = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
let new_verkey = Did::get_ver_key_local(wallet.handle, &did).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_eq!(VERKEY_1, new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_apply_async_invalid_wallet() {
let (sender, receiver) = channel();
Did::replace_keys_apply_async(
INVALID_HANDLE,
DID_1,
move |ec| sender.send(ec).unwrap()
);
let ec = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::WalletInvalidHandle, ec);
}
#[test]
fn replace_keys_apply_timeout() {
let (wallet, did, verkey) = setup();
start_key_replacement(&wallet, &did);
let result = Did::replace_keys_apply_timeout(
wallet.handle,
&did,
VALID_TIMEOUT
);
let new_verkey = Did::get_ver_key_local(wallet.handle, &did).unwrap();
assert_eq!((), result.unwrap());
assert_eq!(VERKEY_1, new_verkey);
assert_ne!(verkey, new_verkey);
}
#[test]
fn replace_keys_apply_timeout_invalid_wallet() {
let result = Did::replace_keys_apply_timeout(
INVALID_HANDLE,
DID_1,
VALID_TIMEOUT
);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn replace_keys_apply_timeout_timeouts() {
let result = Did::replace_keys_apply_timeout(
INVALID_HANDLE,
DID_1,
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod test_store_their_did {
use super::*;
#[test]
fn store_their_did() {
let wallet = Wallet::new();
let config = json!({"did": VERKEY_1}).to_string();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!((), result.unwrap());
let verkey = Did::get_ver_key_local(wallet.handle, VERKEY_1).unwrap();
assert_eq!(VERKEY_1, verkey);
}
#[test]
fn store_their_did_with_verkey() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!((), result.unwrap());
let verkey = Did::get_ver_key_local(wallet.handle, DID_1).unwrap();
assert_eq!(VERKEY_1, verkey);
}
#[test]
fn store_their_did_with_crypto_verkey() {
let wallet = Wallet::new();
let config = json!({
"did": DID_1,
"verkey": format!("{}:ed25519", VERKEY_1)
}).to_string();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!((), result.unwrap());
let verkey = Did::get_ver_key_local(wallet.handle, DID_1).unwrap();
assert_eq!(format!("{}:ed25519", VERKEY_1), verkey);
}
#[test]
fn store_their_did_empty_identify_json() {
let wallet = Wallet::new();
let result = Did::store_their_did(wallet.handle, "{}");
assert_eq!(ErrorCode::CommonInvalidStructure, result.unwrap_err());
}
#[test]
fn store_their_did_invalid_handle() {
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
let result = Did::store_their_did(INVALID_HANDLE, &config);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn store_their_did_abbreviated_verkey() {
let wallet = Wallet::new();
let config = json!({
"did": "8wZcEriaNLNKtteJvx7f8i",
"verkey": "~NcYxiDXkpYi6ov5FcYDi1e"
}).to_string();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!((), result.unwrap());
}
#[test]
fn store_their_did_invalid_did() {
let wallet = Wallet::new();
let config = json!({"did": "InvalidDid"}).to_string();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!(ErrorCode::CommonInvalidStructure, result.unwrap_err());
}
#[test]
fn store_their_did_with_invalid_verkey() {
let wallet = Wallet::new();
let config = json!({
"did": DID_1,
"verkey": "InvalidVerkey"
}).to_string();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!(ErrorCode::CommonInvalidStructure, result.unwrap_err());
}
#[test]
fn store_their_did_with_invalid_crypto_verkey() {
let wallet = Wallet::new();
let config = json!({
"did": DID_1,
"verkey": format!("{}:bad_crypto_type", VERKEY_1)
}).to_string();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!(ErrorCode::UnknownCryptoTypeError, result.unwrap_err());
}
#[test]
fn store_their_did_duplicate() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
Did::store_their_did(wallet.handle, &config).unwrap();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!(ErrorCode::WalletItemAlreadyExists, result.unwrap_err());
}
#[test]
/*
This test resulted from the ticket https://jira.hyperledger.org/browse/IS-802
Previously, an error was being thrown because rollback wasn't happening.
This test ensures the error is no longer occuring.
*/
fn store_their_did_multiple_error_fixed() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
Did::store_their_did(wallet.handle, &config).unwrap();
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!(ErrorCode::WalletItemAlreadyExists, result.unwrap_err());
let result = Did::store_their_did(wallet.handle, &config);
assert_eq!(ErrorCode::WalletItemAlreadyExists, result.unwrap_err());
}
#[test]
fn store_their_did_async_with_verkey() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
let (sender, receiver) = channel();
Did::store_their_did_async(
wallet.handle,
&config,
move |ec| sender.send(ec).unwrap()
);
let ec = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
let verkey = Did::get_ver_key_local(wallet.handle, DID_1).unwrap();
assert_eq!(VERKEY_1, verkey);
}
#[test]
fn store_their_did_async_invalid_wallet() {
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
let (sender, receiver) = channel();
Did::store_their_did_async(
INVALID_HANDLE,
&config,
move |ec| sender.send(ec).unwrap()
);
let ec = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::WalletInvalidHandle, ec);
}
#[test]
fn store_their_did_timeout_with_verkey() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
let result = Did::store_their_did_timeout(
wallet.handle,
&config,
VALID_TIMEOUT
);
assert_eq!((), result.unwrap());
let verkey = Did::get_ver_key_local(wallet.handle, DID_1).unwrap();
assert_eq!(VERKEY_1, verkey);
}
#[test]
fn store_their_did_timeout_invalid_wallet() {
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
let result = Did::store_their_did_timeout(
INVALID_HANDLE,
&config,
VALID_TIMEOUT
);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn store_their_did_timeout_timeouts() {
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
let result = Did::store_their_did_timeout(
INVALID_HANDLE,
&config,
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err())
}
}
#[cfg(test)]
mod test_get_verkey_local {
use super::*;
#[test]
fn get_verkey_local_my_did() {
let wallet = Wallet::new();
let config = json!({"seed": SEED_1}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
let stored_verkey = Did::get_ver_key_local(wallet.handle, &did).unwrap();
assert_eq!(verkey, stored_verkey);
}
#[test]
fn get_verkey_local_their_did() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
Did::store_their_did(wallet.handle, &config).unwrap();
let stored_verkey = Did::get_ver_key_local(wallet.handle, DID_1).unwrap();
assert_eq!(VERKEY_1, stored_verkey);
}
#[test]
fn get_verkey_local_invalid_did() {
let wallet = Wallet::new();
let result = Did::get_ver_key_local(wallet.handle, DID_1);
assert_eq!(ErrorCode::WalletItemNotFound, result.unwrap_err());
}
#[test]
fn get_verkey_local_invalid_wallet() {
let result = Did::get_ver_key_local(INVALID_HANDLE, DID_1);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn get_verkey_local_async() {
let wallet = Wallet::new();
let (sender, receiver) = channel();
let config = json!({"seed": SEED_1}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
Did::get_ver_key_local_async(
wallet.handle,
&did,
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, stored_verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_eq!(VERKEY_1, stored_verkey);
assert_eq!(verkey, stored_verkey);
}
#[test]
fn get_verkey_local_async_invalid_wallet() {
let (sender, receiver) = channel();
Did::get_ver_key_local_async(
INVALID_HANDLE,
DID_1,
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, stored_verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::WalletInvalidHandle, ec);
assert_eq!(String::from(""), stored_verkey);
}
#[test]
fn get_verkey_local_timeout() {
let wallet = Wallet::new();
let config = json!({"seed": SEED_1}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
let stored_verkey = Did::get_ver_key_local_timeout(
wallet.handle,
&did,
VALID_TIMEOUT
).unwrap();
assert_eq!(verkey, stored_verkey);
}
#[test]
fn get_verkey_local_timeout_invalid_wallet() {
let result = Did::get_ver_key_local_timeout(
INVALID_HANDLE,
DID_1,
VALID_TIMEOUT
);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn get_verkey_local_timeout_timeouts() {
let result = Did::get_ver_key_local_timeout(
INVALID_HANDLE,
DID_1,
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod test_get_verkey_ledger {
use super::*;
#[test]
fn get_verkey_my_did() {
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
let stored_verkey = Did::get_ver_key(
-1,
wallet.handle,
&did
).unwrap();
assert_eq!(verkey, stored_verkey);
}
#[test]
fn get_verkey_their_did() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
Did::store_their_did(wallet.handle, &config).unwrap();
let stored_verkey = Did::get_ver_key(
-1,
wallet.handle,
DID_1,
).unwrap();
assert_eq!(VERKEY_1, stored_verkey);
}
#[test]
fn get_verkey_not_on_ledger() {
let wallet = Wallet::new();
let wallet2 = Wallet::new();
let setup = Setup::new(&wallet, SetupConfig {
connect_to_pool: true,
num_trustees: 0,
num_users: 0,
num_nodes: 4
});
let pool_handle = setup.pool_handle.unwrap();
let (did, _verkey) = Did::new(wallet.handle, "{}").unwrap();
let result = Did::get_ver_key(
pool_handle,
wallet2.handle,
&did
);
assert_eq!(ErrorCode::WalletItemNotFound, result.unwrap_err());
}
#[test]
fn get_verkey_on_ledger() {
let wallet = Wallet::new();
let wallet2 = Wallet::new();
let setup = Setup::new(&wallet, SetupConfig {
connect_to_pool: true,
num_trustees: 1,
num_users: 1,
num_nodes: 4
});
let pool_handle = setup.pool_handle.unwrap();
let user = &setup.users.as_ref().unwrap()[0];
let ledger_verkey = Did::get_ver_key(
pool_handle,
wallet2.handle,
&user.did
).unwrap();
assert_eq!(ledger_verkey, user.verkey);
}
#[test]
fn get_verkey_invalid_pool() {
let wallet = Wallet::new();
let result = Did::get_ver_key(-1, wallet.handle, DID_1);
assert_eq!(ErrorCode::PoolLedgerInvalidPoolHandle, result.unwrap_err());
}
#[test]
fn get_verkey_invalid_wallet() {
let result = Did::get_ver_key(-1, INVALID_HANDLE, DID_1);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn get_verkey_async_my_did() {
let (sender, receiver) = channel();
let wallet = Wallet::new();
let (did, verkey) = Did::new(wallet.handle, "{}").unwrap();
Did::get_ver_key_async(
-1,
wallet.handle,
&did,
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, stored_verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_eq!(verkey, stored_verkey);
}
#[test]
fn get_verkey_async_invalid_wallet() {
let (sender, receiver) = channel();
Did::get_ver_key_async(
-1,
INVALID_HANDLE,
DID_1,
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, stored_verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::WalletInvalidHandle, ec);
assert_eq!(String::from(""), stored_verkey);
}
#[test]
fn get_verkey_timeout_my_did() {
let wallet = Wallet::new();
let config = json!({"seed": SEED_1}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
let stored_verkey = Did::get_ver_key_timeout(
-1,
wallet.handle,
&did,
VALID_TIMEOUT
).unwrap();
assert_eq!(verkey, stored_verkey);
}
#[test]
fn get_verkey_timeout_invalid_wallet() {
let result = Did::get_ver_key_timeout(
-1,
INVALID_HANDLE,
DID_1,
VALID_TIMEOUT
);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn get_verkey_timeout_timeouts() {
let result = Did::get_ver_key_timeout(
-1,
INVALID_HANDLE,
DID_1,
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod test_set_metadata {
use super::*;
#[inline]
fn setup() -> (Wallet, String) {
let wallet = Wallet::new();
let (did, _) = Did::new(wallet.handle, "{}").unwrap();
(wallet, did)
}
#[test]
fn set_metadata_my_did() {
let (wallet, did) = setup();
let result = Did::set_metadata(wallet.handle, &did, METADATA);
let metadata = Did::get_metadata(wallet.handle, &did).unwrap();
assert_eq!((), result.unwrap());
assert_eq!(METADATA, metadata);
}
#[test]
fn set_metadata_their_did() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
Did::store_their_did(wallet.handle, &config).unwrap();
let result = Did::set_metadata(wallet.handle, DID_1, METADATA);
let metadata = Did::get_metadata(wallet.handle, DID_1).unwrap();
assert_eq!((), result.unwrap());
assert_eq!(METADATA, metadata);
}
#[test]
fn set_metadata_replace_metadata() {
let (wallet, did) = setup();
Did::set_metadata(wallet.handle, &did, METADATA).unwrap();
let metadata = Did::get_metadata(wallet.handle, &did).unwrap();
assert_eq!(METADATA, metadata);
let next_metadata = "replacement metadata";
Did::set_metadata(wallet.handle, &did, next_metadata).unwrap();
let metadata = Did::get_metadata(wallet.handle, &did).unwrap();
assert_eq!(next_metadata, metadata);
}
#[test]
fn set_metadata_empty_string() {
let (wallet, did) = setup();
let result = Did::set_metadata(wallet.handle, &did, "");
let metadata = Did::get_metadata(wallet.handle, &did).unwrap();
assert_eq!((), result.unwrap());
assert_eq!("", metadata);
}
#[test]
fn set_metadata_invalid_did() {
let wallet = Wallet::new();
let result = Did::set_metadata(wallet.handle, "InvalidDid", METADATA);
assert_eq!(ErrorCode::CommonInvalidStructure, result.unwrap_err());
}
#[test]
fn set_metadata_unknown_did() {
let wallet = Wallet::new();
let result = Did::set_metadata(wallet.handle, DID_1, METADATA);
let metadata = Did::get_metadata(wallet.handle, DID_1).unwrap();
assert_eq!((), result.unwrap());
assert_eq!(METADATA, metadata);
}
#[test]
fn set_metadata_invalid_wallet() {
let result = Did::set_metadata(INVALID_HANDLE, DID_1, METADATA);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn set_metadata_async_my_did() {
let (sender, receiver) = channel();
let (wallet, did) = setup();
Did::set_metadata_async(
wallet.handle,
&did,
METADATA,
move |ec| sender.send(ec).unwrap()
);
let ec = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
let metadata = Did::get_metadata(wallet.handle, &did).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_eq!(METADATA, metadata);
}
#[test]
fn set_metadata_async_invalid_wallet() {
let (sender, receiver) = channel();
Did::set_metadata_async(
INVALID_HANDLE,
DID_1,
METADATA,
move |ec| sender.send(ec).unwrap()
);
let ec = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::WalletInvalidHandle, ec);
}
#[test]
fn set_metadata_timeout_my_did() {
let (wallet, did) = setup();
let result = Did::set_metadata_timeout(
wallet.handle,
&did,
METADATA,
VALID_TIMEOUT
);
let metadata = Did::get_metadata(wallet.handle, &did).unwrap();
assert_eq!((), result.unwrap());
assert_eq!(METADATA, metadata);
}
#[test]
fn set_metadata_timeout_invalid_wallet() {
let result = Did::set_metadata_timeout(
INVALID_HANDLE,
DID_1,
METADATA,
VALID_TIMEOUT
);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn set_metadata_timeout_timeouts() {
let result = Did::set_metadata_timeout(
INVALID_HANDLE,
DID_1,
METADATA,
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod test_get_metadata {
use super::*;
#[inline]
fn setup() -> (Wallet, String) {
let wallet = Wallet::new();
let (did, _) = Did::new(wallet.handle, "{}").unwrap();
(wallet, did)
}
#[test]
fn get_metadata_my_did() {
let (wallet, did) = setup();
Did::set_metadata(wallet.handle, &did, METADATA).unwrap();
let result = Did::get_metadata(wallet.handle, &did);
assert_eq!(METADATA, result.unwrap());
}
#[test]
fn get_metadata_their_did() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
Did::store_their_did(wallet.handle, &config).unwrap();
Did::set_metadata(wallet.handle, DID_1, METADATA).unwrap();
let result = Did::get_metadata(wallet.handle, DID_1);
assert_eq!(METADATA, result.unwrap());
}
#[test]
fn get_metadata_empty_string() {
let (wallet, did) = setup();
Did::set_metadata(wallet.handle, &did, "").unwrap();
let result = Did::get_metadata(wallet.handle, &did);
assert_eq!(String::from(""), result.unwrap());
}
#[test]
fn get_metadata_no_metadata_set() {
let (wallet, did) = setup();
let result = Did::get_metadata(wallet.handle, &did);
assert_eq!(ErrorCode::WalletItemNotFound, result.unwrap_err());
}
#[test]
fn get_metadata_unknown_did() {
let wallet = Wallet::new();
let result = Did::get_metadata(wallet.handle, DID_1);
assert_eq!(ErrorCode::WalletItemNotFound, result.unwrap_err());
}
#[test]
fn get_metadata_invalid_wallet() {
let result = Did::get_metadata(INVALID_HANDLE, DID_1);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn get_metadata_async_my_did() {
let (sender, receiver) = channel();
let (wallet, did) = setup();
Did::set_metadata(wallet.handle, &did, METADATA).unwrap();
Did::get_metadata_async(
wallet.handle,
&did,
move |ec, metadata| sender.send((ec, metadata)).unwrap()
);
let (ec, metadata) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_eq!(METADATA, metadata);
}
#[test]
fn get_metadata_async_invalid_wallet() {
let (sender, receiver) = channel();
Did::get_metadata_async(
INVALID_HANDLE,
DID_1,
move |ec, metadata| sender.send((ec, metadata)).unwrap()
);
let (ec, metadata) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::WalletInvalidHandle, ec);
assert_eq!("", &metadata);
}
#[test]
fn get_metadata_timeout_my_did() {
let (wallet, did) = setup();
Did::set_metadata(wallet.handle, &did, METADATA).unwrap();
let result = Did::get_metadata_timeout(
wallet.handle,
&did,
VALID_TIMEOUT
);
assert_eq!(METADATA, result.unwrap());
}
#[test]
fn get_metadata_timeout_invalid_wallet() {
let result = Did::get_metadata_timeout(
INVALID_HANDLE,
DID_1,
VALID_TIMEOUT
);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn get_metadata_timeout_timeouts() {
let result = Did::get_metadata_timeout(
INVALID_HANDLE,
DID_1,
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod test_set_endpoint {
use super::*;
#[test]
pub fn set_endpoint_succeeds() {
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
match indy::did::Did::set_endpoint(wallet.handle, &did, "192.168.1.10", &verkey) {
Ok(_) => {}
Err(ec) => {
assert!(false, "set_endpoint_works failed {:?}", ec)
}
}
}
#[test]
pub fn set_endpoint_timeout_succeeds() {
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
match indy::did::Did::set_endpoint_timeout(wallet.handle, &did, "192.168.1.10", &verkey, VALID_TIMEOUT) {
Ok(_) => {}
Err(ec) => {
assert!(false, "set_endpoint_works failed {:?}", ec)
}
}
}
#[test]
pub fn set_endpoint_timeout_fails_invalid_timeout() {
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
match indy::did::Did::set_endpoint_timeout(wallet.handle, &did, "192.168.1.10", &verkey, INVALID_TIMEOUT) {
Ok(_) => {
assert!(false, "set_endpoint_timeout failed to return error code other than SUCCESS");
}
Err(ec) => {
if ec != indy::ErrorCode::CommonIOError {
assert!(false, "set_endpoint_timeout failed error_code = {:?}", ec);
}
}
}
}
#[test]
pub fn set_endpoint_async_succeeds() {
let wallet = Wallet::new();
let (sender, receiver) = channel();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
let cb = move |ec| {
sender.send(ec).unwrap();
};
Did::set_endpoint_async(wallet.handle, &did, "192.168.1.10", &verkey, cb);
let error_code = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(error_code, indy::ErrorCode::Success, "set_endpoint_async_succeeds failed {:?}", error_code);
}
}
#[cfg(test)]
mod test_get_endpoint {
use super::*;
#[test]
pub fn get_endpoint_succeeds() {
let end_point_address = "192.168.1.10";
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
let pool_setup = Setup::new(&wallet, SetupConfig {
connect_to_pool: false,
num_trustees: 0,
num_nodes: 4,
num_users: 0,
});
match indy::did::Did::set_endpoint(wallet.handle, &did, end_point_address, &verkey) {
Ok(_) => {}
Err(ec) => {
assert!(false, "get_endpoint_works failed set_endpoint {:?}", ec)
}
}
let pool_handle = indy::pool::Pool::open_ledger(&pool_setup.pool_name, None).unwrap();
let mut test_succeeded : bool = false;
let mut error_code: indy::ErrorCode = indy::ErrorCode::Success;
match indy::did::Did::get_endpoint(wallet.handle, pool_handle, &did) {
Ok(ret_address) => {
let (address, _) = Some(ret_address).unwrap();
if end_point_address.to_string() == address {
test_succeeded = true;
}
},
Err(ec) => {
error_code = ec;
}
}
indy::pool::Pool::close(pool_handle).unwrap();
if indy::ErrorCode::Success != error_code {
assert!(false, "get_endpoint_works failed error code {:?}", error_code);
}
if false == test_succeeded {
assert!(false, "get_endpoint_works failed to successfully compare end_point address");
}
}
#[test]
pub fn get_endpoint_timeout_succeeds() {
let end_point_address = "192.168.1.10";
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
match indy::did::Did::set_endpoint(wallet.handle, &did, end_point_address, &verkey) {
Ok(_) => {}
Err(ec) => {
assert!(false, "get_endpoint_works failed at set endpoint {:?}", ec)
}
}
let pool_setup = Setup::new(&wallet, SetupConfig {
connect_to_pool: false,
num_trustees: 0,
num_nodes: 4,
num_users: 0,
});
let pool_handle = indy::pool::Pool::open_ledger(&pool_setup.pool_name, None).unwrap();
let mut test_succeeded : bool = false;
let mut error_code: indy::ErrorCode = indy::ErrorCode::Success;
match indy::did::Did::get_endpoint_timeout(wallet.handle, pool_handle, &did, VALID_TIMEOUT) {
Ok(ret_address) => {
let (address, _) = Some(ret_address).unwrap();
if end_point_address.to_string() == address {
test_succeeded = true;
}
},
Err(ec) => {
error_code = ec;
}
}
indy::pool::Pool::close(pool_handle).unwrap();
if indy::ErrorCode::Success != error_code {
assert!(false, "get_endpoint_timeout_succeeds failed error code {:?}", error_code);
}
if false == test_succeeded {
assert!(false, "get_endpoint_timeout_succeeds failed to successfully compare end_point address");
}
}
#[test]
pub fn get_endpoint_async_success() {
let end_point_address = "192.168.1.10";
let wallet = Wallet::new();
let (sender, receiver) = channel();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
let pool_setup = Setup::new(&wallet, SetupConfig {
connect_to_pool: false,
num_trustees: 0,
num_nodes: 4,
num_users: 0,
});
match indy::did::Did::set_endpoint(wallet.handle, &did, end_point_address, &verkey) {
Ok(_) => {}
Err(ec) => {
assert!(false, "get_endpoint_async failed set_endpoint {:?}", ec)
}
}
let pool_handle = indy::pool::Pool::open_ledger(&pool_setup.pool_name, None).unwrap();
let cb = move |ec, end_point, ver_key| {
sender.send((ec, end_point, ver_key)).unwrap();
};
Did::get_endpoint_async(wallet.handle, pool_handle, &did, cb);
let (error_code, _, _) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
indy::pool::Pool::close(pool_handle).unwrap();
assert_eq!(error_code, indy::ErrorCode::Success, "get_endpoint_async failed {:?}", error_code);
}
/// ----------------------------------------------------------------------------------------
/// get_endpoint_timeout_fails_invalid_timeout uses an impossibly small time out to trigger error
/// get_endpoint_timeout should return error code since the timeout triggers
/// ----------------------------------------------------------------------------------------
#[test]
pub fn get_endpoint_timeout_fails_invalid_timeout() {
let end_point_address = "192.168.1.10";
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
match indy::did::Did::set_endpoint(wallet.handle, &did, end_point_address, &verkey) {
Ok(_) => {}
Err(ec) => {
assert!(false, "get_endpoint_timeout_fails_invalid_timeout failed at set endpoint {:?}", ec)
}
}
let pool_setup = Setup::new(&wallet, SetupConfig {
connect_to_pool: false,
num_trustees: 0,
num_nodes: 4,
num_users: 0,
});
let pool_handle = indy::pool::Pool::open_ledger(&pool_setup.pool_name, None).unwrap();
let mut error_code: indy::ErrorCode = indy::ErrorCode::Success;
match indy::did::Did::get_endpoint_timeout(wallet.handle, pool_handle, &did, INVALID_TIMEOUT) {
Ok(_) => {
},
Err(ec) => {
error_code = ec;
}
}
indy::pool::Pool::close(pool_handle).unwrap();
assert_eq!(error_code, indy::ErrorCode::CommonIOError);
}
/// ----------------------------------------------------------------------------------------
/// get_endpoint_fails_no_set doesnt call set_endpoint before calling get_endpoint.
/// get_endpoint should return error code since the endpoint has not been set
/// ----------------------------------------------------------------------------------------
#[test]
pub fn get_endpoint_fails_no_set() {
let wallet = Wallet::new();
let config = json!({
"seed": SEED_1
}).to_string();
let (did, _verkey) = Did::new(wallet.handle, &config).unwrap();
let pool_setup = Setup::new(&wallet, SetupConfig {
connect_to_pool: false,
num_trustees: 0,
num_nodes: 4,
num_users: 0,
});
let pool_handle = indy::pool::Pool::open_ledger(&pool_setup.pool_name, None).unwrap();
let mut error_code: indy::ErrorCode = indy::ErrorCode::Success;
match indy::did::Did::get_endpoint(wallet.handle, pool_handle, &did) {
Ok(_) => { },
Err(ec) => {
error_code = ec;
}
}
indy::pool::Pool::close(pool_handle).unwrap();
assert_eq!(error_code, indy::ErrorCode::CommonInvalidState);
}
}
#[cfg(test)]
mod test_abbreviate_verkey {
use super::*;
#[test]
fn abbreviate_verkey_abbreviated() {
let result = Did::abbreviate_verkey(DID_1, VERKEY_1);
assert_eq!(VERKEY_ABV_1, result.unwrap());
}
#[test]
fn abbreviate_verkey_full_verkey() {
let wallet = Wallet::new();
let config = json!({"did": DID_1}).to_string();
let (did, verkey) = Did::new(wallet.handle, &config).unwrap();
let result = Did::abbreviate_verkey(&did, &verkey);
assert_eq!(verkey, result.unwrap());
}
#[test]
fn abbreviate_verkey_invalid_did() {
let result = Did::abbreviate_verkey("InvalidDid", VERKEY_1);
assert_eq!(ErrorCode::CommonInvalidStructure, result.unwrap_err());
}
#[test]
fn abbreviate_verkey_invalid_verkey() {
let result = Did::abbreviate_verkey(DID_1, "InvalidVerkey");
assert_eq!(ErrorCode::CommonInvalidStructure, result.unwrap_err());
}
#[test]
fn abbreviate_verkey_async_abbreviated() {
let (sender, receiver) = channel();
Did::abbreviate_verkey_async(
DID_1,
VERKEY_1,
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::Success, ec);
assert_eq!(VERKEY_ABV_1, verkey);
}
#[test]
fn abbreviate_verkey_async_invalid_did() {
let (sender, receiver) = channel();
Did::abbreviate_verkey_async(
"InvalidDid",
VERKEY_1,
move |ec, verkey| sender.send((ec, verkey)).unwrap()
);
let (ec, verkey) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::CommonInvalidStructure, ec);
assert_eq!("", verkey);
}
#[test]
fn abbreviate_verkey_timeout_abbreviated() {
let result = Did::abbreviate_verkey_timeout(
DID_1,
VERKEY_1,
VALID_TIMEOUT
);
assert_eq!(VERKEY_ABV_1, result.unwrap());
}
#[test]
fn abbreviate_verkey_timeout_invalid_did() {
let result = Did::abbreviate_verkey_timeout(
"InvalidDid",
VERKEY_1,
VALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonInvalidStructure, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn abbreviate_verkey_timeout_timeouts() {
let result = Did::abbreviate_verkey_timeout(
DID_1,
VERKEY_1,
INVALID_TIMEOUT
);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod test_list_with_metadata {
use super::*;
fn setup_multiple(wallet: &Wallet) -> Vec<serde_json::Value> {
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
Did::store_their_did(wallet.handle, &config).unwrap();
let (did1, verkey1) = Did::new(wallet.handle, "{}").unwrap();
let (did2, verkey2) = Did::new(wallet.handle, "{}").unwrap();
Did::set_metadata(wallet.handle, &did1, METADATA).unwrap();
let expected = vec![
json!({
"did": did1,
"verkey": verkey1,
"tempVerkey": null,
"metadata": Some(METADATA.to_string()),
}),
json!({
"did": did2,
"verkey": verkey2,
"tempVerkey": null,
"metadata": null
})
];
expected
}
fn assert_multiple(json: String, expected: Vec<serde_json::Value>) {
let dids: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
assert_eq!(expected.len(), dids.len());
for did in expected {
assert!(dids.contains(&did));
}
}
#[test]
fn list_with_metadata_no_dids() {
let wallet = Wallet::new();
let result = Did::list_with_metadata(wallet.handle);
assert_eq!("[]", result.unwrap());
}
#[test]
fn list_with_metadata_their_did() {
let wallet = Wallet::new();
let config = json!({"did": DID_1, "verkey": VERKEY_1}).to_string();
Did::store_their_did(wallet.handle, &config).unwrap();
let result = Did::list_with_metadata(wallet.handle);
assert_eq!("[]", result.unwrap());
}
#[test]
fn list_with_metadata_cryptonym() {
let wallet = Wallet::new();
let config = json!({"seed": SEED_1, "cid": true}).to_string();
Did::new(wallet.handle, &config).unwrap();
let json = Did::list_with_metadata(wallet.handle).unwrap();
let dids: serde_json::Value = serde_json::from_str(&json).unwrap();
let expected = json!([{
"did": VERKEY_1,
"verkey": VERKEY_1,
"tempVerkey": null,
"metadata": null
}]);
assert_eq!(expected, dids);
}
#[test]
fn list_with_metadata_did_with_metadata() {
let wallet = Wallet::new();
let config = json!({"seed": SEED_1}).to_string();
Did::new(wallet.handle, &config).unwrap();
Did::set_metadata(wallet.handle, DID_1, METADATA).unwrap();
let json = Did::list_with_metadata(wallet.handle).unwrap();
let dids: serde_json::Value = serde_json::from_str(&json).unwrap();
let expected = json!([{
"did": DID_1,
"verkey": VERKEY_1,
"tempVerkey": null,
"metadata": METADATA
}]);
assert_eq!(expected, dids);
}
#[test]
fn list_with_metadata_multiple_dids() {
let wallet = Wallet::new();
let expected = setup_multiple(&wallet);
let dids = Did::list_with_metadata(wallet.handle).unwrap();
assert_multiple(dids, expected);
}
#[test]
fn list_with_metadata_invalid_wallet() {
let result = Did::list_with_metadata(INVALID_HANDLE);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
fn list_with_metadata_async_multiple_dids() {
let (sender, receiver) = channel();
let wallet = Wallet::new();
let expected = setup_multiple(&wallet);
Did::list_with_metadata_async(
wallet.handle,
move |ec, list| sender.send((ec, list)).unwrap()
);
let (_ec, list) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_multiple(list, expected);
}
#[test]
fn list_with_metadata_async_invalid_wallet() {
let (sender, receiver) = channel();
Did::list_with_metadata_async(
INVALID_HANDLE,
move |ec, list| sender.send((ec, list)).unwrap()
);
let (ec, list) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(ErrorCode::WalletInvalidHandle, ec);
assert_eq!("", list);
}
#[test]
fn list_with_metadata_timeout_multiple_dids() {
let wallet = Wallet::new();
let expected = setup_multiple(&wallet);
let json = Did::list_with_metadata_timeout(
wallet.handle,
VALID_TIMEOUT
).unwrap();
assert_multiple(json, expected);
}
#[test]
fn list_with_metadata_timeout_invalid_wallet() {
let result = Did::list_with_metadata_timeout(INVALID_HANDLE, VALID_TIMEOUT);
assert_eq!(ErrorCode::WalletInvalidHandle, result.unwrap_err());
}
#[test]
#[cfg(feature = "timeout_tests")]
fn list_with_metadata_timeout_timeouts() {
let result = Did::list_with_metadata_timeout(INVALID_HANDLE, INVALID_TIMEOUT);
assert_eq!(ErrorCode::CommonIOError, result.unwrap_err());
}
}
#[cfg(test)]
mod test_get_my_metadata {
use super::*;
#[test]
pub fn get_my_metadata_success() {
let wallet = Wallet::new();
let (did, _verkey) = Did::new(wallet.handle, "{}").unwrap();
match Did::get_my_metadata(wallet.handle, &did) {
Ok(_) => {},
Err(ec) => {
assert!(false, "get_my_metadata_success failed with error code {:?}", ec);
}
}
}
#[test]
pub fn get_my_metadata_async_success() {
let wallet = Wallet::new();
let (sender, receiver) = channel();
let (did, _verkey) = Did::new(wallet.handle, "{}").unwrap();
let cb = move |ec, data| {
sender.send((ec, data)).unwrap();
};
Did::get_my_metadata_async(wallet.handle, &did, cb);
let (error_code, _meta_data) = receiver.recv_timeout(VALID_TIMEOUT).unwrap();
assert_eq!(error_code, indy::ErrorCode::Success, "get_my_metadata_async_success failed error_code {:?}", error_code);
}
#[test]
pub fn get_my_metadata_timeout_success() {
let wallet = Wallet::new();
let (did, _verkey) = Did::new(wallet.handle, "{}").unwrap();
match Did::get_my_metadata_timeout(wallet.handle, &did, VALID_TIMEOUT) {
Ok(_) => {},
Err(ec) => {
assert!(false, "get_my_metadata_timeout_success failed with error code {:?}", ec);
}
}
}
#[test]
pub fn get_my_metadata_invalid_timeout_error() {
let wallet = Wallet::new();
let (did, _verkey) = Did::new(wallet.handle, "{}").unwrap();
match Did::get_my_metadata_timeout(wallet.handle, &did, INVALID_TIMEOUT) {
Ok(_) => {
assert!(false, "get_my_metadata_invalid_timeout_error failed to timeout");
},
Err(ec) => {
assert_eq!(ec, indy::ErrorCode::CommonIOError, "get_my_metadata_invalid_timeout_error failed with error code {:?}", ec);
}
}
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
extern crate proc_macro;
mod expand;
use self::expand::{expand, Mode};
use proc_macro::TokenStream;
use syn::parse::Nothing;
use syn::parse_macro_input;
// Expand from:
//
// #[fbinit::main]
// fn main(fb: FacebookInit) {
// ...
// }
//
// to:
//
// fn main() {
// let fb: FacebookInit = fbinit::r#impl::perform_init();
// ...
// }
//
// If async, also add a #[tokio::main] attribute.
#[proc_macro_attribute]
pub fn main(args: TokenStream, input: TokenStream) -> TokenStream {
parse_macro_input!(args as Nothing);
expand(Mode::Main, parse_macro_input!(input))
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
// Same thing, expand:
//
// #[fbinit::test]
// fn name_of_test(fb: FacebookInit) {
// ...
// }
//
// to:
//
// #[test]
// fn name_of_test() {
// let fb: FacebookInit = fbinit::r#impl::perform_init();
// ...
// }
//
// with either #[test] or #[tokio::test] attribute.
#[proc_macro_attribute]
pub fn test(args: TokenStream, input: TokenStream) -> TokenStream {
parse_macro_input!(args as Nothing);
expand(Mode::Test, parse_macro_input!(input))
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
#[proc_macro_attribute]
pub fn compat_test(args: TokenStream, input: TokenStream) -> TokenStream {
parse_macro_input!(args as Nothing);
expand(Mode::CompatTest, parse_macro_input!(input))
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
|
use fixed_hash::*;
use impl_codec::impl_fixed_hash_codec;
use impl_rlp::impl_fixed_hash_rlp;
use impl_serde::impl_fixed_hash_serde;
construct_fixed_hash! { pub struct H768(96); }
impl_fixed_hash_rlp!(H768, 96);
impl_fixed_hash_serde!(H768, 96);
impl_fixed_hash_codec!(H768, 96);
|
use anyhow::{Context, Result};
use console::style;
use log::*;
use std::env;
use std::io;
use std::path::{Path, PathBuf};
use std::process;
use structopt::{
clap::arg_enum, clap::crate_authors, clap::crate_description, clap::crate_version,
clap::AppSettings, StructOpt,
};
use uvm_cli::{options::ColorOption, set_colors_enabled, set_loglevel};
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 {
/// the build platform to open the project with
#[structopt(short, long, possible_values = &UnityPlatform::variants(), case_insensitive = true)]
platform: Option<UnityPlatform>,
/// print more output
#[structopt(short, long, parse(from_occurrences))]
verbose: i32,
/// Detects a unity project recursivly from current working or <project-path> directory.
#[structopt(short, long)]
recursive: bool,
/// Will launch try to launch the project with the Unity version the project was created from.
#[structopt(short, long)]
force_project_version: bool,
/// Color:.
#[structopt(short, long, possible_values = &ColorOption::variants(), case_insensitive = true, default_value)]
color: ColorOption,
/// Path to the Unity Project
#[structopt(parse(from_os_str))]
project_path: Option<PathBuf>,
}
fn main() -> Result<()> {
let opt = Opts::from_args();
set_colors_enabled(&opt.color);
set_loglevel(opt.verbose);
launch(&opt).context("failed to launch Unity")?;
Ok(())
}
arg_enum! {
#[derive(Debug, Clone)]
pub enum UnityPlatform {
Win32,
Win64,
OSX,
Linux,
Linux64,
IOS,
Android,
Web,
WebStreamed,
WebGl,
XboxOne,
PS4,
PSP2,
WsaPlayer,
Tizen,
SamsungTV,
}
}
fn get_installation(
project_path: &Path,
use_project_version: bool,
) -> uvm_core::error::Result<uvm_core::Installation> {
if use_project_version {
let version = uvm_core::dectect_project_version(&project_path, None)?;
let installation = uvm_core::find_installation(&version)?;
return Ok(installation);
}
let installation = uvm_core::current_installation()?;
Ok(installation)
}
fn launch(options: &Opts) -> Result<()> {
let project_path = options
.project_path
.as_ref()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| env::current_dir().expect("current working directory"));
let project_path = uvm_core::detect_unity_project_dir(&project_path, options.recursive)?;
info!("launch project: {}", style(&project_path.display()).cyan());
let installtion = get_installation(&project_path, options.force_project_version)
.map_err(|_| io::Error::new(io::ErrorKind::Other, "Failed to fetch unity installation!"))?;
info!(
"launch unity version: {}",
style(installtion.version().to_string()).cyan()
);
let mut command = process::Command::new(
installtion
.exec_path()
.canonicalize()
.unwrap()
.to_str()
.unwrap(),
);
if let Some(ref platform) = options.platform {
command.arg("-buildTarget").arg(platform.to_string());
};
command
.arg("-projectPath")
.arg(project_path.canonicalize().unwrap().to_str().unwrap());
command.spawn()?;
Ok(())
}
|
use {
crate::{
client::{self, RequestType},
entities::*,
Client,
},
std::error::Error,
};
/// Get the metadata of every song on listen.moe
pub async fn get(listen_moe_client: &Client) -> Result<Vec<SongAPI>, Box<dyn Error>> {
Ok(client::perform_request::<GeneralMessage>(
RequestType::Get,
"/songs".into(),
Some(listen_moe_client),
)
.await?
.1
.songs)
}
|
use crate::exactstreamer::ExactStreamer;
use crate::gen::Generator;
use cpal::traits::DeviceTrait;
use cpal::traits::EventLoopTrait;
use cpal::traits::HostTrait;
use cpal::{Format, Host, SampleRate, StreamData, UnknownTypeOutputBuffer};
use parking_lot::RwLock;
use std::sync::Arc;
pub const GENERATOR_BUFFER_SIZE: usize = 256;
pub const GENERATOR_CHANNEL_SIZE: usize = 6;
pub struct Audio {}
/// starts audio streaming to an audio device and also steps the generator with a fixed buffer of size `GENERATOR_BUFFER_SIZE`
pub fn init(
gen: Arc<RwLock<Generator>>,
sample_rate: u32,
) -> Result<(Audio, crossbeam::Receiver<Vec<f32>>), String> {
let (generator_sender, device_receiver) = crossbeam::channel::bounded(GENERATOR_CHANNEL_SIZE);
let (generator_fft_sender, fft_receiver) = crossbeam::channel::bounded(GENERATOR_CHANNEL_SIZE);
let host: Host = cpal::default_host();
let event_loop = host.event_loop();
let speaker = host
.default_output_device()
.ok_or_else(|| "Failed to get default audio output device".to_string())?;
println!(
"Audio driver: {:?}\nSamplerate: {} Hz",
host.id(),
sample_rate
);
println!("Audio output device: {}", speaker.name().unwrap());
let format = speaker
.default_output_format()
.expect("Failed to get default audio device's default output format");
println!("Audio output format: {:?}", format.data_type);
let speaker_stream_id = event_loop
.build_output_stream(
&speaker,
&Format {
sample_rate: SampleRate(sample_rate),
channels: format.channels,
data_type: format.data_type,
},
)
.expect("Failed to build audio output stream");
event_loop.play_stream(speaker_stream_id).unwrap();
let channels = format.channels as usize;
std::thread::spawn({
move || {
let mut stream = ExactStreamer::new(GENERATOR_BUFFER_SIZE, device_receiver);
let mut buf = [0.0; 8192];
event_loop.run(move |_stream_id, data| match data {
Ok(StreamData::Output { buffer }) => match buffer {
UnknownTypeOutputBuffer::F32(mut data) => {
let _ = stream.fill(&mut buf[..data.len() / channels]);
data.chunks_mut(channels)
.zip(buf.iter())
.for_each(|(a, &b)| {
a.iter_mut().for_each(|a| *a = b);
});
}
UnknownTypeOutputBuffer::U16(mut data) => {
let _ = stream.fill(&mut buf[..data.len() / channels]);
data.chunks_mut(channels)
.zip(buf.iter())
.for_each(|(a, &b)| {
let v = if b > 1.0 {
std::u16::MAX
} else if b < -1.0 {
0
} else {
(((b + 1.0) * std::u16::MAX as f32) as u32 / 2) as u16
};
a.iter_mut().for_each(|a| *a = v);
});
}
UnknownTypeOutputBuffer::I16(mut data) => {
let _ = stream.fill(&mut buf[..data.len() / channels]);
data.chunks_mut(channels)
.zip(buf.iter())
.for_each(|(a, &b)| {
let v = (if b > 1.0 {
std::u16::MAX
} else if b < -1.0 {
0
} else {
(((b + 1.0) * std::u16::MAX as f32) as u32 / 2) as u16
} as i32
+ std::u16::MIN as i32)
as i16;
a.iter_mut().for_each(|a| *a = v);
});
}
},
Err(e) => {
println!("== An error occurred: {}", e);
}
_ => (),
});
}
});
std::thread::spawn({
move || {
let mut buf = [0.0f32; GENERATOR_BUFFER_SIZE];
loop {
// contains lock guard
{
gen.write().generate(&mut buf);
}
let _ = generator_fft_sender.try_send(buf.to_vec());
if generator_sender.send(buf.to_vec()).is_err() {
break;
}
}
}
});
Ok((Audio {}, fft_receiver))
}
|
#[derive(Debug)]
pub struct Args {
pub file_name: String,
}
pub fn get_args() -> Result<Args, String> {
let raw_args = std::env::args().collect::<Vec<_>>();
match &raw_args[..] {
[_, file] => Ok(Args {
file_name: file.to_string(),
}),
[_] => Err("Missing file argument".to_string()),
_ => Err("Too much arguments, only need 1 file name".to_string()),
}
}
|
use domain_client_block_preprocessor::runtime_api::StateRootExtractor;
use domain_client_block_preprocessor::xdm_verifier::verify_xdm;
use sc_transaction_pool::error::Result as TxPoolResult;
use sc_transaction_pool_api::error::Error as TxPoolError;
use sc_transaction_pool_api::TransactionSource;
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_core::traits::SpawnNamed;
use sp_domains::{DomainId, DomainsApi};
use sp_runtime::traits::{Block as BlockT, NumberFor};
use std::marker::PhantomData;
use std::sync::Arc;
use subspace_transaction_pool::PreValidateTransaction;
pub struct DomainTxPreValidator<Block, CBlock, Client, CClient, SRE> {
domain_id: DomainId,
client: Arc<Client>,
spawner: Box<dyn SpawnNamed>,
consensus_client: Arc<CClient>,
state_root_extractor: SRE,
_phantom_data: PhantomData<(Block, CBlock)>,
}
impl<Block, CBlock, Client, CClient, SRE> Clone
for DomainTxPreValidator<Block, CBlock, Client, CClient, SRE>
where
SRE: Clone,
{
fn clone(&self) -> Self {
Self {
domain_id: self.domain_id,
client: self.client.clone(),
spawner: self.spawner.clone(),
consensus_client: self.consensus_client.clone(),
state_root_extractor: self.state_root_extractor.clone(),
_phantom_data: self._phantom_data,
}
}
}
impl<Block, CBlock, Client, CClient, SRE>
DomainTxPreValidator<Block, CBlock, Client, CClient, SRE>
{
pub fn new(
domain_id: DomainId,
client: Arc<Client>,
spawner: Box<dyn SpawnNamed>,
consensus_client: Arc<CClient>,
state_root_extractor: SRE,
) -> Self {
Self {
domain_id,
client,
spawner,
consensus_client,
state_root_extractor,
_phantom_data: Default::default(),
}
}
}
#[async_trait::async_trait]
impl<Block, CBlock, Client, CClient, SRE> PreValidateTransaction
for DomainTxPreValidator<Block, CBlock, Client, CClient, SRE>
where
Block: BlockT,
CBlock: BlockT,
CBlock::Hash: From<Block::Hash>,
NumberFor<CBlock>: From<NumberFor<Block>>,
Client: ProvideRuntimeApi<Block> + Send + Sync,
CClient: HeaderBackend<CBlock> + ProvideRuntimeApi<CBlock> + 'static,
CClient::Api: DomainsApi<CBlock, NumberFor<Block>, Block::Hash>,
SRE: StateRootExtractor<Block> + Send + Sync,
{
type Block = Block;
async fn pre_validate_transaction(
&self,
at: Block::Hash,
_source: TransactionSource,
uxt: Block::Extrinsic,
) -> TxPoolResult<()> {
if !verify_xdm::<CClient, CBlock, Block, SRE>(
&self.consensus_client,
at,
&self.state_root_extractor,
&uxt,
)? {
return Err(TxPoolError::ImmediatelyDropped.into());
}
Ok(())
}
}
|
use async_trait::async_trait;
use common::result::Result;
use crate::domain::catalogue::Publication;
#[async_trait]
pub trait PublicationService: Sync + Send {
async fn get_by_id(&self, id: &str) -> Result<Publication>;
}
|
// Added as part the code review and testing
// by ChainSafe Systems Aug 2021
use crate::cmix::{Scheduling, SoftwareHashes};
use super::*;
use mock::*;
use frame_support::{assert_noop, assert_ok};
type SoftwareHash = <mock::Test as frame_system::Config>::Hash;
///////////////////////////////
// set_cmix_hashes //
///////////////////////////////
#[test]
fn set_cmix_hashes_can_call_with_admin_during_permission_period() {
ExtBuilder::default()
.with_admin_permission(10)
.build_and_execute(|| {
run_to_block(10); // admin period is inclusive
let new_hashes = SoftwareHashes {
server: SoftwareHash::repeat_byte(0x55),
..Default::default()
};
assert_ok!(XXCmix::set_cmix_hashes(
Origin::root(),
new_hashes.clone()
));
assert_eq!(XXCmix::cmix_hashes(), new_hashes,);
assert_eq!(
*xx_cmix_events().last().unwrap(),
RawEvent::CmixHashesUpdated
);
});
}
#[test]
fn set_cmix_hashes_fails_outside_permission_period() {
ExtBuilder::default()
.with_admin_permission(10)
.build_and_execute(|| {
run_to_block(11);
assert_noop!(
XXCmix::set_cmix_hashes(Origin::root(), Default::default()),
Error::<Test>::AdminPermissionExpired,
);
});
}
////////////////////////////////////
// set_scheduling_account //
////////////////////////////////////
#[test]
fn set_scheduling_account_can_call_with_admin_during_permission_period() {
let new_scheduling_account = 1;
ExtBuilder::default()
.with_admin_permission(10)
.build_and_execute(|| {
run_to_block(10);
assert_ok!(XXCmix::set_scheduling_account(
Origin::root(),
new_scheduling_account
));
assert_eq!(XXCmix::scheduling_account(), new_scheduling_account,);
assert_eq!(
*xx_cmix_events().last().unwrap(),
RawEvent::SchedulingAccountUpdated
);
});
}
////////////////////////////////////
// set_next_cmix_variables //
////////////////////////////////////
#[test]
fn set_next_cmix_variables_can_call_with_cmix_vars_origin() {
let new_variables = cmix::Variables {
scheduling: Scheduling {
team_size: 4,
..Default::default()
},
..Default::default()
};
ExtBuilder::default().build_and_execute(|| {
start_active_era(1);
let init_cmix_vars = XXCmix::cmix_variables();
assert_ok!(XXCmix::set_next_cmix_variables(
Origin::root(),
new_variables.clone()
));
assert_eq!(
XXCmix::next_cmix_variables(),
Some(new_variables.clone()),
);
// actual variables have not been set yet
// Not set until next era
assert_eq!(XXCmix::cmix_variables(), init_cmix_vars);
// In the next era they are set
start_active_era(2);
assert_eq!(XXCmix::cmix_variables(), new_variables);
assert_eq!(
*xx_cmix_events().last().unwrap(),
RawEvent::CmixVariablesUpdated
);
});
}
////////////////////////////////////////////////////////
// submit_cmix_points / submit_cmix_deductions //
////////////////////////////////////////////////////////
#[test]
fn cmix_points_fails_if_not_scheduling() {
ExtBuilder::default().build_and_execute(|| {
assert_noop!(
XXCmix::submit_cmix_points(Origin::signed(1), Vec::new()),
Error::<Test>::MustBeScheduling,
);
assert_noop!(
XXCmix::submit_cmix_deductions(Origin::signed(1), Vec::new()),
Error::<Test>::MustBeScheduling,
);
});
}
#[test]
fn cmix_points_adds_remove_points_in_staking_pallet() {
let scheduling = 1;
let a = 2;
let first_addition = 10;
let second_addition = 33;
ExtBuilder::default()
.with_scheduling_acccount(scheduling)
.build_and_execute(|| {
start_active_era(1);
assert_ok!(XXCmix::submit_cmix_points(
Origin::signed(scheduling),
vec![(a, first_addition)]
),);
assert_ok!(XXCmix::submit_cmix_points(
Origin::signed(scheduling),
vec![(a, second_addition)]
),);
assert_eq!(
Staking::eras_reward_points(active_era()).individual.get(&a),
Some(&(first_addition + second_addition + 1))
);
// now deduct. Should not go below 1
assert_ok!(XXCmix::submit_cmix_deductions(
Origin::signed(scheduling),
vec![(a, 99)]
),);
assert_eq!(
Staking::eras_reward_points(active_era()).individual.get(&a),
Some(&1)
);
assert_eq!(
xx_cmix_events(),
vec![
RawEvent::CmixPointsAdded,
RawEvent::CmixPointsAdded,
RawEvent::CmixPointsDeducted
]
);
});
}
///////////////////////////////////
// set_cmix_address_space //
///////////////////////////////////
#[test]
fn set_cmix_address_space_fails_if_not_scheduling() {
ExtBuilder::default().build_and_execute(|| {
assert_noop!(
XXCmix::set_cmix_address_space(Origin::signed(1), 0x77),
Error::<Test>::MustBeScheduling,
);
});
}
#[test]
fn set_cmix_address_space_sets_storage() {
let scheduling = 1;
let new_address_space = 0x77;
ExtBuilder::default()
.with_scheduling_acccount(scheduling)
.build_and_execute(|| {
assert_ok!(XXCmix::set_cmix_address_space(
Origin::signed(1),
new_address_space
));
assert_eq!(XXCmix::cmix_address_space(), new_address_space);
});
}
|
#[allow(unused_imports)]
use super::prelude::*;
use super::intcode::IntcodeDevice;
type Input = IntcodeDevice;
pub fn input_generator(input: &str) -> Input {
input.parse().expect("Error parsing the IntcodeDevice")
}
pub fn part1(input: &Input) -> i64 {
let mut devices = (0..50).map(|ip| {
let mut device = input.clone();
device.input.push_back(ip);
device
}).collect::<Vec<_>>();
for ip in (0..devices.len()).cycle() {
let device = &mut devices[ip];
if device.input.len() == 0 {
device.input.push_back(-1);
}
device.execute();
let output = device.output.drain(..).collect::<Vec<_>>();
for o in output.chunks(3) {
if o.len() != 3 {
panic!("Invalid packet size")
} else if o[0] == 255 {
return o[2]
} else if o[0] >= 0 && o[0] < 50 {
devices[o[0] as usize].input.extend(&o[1..])
} else {
panic!("Invalid ip")
}
}
}
unreachable!();
}
pub fn part2(input: &Input) -> i64 {
let mut devices = (0..50).map(|ip| {
let mut device = input.clone();
device.input.push_back(ip);
device
}).collect::<Vec<_>>();
let mut sent = true;
let mut nat = [0, 0];
let mut nat_seen = std::collections::HashSet::new();
loop {
if !sent {
if nat_seen.insert(nat[1]) {
devices[0].input.extend(&nat);
} else {
return nat[1]
}
}
sent = false;
for ip in 0..devices.len() {
let device = &mut devices[ip];
if device.input.len() == 0 {
device.input.push_back(-1);
}
device.execute();
let output = devices[ip].output.drain(..).collect::<Vec<_>>();
for packet in output.chunks(3) {
if packet.len() != 3 {
panic!("Invalid packet size")
} else if packet[0] == 255 {
nat = [packet[1], packet[2]];
} else if packet[0] >= 0 && packet[0] < 50 {
devices[packet[0] as usize].input.extend(&packet[1..])
} else {
panic!("Invalid ip")
}
sent = true;
}
}
}
}
|
use crate::geometry::{Position, Rect, Size};
/// Defines the drawing bounds of an object.
pub trait Bounds {
/// Gets the object position.
fn get_position(&self) -> Position;
/// Gets the object size.
fn get_size(&self) -> Size;
// Gets bounds as a Rect.
fn get_bounds(&self) -> Rect {
Rect {
pos: self.get_position(),
size: self.get_size(),
}
}
}
/// Writable bounds.
pub trait BoundsMut: Bounds {
/// Sets the object position.
fn set_position(&mut self, position: Position);
/// Sets the object size.
fn set_size(&mut self, size: Size);
/// Sets the object bounds.
fn set_bounds(&mut self, bounds: Rect) {
self.set_position(bounds.pos);
self.set_size(bounds.size);
}
}
impl Bounds for Rect {
#[inline]
fn get_position(&self) -> Position {
self.pos
}
#[inline]
fn get_size(&self) -> Size {
self.size
}
#[inline]
fn get_bounds(&self) -> Rect {
*self
}
}
impl BoundsMut for Rect {
#[inline]
fn set_position(&mut self, position: Position) {
self.pos = position;
}
#[inline]
fn set_size(&mut self, size: Size) {
self.size = size;
}
#[inline]
fn set_bounds(&mut self, bounds: Rect) {
*self = bounds;
}
}
impl Bounds for Position {
#[inline]
fn get_position(&self) -> Position {
*self
}
#[inline]
fn get_size(&self) -> Size {
Default::default()
}
}
impl Bounds for () {
#[inline]
fn get_position(&self) -> Position {
Default::default()
}
#[inline]
fn get_size(&self) -> Size {
Default::default()
}
}
|
use crate::{error::ProcessingError, fuzzers, search::read_runs};
use indicatif::ParallelProgressIterator;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use serde_json::Value;
use std::{
fs::{read_dir, DirEntry, File},
path::{Path, PathBuf},
time::Instant,
};
use url::Url;
/// A separate struct for raw Sentry events.
/// A custom `Deserialize` impl might be more efficient
#[derive(Debug, serde::Deserialize)]
struct RawSentryEvent {
#[serde(rename(deserialize = "eventID"))]
event_id: String,
#[serde(rename(deserialize = "groupID"))]
group_id: String,
title: String,
message: String,
culprit: String,
tags: Vec<Tag>,
entries: Vec<Entry>,
metadata: Metadata,
}
#[derive(Debug, serde::Deserialize)]
struct Tag {
key: String,
value: String,
}
#[derive(Debug, serde::Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all(deserialize = "snake_case"))]
enum Entry {
Exception { data: ExceptionData },
Request { data: RequestData },
Message,
Breadcrumbs,
}
#[derive(Debug, serde::Deserialize)]
struct ExceptionData {
values: Vec<ExceptionValue>,
}
#[derive(Debug, serde::Deserialize)]
struct RequestData {
method: Option<String>,
url: String,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
struct ExceptionValue {
r#type: String,
value: Option<String>,
stacktrace: Option<Stacktrace>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
struct Stacktrace {
frames: Vec<Frame>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
struct Frame {
#[serde(rename(deserialize = "lineNo"))]
line_no: Option<usize>,
#[serde(rename(deserialize = "colNo"))]
col_no: Option<usize>,
function: String,
filename: String,
#[serde(skip_serializing)]
// Used in some corner-cases to determine HTTP method
vars: Value,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
#[serde(rename_all(deserialize = "snake_case"))]
enum Metadata {
Error { r#type: String, value: String },
OnlyTitle { title: String },
}
#[derive(Debug, serde::Serialize)]
struct SentryEvent {
#[serde(rename(deserialize = "eventID"))]
event_id: String,
#[serde(rename(deserialize = "groupID"))]
group_id: String,
title: String,
message: String,
culprit: String,
// Tag with the `transaction` key
transaction: Option<String>,
// `method` and `path` are extracted from the `entry` object with the `request` type if it is available
// In some cases they are extracted from the stacktrace & other location
method: Option<String>,
path: Option<String>,
exceptions: Vec<Vec<ExceptionValue>>,
metadata: Metadata,
}
pub fn parse_events(
in_directory: &Path,
out_directory: &Path,
fuzzers: &[fuzzers::Fuzzer],
targets: &[String],
indices: &[String],
) -> Result<(), ProcessingError> {
let start = Instant::now();
let paths = read_runs(in_directory, fuzzers, targets, indices)?;
let total: usize = paths
.par_iter()
.progress_count(paths.len() as u64)
.map(|entry| process_run(entry, out_directory))
.sum();
println!(
"SENTRY: Processed {} events in {:.3} seconds",
total,
Instant::now().duration_since(start).as_secs_f32()
);
Ok(())
}
fn process_run(entry: &DirEntry, out_directory: &Path) -> usize {
let sentry_events_dir = entry.path().join("sentry_events");
if sentry_events_dir.exists() {
let paths: Vec<_> = read_dir(sentry_events_dir)
.expect("Failed to read dir")
.map(|e| e.expect("Invalid entry").path())
.collect();
let events: Vec<_> = paths.par_iter().filter_map(process_file).collect();
let output_path = out_directory
.join(entry.path().file_name().expect("Missing directory name"))
.join("sentry.json");
let output_file = File::create(&output_path).expect("Failed to create file");
serde_json::to_writer(output_file, &events).expect("Failed to serialize events");
events.len()
} else {
0
}
}
fn should_be_skipped(event: &RawSentryEvent) -> bool {
// Some Python projects emit such lines sometimes
event.title.contains("code 400, message Bad request syntax")
// Emitted by Tornado on SIGTERM
|| event.title.contains("received signal 15, stopping")
|| event.title.contains("Received signal SIGTERM")
// Logs from Jupyter
|| event.title.contains("To access the server, open this file in a browser:")
// Jupyter Server specific log entry
|| event.title == "{"
}
fn process_file(path: &PathBuf) -> Option<SentryEvent> {
let file = File::open(path).expect("Can not open file");
let raw_event: Result<RawSentryEvent, _> = serde_json::from_reader(file);
match raw_event {
Ok(raw_event) => {
if should_be_skipped(&raw_event) {
return None;
}
let get_transaction = |tags: &[Tag]| -> Option<String> {
for tag in tags {
if tag.key == "transaction" {
return Some(tag.value.clone());
}
}
None
};
let transaction = get_transaction(&raw_event.tags);
let get_endpoint = |entries: &[Entry]| -> (Option<String>, Option<String>) {
for entry in entries {
match entry {
Entry::Request {
data: RequestData { method, url },
} => {
if let Some(method) = method {
let path = Url::parse(url).expect("Invalid URL").path().to_owned();
return (Some(method.clone()), Some(path));
}
}
Entry::Message | Entry::Breadcrumbs | Entry::Exception { .. } => continue,
}
}
// It may be a Gunicorn-level error that is logged differently
if let Some((_, path)) = raw_event.message.split_once("Error handling request ") {
for entry in entries {
match entry {
// The only place where we can get the HTTP method is local variables in one of the
// stackframes
Entry::Exception {
data: ExceptionData { values },
} => {
for ExceptionValue { stacktrace, .. } in values {
if let Some(Stacktrace { frames }) = stacktrace {
for Frame { vars, .. } in frames {
if let Some(value) =
vars["environ"]["REQUEST_METHOD"].as_str()
{
let method = &value[1..value.len() - 1];
return (
Some(method.to_owned()),
Some(path.to_owned()),
);
}
}
}
}
}
Entry::Message | Entry::Breadcrumbs | Entry::Request { .. } => continue,
}
}
};
(None, None)
};
let (method, path) = get_endpoint(&raw_event.entries);
let exceptions = {
let mut out = Vec::new();
for entry in &raw_event.entries {
match entry {
Entry::Exception {
data: ExceptionData { values },
} => out.push(values.clone()),
Entry::Message | Entry::Breadcrumbs | Entry::Request { .. } => continue,
}
}
out
};
Some(SentryEvent {
event_id: raw_event.event_id,
group_id: raw_event.group_id,
title: raw_event.title,
message: raw_event.message,
culprit: raw_event.culprit,
transaction,
method,
path,
exceptions,
metadata: raw_event.metadata,
})
}
Err(error) => {
panic!("Invalid file: {:?} ({})", path, error);
}
}
}
|
use std::fs::File;
use std::io::Read;
#[derive(PartialEq, Clone, Debug)]
enum GridElement {
Empty,
Tree,
}
fn solve_part1(map: &[Vec<GridElement>]) -> usize {
tree_in_slope(map, 3, 1)
}
fn solve_part2(map: &[Vec<GridElement>]) -> usize {
tree_in_slope(map, 1, 1)
* tree_in_slope(map, 3, 1)
* tree_in_slope(map, 5, 1)
* tree_in_slope(map, 7, 1)
* tree_in_slope(map, 1, 2)
}
fn tree_in_slope(map: &[Vec<GridElement>], vx: usize, vy: usize) -> usize {
let max_x = map[0].len();
let mut tree_count = 0;
let mut pos_x = 0;
for line in map.iter().step_by(vy) {
if line[pos_x % max_x] == GridElement::Tree {
tree_count += 1;
}
pos_x += vx;
}
tree_count
}
fn parse_part1(input: &str) -> Vec<Vec<GridElement>> {
input
.lines()
.map(|line| {
line.chars()
.map(|c| match c {
'.' => GridElement::Empty,
'#' => GridElement::Tree,
_ => unimplemented!(),
})
.collect()
})
.collect()
}
pub fn part1() {
let mut file = File::open("input/2020/day3.txt").unwrap();
let mut input = String::new();
file.read_to_string(&mut input).unwrap();
println!("{}", solve_part1(&parse_part1(&input)));
}
pub fn part2() {
let mut file = File::open("input/2020/day3.txt").unwrap();
let mut input = String::new();
file.read_to_string(&mut input).unwrap();
println!("{}", solve_part2(&parse_part1(&input)));
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn solve_day3_part1_example() {
assert_eq!(
solve_part1(&vec![
vec![
GridElement::Empty,
GridElement::Empty,
GridElement::Tree,
GridElement::Tree
],
vec![
GridElement::Empty,
GridElement::Empty,
GridElement::Empty,
GridElement::Tree
],
vec![
GridElement::Empty,
GridElement::Empty,
GridElement::Tree,
GridElement::Empty
],
]),
2
);
}
#[test]
fn parse_day3_part1_example() {
assert_eq!(
parse_part1("..##\n#...\n.#..\n"),
vec![
vec![
GridElement::Empty,
GridElement::Empty,
GridElement::Tree,
GridElement::Tree
],
vec![
GridElement::Tree,
GridElement::Empty,
GridElement::Empty,
GridElement::Empty
],
vec![
GridElement::Empty,
GridElement::Tree,
GridElement::Empty,
GridElement::Empty
],
]
);
}
}
|
pub mod protobuf_types;
mod adler_read;
mod adler_write;
mod backup_format;
mod bundle_format;
mod encryption_key_info;
mod file_format;
mod header_format;
mod index_format;
mod instruction_format;
mod protobuf_message;
mod storage_info_format;
pub use self::adler_read::AdlerRead;
pub use self::adler_read::adler_verify_hash;
pub use self::adler_read::adler_verify_hash_and_eof;
pub use self::adler_write::AdlerWrite;
pub use self::adler_write::AdlerWriter;
pub use self::adler_write::adler_write_hash;
pub use self::backup_format::backup_read_path;
pub use self::bundle_format::DiskBundleInfo;
pub use self::bundle_format::bundle_info_read_path;
pub use self::bundle_format::bundle_read_path;
pub use self::bundle_format::bundle_write_direct;
pub use self::encryption_key_info::DiskEncryptionKeyInfoRef;
pub use self::file_format::file_open_with_crypto_and_adler;
pub use self::file_format::writer_wrap_with_crypto_and_adler;
pub use self::header_format::DiskFileHeader;
pub use self::index_format::DiskIndexBundleHeader;
pub use self::index_format::index_read_path;
pub use self::index_format::index_write_auto;
pub use self::index_format::index_write_direct;
pub use self::index_format::index_write_with_id;
pub use self::instruction_format::DiskBackupInstruction;
pub use self::protobuf_message::protobuf_message_read;
pub use self::protobuf_message::protobuf_message_write;
pub use self::storage_info_format::DiskStorageInfo;
pub use self::storage_info_format::storage_info_read;
// ex: noet ts=4 filetype=rust
|
use std::net::Ipv4Addr;
use api::start_server;
use shared::Settings;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
pretty_env_logger::init();
let settings = Settings {
address: Ipv4Addr::new(0, 0, 0, 0),
port: 8080,
};
start_server(settings).await
}
|
//! Halstead complexity metrics
use std::collections::HashMap;
use std::fmt::Write;
use sqlparser::ast::*;
use crate::visitor::{ Visitor, Acceptor };
/// Our definition of "operators" in SQL.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Operator {
/// A Common table Expression
Cte,
/// A table alias (`table_name(column1, column2, ...)`)
TableAlias,
/// A set operation.
Set {
op: SetOperator,
all: bool,
},
/// `VALUES (...), (...)`
Values,
/// The `SELECT ...` part of a SELECT clause, without the `FROM`.
Select { distinct: bool },
/// `FROM ...`
From,
/// `CASE ... WHEN ...`
Case,
/// `... IS NULL`
IsNull,
/// `... IS NOT NULL`
IsNotNull,
/// `EXISTS ...`
Exists,
/// Any other unary operator
Unary(UnaryOperator),
/// `IN ...` (list or subquery)
In,
/// `CAST(... AS ...)` type conversion
Cast,
/// Function call
Function,
/// Any other binary operator
Binary(BinaryOperator),
/// `... [NOT] BETWEEN ... AND ...`
Between { negated: bool },
/// `ORDER BY` clause
OrderBy,
/// `GROUP BY` clause
GroupBy,
/// `WHERE` clause
Where,
/// `HAVING` clause
Having,
/// `LIMIT` clause
Limit,
/// `OFFSET` clause
Offset,
/// `FETCH [FIRST | LAST] ... [ROWS]` clause
Fetch,
/// `[INNER] JOIN`
InnerJoin,
/// `LEFT [OUTER] JOIN`
LeftJoin,
/// `RIGHT [OUTER] JOIN`
RightJoin,
/// `[FULL] OUTER JOIN`
OuterJoin,
/// `CROSS JOIN`
CrossJoin,
/// `CROSS APPLY`
CrossApply,
/// `OUTER APPLY`
OuterApply,
/// `ON ...` JOIN constraint
OnJoinConstraint,
/// `USING ...` JOIN constraint
UsingJoinConstraint,
/// `NATURAL` JOIN constraint
NaturalJoinConstraint,
}
/// Our definition of "operands" in SQL.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Operand {
/// An identifier.
Ident(String),
/// `*`, all columns.
Wildcard,
/// `NULL` literal.
Null,
/// A Boolean literal.
Boolean(bool),
/// A numeric literal.
Number(String),
/// A string literal.
String(String),
}
/// Visitor for computing Halstead measures.
#[derive(Clone, Default, Debug)]
struct HalsteadVisitor {
/// Accumulates the count of operators.
operators: HashMap<Operator, usize>,
/// Accumulates the count of operands.
operands: HashMap<Operand, usize>,
}
impl HalsteadVisitor {
/// Increment the number of operators.
fn add_operator(&mut self, op: Operator) {
*self.operators.entry(op).or_insert(0) += 1;
}
/// Increment the number of operands.
fn add_operand(&mut self, op: Operand) {
*self.operands.entry(op).or_insert(0) += 1;
}
}
impl Visitor for HalsteadVisitor {
fn visit_query(&mut self, query: &Query) {
// `Query` is not a single operator, it represents
// different parts of a `SELECT` in one type.
// So do not add a separate `Operator::Select` here
// (that will be handled by the visitor of the body,
// which is a `SetExpr`).
//
// Do add operators for the different sub-clauses, however.
// These (ORDER BY, LIMIT, OFFSET, FETCH) do not have
// their own visitor methods, because they should not be
// counted as separate AST nodes -- they are markers for
// the actual children of a select, which is their inner
// expression. However, they are operators on their own,
// so it is useful to include them in the Halstead metric.
if query.order_by.len() > 0 {
// NB: we intentionally do not distinguish
// between ASCENDING and DESCENDING sorts.
self.add_operator(Operator::OrderBy);
}
if query.limit.is_some() {
self.add_operator(Operator::Limit);
}
if query.offset.is_some() {
self.add_operator(Operator::Offset);
}
if query.fetch.is_some() {
// Similarly, we do not distinguish between
// syntactically different forms of `FETCH`.
// An argument could be made for doing so,
// however.
self.add_operator(Operator::Fetch);
}
}
fn visit_with(&mut self, _with: &With) {
// `With` is not a single operator, it represents
// one or many CTEs.
// So do not add a separate `Operator::With` here
// -- the `visit_cte()` method will handle each
// CTE on its own. The `WITH` clause merely makes
// the distinction between there being any CTEs
// or there being none, so it's not an operator
// on its own right.
}
fn visit_cte(&mut self, _cte: &Cte) {
self.add_operator(Operator::Cte);
}
fn visit_set_op(
&mut self,
op: SetOperator,
all: bool,
_left: &SetExpr,
_right: &SetExpr,
) {
self.add_operator(Operator::Set { op, all });
}
fn visit_values(&mut self, _values: &Values) {
self.add_operator(Operator::Values);
}
fn visit_select(&mut self, select: &Select) {
// We want to treat `SELECT` and `SELECT DISTINCT`
// as different kinds of operators.
self.add_operator(Operator::Select {
distinct: select.distinct,
});
// See the comment in `visit_query()` for a description
// of the disctinction between AST nodes and operators,
// and why we explicitly visit components of the `Select`
// whereas these components have no corresponding visitor
// methods.
if select.top.is_some() {
todo!("SELECT TOP ... is not yet supported");
}
if select.from.len() > 0 {
self.add_operator(Operator::From);
}
if select.selection.is_some() {
self.add_operator(Operator::Where);
}
if select.group_by.len() > 0 {
self.add_operator(Operator::GroupBy);
}
if select.having.is_some() {
self.add_operator(Operator::Having);
}
}
fn visit_ident(&mut self, ident: &Ident) {
// ignore quote style
self.add_operand(Operand::Ident(ident.value.clone()));
}
fn visit_compound_ident(&mut self, idents: &[Ident]) {
let mut ident = String::from(&idents[0].value);
for part in &idents[1..] {
write!(ident, ".{}", part.value).unwrap();
}
self.add_operand(Operand::Ident(ident))
}
fn visit_wildcard(&mut self) {
self.add_operand(Operand::Wildcard);
}
fn visit_table_alias(&mut self, _alias: &TableAlias) {
self.add_operator(Operator::TableAlias);
}
fn visit_object_name(&mut self, name: &ObjectName) {
// An object name is just a compound identifier in disguise.
self.visit_compound_ident(&name.0);
}
fn visit_join(&mut self, join: &Join) {
use JoinOperator::*;
// the JOIN kind and the constraint kind are
// not explicitly visited by `Join::accept`.
let (kind, constraint) = match join.join_operator {
Inner(ref c) => (Operator::InnerJoin, Some(c)),
LeftOuter(ref c) => (Operator::LeftJoin, Some(c)),
RightOuter(ref c) => (Operator::RightJoin, Some(c)),
FullOuter(ref c) => (Operator::OuterJoin, Some(c)),
CrossJoin => (Operator::CrossJoin, None),
CrossApply => (Operator::CrossApply, None),
OuterApply => (Operator::OuterApply, None),
};
self.add_operator(kind);
if let Some(constraint) = constraint {
let kind = match *constraint {
JoinConstraint::On(_) => Operator::OnJoinConstraint,
JoinConstraint::Using(_) => Operator::UsingJoinConstraint,
JoinConstraint::Natural => Operator::NaturalJoinConstraint,
JoinConstraint::None => return,
};
self.add_operator(kind);
}
}
fn visit_unary_op(&mut self, op: &Expr) {
let kind = match *op {
Expr::IsNull(_) => Operator::IsNull,
Expr::IsNotNull(_) => Operator::IsNotNull,
Expr::Exists(_) => Operator::Exists,
Expr::UnaryOp { ref op, expr: _ } => Operator::Unary(op.clone()),
_ => unreachable!("not a unary operator: `{}`", op),
};
self.add_operator(kind);
}
fn visit_binary_op(&mut self, op: &Expr) {
let kind = match *op {
Expr::InList { .. } | Expr::InSubquery { .. } => Operator::In,
Expr::Cast { .. } => Operator::Cast,
Expr::Function(_) => Operator::Function,
Expr::BinaryOp { ref op, .. } => Operator::Binary(op.clone()),
_ => unreachable!("not a binary operator: `{}`", op),
};
self.add_operator(kind);
}
fn visit_between(&mut self, negated: bool) {
self.add_operator(Operator::Between { negated });
}
fn visit_value(&mut self, value: &Value) {
let operand = match *value {
Value::Null => Operand::Null,
Value::Boolean(b) => Operand::Boolean(b),
Value::Number(ref n, _) => Operand::Number(n.clone()),
| Value::SingleQuotedString(ref s)
| Value::DoubleQuotedString(ref s)
| Value::NationalStringLiteral(ref s)
| Value::HexStringLiteral(ref s) // maybe handle this differently?
=> Operand::String(s.clone()),
Value::Interval { .. } => todo!("INTERVAL is not yet supported"),
};
self.add_operand(operand);
}
fn visit_type(&mut self, _type: &DataType) {
todo!()
}
fn visit_case(
&mut self,
_discriminant: Option<&Expr>,
_conditions: &[Expr],
_results: &[Expr],
_else_result: Option<&Expr>,
) {
self.add_operator(Operator::Case);
}
}
/// Computes all Halstead metrics.
#[derive(Clone, Copy, Debug)]
pub struct HalsteadMetrics {
/// Program vocabulary, `eta = eta_1 + eta_2`
pub vocabulary: f64,
/// Program length, `N = N_1 + N_2`
pub length: f64,
/// Calculated estimated program length,
/// `N_hat = eta_1 * log2(eta_1) + eta_2 * log2(eta_2)`
pub estimated_length: f64,
/// Program volume, `V = N * log2(eta)`
pub volume: f64,
/// Difficulty of understanding, `D = eta_1 / 2 * N_2 / eta_2`
pub difficulty: f64,
/// Implementation effort, `E = D * V`
pub effort: f64,
}
impl HalsteadMetrics {
/// Compute Halstead metrics from `eta_1`, `eta_2`, `N_1`, `N_2`
pub fn new(eta_1: usize, eta_2: usize, n_1: usize, n_2: usize) -> Self {
let eta_1 = eta_1 as f64;
let eta_2 = eta_2 as f64;
let n_1 = n_1 as f64;
let n_2 = n_2 as f64;
let eta = eta_1 + eta_2;
let n = n_1 + n_2;
let n_hat = eta_1 * f64::log2(eta_1) + eta_2 * f64::log2(eta_2);
let v = n * f64::log2(eta);
let d = eta_1 / 2.0 * (n_2 / eta_2);
let e = d * v;
HalsteadMetrics {
vocabulary: eta,
length: n,
estimated_length: n_hat,
volume: v,
difficulty: d,
effort: e,
}
}
}
/// Returns the total number of nodes in the AST.
pub fn halstead_metrics(stmt: &Statement) -> HalsteadMetrics {
let mut v = HalsteadVisitor::default();
stmt.accept(&mut v);
let eta_1 = v.operators.len();
let eta_2 = v.operands.len();
let n_1 = v.operators.values().sum::<usize>();
let n_2 = v.operands.values().sum::<usize>();
HalsteadMetrics::new(eta_1, eta_2, n_1, n_2)
}
|
use std;
use std::sync::Arc;
use warp;
use warp::Filter;
use super::Result;
use crate::controller::{SimpleWishlistController, WishlistController};
use crate::reject::handle_rejection;
macro_rules! reply_future {
($controller:ident, $method:ident) => {{
|controller: Arc<dyn $controller>| async move {
match controller.$method() {
Ok(output) => Ok(warp::reply::json(&output)),
Err(e) => Err(warp::reject::custom(e)),
}
}
}};
}
pub async fn create_routes() -> Result<impl warp::Filter<Extract = impl warp::Reply> + Clone> {
let wishlist_controller: Arc<dyn WishlistController> =
Arc::new(SimpleWishlistController::new()?);
let wishlist_controller_filter = warp::any().map(move || wishlist_controller.clone());
let log_filter = warp::log("api");
let route_get_last_wishlist = warp::get()
.and(warp::path("api"))
.and(warp::path("wishlist"))
.and(warp::path("last"))
.and(warp::path::end())
.and(wishlist_controller_filter.clone())
.and_then(reply_future!(WishlistController, get_last_wishlist));
let routes = route_get_last_wishlist
.recover(handle_rejection)
.with(log_filter);
Ok(routes)
}
|
fn main() {
proconio::input! {
n: usize,
x: i32,
a: [i32; n],
}
let vec:Vec<String> = a.iter()
.filter(|&e| e != &x)
.cloned()
.map(|x| x.to_string())
.collect();
print!("{}", vec.join(" "));
}
|
use crate::types::linalg::dimension::Dimension;
use std::ops::{Add, Mul, Sub};
#[derive(Clone, PartialEq)]
#[repr(C)]
pub struct Matrix<T> {
pub data: Vec<T>,
pub dimension: Dimension,
}
impl Matrix<f32> {
pub fn zero4() -> Matrix<f32> {
Matrix::from_data(vec![0.; 16], Dimension::new(4, 4))
}
pub fn identity4() -> Matrix<f32> {
Matrix::from_data(
vec![
1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.,
],
Dimension::new(4, 4),
)
}
pub fn scale4(self, s1: f32, s2: f32, s3: f32) -> Matrix<f32> {
let mut res = Matrix::identity4();
res.data[res.dimension.to_index(0, 0)] = s1;
res.data[res.dimension.to_index(1, 1)] = s2;
res.data[res.dimension.to_index(2, 2)] = s3;
self.mul(res)
}
pub fn sscale4(self, s: f32) -> Matrix<f32> {
self.scale4(s, s, s)
}
pub fn translate4(self, t1: f32, t2: f32, t3: f32) -> Matrix<f32> {
let mut res = Matrix::identity4();
res.data[res.dimension.to_index(0, 3)] = t1;
res.data[res.dimension.to_index(1, 3)] = t2;
res.data[res.dimension.to_index(2, 3)] = t3;
self.mul(res)
}
pub fn ttranslate4(self, t: f32) -> Matrix<f32> {
self.translate4(t, t, t)
}
pub fn rotate4(self, rx: f32, ry: f32, rz: f32, theta: f32) -> Matrix<f32> {
let mut res = Matrix::zero4();
let cos = theta.cos();
let sin = theta.sin();
res.data[res.dimension.to_index(0, 0)] = cos + rx * rx * (1.0 - cos);
res.data[res.dimension.to_index(0, 1)] = rx * ry * (1.0 - cos) - rz * sin;
res.data[res.dimension.to_index(0, 2)] = rx * rz * (1.0 - cos) + ry * sin;
res.data[res.dimension.to_index(1, 0)] = ry * rx * (1.0 - cos) + rz * sin;
res.data[res.dimension.to_index(1, 1)] = cos + ry * ry * (1.0 - cos);
res.data[res.dimension.to_index(1, 2)] = ry * rz * (1.0 - cos) - rx * sin;
res.data[res.dimension.to_index(2, 0)] = rz * rx * (1.0 - cos) - ry * sin;
res.data[res.dimension.to_index(2, 1)] = rz * ry * (1.0 - cos) + rx * sin;
res.data[res.dimension.to_index(2, 2)] = cos + rz * rz * (1.0 - cos);
res.data[res.dimension.to_index(3, 3)] = 1.;
self.mul(res)
}
pub fn rot90(self, rx: f32, ry: f32, rz: f32) -> Matrix<f32> {
self.rotate4(rx, ry, rz, 90.0f32.to_radians())
}
pub fn rot180(self, rx: f32, ry: f32, rz: f32) -> Matrix<f32> {
self.rotate4(rx, ry, rz, 180.0f32.to_radians())
}
pub fn rot270(self, rx: f32, ry: f32, rz: f32) -> Matrix<f32> {
self.rotate4(rx, ry, rz, 270.0f32.to_radians())
}
}
impl<T: Copy> Matrix<T> {
pub fn from_data(data: Vec<T>, dimension: Dimension) -> Self {
debug_assert!(!data.is_empty());
Matrix { dimension, data }
}
pub fn as_ptr(&self) -> *const T {
self.data.as_ptr()
}
pub fn apply_closure<F>(&mut self, closure: F)
where
F: Fn(T, usize) -> T,
{
for index in self.dimension.iter() {
self.data[index] = closure(self.data[index], index);
}
}
pub fn from_closure<F>(closure: F, dimension: Dimension) -> Matrix<T>
where
F: Fn(usize) -> T,
{
let mut data = Vec::with_capacity(dimension.rows * dimension.columns);
for index in dimension.iter() {
data.push(closure(index));
}
Matrix { dimension, data }
}
pub fn closure_into_buffer<F>(&mut self, closure: F)
where
F: Fn(usize) -> T,
{
for index in self.dimension.iter() {
self.data[index] = closure(index);
}
}
}
//Matrix Matrix Addition and Subtraction
impl<T: Add<T, Output = T> + Copy> Add for Matrix<T> {
type Output = Matrix<T>;
fn add(mut self, other: Matrix<T>) -> Self::Output {
debug_assert!(self.dimension == other.dimension);
self.apply_closure(|t, index| t + other.data[index]);
self
}
}
impl<'a, 'b, T: Add<T, Output = T> + Copy> Add<&'b Matrix<T>> for &'a Matrix<T> {
type Output = Matrix<T>;
fn add(self, other: &'b Matrix<T>) -> Self::Output {
debug_assert!(self.dimension == other.dimension);
Matrix::from_closure(|index| self.data[index] + other.data[index], self.dimension)
}
}
impl<T: Sub<T, Output = T> + Copy> Sub for Matrix<T> {
type Output = Matrix<T>;
fn sub(mut self, other: Matrix<T>) -> Self::Output {
debug_assert!(self.dimension == other.dimension);
self.apply_closure(|t, index| t - other.data[index]);
self
}
}
impl<'a, 'b, T: Sub<T, Output = T> + Copy> Sub<&'b Matrix<T>> for &'a Matrix<T> {
type Output = Matrix<T>;
fn sub(self, other: &'b Matrix<T>) -> Self::Output {
debug_assert!(self.dimension == other.dimension);
Matrix::from_closure(|index| self.data[index] - other.data[index], self.dimension)
}
}
//Matrix Scalar Addition and Subtraction and Multiplication
impl<T: Add<T, Output = T> + Copy> Add<T> for Matrix<T> {
type Output = Matrix<T>;
fn add(mut self, other: T) -> Self::Output {
self.apply_closure(|t, _| t + other);
self
}
}
impl<'a, T: Add<T, Output = T> + Copy> Add<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn add(self, other: T) -> Self::Output {
Matrix::from_closure(|index| self.data[index] + other, self.dimension)
}
}
impl<T: Sub<T, Output = T> + Copy> Sub<T> for Matrix<T> {
type Output = Matrix<T>;
fn sub(mut self, other: T) -> Self::Output {
self.apply_closure(|t, _| t - other);
self
}
}
impl<'a, T: Sub<T, Output = T> + Copy> Sub<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn sub(self, other: T) -> Self::Output {
Matrix::from_closure(|index| self.data[index] - other, self.dimension)
}
}
impl<T: Mul<T, Output = T> + Copy> Mul<T> for Matrix<T> {
type Output = Matrix<T>;
fn mul(mut self, other: T) -> Self::Output {
self.apply_closure(|t, _| t * other);
self
}
}
impl<'a, T: Mul<T, Output = T> + Copy> Mul<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: T) -> Self::Output {
Matrix::from_closure(|index| self.data[index] * other, self.dimension)
}
}
//Matrix Matrix Multiplication
pub trait Zero: Sized + Add<Self, Output = Self> {
fn zero() -> Self;
}
impl Zero for i32 {
#[inline(always)]
fn zero() -> Self {
0
}
}
impl Zero for f32 {
#[inline(always)]
fn zero() -> Self {
0.
}
}
impl<T: Mul<T, Output = T> + Add<T, Output = T> + Zero + Copy> Mul<Matrix<T>> for Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: Matrix<T>) -> Self::Output {
debug_assert!(self.dimension.columns == other.dimension.rows);
let output_dimension = Dimension::new(self.dimension.rows, other.dimension.columns);
Matrix::from_closure(
|index| {
let (row, colm) = output_dimension.to_xy(index);
(0..self.dimension.columns).fold(Zero::zero(), |curr, i| {
curr + self.data[self.dimension.to_index(row, i)]
* other.data[other.dimension.to_index(i, colm)]
})
},
output_dimension,
)
}
}
impl<'a, 'b, T: Mul<T, Output = T> + Add<T, Output = T> + Zero + Copy> Mul<&'a Matrix<T>>
for &'b Matrix<T>
{
type Output = Matrix<T>;
fn mul(self, other: &'a Matrix<T>) -> Self::Output {
debug_assert!(self.dimension.columns == other.dimension.rows);
let output_dimension = Dimension::new(self.dimension.rows, other.dimension.columns);
Matrix::from_closure(
|index| {
let (row, colm) = output_dimension.to_xy(index);
(0..self.dimension.columns).fold(Zero::zero(), |curr, i| {
curr + self.data[self.dimension.to_index(row, i)]
* other.data[other.dimension.to_index(i, colm)]
})
},
output_dimension,
)
}
}
//Matrix Matrix Buffered Multiplication
impl<T: Mul<T, Output = T> + Add<T, Output = T> + Zero + Copy> Matrix<T> {
pub fn buffered_mul(&mut self, m1: &Matrix<T>, m2: &Matrix<T>) {
debug_assert_eq!(m1.dimension.columns, m2.dimension.rows);
debug_assert!(
self.dimension.rows == m1.dimension.rows
&& self.dimension.columns == m2.dimension.columns
);
let output_dimension = self.dimension;
self.closure_into_buffer(|index| {
let (row, colm) = output_dimension.to_xy(index);
(0..m1.dimension.columns).fold(Zero::zero(), |curr, i| {
curr + m1.data[m1.dimension.to_index(row, i)]
* m2.data[m2.dimension.to_index(i, colm)]
})
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn test_matmul() {
let matrix1 = Matrix::from_data(vec![1, 2, 3, 4, 5, 6, 7, 8, 9], Dimension::new(3, 3));
let res = &matrix1 * &matrix1;
debug_assert!(vec![30, 36, 42, 66, 81, 96, 102, 126, 150] == res.data);
}
}
|
use crate::error_system::OsuKeyboardError;
pub mod keyboard_processor;
pub trait Processor {
fn setup(&self) -> Result<(), OsuKeyboardError>;
fn run(&self) -> Result<!, OsuKeyboardError>;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.