text stringlengths 8 4.13M |
|---|
use std::iter::{Extend, IntoIterator};
#[derive(Debug, Default)]
pub struct MySqlQueryResult {
pub(super) rows_affected: u64,
pub(super) last_insert_id: u64,
}
impl MySqlQueryResult {
pub fn last_insert_id(&self) -> u64 {
self.last_insert_id
}
pub fn rows_affected(&self) -> u64 {
self.rows_affected
}
}
impl Extend<MySqlQueryResult> for MySqlQueryResult {
fn extend<T: IntoIterator<Item = MySqlQueryResult>>(&mut self, iter: T) {
for elem in iter {
self.rows_affected += elem.rows_affected;
self.last_insert_id = elem.last_insert_id;
}
}
}
#[cfg(feature = "any")]
impl From<MySqlQueryResult> for crate::any::AnyQueryResult {
fn from(done: MySqlQueryResult) -> Self {
crate::any::AnyQueryResult {
rows_affected: done.rows_affected,
last_insert_id: Some(done.last_insert_id as i64),
}
}
}
|
use std::collections::BinaryHeap;
use std::collections::HashSet;
#[derive(Clone, Copy, PartialEq, Eq)]
struct NodeCand {
cost: i64,
vid: usize,
}
// to minimize binaryHeap, inverse order
impl Ord for NodeCand {
fn cmp(&self, other: &NodeCand) -> std::cmp::Ordering {
other.cost.cmp(&self.cost)
}
}
impl PartialOrd for NodeCand {
fn partial_cmp(&self, other: &NodeCand) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
struct Prim {}
impl Prim {
// adjacency list is (cost, vid), 0-indexed, undirected
fn build(adjl: Vec<Vec<(i64, usize)>>) -> i64 {
// set managing spaninng tree
let mut used: HashSet<usize> = HashSet::new();
let mut heap: BinaryHeap<NodeCand> = BinaryHeap::new();
let mut total = 0;
// 0 as start
heap.push(NodeCand { cost: 0, vid: 0 });
while let Some(NodeCand { cost, vid }) = heap.pop() {
if used.contains(&vid) {
continue;
} else {
used.insert(vid);
total += cost;
for n in &adjl[vid] {
if !used.contains(&n.1) {
heap.push(NodeCand {
cost: n.0,
vid: n.1,
});
}
}
}
}
total
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_prim() {
let n = 5;
let adjl: Vec<Vec<(i64, usize)>> = vec![
vec![(2, 1), (3, 2), (1, 3)],
vec![(2, 0), (4, 3)],
vec![(3, 0), (1, 3), (1, 4)],
vec![(1, 0), (4, 1), (1, 2), (3, 4)],
vec![(1, 2), (3, 3)],
];
let p = Prim::build(adjl);
println!("{:?}", p);
}
}
fn main() {}
|
use std::time::{Duration, Instant};
use amethyst::utils::fps_counter::FpsCounter;
use super::system_prelude::*;
pub struct DebugSystem {
to_print: Vec<String>,
last_fps_print: Instant,
}
const PRINT_EVERY_MS: u64 = 1000;
impl<'a> System<'a> for DebugSystem {
type SystemData = (
ReadExpect<'a, Settings>,
Read<'a, FpsCounter>,
Read<'a, PlayerDeaths>,
Read<'a, TimerRes>,
);
fn run(
&mut self,
(settings, fps_counter, player_deaths, timer): Self::SystemData,
) {
let now = Instant::now();
let debug_settings = &settings.debug;
if now - self.last_fps_print >= Duration::from_millis(PRINT_EVERY_MS) {
if debug_settings.print_fps {
self.print_fps(&fps_counter);
}
if debug_settings.print_deaths {
self.print_deaths(&player_deaths);
}
if debug_settings.print_time {
self.print_time(&timer);
}
self.last_fps_print = now;
}
self.print();
}
}
impl DebugSystem {
fn print(&mut self) {
if !self.to_print.is_empty() {
println!("{}", self.to_print.join("\n"));
}
self.to_print.clear();
}
fn print_fps(&mut self, fps_counter: &FpsCounter) {
let fps_frame = fps_counter.frame_fps();
let fps_avg = fps_counter.sampled_fps();
self.push_text(format!(
"fps: {:.02} (avg: {:.02})",
fps_frame, fps_avg
));
}
fn print_deaths(&mut self, player_deaths: &PlayerDeaths) {
self.push_text(format!("player deaths: {}", player_deaths.0));
}
fn print_time(&mut self, timer_res: &TimerRes) {
if let Some(timer) = timer_res.0.as_ref() {
self.push_text(format!("time: {}", timer.time_output()));
}
}
fn push_text<S>(&mut self, text: S)
where
S: ToString,
{
self.to_print.push(text.to_string());
}
}
impl Default for DebugSystem {
fn default() -> Self {
Self {
to_print: Vec::new(),
last_fps_print: Instant::now(),
}
}
}
|
use AsMutLua;
use AsLua;
use Push;
use PushGuard;
use LuaRead;
macro_rules! tuple_impl {
($ty:ident) => (
impl<LU, $ty> Push<LU> for ($ty,) where LU: AsMutLua, $ty: Push<LU> {
fn push_to_lua(self, lua: LU) -> PushGuard<LU> {
self.0.push_to_lua(lua)
}
}
impl<LU, $ty> LuaRead<LU> for ($ty,) where LU: AsMutLua, $ty: LuaRead<LU> {
fn lua_read_at_position(lua: LU, index: i32) -> Result<($ty,), LU> {
LuaRead::lua_read_at_position(lua, index).map(|v| (v,))
}
}
);
($first:ident, $($other:ident),+) => (
#[allow(non_snake_case)]
impl<LU, $first: for<'a> Push<&'a mut LU>, $($other: for<'a> Push<&'a mut LU>),+>
Push<LU> for ($first, $($other),+) where LU: AsMutLua
{
fn push_to_lua(self, mut lua: LU) -> PushGuard<LU> {
match self {
($first, $($other),+) => {
let mut total = $first.push_to_lua(&mut lua).forget();
$(
total += $other.push_to_lua(&mut lua).forget();
)+
PushGuard { lua: lua, size: total }
}
}
}
}
// TODO: what if T or U are also tuples? indices won't match
#[allow(unused_assignments)]
#[allow(non_snake_case)]
impl<LU, $first: for<'a> LuaRead<&'a mut LU>, $($other: for<'a> LuaRead<&'a mut LU>),+>
LuaRead<LU> for ($first, $($other),+) where LU: AsLua
{
fn lua_read_at_position(mut lua: LU, index: i32) -> Result<($first, $($other),+), LU> {
let mut i = index;
let $first: $first = match LuaRead::lua_read_at_position(&mut lua, i) {
Ok(v) => v,
Err(_) => return Err(lua)
};
i += 1;
$(
let $other: $other = match LuaRead::lua_read_at_position(&mut lua, i) {
Ok(v) => v,
Err(_) => return Err(lua)
};
i += 1;
)+
Ok(($first, $($other),+))
}
}
tuple_impl!($($other),+);
);
}
tuple_impl!(A, B, C, D, E, F, G, H, I, J, K, L, M);
|
use libc::printf as _printf;
use wasmer_runtime_core::Instance;
/// putchar
pub use libc::putchar;
/// printf
pub extern "C" fn printf(memory_offset: i32, extra: i32, instance: &Instance) -> i32 {
debug!("emscripten::printf {}, {}", memory_offset, extra);
unsafe {
let addr = instance.memory_offset_addr(0, memory_offset as _) as _;
_printf(addr, extra)
}
}
|
use std::cmp::Ordering;
use std::convert::From;
use std::f32::EPSILON;
use std::fmt;
use std::ops::{Add, Sub};
pub type Tick = u64;
impl PartialEq<Time> for Tick {
fn eq(&self, time: &Time) -> bool {
*self == time.tick
}
}
impl PartialOrd<Time> for Tick {
fn partial_cmp(&self, time: &Time) -> Option<Ordering> {
self.partial_cmp(&time.tick)
}
}
#[derive(Clone, Copy)]
pub struct Time {
tick: Tick,
fractional_tick: f32,
}
impl Time {
pub fn new(tick: Tick, fractional_tick: f32) -> Self {
Self {
tick,
fractional_tick,
}
}
pub fn get_tick(&self) -> Tick {
self.tick
}
pub fn get_fractional_tick(&self) -> f32 {
self.fractional_tick
}
pub fn as_f32(&self) -> f32 {
self.tick as f32 + self.fractional_tick
}
}
impl Add<Tick> for Time {
type Output = Self;
fn add(self, tick: Tick) -> Self {
Self {
tick: self.tick + tick,
fractional_tick: self.fractional_tick,
}
}
}
impl Add for Time {
type Output = Self;
fn add(self, other: Self) -> Self {
let tick = self.tick + other.tick;
let fraction = self.fractional_tick + other.fractional_tick;
Self {
tick: tick + fraction.trunc() as u64,
fractional_tick: fraction.fract(),
}
}
}
impl fmt::Debug for Time {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.tick)?;
write!(f, "{}", &format!("{:.4}", self.fractional_tick)[1..])
}
}
impl Eq for Time { }
impl From<f64> for Time {
fn from(ticks: f64) -> Self {
Self {
tick: ticks.trunc() as u64,
fractional_tick: ticks.fract() as f32,
}
}
}
impl From<Tick> for Time {
fn from(tick: Tick) -> Self {
Self {
tick,
fractional_tick: 0.0,
}
}
}
impl PartialEq<Tick> for Time {
fn eq(&self, tick: &Tick) -> bool {
self.tick == *tick && self.fractional_tick < EPSILON
}
}
impl PartialEq<Time> for Time {
fn eq(&self, other: &Time) -> bool {
self.tick == other.tick && (self.fractional_tick - other.fractional_tick).abs() < EPSILON
}
}
impl PartialOrd<Tick> for Time {
fn partial_cmp(&self, tick: &Tick) -> Option<Ordering> {
self.tick.partial_cmp(tick)
}
}
impl PartialOrd<Time> for Time {
fn partial_cmp(&self, other: &Time) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Time {
fn cmp(&self, other: &Time) -> Ordering {
if self.tick != other.tick {
self.tick.cmp(&other.tick)
} else {
self.fractional_tick.partial_cmp(&other.fractional_tick).unwrap_or(Ordering::Equal)
}
}
}
impl Sub<Tick> for Time {
type Output = Self;
fn sub(self, tick: Tick) -> Self {
assert!(self >= tick);
Self {
tick: self.tick - tick,
fractional_tick: self.fractional_tick,
}
}
}
impl Sub for Time {
type Output = Self;
fn sub(self, other: Self) -> Self {
assert!(self >= other);
let mut tick = self.tick - other.tick;
let mut fractional_tick = self.fractional_tick - other.fractional_tick;
if fractional_tick < 0.0 {
tick -= 1;
fractional_tick += 1.0;
}
Self {
tick,
fractional_tick,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_time_addition() {
let base = Time::new(20, 0.5);
assert_eq!(base + Tick::from(1u64), Time::new(21, 0.5));
assert_eq!(base + Tick::from(7u64), Time::new(27, 0.5));
assert_eq!(base + Time::from(0.5), Time::new(21, 0.0));
assert_eq!(base + Time::from(0.567), Time::new(21, 0.067));
assert_eq!(base + Time::from(3.234), Time::new(23, 0.734));
}
#[test]
fn test_time_subtraction() {
let base = Time::new(20, 0.5);
assert_eq!(base - Tick::from(1u64), Time::new(19, 0.5));
assert_eq!(base - Tick::from(7u64), Time::new(13, 0.5));
assert_eq!(base - Time::from(0.5), Time::new(20, 0.0));
assert_eq!(base - Time::from(0.567), Time::new(19, 0.933));
assert_eq!(base - Time::from(3.234), Time::new(17, 0.266));
}
} |
// Let's try to work on a famous fun programming problem based on the popular
// 99 bottles of the beer song.
// Song:
// 99 bottles of beer on the wall, 99 bottles of beer.
// Take one down and pass it around, 98 bottles of beer on the wall.
// 98 bottles of beer on the wall, 98 bottles of beer.
// Take one down and pass it around, 97 bottles of beer on the wall.
// ……...
// 3 bottles of beer on the wall, 3 bottles of beer.
// Take one down and pass it around, 2 bottles of beer on the wall.
// 2 bottles of beer on the wall, 2 bottles of beer.
// Take one down and pass it around, 1 bottle of beer on the wall.
// 1 bottle of beer on the wall, 1 bottle of beer.
// Take it down and pass it around, no more bottles of beer on the wall.
// No more bottles of beer on the wall, no more bottles of beer.
// Go to the store and buy some more, 99 bottles of beer on the wall.
fn main() {
let mut count = 1;
for i in (0..100).rev() {
if i != 0 {
println!("\n{} bottles of beer on the wall, {} bottles of beer.",i,i);
println!("Take one down and pass it around, {} bottles of beer on the wall.",i-1);
count = count + 1;
}
else if i == 0 {
println!("\nNo more bottles of beer on the wall, no more bottles of beer.");
println!("Go to the store and buy some more, 99 bottles of beer on the wall.");
}
}
} |
//! Сигнатуры, структурные составляющие файла
//!
//! Файл *.chg разбит тексовыми вставками на отдельные блоки.
mod file_type;
mod barpbres_fe;
mod bkngwl_bnw;
mod boknagr_bkn;
mod clmn_uni;
mod coeffs_rsu;
mod elems_fe;
mod elemsres_fe;
mod elsss_fe;
mod etnames_et;
mod expert;
mod head_fe;
mod isoar_fe;
mod loadcomb_cds;
mod material_mt;
mod ndunions_fe;
mod nodes_fe;
mod nodesres_fe;
mod object_nam;
mod pop_cut;
mod procalc_set;
mod prores_use;
mod rab_a0;
mod rab_e;
mod rab_o0;
mod rab_sdr;
mod rab_zag;
mod reper_pos;
mod rigbodys_fe;
mod rigids_fe;
mod rzagnums_fe;
mod seism_rsp;
mod slits_slt;
mod sltwlexp_grp;
mod szinfo_szi;
mod vnum_fe;
mod wallascn_uni;
mod wind_rsp;
mod zagrcmbs_zc;
mod zagrs_fe;
pub mod building;
pub mod building_raw;
use byteorder::{LittleEndian, WriteBytesExt};
/// Преобразование в байты
pub trait HasWrite {
/// Тело сигнатуры в байты
fn write(&self) -> Vec<u8>;
/// Имя сигнатуры
fn name(&self) -> &str;
}
/// Смещение, до конца данных в сигнатуре в байты
fn offset(len: usize) -> [u8; 8] {
let offset = len as u64;
let mut buff8 = [0u8; 8];
buff8
.as_mut()
.write_u64::<LittleEndian>(offset)
.expect("offset_err");
buff8
}
|
use clap::Command;
use crates_io_api::CrateResponse;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io;
use std::path::Path;
use std::time::Duration;
fn cli() -> Command {
Command::new("AreWeGuiYet CLI")
.subcommand_required(true)
.arg_required_else_help(true)
.about("CLI for fetching data from various sources for the AreWeGuiYet website")
.subcommand(Command::new("clean").about("Remove the data"))
.subcommand(Command::new("fetch").about("Fetch new data"))
}
pub fn execute_cli() {
let matches = cli().get_matches();
let root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
match matches.subcommand() {
Some(("clean", _)) => ExternalData::clean(root),
Some(("fetch", _)) => fetch(root),
_ => unreachable!(),
}
}
/// All the info in the ecosystem file
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct Ecosystem {
#[serde(rename = "crate")]
crates: HashMap<String, Crate>,
}
impl Ecosystem {
fn load(root: &Path) -> Self {
let s =
fs::read_to_string(root.join("ecosystem.toml")).expect("failed reading ecosystem.toml");
toml::from_str(&s).unwrap_or_else(|err| panic!("failed parsing ecosystem.toml: {err}"))
}
}
/// Crate info in ecosystem file
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
struct Crate {
name: Option<String>,
/// Should be either missing or true; implied to be false
#[serde(default)]
#[serde(rename = "skip-crates-io")]
skip_crates_io: bool,
repo: Option<String>,
description: Option<String>,
docs: Option<String>,
#[serde(default)]
tags: Vec<String>,
}
/// Data from various sources that we're currently storing.
#[derive(Serialize, Deserialize, Default)]
struct ExternalData {
/// A map of crate IDs to crate data fetched from crates.io.
crates_io: BTreeMap<String, CrateResponse>,
}
impl ExternalData {
const FILE: &str = "content/external_data.json";
fn clean(root: &Path) {
// Remove the data, and ignore if the file was not found
if let Err(err) = fs::remove_file(root.join(Self::FILE)) {
if err.kind() != io::ErrorKind::NotFound {
panic!("failed to remove the external data file: {err}");
}
};
println!("External data file removed.");
}
fn load(root: &Path) -> Self {
// Remove the data, and return Default if the file was not found
match fs::read_to_string(root.join(Self::FILE)) {
Ok(s) => serde_json::from_str(&s).expect("failed parsing external data"),
Err(err) => {
if err.kind() == io::ErrorKind::NotFound {
Default::default()
} else {
panic!("failed reading external data file: {err}");
}
}
}
}
fn write(&self, root: &Path) {
let s = serde_json::to_string_pretty(self).expect("failed to serialize external data");
fs::write(root.join(Self::FILE), s).expect("failed to write data file");
}
}
fn fetch(root: &Path) {
let mut data = ExternalData::load(root);
// Add crate information from crates.io
let ecosystem = Ecosystem::load(root);
println!("Found {} crates.", ecosystem.crates.len());
let client = crates_io_api::SyncClient::new(
"areweguiyet_cli (areweguiyet.com)",
// Use the recommended rate limit
Duration::from_millis(1000),
)
.expect("failed initializing crates.io client");
let mut compiled_ecosystem = BTreeMap::new();
for (crate_id, krate) in &ecosystem.crates {
if krate.skip_crates_io {
compiled_ecosystem.insert(
crate_id.to_string(),
CompiledCrate {
name: krate.name.clone().unwrap_or_else(|| crate_id.to_string()),
crates_io: None,
repo: krate.repo.clone(),
description: krate.description.clone(),
docs: krate.docs.clone(),
tags: krate.tags.clone(),
},
);
continue;
}
if !data.crates_io.contains_key(crate_id) {
print!("Requesting crates.io data for {crate_id}... ");
let response = client
.get_crate(crate_id)
.unwrap_or_else(|err| panic!("could not find crate {crate_id}: {err}"));
data.crates_io.insert(crate_id.to_string(), response);
println!("done.");
}
let compiled_crate = get_compiled_crate(crate_id, krate, &data.crates_io[crate_id]);
compiled_ecosystem.insert(crate_id.clone(), compiled_crate);
}
// Write compiled ecosystem file
let s = serde_json::to_string(&compiled_ecosystem)
.expect("failed to serialize the compiled ecosystem");
fs::write(root.join("static/compiled_ecosystem.json"), s)
.expect("failed writing compiled ecosystem");
data.write(root);
println!("External data fetched.");
}
/// Crate info that gets put into the compiled ecosystem file.
#[derive(Serialize)]
struct CompiledCrate {
name: String,
crates_io: Option<String>,
repo: Option<String>,
description: Option<String>,
docs: Option<String>,
tags: Vec<String>,
}
/// Merge saved data with data from crates io (if the crate is on crates io).
///
/// No fields will be overwritten if they are already specified.
///
/// Issues errors if the data from crates io is the same as the local data.
fn get_compiled_crate(crate_id: &str, krate: &Crate, crates_io: &CrateResponse) -> CompiledCrate {
let crates_io_api::Crate {
repository,
description,
documentation,
..
} = crates_io.crate_data.clone();
if krate.repo.is_some() && krate.repo == repository {
panic!(
"Please remove {crate_id}'s repo in ecosystem.toml since it duplicates the value on crates.io",
);
}
if krate.description.is_some() && krate.description == description {
panic!(
"Please remove {crate_id}'s description in ecosystem.toml since it duplicates the value on crates.io",
);
}
if krate.docs.is_some() && krate.docs == documentation {
panic!(
"Please remove {crate_id}'s docs in ecosystem.toml since it duplicates the value on crates.io",
);
}
CompiledCrate {
name: krate.name.clone().unwrap_or_else(|| crate_id.to_string()),
crates_io: Some(format!("https://crates.io/crates/{crate_id}")),
repo: krate.repo.clone().or(repository),
description: krate.description.clone().or(description),
docs: krate.docs.clone().or(documentation),
tags: krate.tags.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_cli() {
cli().debug_assert();
}
}
|
pub mod cluster;
pub mod models;
pub mod tenant;
/*macro_rules! error {
($txt:expr, $($args:expr), *) => {
return Box::new(io::Error::new(io::ErrorKind::Other, format!($txt)));
};
}*/
|
use crate::generator::{Callback, Generator};
use crate::util::camera::Camera;
use crate::util::outputbuffer::OutputBuffer;
#[derive(Debug)]
pub struct BasicGenerator;
impl Generator for BasicGenerator {
fn generate(&self, camera: &Camera, callback: &Callback) -> OutputBuffer {
let mut output = OutputBuffer::with_size(camera.width, camera.height);
for x in 0..camera.width {
for y in 0..camera.height {
let res = callback(x, y);
output.set_at(x, y, res);
}
}
output
}
}
|
//! Example webapp using [`willow`](https://docs.rs/willow/).
#![allow(clippy::blacklisted_name)]
#![warn(missing_docs)]
use nalgebra::{Matrix4, Vector3};
use wasm_bindgen::prelude::*;
use web_sys::WebGlRenderingContext;
use willow::{
AspectFix, Attribute, BufferDataUsage, Clear, Context, Indices, Program, ProgramData,
RenderPrimitiveType, Uniform,
};
/// This type wraps the program with the `foo.vert` and `foo.frag` shaders.
#[derive(Program)]
#[willow(path = "foo")]
pub struct Foo {
data: ProgramData,
u_alpha: Uniform<f32>,
u_transform: Uniform<Matrix4<f32>>,
a_color: Attribute<Vector3<f32>>,
a_offset: Attribute<Vector3<f32>>,
}
/// WebGL entry function.
#[wasm_bindgen(start)]
pub fn main() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
wasm_logger::init(wasm_logger::Config::default());
let canvas = web_sys::window()
.unwrap()
.document()
.unwrap()
.get_element_by_id("canvas")
.unwrap();
let context = Context::from_canvas(canvas, AspectFix::FromWidth).unwrap();
let (foo,) = willow::create_programs!(context => Foo);
context.clear(Clear {
color: Some([0., 0., 0., 1.]),
depth: Some(1.),
stencil: None,
});
context.native.enable(WebGlRenderingContext::DEPTH_TEST);
context.native.depth_func(WebGlRenderingContext::LEQUAL);
let attrs = Foo::prepare_buffer(
&context,
&[
FooAttr {
a_offset: Vector3::new(1.0, 0.0, 0.0),
a_color: Vector3::new(1.0, 0.0, 0.0),
},
FooAttr {
a_offset: Vector3::new(-1.0, -1.0, 0.0),
a_color: Vector3::new(1.0, 1.0, 0.0),
},
FooAttr {
a_offset: Vector3::new(-1.0, 1.0, 0.0),
a_color: Vector3::new(0.0, 1.0, 0.0),
},
FooAttr {
a_offset: Vector3::new(0.0, 0.0, 1.0),
a_color: Vector3::new(0.0, 0.0, 1.0),
},
],
BufferDataUsage::StaticDraw,
);
let indices = Indices::new(
&context,
&[0, 1, 2, 0, 1, 3, 1, 2, 3, 2, 0, 3],
BufferDataUsage::StaticDraw,
)
.unwrap();
foo.with_uniforms()
.u_alpha(1.0)
.u_transform(
Matrix4::new_perspective(context.aspect(), 1.5, 0.01, 5.)
* nalgebra::Rotation::from_euler_angles(0.5, 0.5, 0.5)
.to_homogeneous()
.append_translation(&Vector3::new(0., 0., -2.)),
)
.draw(&context, RenderPrimitiveType::Triangles, &attrs, &indices)
.unwrap();
}
|
use std::ops;
use std::f32;
use super::deg2rad;
#[derive(Debug, Clone, PartialEq)]
pub struct Vec3 {
pub x: f32,
pub y: f32,
pub z: f32
}
// indices
impl ops::Index<usize> for Vec3 {
type Output = f32;
fn index<'a>(&'a self, index: usize) -> &'a f32 {
match index {
0 => &self.x,
1 => &self.y,
2 => &self.z,
_ => panic!()
}
}
}
impl ops::IndexMut<usize> for Vec3 {
fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut f32 {
match index {
0 => &mut self.x,
1 => &mut self.y,
2 => &mut self.z,
_ => panic!()
}
}
}
// add ops
impl ops::Add for Vec3 {
type Output = Vec3;
fn add(self, other: Vec3) -> Vec3 {
Vec3 {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z
}
}
}
impl ops::AddAssign for Vec3 {
fn add_assign(&mut self, other: Vec3) {
*self = self.clone() + other;
}
}
// sub ops
impl ops::Sub for Vec3 {
type Output = Vec3;
fn sub(self, other: Vec3) -> Vec3 {
Vec3 {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z
}
}
}
impl ops::SubAssign for Vec3 {
fn sub_assign(&mut self, other: Vec3) {
*self = self.clone() - other;
}
}
// mul ops
impl ops::Mul<Vec3> for Vec3 {
type Output = Vec3;
fn mul(self, other: Vec3) -> Vec3 {
Vec3 {
x: self.x * other.x,
y: self.y * other.y,
z: self.z * other.z
}
}
}
impl ops::Mul<f32> for Vec3 {
type Output = Vec3;
fn mul(self, real: f32) -> Vec3 {
Vec3 {
x: self.x * real,
y: self.y * real,
z: self.z * real
}
}
}
impl ops::MulAssign<Vec3> for Vec3 {
fn mul_assign(&mut self, other: Vec3) {
*self = self.clone() * other;
}
}
impl ops::MulAssign<f32> for Vec3 {
fn mul_assign(&mut self, other: f32) {
*self = self.clone() * other;
}
}
// div ops
impl ops::Div<Vec3> for Vec3 {
type Output = Vec3;
fn div(self, other: Vec3) -> Vec3 {
Vec3 {
x: self.x / other.x,
y: self.y / other.y,
z: self.z / other.z
}
}
}
impl ops::Div<f32> for Vec3 {
type Output = Vec3;
fn div(self, real: f32) -> Vec3 {
Vec3 {
x: self.x / real,
y: self.y / real,
z: self.z / real
}
}
}
impl ops::DivAssign<Vec3> for Vec3 {
fn div_assign(&mut self, other: Vec3) {
*self = self.clone() / other;
}
}
impl ops::DivAssign<f32> for Vec3 {
fn div_assign(&mut self, other: f32) {
*self = self.clone() / other;
}
}
// other functions
impl Vec3 {
pub fn lenght(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2) + self.z.powi(2)).sqrt()
}
pub fn dot(&self, other: Vec3) -> f32 {
self.x * other.x + self.y * other.y + self.z * other.z
}
pub fn cross(&self, other: Vec3) -> Vec3 {
Vec3 {
x: self.y * other.z - self.z * other.y,
y: self.z * other.x - self.x * other.z,
z: self.x * other.y - self.y * other.x
}
}
pub fn normalized(&self) -> Vec3 {
self.clone() / self.clone().lenght()
}
pub fn distance_to(&self, other: Vec3) -> f32 {
((self.x - other.x).powi(2) + (self.y - other.y).powi(2) + (self.z - other.z).powi(2)).sqrt()
}
// todo (if needed)
pub fn rotate_x(&self, degrees: f32) -> Vec3 {
Vec3 {
x: self.x,
y: self.y,
z: self.z
}
}
pub fn rotate_y(&self, degrees: f32) -> Vec3 {
Vec3 {
x: self.x,
y: self.y,
z: self.z
}
}
pub fn rotate_z(&self, degrees: f32) -> Vec3 {
Vec3 {
x: self.x,
y: self.y,
z: self.z
}
}
} |
#[macro_use]
extern crate diesel;
use actix_web::{get, middleware, post, web, App, Error, HttpServer, HttpRequest, HttpResponse, Responder};
use tera::{Tera, Context};
use listenfd::ListenFd;
use diesel::prelude::*;
use diesel::r2d2::{self, ConnectionManager};
use uuid::Uuid;
mod actions;
mod models;
mod schema;
type DbPool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
// Finds character by uid
#[get("/character/{character_id}")]
async fn get_character(
pool: web::Data<DbPool>,
character_uid: web::Path<Uuid>,
) -> Result<HttpResponse, Error> {
let character_uid = character_uid.into_inner();
let conn = pool.get().expect("couldn't get db connection from pool");
// use web::block to offload blocking Diesel code without blocking server thread
let character = web::block(move || actions::find_character_by_uid(character_uid, &conn))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
if let Some(character) = character {
Ok(HttpResponse::Ok().json(character))
} else {
let res = HttpResponse::NotFound()
.body(format!("No user found with uid: {}", character_uid));
Ok(res)
}
}
// Inserts new character with name defined in form
#[post("/character")]
async fn add_character(
pool: web::Data<DbPool>,
form: web::Json<models::NewCharacter>,
) -> Result<HttpResponse, Error> {
let conn = pool.get().expect("couldn't get db connection from pool");
// use web::block to offload blocking Diesel code without blocking server thread
let character = web::block(move || actions::insert_new_character(&form.name, &conn))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
Ok(HttpResponse::Ok().json(character))
}
// For rendering to templates
async fn render_tmpl(data: web::Data<AppData>, req:HttpRequest) -> impl Responder {
let name = req.match_info().get("name").unwrap();
let mut ctx = Context::new();
ctx.insert("name", name);
let rendered = data.tmpl.render("index.html", &ctx).unwrap();
HttpResponse::Ok().body(rendered)
}
// For rendering to templates
struct AppData {
tmpl: Tera
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
dotenv::dotenv().ok();
// set up database connection pool
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
let manager = ConnectionManager::<SqliteConnection>::new(connspec);
let pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
let bind = "127.0.0.1:7000";
let mut listenfd = ListenFd::from_env();
let mut server = HttpServer::new(move || {
// templating engine
// add html files here so they will be compiled
let tera = Tera::new(
concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")
).unwrap();
App::new()
// set up DB pool to be used with web::Data<Pool> extractor
.data(pool.clone())
.wrap(middleware::Logger::default())
.service(get_character)
.service(add_character)
// method for binding templates for compiliation
// .data(AppData {tmpl: tera})
});
server = if let Some(listener) = listenfd.take_tcp_listener(0).unwrap() {
println!("Server listening at: {:?}", listener);
server.listen(listener)?
} else {
println!("Starting server at {}", &bind);
server.bind(&bind)?
};
server.run().await
}
|
use crate::{coinbase, crypto_service, models};
const COINBASE_API_URL: &str = "https://api.pro.coinbase.com";
pub async fn get_trades_data_for_pair(
coin_pair: &str,
) -> models::CoinPairData<Vec<coinbase::models::Trade>> {
let exchange_name = "coinbase";
let data_type = "trades";
let trades = get_trades_for_pair(&coin_pair).await.unwrap();
let trades_data = models::CoinPairData::<Vec<coinbase::models::Trade>> {
coin_pair: String::from(coin_pair),
data_set: trades,
data_type: String::from(data_type),
exchange_name: String::from(exchange_name),
};
trades_data
}
pub async fn get_trades_for_pair(
crypto_pair: &str,
) -> std::result::Result<
Vec<coinbase::models::Trade>,
Box<dyn std::error::Error + Send + Sync + 'static>,
> {
let root_url = format!("{}/products/{}/trades", COINBASE_API_URL, crypto_pair);
let query_url = format!("{}?limit=10", root_url);
let response = crypto_service::get_data_from_exchange(&query_url).await?;
Ok(response)
}
fn raw_offer_data(raw: &Vec<(String, String, u32)>) -> Vec<coinbase::models::OfferData> {
raw.iter()
.map(|item| coinbase::models::OfferData {
price: item.0.parse().unwrap(),
size: item.1.parse().unwrap(),
num_orders: item.2,
})
.collect()
}
pub async fn get_orderbooks_data_for_pair(
coin_pair: &str,
) -> models::CoinPairData<coinbase::models::OrderBookDTO> {
let exchange_name = "coinbase";
let data_type = "orderbooks";
let orderbooks = get_orderbooks_for_pair(&coin_pair).await.unwrap();
let orderbooks = coinbase::models::OrderBookDTO {
sequence: orderbooks.sequence,
asks: raw_offer_data(&orderbooks.asks),
bids: raw_offer_data(&orderbooks.bids),
};
let orderbook_data = models::CoinPairData::<coinbase::models::OrderBookDTO> {
coin_pair: String::from(coin_pair),
data_set: orderbooks,
data_type: String::from(data_type),
exchange_name: String::from(exchange_name),
};
orderbook_data
}
pub async fn get_orderbooks_for_pair(
crypto_pair: &str,
) -> std::result::Result<
coinbase::models::RawOrderBook,
Box<dyn std::error::Error + Send + Sync + 'static>,
> {
let root_url = format!("{}/products/{}/book", COINBASE_API_URL, crypto_pair);
let query_url = format!("{}?level=2", root_url);
let response: coinbase::models::RawOrderBook =
crypto_service::get_data_from_exchange(&query_url).await?;
Ok(response)
}
|
use serenity::{
builder::CreateEmbed,
client::Context,
framework::standard::{macros::command, CommandResult},
model::prelude::Message,
};
// command name is example
#[command("example")]
// aliases are ex and ax
#[aliases("ex", "ax")]
// rate limit bucket is "heavy" (the one we made in fn entrypoint)
#[bucket = "heavy"]
#[description = "A example command."]
async fn cmd_example(ctx: &Context, msg: &Message) -> CommandResult {
let mut embed = CreateEmbed::default();
embed.title("Template Command");
msg.channel_id
.send_message(&ctx, |m| {
m.embed(|e| {
*e = embed;
e
})
})
.await?;
Ok(())
}
|
#[doc = "Reader of register PREPHY"]
pub type R = crate::R<u32, super::PREPHY>;
#[doc = "Reader of field `R0`"]
pub type R0_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Ethernet PHY Module Peripheral Ready"]
#[inline(always)]
pub fn r0(&self) -> R0_R {
R0_R::new((self.bits & 0x01) != 0)
}
}
|
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use rand::prelude::*;
use rand_distr::Pareto;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
fn pure_read(lotable: Arc<RwLock<HashMap<String, u64>>>, key: String, thread_count: u64) {
let mut threads = vec![];
for thread_no in 0..thread_count {
let lotable = lotable.clone();
let key = key.clone();
let t = std::thread::Builder::new()
.name(format!("t_{}", thread_no))
.spawn(move || {
let loguard = lotable.read().unwrap();
loguard.get(&key);
// if let Ok(loguard) = lotable.read() {
// loguard.get(&key);
// }
})
.unwrap();
threads.push(t);
}
for t in threads.into_iter() {
t.join().unwrap();
}
}
fn bench_arc_rwlock_pure_reads(c: &mut Criterion) {
let lotable = {
let mut table: HashMap<String, u64> = HashMap::new();
table.insert("data".into(), 1_u64);
Arc::new(RwLock::new(table))
};
let key: String = "CORE".into();
let threads = 8;
let mut group = c.benchmark_group("arc_rwlock_read_throughput");
group.throughput(Throughput::Elements(threads as u64));
group.bench_function("pure reads", move |b| {
b.iter_batched(
|| (lotable.clone(), key.clone()),
|vars| pure_read(vars.0, vars.1, threads),
BatchSize::SmallInput,
)
});
}
////////////////////////////////
fn rw_pareto(
lotable: Arc<RwLock<HashMap<String, u64>>>,
key: String,
dist: f64,
thread_count: u64,
) {
let mut threads = vec![];
for thread_no in 0..thread_count {
let lotable = lotable.clone();
let key = key.clone();
let t = std::thread::Builder::new()
.name(format!("t_{}", thread_no))
.spawn(move || {
if dist < 0.8_f64 {
let loguard = lotable.read().unwrap();
loguard.get(&key);
// if let Ok(loguard) = lotable.read() {
// loguard.get(&key);
// }
} else {
let loguard = lotable.read().unwrap();
let data: u64 = *loguard.get(&key).unwrap();
// if let Ok(loguard) = lotable.read() {
// if let Some(datac) = loguard.get(&key) {
// data = *datac;
// }
// }
let mut loguard = lotable.write().unwrap();
loguard.insert(key, data + 1);
// if let Ok(mut loguard) = lotable.write() {
// loguard.insert(key, data + 1);
// }
}
})
.unwrap();
threads.push(t);
}
for t in threads.into_iter() {
t.join().unwrap();
}
}
fn bench_arc_rwlock_rw_pareto(c: &mut Criterion) {
let lotable = {
let mut table: HashMap<String, u64> = HashMap::new();
table.insert("data".into(), 1_u64);
Arc::new(RwLock::new(table))
};
let key: String = "CORE".into();
let threads = 8;
let mut group = c.benchmark_group("arc_rwlock_rw_pareto_throughput");
group.throughput(Throughput::Elements(threads as u64));
group.bench_function("rw_pareto", move |b| {
b.iter_batched(
|| {
let dist: f64 =
1. / thread_rng().sample(Pareto::new(1., 5.0_f64.log(4.0_f64)).unwrap());
(lotable.clone(), key.clone(), dist)
},
|vars| rw_pareto(vars.0, vars.1, vars.2, threads),
BatchSize::SmallInput,
)
});
}
////////////////////////////////
fn pure_writes(lotable: Arc<RwLock<HashMap<String, u64>>>, key: String, thread_count: u64) {
let mut threads = vec![];
for thread_no in 0..thread_count {
let lotable = lotable.clone();
let key = key.clone();
let t = std::thread::Builder::new()
.name(format!("t_{}", thread_no))
.spawn(move || {
if let Ok(mut loguard) = lotable.write() {
loguard.insert(key, thread_no);
}
})
.unwrap();
threads.push(t);
}
for t in threads.into_iter() {
t.join().unwrap();
}
}
fn bench_arc_rwlock_pure_writes(c: &mut Criterion) {
let lotable = {
let mut table: HashMap<String, u64> = HashMap::new();
table.insert("data".into(), 1_u64);
Arc::new(RwLock::new(table))
};
let key: String = "CORE".into();
let threads = 8;
let mut group = c.benchmark_group("arc_rwlock_write_throughput");
group.throughput(Throughput::Elements(threads as u64));
group.bench_function("pure writes", move |b| {
b.iter_batched(
|| (lotable.clone(), key.clone()),
|vars| pure_writes(vars.0, vars.1, threads),
BatchSize::SmallInput,
)
});
}
criterion_group! {
name = arc_rwlock_benches;
config = Criterion::default();
targets = bench_arc_rwlock_pure_reads, bench_arc_rwlock_rw_pareto, bench_arc_rwlock_pure_writes
}
criterion_main!(arc_rwlock_benches);
|
use std::fmt::{Debug, Display};
use async_trait::async_trait;
use data_types::{ParquetFile, PartitionId};
pub mod catalog;
pub mod mock;
pub mod rate_limit;
/// Finds files in a partition for compaction
#[async_trait]
pub trait PartitionFilesSource: Debug + Display + Send + Sync {
/// Get undeleted parquet files for given partition.
///
/// This MUST NOT perform any filtering (expect for the "not marked for deletion" flag).
///
/// This method performs retries.
async fn fetch(&self, partition: PartitionId) -> Vec<ParquetFile>;
}
|
use crate::types::Float;
use crate::types::Int;
use crate::types::Number;
use core::intrinsics;
use num::Num;
use num::ToPrimitive;
use crate::efloat::EFloat;
use std::f64;
pub mod consts {
use super::next_float_up;
use super::Float;
use std::f64;
pub static INFINITY: Float = f64::INFINITY;
pub static NAN: Float = f64::NAN;
pub static PI: Float = f64::consts::PI;
pub const EPSILON: Float = f64::EPSILON;
}
pub fn acos(v: Float) -> Float {
v.acos()
}
pub fn atan(v: Float) -> Float {
v.atan()
}
pub fn atan2(v: Float, other: Float) -> Float {
v.atan2(other)
}
pub fn ceil(v: Float) -> Float {
v.ceil()
}
pub fn clamp(v: Float, low: Float, high: Float) -> Float {
if v < low {
low
} else if v > high {
high
} else {
v
}
}
pub fn cos(v: Float) -> Float {
v.cos()
}
pub fn degrees(radians: Float) -> Float {
180.0 / consts::PI * radians
}
pub fn floor(v: Float) -> Float {
v.floor()
}
pub fn find_interval(size: Int, pred: &Fn(Int) -> bool) -> Int {
let mut first = 0;
let mut length = size;
while length > 0 {
let half = length >> 1;
let middle = first + half;
// bisect range based on value of pred at middle
if pred(middle) {
first = middle + 1;
length -= half + 1;
} else {
length = half;
}
}
clamp((first - 1) as Float, 0.0, (size - 2) as Float) as Int
}
pub fn gamma(n: Float) -> Float {
(n * consts::EPSILON) / (1.0 - n * consts::EPSILON)
}
pub fn is_inf(v: Float) -> bool {
match v {
f64::INFINITY => true,
_ => false,
}
}
pub fn lerp<T: Number>(t: T, v1: T, v2: T) -> T {
(T::one() - t) * v1 + t * v2
}
pub fn max<T: Number>(v1: T, v2: T) -> T {
if v1 >= v2 {
v1
} else {
v2
}
}
pub fn min<T: Number>(v1: T, v2: T) -> T {
if v1 <= v2 {
v1
} else {
v2
}
}
pub fn next_float_up(v: Float) -> Float {
Float::from_bits(v.to_bits() + 1)
}
pub fn next_float_down(v: Float) -> Float {
Float::from_bits(v.to_bits() - 1)
}
pub fn radians(degrees: Float) -> Float {
consts::PI / 180.0 * degrees
}
//pub fn quadratic(a: Float, b: Float, c: Float) -> Option<(EFloat, EFloat)> {
// let discriminant = b * b - 4. * a * c;
// if discriminant < 0. {
// return None;
// }
// let root_discriminant = discriminant.sqrt();
// let float_root_discriminant =
//}
pub fn sin(v: Float) -> Float {
v.sin()
}
pub fn tan(v: Float) -> Float {
v.tan()
}
pub trait Sqrt {
fn sqrt(self) -> f64;
}
macro_rules! sqrt_impl {
( $t:ty, $zero:expr ) => {
impl Sqrt for $t {
fn sqrt(self) -> f64 {
if self < $zero {
consts::NAN
} else {
unsafe { intrinsics::sqrtf64(self as f64) }
}
}
}
};
}
sqrt_impl!(u8, 0);
sqrt_impl!(u16, 0);
sqrt_impl!(u32, 0);
sqrt_impl!(u64, 0);
#[cfg(has_i128)]
sqrt_impl!(u128, 0);
sqrt_impl!(usize, 0);
sqrt_impl!(i8, 0);
sqrt_impl!(i16, 0);
sqrt_impl!(i32, 0);
sqrt_impl!(i64, 0);
#[cfg(has_i128)]
sqrt_impl!(i128, 0);
sqrt_impl!(isize, 0);
sqrt_impl!(f32, 0.0);
sqrt_impl!(f64, 0.0);
pub fn sqrt<T>(v: T) -> f64 where T: Sqrt {
v.sqrt()
}
|
use chrono::Utc;
use serenity::builder::CreateEmbed;
use serenity::model::user::User;
use crate::constants::PLACEHOLDER;
use crate::models::apod::Apod;
use crate::models::launch::Launch;
use crate::models::url::VidURL;
use crate::services::database::launch::DBLaunch;
pub fn create_basic_embed() -> CreateEmbed {
let mut e = CreateEmbed::default();
e.timestamp(Utc::now());
e
}
pub fn create_launch_embed(n: &Launch, r: &String) -> CreateEmbed {
let mut e = create_basic_embed();
e.title(&n.name);
e.description(format!(
"> {}",
&n.mission.clone().unwrap_or_default().description
));
e.field(
"Rocket",
format!(
"➤ Name: **{}**\n➤ Total Launches: **{}**",
&n.rocket.configuration.name, &n.rocket.configuration.total_launch_count
),
false,
);
e.field(
"Launch",
format!(
"➤ Status: **{}**\n➤ Probability: **{}%**",
&n.status.description,
&n.probability.unwrap_or(-0)
),
false,
);
e.image(
&n.rocket
.configuration
.image_url
.as_ref()
.unwrap_or(&PLACEHOLDER.to_string()),
);
e.url(&n.vid_urls.get(0).unwrap_or(&VidURL::default()).url);
e.color(0x00adf8);
e.footer(|f| f.text(&n.id.to_string()));
e.author(|a| a.name(format!("Time Remaining: {} hours", r)));
e
}
pub fn create_apod_embed(a: &Apod) -> CreateEmbed {
let mut e = create_basic_embed();
e.title(&a.title);
e.image(&a.hdurl);
e.description(format!("> {}", &a.explanation));
e.footer(|f| {
f.text(format!(
"Copyright © {}. All Rights Reserved.",
&a.copyright.as_ref().unwrap_or(&"NASA".to_string())
))
});
e.color(0x5694c7);
e
}
pub fn create_reminder_embed(user: &User, msg: &str, next_launch: &DBLaunch) -> CreateEmbed {
let mut e = create_basic_embed();
let mut stream = "I'm unaware of any stream :(".to_string();
if let Some(vid_url) = &next_launch.vid_url {
stream = format!("[Stream]({})", &vid_url)
}
e.author(|a| a.name(&next_launch.name)).thumbnail(
&next_launch
.image_url
.as_ref()
.unwrap_or(&PLACEHOLDER.to_string()),
);
e.title("Launch Reminder");
e.description(format!("{}\n\n{}", msg, stream));
e.colour(0xcc0099);
// .timestamp(&dt)
e.footer(|f| {
f.text(format!(
"This reminder is for launch ID: {}",
&next_launch.launch_id
))
.icon_url(user.face())
});
e
}
|
use atoms::{Location, Token, TokenType};
use std::sync::Arc;
///
/// A Tokenizer is a 'class' that handles creating a
/// list of tokens from a file buffer.
///
/// NOTE: The tokens produced by this tokenizer must not outlive
/// the file buffer and file name provided to the tokenizer.
///
pub struct Tokenizer<'file> {
///
/// The current location we are at.
///
location: Location,
///
/// The contents of the file we are tokenizing.
///
file: &'file str,
///
/// Whether or not we are ignoring whitespace at the moment.
///
ignore_whitespace: bool,
///
/// Whether or not we are reading a line comment at the moment.
///
reading_line_comment: bool,
///
/// Whether or not we are reading a multiline comment at the moment.
///
reading_multiline: bool,
///
/// Whether or not we are reading a string literal.
///
reading_str_literal: bool,
///
/// Whether or not we are reading a char literal.
///
reading_char_literal: bool,
}
impl<'file> Tokenizer<'file> {
///
/// Create a new tokenizer from the filename and its contents.
///
pub fn new(filename: String, file: &str) -> Tokenizer {
let location = Location {
filename: Arc::new(filename),
line: 1,
column: 1,
index: 0,
};
let ignore_whitespace = true;
let reading_line_comment = false;
let reading_multiline = false;
let reading_str_literal = false;
let reading_char_literal = false;
Tokenizer {
location,
file,
ignore_whitespace,
reading_line_comment,
reading_multiline,
reading_str_literal,
reading_char_literal,
}
}
///
/// Consume the Tokenizer, generating a list of tokens from the file and filename
/// provided to the tokenizer.
///
pub fn tokenize(mut self) -> Vec<Token> {
let mut tokens = Vec::new();
while let Some(c) = self.peek() {
if let Some(token) = self.read_token(c) {
tokens.push(token);
}
}
tokens.push(Token::new(
self.location,
"EOF".into(),
TokenType::EndOfFile,
));
tokens
}
///
/// Read a token that begins with the specified character from the file.
///
fn read_token(&mut self, c: char) -> Option<Token> {
if c.is_whitespace() {
self.read_whitespace()
} else if c.is_numeric() {
Some(self.read_numeric())
} else if c.is_alphabetic() {
Some(self.read_alphabetic())
} else {
Some(self.read_symbol())
}
}
///
/// Read whitespace as a token or skip through it depending on the
/// circumstance.
///
fn read_whitespace(&mut self) -> Option<Token> {
///
/// Checks the type of whitespace we have.
///
fn deduce_type(string: &str) -> TokenType {
match string {
"\n" => TokenType::NewLine,
"\t" | "\r" | " " => TokenType::Whitespace,
_ => unreachable!(),
}
}
if self.ignore_whitespace {
self.advance_position();
return None;
}
let start = self.location.clone();
self.advance_position();
let end = self.location.clone();
let string = &self.file[start.index..end.index];
// NOTE(zac, 4/NOV/2017): Terminate any line comments ( '//'s ) at the first
// newline we find.
if string == "\n" && self.reading_line_comment {
self.reading_line_comment = false;
self.ignore_whitespace = true;
}
let ttype = deduce_type(string);
Some(Token::new(start, string.into(), ttype))
}
///
/// Read a numberic token from the file.
///
fn read_numeric(&mut self) -> Token {
let start = self.location.clone();
let mut read_decimal = false;
while self.next_is_numeric_char(&mut read_decimal) {
self.advance_position();
}
let end = self.location.clone();
let ttype = if read_decimal {
TokenType::DecimalLiteral
} else {
TokenType::IntegerLiteral
};
let string = &self.file[start.index..end.index];
Token::new(start, string.into(), ttype)
}
///
/// Read a token that begins with an alphabetic letter.
///
fn read_alphabetic(&mut self) -> Token {
///
/// Deduce the type of the specified string.
///
fn deduce_type(string: &str) -> TokenType {
match string {
"true" | "false" => TokenType::BooleanLiteral,
"if" => TokenType::IfKeyword,
"while" => TokenType::WhileKeyword,
"struct" => TokenType::StructKeyword,
"int" => TokenType::IntKeyword,
"float" => TokenType::FloatKeyword,
"bool" => TokenType::BoolKeyword,
_ => TokenType::Identifier,
}
}
let start = self.location.clone();
while self.next_is_ident_char() {
self.advance_position();
}
let end = self.location.clone();
let string = &self.file[start.index..end.index];
let ttype = deduce_type(string);
Token::new(start, string.into(), ttype)
}
///
/// Reads a token that begins with a symbol.
///
fn read_symbol(&mut self) -> Token {
///
/// Deduce the type of the specified string.
///
fn deduce_type(string: &str) -> TokenType {
match string {
";" => TokenType::Semicolon,
":" => TokenType::Colon,
"(" => TokenType::OpenParen,
")" => TokenType::CloseParen,
"{" => TokenType::OpenBrace,
"}" => TokenType::CloseBrace,
"," => TokenType::Comma,
"+" => TokenType::Plus,
"-" => TokenType::Minus,
"->" => TokenType::Arrow,
"=" => TokenType::EqualsSign,
"==" => TokenType::EqualsOperator,
"*" => TokenType::Asterisk,
"|" => TokenType::Pipe,
"&" => TokenType::Ampersand,
"/" => TokenType::ForwardSlash,
"//" => TokenType::OpenLineComment,
"/*" => TokenType::OpenMultilineComment,
"*/" => TokenType::CloseMultilineComment,
"\"" => TokenType::Quote,
"'" => TokenType::Tick,
_ => TokenType::UnknownSymbol,
}
}
let start = self.location.clone();
let read = self.advance_position();
// NOTE(zac, 4/NOV/2017): Only bother checking for multi-char symbols if
// the next char exists.
if let Some(c) = self.peek() {
self.check_for_multichar_symbol(read, c);
}
let end = self.location.clone();
let string = &self.file[start.index..end.index];
let ttype = deduce_type(string);
Token::new(start, string.into(), ttype)
}
///
/// Checks for a multichar symbol or a symbol that will effect tokenizer state.
/// If it is a multi-char symbol, it will make the necessary self.next() calls.
///
fn check_for_multichar_symbol(&mut self, read: char, peeked: char) {
match read {
'/' => self.handle_forward_slash(peeked),
'*' => self.handle_asterisk(peeked),
'"' => self.handle_quote(),
'\'' => self.handle_tick(),
'=' => self.handle_equals(peeked),
'-' => self.handle_minus(peeked),
_ => (),
}
}
///
/// Handle multi-character symbols that begin with a '/'.
///
fn handle_forward_slash(&mut self, peeked: char) {
// LINE COMMENTS ( '//'s )
if peeked == '/' {
if self.ignore_whitespace {
// ie. if we are not reading something already.
self.advance_position();
self.reading_line_comment = true;
self.ignore_whitespace = false;
}
// NOTE(zac, 4/NOV/2017): We check for the end of this token in read_whitespace, as
// line comments are closed by the newline character '\n'.
}
// MULT-LINE COMMENT START ( '/*'s )
else if peeked == '*' && self.ignore_whitespace {
// ie. if we are not reading something already.
self.advance_position();
self.reading_multiline = true;
self.ignore_whitespace = false;
}
}
///
/// handle multi-char symbols that begin with a '-'.
///
fn handle_minus(&mut self, peeked: char) {
if peeked == '>' {
self.advance_position();
}
}
///
/// Handle multi-char symbols that begin with a '*'.
///
fn handle_asterisk(&mut self, peeked: char) {
if peeked == '/' && self.reading_multiline {
self.advance_position();
self.reading_multiline = false;
self.ignore_whitespace = true;
}
}
///
/// Handle the " character. Used in Tokenizer::handle_multichar_character
/// (despite not being a multichar character, technically).
///
fn handle_quote(&mut self) {
// HANDLE CLOSING.
if self.reading_str_literal {
self.reading_str_literal = false;
self.ignore_whitespace = true;
}
// HANDLE OPENING
else if self.ignore_whitespace {
// ie. if we are not reading something.
self.reading_str_literal = true;
self.ignore_whitespace = false;
}
}
///
/// Handle the ' character. Used in Tokenizer::handle_multichar_character
/// (despite not being a multichar character, technically)
///
fn handle_tick(&mut self) {
// HANDLE CLOSING.
if self.reading_char_literal {
self.reading_char_literal = false;
self.ignore_whitespace = true;
}
// HANDLE OPENING
else if self.ignore_whitespace {
// ie. if we are not reading something.
self.reading_char_literal = true;
self.ignore_whitespace = false;
}
}
///
/// Check for an '==' operator (assuming the read character was '=').
///
fn handle_equals(&mut self, peeked: char) {
if peeked == '=' {
self.advance_position();
}
}
///
/// Checks to see if the next character is a valid numeric string.
/// Will adjust read_decimal to true if we read a single decimal point, and
/// then not accept a decimal after that for this literal.
///
fn next_is_numeric_char(&self, read_decimal: &mut bool) -> bool {
self.peek().map_or(false, |c| {
if c == '.' && !*read_decimal {
*read_decimal = true;
true
} else {
c.is_numeric() || c == '_'
}
})
}
///
/// Checks to see if the next character is a valid identifier character.
///
fn next_is_ident_char(&self) -> bool {
self.peek()
.map_or(false, |c| c.is_alphanumeric() || c == '_')
}
///
/// Takes a peek at the next character without advancing the current location.
/// Returns None if no character exists.
///
fn peek(&self) -> Option<char> {
let index = self.location.index;
self.file.chars().nth(index)
}
///
/// Retreive the next character from the file, panicing if no such character exists.
/// (Use peek first if you are unsure the token exists).
///
fn advance_position(&mut self) -> char {
let c = self.peek()
.expect("INTERNAL COMPILER ERROR: Tried to read a character that doesn't exist.");
self.location.index += 1;
match c {
'\n' => {
self.location.line += 1;
self.location.column = 1;
}
_ => self.location.column += 1,
}
c
}
}
|
{{#>set_constraints constraints~}}
{{#>loop_nest loop_nest~}}
{{#ifeq action "FilterSelf"}}{{>filter_self choice=../../../../this}}{{/ifeq~}}
{{#with action.FilterRemote}}{{>choice_filter}}{{/with~}}
{{#with action.IncrCounter}}{{>incr_counter}}{{/with~}}
{{#with action.UpdateCounter}}{{>update_counter}}{{/with~}}
{{#with action.Trigger}}{{>trigger_on_change}}{{/with~}}
{{/loop_nest~}}
{{/set_constraints~}}
|
/*
* Copyright 2020 Fluence Labs Limited
*
* 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.
*/
#![cfg(test)]
#![recursion_limit = "512"]
#![warn(missing_debug_implementations, rust_2018_idioms, missing_docs)]
#![deny(
dead_code,
nonstandard_style,
unused_imports,
unused_mut,
unused_variables,
unused_unsafe,
unreachable_patterns
)]
mod utils;
use crate::utils::*;
use faas_api::{service, FunctionCall, Protocol};
use libp2p::{identity::PublicKey::Ed25519, PeerId};
use serde_json::Value;
use trust_graph::{current_time, Certificate};
use parity_multiaddr::Multiaddr;
use std::str::FromStr;
use std::thread::sleep;
#[test]
// Send calls between clients through relays
fn send_call() {
let (sender, mut receiver) = ConnectedClient::make_clients().expect("connect clients");
let uuid = uuid();
let call = FunctionCall {
uuid: uuid.clone(),
target: Some(receiver.relay_address()),
reply_to: Some(sender.relay_address()),
name: None,
arguments: Value::Null,
};
sender.send(call);
let received = receiver.receive();
assert_eq!(received.uuid, uuid);
// Check there is no more messages
let bad = receiver.maybe_receive();
assert_eq!(
bad,
None,
"received unexpected message {}, previous was {}",
bad.as_ref().unwrap().uuid,
received.uuid
);
}
#[test]
fn invalid_relay_signature() {
let (mut sender, receiver) = ConnectedClient::make_clients().expect("connect clients");
let target = receiver.relay_address();
let target = target
.protocols()
.into_iter()
.map(|p| {
if let Protocol::Signature(_) = p {
Protocol::Signature(receiver.sign("/incorrect/path".as_bytes()))
} else {
p
}
})
.collect();
let uuid = uuid();
let call = FunctionCall {
uuid: uuid.clone(),
target: Some(target),
reply_to: Some(sender.relay_address()),
name: None,
arguments: Value::Null,
};
sender.send(call);
let reply = sender.receive();
assert!(reply.uuid.starts_with("error_"));
let err_msg = reply.arguments["reason"].as_str().expect("reason");
assert!(err_msg.contains("invalid signature"));
}
#[test]
fn missing_relay_signature() {
enable_logs();
let (mut sender, receiver) = ConnectedClient::make_clients().expect("connect clients");
let target = Protocol::Peer(receiver.node.clone()) / receiver.client_address();
let uuid = uuid();
let call = FunctionCall {
uuid: uuid.clone(),
target: Some(target),
reply_to: Some(sender.relay_address()),
name: None,
arguments: Value::Null,
};
sender.send(call);
let reply = sender.receive();
assert!(reply.uuid.starts_with("error_"));
let err_msg = reply.arguments["reason"].as_str().expect("reason");
assert!(err_msg.contains("missing relay signature"));
}
#[test]
// Provide service, and check that call reach it
fn call_service() {
let service_id = "someserviceilike";
let (mut provider, consumer) = ConnectedClient::make_clients().expect("connect clients");
// Wait until Kademlia is ready // TODO: wait for event from behaviour instead?
sleep(KAD_TIMEOUT);
let provide = provide_call(service_id, provider.relay_address());
provider.send(provide);
let call_service = service_call(service_id, consumer.relay_address());
consumer.send(call_service.clone());
let to_provider = provider.receive();
assert_eq!(
call_service.uuid, to_provider.uuid,
"Got: {:?}",
to_provider
);
assert_eq!(
to_provider.target,
Some(provider.client_address().extend(service!(service_id)))
);
}
#[test]
fn call_service_reply() {
let service_id = "plzreply";
let (mut provider, mut consumer) = ConnectedClient::make_clients().expect("connect clients");
// Wait until Kademlia is ready // TODO: wait for event from behaviour instead?
sleep(KAD_TIMEOUT);
let provide = provide_call(service_id, provider.relay_address());
provider.send(provide);
let call_service = service_call(service_id, consumer.relay_address());
consumer.send(call_service);
let to_provider = provider.receive();
assert_eq!(to_provider.reply_to, Some(consumer.relay_address()));
let reply = reply_call(to_provider.reply_to.unwrap());
provider.send(reply.clone());
let to_consumer = consumer.receive();
assert_eq!(reply.uuid, to_consumer.uuid, "Got: {:?}", to_consumer);
assert_eq!(to_consumer.target, Some(consumer.client_address()));
}
#[test]
// 1. Provide some service
// 2. Disconnect provider – service becomes unregistered
// 3. Check that calls to service fail
// 4. Provide same service again, via different provider
// 5. Check that calls to service succeed
fn provide_disconnect() {
let service_id = "providedisconnect";
let (mut provider, mut consumer) = ConnectedClient::make_clients().expect("connect clients");
// Wait until Kademlia is ready // TODO: wait for event from behaviour instead?
sleep(KAD_TIMEOUT);
// Register service
let provide = provide_call(service_id, provider.relay_address());
provider.send(provide);
// Check there was no error // TODO: maybe send reply from relay?
let error = provider.maybe_receive();
assert_eq!(error, None);
// Disconnect provider, service should be deregistered
provider.client.stop();
// Send call to the service, should fail
let mut call_service = service_call(service_id, consumer.relay_address());
call_service.name = Some("Send call to the service, should fail".into());
consumer.send(call_service.clone());
let error = consumer.receive();
assert!(error.uuid.starts_with("error_"));
// Register the service once again
// let bootstraps = vec![provider.node_address.clone(), consumer.node_address.clone()];
let mut provider =
ConnectedClient::connect_to(provider.node_address).expect("connect provider");
let provide = provide_call(service_id, provider.relay_address());
provider.send(provide);
let error = provider.maybe_receive();
assert_eq!(error, None);
// Send call to the service once again, should succeed
call_service.name = Some("Send call to the service , should succeed".into());
consumer.send(call_service.clone());
let to_provider = provider.receive();
assert_eq!(call_service.uuid, to_provider.uuid);
assert_eq!(
to_provider.target,
Some(provider.client_address().extend(service!(service_id)))
);
}
#[test]
// Receive error when there's not enough nodes to store service in DHT
fn provide_error() {
let mut provider = ConnectedClient::new().expect("connect client");
let service_id = "failedservice";
let provide = provide_call(service_id, provider.relay_address());
provider.send(provide);
let error = provider.receive();
assert!(error.uuid.starts_with("error_"));
}
#[test]
fn reconnect_provide() {
let service_id = "popularservice";
let swarms = make_swarms(5);
sleep(KAD_TIMEOUT);
let consumer = ConnectedClient::connect_to(swarms[1].1.clone()).expect("connect consumer");
for _i in 1..20 {
for swarm in swarms.iter() {
let provider = ConnectedClient::connect_to(swarm.1.clone()).expect("connect provider");
let provide_call = provide_call(service_id, provider.relay_address());
provider.send(provide_call);
sleep(SHORT_TIMEOUT);
}
}
sleep(SHORT_TIMEOUT);
let mut provider = ConnectedClient::connect_to(swarms[0].1.clone()).expect("connect provider");
let provide_call = provide_call(service_id, provider.relay_address());
provider.send(provide_call);
sleep(KAD_TIMEOUT);
let call_service = service_call(service_id, consumer.relay_address());
consumer.send(call_service.clone());
let to_provider = provider.receive();
assert_eq!(to_provider.uuid, call_service.uuid);
}
#[test]
fn get_certs() {
let cert = get_cert();
let first_key = cert.chain.first().unwrap().issued_for.clone();
let last_key = cert.chain.last().unwrap().issued_for.clone();
let trust = Trust {
root_weights: vec![(first_key, 1)],
certificates: vec![cert.clone()],
cur_time: current_time(),
};
let swarm_count = 5;
let swarms = make_swarms_with(swarm_count, |bs, maddr| {
create_swarm(bs, maddr, Some(trust.clone()))
});
sleep(KAD_TIMEOUT);
let mut consumer = ConnectedClient::connect_to(swarms[1].1.clone()).expect("connect consumer");
let peer_id = PeerId::from(Ed25519(last_key));
let call = certificates_call(peer_id, consumer.relay_address());
consumer.send(call.clone());
// If count is small, all nodes should fit in neighborhood, and all of them should reply
for _ in 0..swarm_count {
let reply = consumer.receive();
assert_eq!(reply.arguments["msg_id"], call.arguments["msg_id"]);
let reply_certs = &reply.arguments["certificates"][0]
.as_str()
.expect("get str cert");
let reply_certs = Certificate::from_str(reply_certs).expect("deserialize cert");
assert_eq!(reply_certs, cert);
}
}
// TODO: test on get_certs error
#[test]
fn add_certs() {
let cert = get_cert();
let first_key = cert.chain.first().unwrap().issued_for.clone();
let last_key = cert.chain.last().unwrap().issued_for.clone();
let trust = Trust {
root_weights: vec![(first_key, 1)],
certificates: vec![],
cur_time: current_time(),
};
let swarm_count = 5;
let swarms = make_swarms_with(swarm_count, |bs, maddr| {
create_swarm(bs, maddr, Some(trust.clone()))
});
sleep(KAD_TIMEOUT);
let mut registrar = ConnectedClient::connect_to(swarms[1].1.clone()).expect("connect consumer");
let peer_id = PeerId::from(Ed25519(last_key));
let call = add_certificates_call(peer_id, registrar.relay_address(), vec![cert]);
registrar.send(call.clone());
// If count is small, all nodes should fit in neighborhood, and all of them should reply
for _ in 0..swarm_count {
let reply = registrar.receive();
assert_eq!(reply.arguments["msg_id"], call.arguments["msg_id"]);
}
}
#[test]
fn add_certs_invalid_signature() {
let mut cert = get_cert();
let first_key = cert.chain.first().unwrap().issued_for.clone();
let last_key = cert.chain.last().unwrap().issued_for.clone();
let trust = Trust {
root_weights: vec![(first_key, 1)],
certificates: vec![],
cur_time: current_time(),
};
let swarm_count = 5;
let swarms = make_swarms_with(swarm_count, |bs, maddr| {
create_swarm(bs, maddr, Some(trust.clone()))
});
sleep(KAD_TIMEOUT);
// invalidate signature in last trust in `cert`
let signature = &mut cert.chain.last_mut().unwrap().signature;
signature.iter_mut().for_each(|b| *b = b.saturating_add(1));
let mut registrar = ConnectedClient::connect_to(swarms[1].1.clone()).expect("connect consumer");
let peer_id = PeerId::from(Ed25519(last_key));
let call = add_certificates_call(peer_id, registrar.relay_address(), vec![cert]);
registrar.send(call.clone());
// check it's an error
let reply = registrar.receive();
assert!(reply.uuid.starts_with("error_"));
let err_msg = reply.arguments["reason"].as_str().expect("reason");
assert!(err_msg.contains("Signature is not valid"));
}
#[test]
fn identify() {
use faas_api::Protocol::Peer;
use serde_json::json;
let swarms = make_swarms(5);
sleep(KAD_TIMEOUT);
let mut consumer = ConnectedClient::connect_to(swarms[1].1.clone()).expect("connect consumer");
let mut identify_call = service_call("identify", consumer.relay_address());
let msg_id = uuid();
identify_call.arguments = json!({ "msg_id": msg_id });
consumer.send(identify_call.clone());
fn check_reply(consumer: &mut ConnectedClient, swarm_addr: &Multiaddr, msg_id: &str) {
let reply = consumer.receive();
#[rustfmt::skip]
let reply_msg_id = reply.arguments.get("msg_id").expect("not empty").as_str().expect("str");
assert_eq!(reply_msg_id, msg_id);
let addrs = reply.arguments["addresses"].as_array().expect("not empty");
assert!(!addrs.is_empty());
let addr: Multiaddr = addrs.first().unwrap().as_str().unwrap().parse().unwrap();
assert_eq!(&addr, swarm_addr);
}
check_reply(&mut consumer, &swarms[1].1, &msg_id);
for swarm in swarms {
identify_call.target = Some(Peer(swarm.0.clone()) / service!("identify"));
consumer.send(identify_call.clone());
check_reply(&mut consumer, &swarm.1, &msg_id);
}
}
|
use std::io;
use std::net::SocketAddr;
use std::thread;
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;
use tokio_core::net::UdpCodec;
use futures::{Future, Stream};
use futures::sync::mpsc;
use futures::Sink;
pub struct LineCodec;
impl UdpCodec for LineCodec {
type In = (SocketAddr, Vec<u8>);
type Out = (SocketAddr, Vec<u8>);
fn decode(&mut self, addr: &SocketAddr, buf: &[u8]) -> io::Result<Self::In> {
Ok((*addr, buf.to_vec()))
}
fn encode(&mut self, (addr, buf): Self::Out, into: &mut Vec<u8>) -> SocketAddr {
into.extend(buf);
addr
}
}
pub fn receiver(addr: SocketAddr, tx: mpsc::Sender<Vec<u8>>) -> thread::JoinHandle<()> {
thread::spawn(move || {
let mut core = Core::new().unwrap();
let handle = core.handle();
let a = UdpSocket::bind(&addr, &handle).unwrap();
let (_, a_stream) = a.framed(LineCodec).split();
let a = a_stream.map_err(|_| ()).fold(tx, |sender, (_, x): (SocketAddr, Vec<u8>)| {
let sender = sender.send(x).wait().unwrap();
Ok(sender)
});
drop(core.run(a));
})
}
pub fn sender<S>(stream: S) -> thread::JoinHandle<()>
where S: Stream<Item=(SocketAddr, Vec<u8>), Error=()> + Send + Sized + 'static {
thread::spawn(move || {
let mut core = Core::new().unwrap();
let handle = core.handle();
let local_addr: SocketAddr = "0.0.0.0:0".parse().unwrap();
let a = UdpSocket::bind(&local_addr, &handle).unwrap();
let (a_sink, _) = a.framed(LineCodec).split();
let sender = a_sink.sink_map_err(|e| {
eprintln!("err {:?}", e);
}).send_all(stream);
//handle.spawn(sender.then(|_| Ok(())));
drop(core.run(sender));
})
}
|
//! If any available, this provides handles for various forms of asynchronous
//! drivers that can be used in combination with audio interfaces.
mod atomic_waker;
use crate::Result;
use std::cell::Cell;
use std::future::Future;
use std::ptr;
thread_local! {
static RUNTIME: Cell<*const Runtime> = Cell::new(ptr::null());
}
cfg_events_driver! {
pub(crate) mod events;
#[doc(hidden)]
pub use self::events::EventsDriver;
pub(crate) fn with_events<F, T>(f: F) -> T where F: FnOnce(&EventsDriver) -> T {
RUNTIME.with(|rt| {
// Safety: we maintain tight control of how and when RUNTIME is
// constructed.
let rt = unsafe { rt.get().as_ref().expect("missing audio runtime") };
f(&rt.events)
})
}
}
cfg_poll_driver! {
pub(crate) mod poll;
#[doc(hidden)]
pub use self::poll::{PollDriver, AsyncPoll};
pub(crate) fn with_poll<F, T>(f: F) -> T where F: FnOnce(&PollDriver) -> T {
RUNTIME.with(|rt| {
// Safety: we maintain tight control of how and when RUNTIME is
// constructed.
let rt = unsafe { rt.get().as_ref().expect("missing audio runtime") };
f(&rt.poll)
})
}
}
/// The audio runtime.
///
/// This is necessary to use with asynchronous audio-related APIs.
///
/// To run an asynchronous task inside of the audio runtime, we use the
/// [wrap][Runtime::wrap] function.
///
/// # Examples
///
/// ```rust,no_run
/// # async fn task() {}
/// # #[tokio::main] async fn main() -> anyhow::Result<()> {
/// let runtime = audio_device::runtime::Runtime::new()?;
/// runtime.wrap(task()).await;
/// # Ok(()) }
/// ```
pub struct Runtime {
#[cfg(feature = "events-driver")]
events: self::events::EventsDriver,
#[cfg(feature = "poll-driver")]
poll: self::poll::PollDriver,
}
impl Runtime {
/// Construct a new audio runtime.
pub fn new() -> Result<Self> {
Ok(Self {
#[cfg(feature = "events-driver")]
events: self::events::EventsDriver::new()?,
#[cfg(feature = "poll-driver")]
poll: self::poll::PollDriver::new()?,
})
}
/// Construct a runtime guard that when in scope will provide thread-local
/// access to runtime drivers.
pub fn enter(&self) -> RuntimeGuard<'_> {
let old = RUNTIME.with(|rt| rt.replace(self as *const _));
RuntimeGuard {
_runtime: self,
old,
}
}
/// Run the given asynchronous task inside of the runtime.
///
/// # Examples
///
/// ```rust,no_run
/// # async fn task() {}
/// # #[tokio::main] async fn main() -> anyhow::Result<()> {
/// let runtime = audio_device::runtime::Runtime::new()?;
/// runtime.wrap(task()).await;
/// # Ok(()) }
/// ```
pub async fn wrap<F>(&self, f: F) -> F::Output
where
F: Future,
{
use std::pin::Pin;
use std::task::{Context, Poll};
return GuardFuture(self, f).await;
struct GuardFuture<'a, F>(&'a Runtime, F);
impl<'a, F> Future for GuardFuture<'a, F>
where
F: Future,
{
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let _guard = self.0.enter();
let future = unsafe { Pin::map_unchecked_mut(self, |this| &mut this.1) };
future.poll(cx)
}
}
}
/// Shutdown and join the runtime.
pub fn join(self) {
#[cfg(feature = "events-driver")]
let _ = self.events.join();
#[cfg(feature = "poll-driver")]
let _ = self.poll.join();
}
}
/// The runtime guard constructed with [Runtime::enter].
///
/// Runtime plumbing is available as long as this guard is in scope.
pub struct RuntimeGuard<'a> {
// NB: prevent the guard from outliving the runtime it was constructed from.
_runtime: &'a Runtime,
old: *const Runtime,
}
impl Drop for RuntimeGuard<'_> {
fn drop(&mut self) {
RUNTIME.with(|rt| {
rt.set(self.old);
})
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
mod segments;
pub use segments::{RasterSegments, RasterSegmentsIter};
use std::{iter, rc::Rc};
#[cfg(feature = "tracing")]
use fuchsia_trace::duration;
use crate::{
path::Path,
point::Point,
segment::Segment,
tile::{TileContour, TileContourBuilder},
};
// Used in spinel-mold.
#[doc(hidden)]
#[derive(Debug)]
pub struct RasterInner {
segments: RasterSegments,
tile_contour: TileContour,
}
impl RasterInner {
// Used in spinel-mold.
#[doc(hidden)]
pub fn translated(inner: &Rc<RasterInner>, translation: Point<i32>) -> Raster {
Raster {
inner: Rc::clone(inner),
translation,
translated_tile_contour: Some(inner.tile_contour.translated(translation)),
}
}
}
/// A rasterized, printable version of zero or more paths.
///
/// Rasters are pixel-grid-aware compact representations of vector content. They store information
/// only about the outlines that they define.
#[derive(Clone, Debug)]
pub struct Raster {
// Used in spinel-mold.
#[doc(hidden)]
pub inner: Rc<RasterInner>,
translation: Point<i32>,
translated_tile_contour: Option<TileContour>,
}
impl Raster {
fn rasterize(segments: impl Iterator<Item = Segment<i32>>) -> RasterSegments {
#[cfg(feature = "tracing")]
duration!("gfx", "Raster::rasterize");
segments.collect()
}
fn build_contour(segments: &RasterSegments) -> TileContour {
#[cfg(feature = "tracing")]
duration!("gfx", "Raster::tile_contour");
let mut tile_contour_builder = TileContourBuilder::new();
for segment in segments.iter() {
tile_contour_builder.enclose(&segment);
}
tile_contour_builder.build()
}
fn from_segments(segments: impl Iterator<Item = Segment<f32>>) -> Self {
let segments =
Self::rasterize(segments.flat_map(|segment| segment.to_sp_segments()).flatten());
let tile_contour = Self::build_contour(&segments);
Self {
inner: Rc::new(RasterInner { segments, tile_contour }),
translation: Point::new(0, 0),
translated_tile_contour: None,
}
}
/// Creates a new raster from a `path`.
///
/// # Examples
/// ```
/// # use crate::mold::{Path, Raster};
/// let raster = Raster::new(&Path::new());
/// ```
pub fn new(path: &Path) -> Self {
Self::from_segments(path.segments())
}
/// Creates a new raster from a `path` by applying `transform`.
///
/// # Examples
/// ```
/// # use crate::mold::{Path, Raster};
/// let double = [2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0];
/// let raster = Raster::with_transform(&Path::new(), &double);
/// ```
pub fn with_transform(path: &Path, transform: &[f32; 9]) -> Self {
Self::from_segments(path.transformed(transform))
}
/// Creates an empty raster.
///
/// # Examples
/// ```
/// # use crate::mold::Raster;
/// let raster = Raster::empty();
/// ```
pub fn empty() -> Self {
Self::from_segments(iter::empty())
}
pub(crate) fn maxed() -> Self {
let inner = RasterInner {
segments: RasterSegments::new(),
tile_contour: TileContourBuilder::maxed(),
};
Self { inner: Rc::new(inner), translation: Point::new(0, 0), translated_tile_contour: None }
}
/// Creates a new raster from an `Iterator` of `paths`.
///
/// # Examples
/// ```
/// # use crate::mold::{Path, Raster};
/// use std::iter;
/// let raster = Raster::from_paths(iter::once(&Path::new()));
/// ```
pub fn from_paths<'a, I>(paths: I) -> Self
where
I: IntoIterator<Item = &'a Path>,
{
Self::from_segments(paths.into_iter().map(Path::segments).flatten())
}
/// Creates a new raster from an `Iterator` `paths` of `(path, transform)` tuples.
///
/// # Examples
/// ```
/// # use crate::mold::{Path, Raster};
/// use std::iter;
/// let double = [2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0];
/// let raster = Raster::from_paths_and_transforms(iter::once((&Path::new(), &double)));
/// ```
pub fn from_paths_and_transforms<'a, I>(paths: I) -> Self
where
I: IntoIterator<Item = (&'a Path, &'a [f32; 9])>,
{
Self::from_segments(
paths.into_iter().map(|(path, transform)| path.transformed(transform)).flatten(),
)
}
/// Translates raster by `translation` pixels.
///
/// # Examples
/// ```
/// # use crate::mold::{Point, Raster};
/// # let mut raster = Raster::empty();
/// raster.translate(Point::new(1, 0));
/// raster.translate(Point::new(1, 0)); // Adds to first translation.
/// // Total Ox translation: 2
/// ```
pub fn translate(&mut self, translation: Point<i32>) {
let translation =
{ Point::new(self.translation.x + translation.x, self.translation.y + translation.y) };
self.set_translation(translation);
}
/// Sets raster translation to `translation` pixels.
///
/// # Examples
/// ```
/// # use crate::mold::{Point, Raster};
/// # let mut raster = Raster::empty();
/// raster.set_translation(Point::new(1, 0));
/// raster.set_translation(Point::new(1, 0)); // Resets first translation.
/// // Total Ox translation: 1
/// ```
pub fn set_translation(&mut self, translation: Point<i32>) {
let inner = &self.inner;
if self.translation != translation {
self.translation = translation;
self.translated_tile_contour = Some(inner.tile_contour.translated(translation));
}
}
fn from_segments_and_contour<'r>(segments: RasterSegments, tile_contour: TileContour) -> Self {
Self {
inner: Rc::new(RasterInner { segments, tile_contour }),
translation: Point::new(0, 0),
translated_tile_contour: None,
}
}
/// Creates a uinion-raster from all `rasters`.
///
/// # Examples
/// ```
/// # use crate::mold::Raster;
/// use std::iter;
/// let union = Raster::union(iter::repeat(&Raster::empty()).take(3));
/// ```
pub fn union<'r>(rasters: impl Iterator<Item = &'r Self>) -> Self {
let mut tile_contour = TileContourBuilder::empty();
let segments = rasters
.map(|raster| {
tile_contour = tile_contour.union(raster.tile_contour());
raster.segments().iter().map(move |segment| segment.translate(raster.translation))
})
.flatten()
.collect();
Self::from_segments_and_contour(segments, tile_contour)
}
/// Creates a uinion-raster from all `rasters` but discards all segment data.
///
/// # Examples
/// ```
/// # use crate::mold::Raster;
/// use std::iter;
/// let union = Raster::union_without_segments(iter::repeat(&Raster::empty()).take(3));
/// ```
pub fn union_without_segments<'r>(rasters: impl Iterator<Item = &'r Self>) -> Self {
Self::from_segments_and_contour(
RasterSegments::new(),
rasters.fold(TileContourBuilder::empty(), |tile_contour, raster| {
tile_contour.union(raster.tile_contour())
}),
)
}
pub(crate) fn segments(&self) -> &RasterSegments {
&self.inner.segments
}
pub(crate) fn tile_contour(&self) -> &TileContour {
self.translated_tile_contour.as_ref().unwrap_or(&self.inner.tile_contour)
}
pub(crate) fn translation(&self) -> Point<i32> {
self.translation
}
}
impl Eq for Raster {}
impl PartialEq for Raster {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.inner, &other.inner) && self.translation == other.translation
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::PIXEL_WIDTH;
fn to_and_fro(segments: &[Segment<i32>]) -> Vec<Segment<i32>> {
segments.into_iter().cloned().collect::<RasterSegments>().iter().collect()
}
#[test]
fn raster_segments_one_segment_all_end_point_combinations() {
for x in -PIXEL_WIDTH..=PIXEL_WIDTH {
for y in -PIXEL_WIDTH..=PIXEL_WIDTH {
let segments = vec![Segment::new(Point::new(0, 0), Point::new(x, y))];
assert_eq!(to_and_fro(&segments), segments);
}
}
}
#[test]
fn raster_segments_one_segment_negative() {
let segments = vec![Segment::new(Point::new(0, 0), Point::new(-PIXEL_WIDTH, -PIXEL_WIDTH))];
assert_eq!(to_and_fro(&segments), segments);
}
#[test]
fn raster_segments_two_segments_common() {
let segments = vec![
Segment::new(Point::new(0, 0), Point::new(PIXEL_WIDTH, PIXEL_WIDTH)),
Segment::new(
Point::new(PIXEL_WIDTH, PIXEL_WIDTH),
Point::new(PIXEL_WIDTH * 2, PIXEL_WIDTH * 2),
),
];
assert_eq!(to_and_fro(&segments), segments);
}
#[test]
fn raster_segments_two_segments_different() {
let segments = vec![
Segment::new(Point::new(0, 0), Point::new(PIXEL_WIDTH, PIXEL_WIDTH)),
Segment::new(
Point::new(PIXEL_WIDTH * 5, PIXEL_WIDTH * 5),
Point::new(PIXEL_WIDTH * 6, PIXEL_WIDTH * 6),
),
];
assert_eq!(to_and_fro(&segments), segments);
}
#[test]
fn raster_union() {
let mut path1 = Path::new();
path1.line(Point::new(0.0, 0.0), Point::new(1.0, 1.0));
let mut path2 = Path::new();
path2.line(Point::new(1.0, 1.0), Point::new(2.0, 2.0));
let union = Raster::union([Raster::new(&path1), Raster::new(&path2)].into_iter());
assert_eq!(
union.inner.segments.iter().collect::<Vec<_>>(),
vec![
Segment::new(Point::new(0, 0), Point::new(PIXEL_WIDTH, PIXEL_WIDTH)),
Segment::new(
Point::new(PIXEL_WIDTH, PIXEL_WIDTH),
Point::new(PIXEL_WIDTH * 2, PIXEL_WIDTH * 2),
),
]
);
assert_eq!(union.inner.tile_contour.tiles(), vec![(0, 0)]);
}
#[test]
fn raster_union_without_segments() {
let mut path1 = Path::new();
path1.line(Point::new(0.0, 0.0), Point::new(1.0, 1.0));
let mut path2 = Path::new();
path2.line(Point::new(1.0, 1.0), Point::new(2.0, 2.0));
let union =
Raster::union_without_segments([Raster::new(&path1), Raster::new(&path2)].into_iter());
assert_eq!(union.inner.segments.iter().collect::<Vec<_>>(), vec![]);
assert_eq!(union.inner.tile_contour.tiles(), vec![(0, 0)]);
}
}
|
use crate::formats::{ReferenceFormat, ReferenceFormatSpecification, HASHES};
use crate::object::{ObjectHash, ObjectId, HASH_LENGTH, UUID_LENGTH};
use crate::Result;
use std::collections::{hash_map, HashMap};
use std::convert::TryInto;
use std::io;
use std::io::{BufRead, Read, Write};
use std::mem::size_of;
use std::ops::Index;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
type HashesDataType = HashMap<ObjectId, ObjectHash>;
const ENTRY_LENGTH: usize = UUID_LENGTH + HASH_LENGTH;
pub struct Hashes {
last_updated: SystemTime,
data: HashesDataType,
}
impl Hashes {
pub fn new() -> Self {
Hashes {
last_updated: SystemTime::now(),
data: HashMap::new(),
}
}
pub fn insert(&mut self, id: &ObjectId, hash: &ObjectHash) -> Option<ObjectHash> {
self.data.insert(*id, *hash)
}
pub fn remove(&mut self, id: &ObjectId) -> Option<ObjectHash> {
self.data.remove(id)
}
pub fn get_hash(&self, id: &ObjectId) -> Option<&ObjectHash> {
self.data.get(id)
}
pub fn get_id(&self, hash: &ObjectHash) -> Option<&ObjectId> {
self.data.iter().find(|x| *x.1 == *hash).map(|x| x.0)
}
pub fn get_last_updated(&self) -> &SystemTime {
&self.last_updated
}
pub fn get_ids(&self) -> hash_map::Keys<'_, ObjectId, ObjectHash> {
self.data.keys()
}
pub fn iter(&self) -> hash_map::Iter<'_, ObjectId, ObjectHash> {
self.data.iter()
}
}
impl ReferenceFormat for Hashes {
fn specification() -> &'static ReferenceFormatSpecification {
&HASHES
}
fn load<R: BufRead + Read>(&mut self, reader: &mut R) -> Result<()> {
Self::check_magic_bytes(reader)?;
let mut timestamp = [0u8; size_of::<u64>()];
reader.read_exact(&mut timestamp)?;
let timestamp = u64::from_le_bytes(timestamp);
self.last_updated = UNIX_EPOCH + Duration::from_millis(timestamp);
let mut entry_buf = Vec::with_capacity(UUID_LENGTH + HASH_LENGTH);
loop {
entry_buf.clear();
let entry_bytes_read = reader
.take(ENTRY_LENGTH as u64)
.read_to_end(&mut entry_buf)?;
if entry_bytes_read == 0 {
break;
}
if entry_bytes_read < UUID_LENGTH + HASH_LENGTH {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into());
}
self.data.insert(
entry_buf[..UUID_LENGTH].try_into()?,
entry_buf[UUID_LENGTH..].try_into()?,
);
}
Ok(())
}
fn save<W: Write>(&self, writer: &mut W) -> Result<()> {
writer.write_all(Self::specification().magic_bytes)?;
let now: u64 = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis()
.try_into()
.unwrap();
writer.write_all(&now.to_le_bytes())?;
for (id, hash) in self.data.iter() {
assert_eq!(id.len(), UUID_LENGTH);
assert_eq!(hash.len(), HASH_LENGTH);
writer.write_all(id)?;
writer.write_all(hash)?;
}
Ok(())
}
}
impl Index<ObjectId> for Hashes {
type Output = ObjectHash;
fn index(&self, index: ObjectId) -> &Self::Output {
&self.get_hash(&index).unwrap()
}
}
impl Default for Hashes {
fn default() -> Self {
Hashes::new()
}
}
|
use super::DirEntryTrait;
use crate::fs::FileTypeTrait;
use crate::fs::StandaloneFileType;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct DirEntry {
raw: PathBuf,
file_type: StandaloneFileType,
}
impl DirEntry {
pub fn from_path<P: Into<PathBuf>>(raw: P) -> Result<Self, io::Error> {
let path_buf = raw.into();
let metadata = path_buf.metadata()?;
let file_type = metadata.file_type();
Ok(Self::from_path_with_file_type(
path_buf,
StandaloneFileType::from_file_type(&file_type),
))
}
pub fn from_path_with_file_type<P: Into<PathBuf>>(
raw: P,
file_type: StandaloneFileType,
) -> Self {
DirEntry {
raw: raw.into(),
file_type,
}
}
}
impl DirEntryTrait for DirEntry {
/// The full path that this entry represents.
///
/// See [`walkdir::DirEntry::path`] for more details
fn path(&self) -> &Path {
&self.raw
}
/// Return `true` if and only if this entry was created from a symbolic
/// link. This is unaffected by the [`follow_links`] setting.
///
/// See [`walkdir::DirEntry::path_is_symlink`] for more details
fn path_is_symlink(&self) -> bool {
self.file_type.is_symlink()
}
/// Return the metadata for the file that this entry points to.
///
/// See [`walkdir::DirEntry::metadata`] for more details
fn metadata(&self) -> io::Result<fs::Metadata> {
self.raw.metadata()
}
/// Return the file type for the file that this entry points to.
///
/// See [`walkdir::DirEntry::file_type`] for more details
fn file_type(&self) -> Box<dyn FileTypeTrait> {
Box::new(self.file_type.clone())
}
/// Return the file name of this entry.
///
/// See [`walkdir::DirEntry::file_name`] for more details
fn file_name(&self) -> &OsStr {
self.raw
.file_name()
.expect("An invalid DirEntry instance has been created. This must not have happened")
}
}
|
use std::str::FromStr;
use postgres::{Client as PostgresClient, NoTls};
error_chain! {
types {
ConnectionError, ConnectionErrorKind, ConnectionResultExt, ConnectionResult;
}
foreign_links {
PostgresConnect(::postgres::error::Error);
}
errors {
MalformedConnectionString {
description("The connection string was malformed.")
}
RequiredPartMissing(part: String) {
description("Required connection string part missing")
display("Required connection string part missing: '{}'", part)
}
TlsNotSupported {
description("TLS connections are not currently supported.")
}
}
}
#[derive(Debug)]
pub struct Connection {
database: String,
uri: String,
}
impl Connection {
pub fn database(&self) -> &str {
&self.database
}
pub fn connect_host(&self) -> ConnectionResult<PostgresClient> {
Ok(PostgresClient::connect(&self.uri, NoTls)?)
}
pub fn connect_database(&self) -> ConnectionResult<PostgresClient> {
Ok(PostgresClient::connect(&self.uri_with_database(), NoTls)?)
}
fn uri_with_database(&self) -> String {
format!("{}/{}", self.uri, self.database)
}
}
impl FromStr for Connection {
type Err = ConnectionError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
use std::collections::HashMap;
// First up, parse the connection string
let mut parts = HashMap::new();
for section in input.split(';') {
if section.trim().is_empty() {
continue;
}
let pair: Vec<&str> = section.split('=').collect();
if pair.len() != 2 {
bail!(ConnectionErrorKind::MalformedConnectionString);
}
parts.insert(pair[0], pair[1]);
}
let host = match parts.get(&"host") {
Some(host) => *host,
None => bail!(ConnectionErrorKind::RequiredPartMissing("host".to_owned())),
};
let database = match parts.get(&"database") {
Some(database) => *database,
None => bail!(ConnectionErrorKind::RequiredPartMissing("database".to_owned())),
};
let user = match parts.get(&"userid") {
Some(user) => *user,
None => bail!(ConnectionErrorKind::RequiredPartMissing("userid".to_owned())),
};
let mut builder = ConnectionBuilder::new(database, host, user);
if let Some(password) = parts.get("password") {
builder.with_password(*password);
}
if let Some(port) = parts.get("port") {
match u16::from_str(port) {
Ok(port) => builder.with_port(port),
Err(_) => bail!(ConnectionErrorKind::MalformedConnectionString),
};
}
if let Some(tls_mode) = parts.get("tlsmode") {
builder.with_tls_mode(*tls_mode);
}
// Make sure we have enough for a connection string
builder.build()
}
}
pub struct ConnectionBuilder {
database: String,
host: String,
user: String,
password: Option<String>,
port: Option<u16>,
tls_mode: bool,
}
impl ConnectionBuilder {
pub fn new<S: Into<String>>(database: S, host: S, user: S) -> ConnectionBuilder {
ConnectionBuilder {
database: database.into(),
host: host.into(),
user: user.into(),
password: None,
port: None,
tls_mode: false,
}
}
pub fn with_password<S: Into<String>>(&mut self, value: S) -> &mut ConnectionBuilder {
self.password = Some(value.into());
self
}
pub fn with_port(&mut self, value: u16) -> &mut ConnectionBuilder {
self.port = Some(value);
self
}
pub fn with_tls_mode(&mut self, value: &str) -> &mut ConnectionBuilder {
self.tls_mode = value.eq_ignore_ascii_case("true");
self
}
pub fn build(&self) -> ConnectionResult<Connection> {
if self.tls_mode {
Err(ConnectionErrorKind::TlsNotSupported.into())
} else {
let fq_host = match self.port {
Some(port) => format!("{}:{}", self.host, port),
None => self.host.to_owned(),
};
let uri = match self.password {
Some(ref password) => format!("postgres://{}:{}@{}", self.user, password, fq_host),
None => format!("postgres://{}@{}", self.user, fq_host),
};
Ok(Connection {
database: self.database.clone(),
uri,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! assert_error_kind {
($err:expr, $kind:pat) => {
match *$err.kind() {
$kind => assert!(true, "{:?} is of kind {:?}", $err, stringify!($kind)),
_ => assert!(false, "{:?} is NOT of kind {:?}", $err, stringify!($kind)),
}
};
}
#[test]
fn builder_basic_works() {
let connection = ConnectionBuilder::new("database", "host", "user").build().unwrap();
assert_eq!("database", connection.database());
assert_eq!("postgres://user@host", connection.uri);
}
#[test]
fn builder_with_password_works() {
let connection = ConnectionBuilder::new("database", "host", "user")
.with_password("password")
.build()
.unwrap();
assert_eq!("database", connection.database());
assert_eq!("postgres://user:password@host", connection.uri);
}
#[test]
fn builder_with_tls_fails() {
let error = ConnectionBuilder::new("database", "host", "user")
.with_tls_mode("true")
.build()
.unwrap_err();
assert_error_kind!(error, ConnectionErrorKind::TlsNotSupported);
}
#[test]
fn parse_basic_works() {
let connection: Connection = "host=localhost;database=db1;userid=user;".parse().unwrap();
assert_eq!("db1", connection.database());
assert_eq!("postgres://user@localhost", connection.uri);
}
#[test]
fn parse_with_password_works() {
let connection: Connection = "host=localhost;database=db1;userid=user;password=secret;"
.parse()
.unwrap();
assert_eq!("db1", connection.database());
assert_eq!("postgres://user:secret@localhost", connection.uri);
}
#[test]
fn parse_without_host_fails() {
let error = "database=db1;userid=user;".parse::<Connection>().unwrap_err();
assert_error_kind!(error, ConnectionErrorKind::RequiredPartMissing(_));
}
#[test]
fn parse_without_database_fails() {
let error = "host=localhost;userid=user;".parse::<Connection>().unwrap_err();
assert_error_kind!(error, ConnectionErrorKind::RequiredPartMissing(_));
}
#[test]
fn parse_without_user_fails() {
let error = "host=localhost;database=db1".parse::<Connection>().unwrap_err();
assert_error_kind!(error, ConnectionErrorKind::RequiredPartMissing(_));
}
}
|
pub mod interop;
use ipfs::Node;
/// The way in which nodes are connected to each other; to be used with spawn_nodes.
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Topology {
/// no connections
None,
/// a > b > c
Line,
/// a > b > c > a
Ring,
/// a <> b <> c <> a
Mesh,
/// a > b, a > c
Star,
}
#[allow(dead_code)]
pub async fn spawn_nodes(count: usize, topology: Topology) -> Vec<Node> {
let mut nodes = Vec::with_capacity(count);
for i in 0..count {
let node = Node::new(i.to_string()).await;
nodes.push(node);
}
match topology {
Topology::Line | Topology::Ring => {
for i in 0..(count - 1) {
nodes[i]
.connect(nodes[i + 1].addrs[0].clone())
.await
.unwrap();
}
if topology == Topology::Ring {
nodes[count - 1]
.connect(nodes[0].addrs[0].clone())
.await
.unwrap();
}
}
Topology::Mesh => {
for i in 0..count {
for (j, peer) in nodes.iter().enumerate() {
if i != j {
nodes[i].connect(peer.addrs[0].clone()).await.unwrap();
}
}
}
}
Topology::Star => {
for node in nodes.iter().skip(1) {
nodes[0].connect(node.addrs[0].clone()).await.unwrap();
}
}
Topology::None => {}
}
nodes
}
#[cfg(test)]
mod tests {
use super::*;
const N: usize = 5;
#[tokio::test(max_threads = 1)]
async fn check_topology_line() {
let nodes = spawn_nodes(N, Topology::Line).await;
for (i, node) in nodes.iter().enumerate() {
if i == 0 || i == N - 1 {
assert_eq!(node.peers().await.unwrap().len(), 1);
} else {
assert_eq!(node.peers().await.unwrap().len(), 2);
}
}
}
#[tokio::test(max_threads = 1)]
async fn check_topology_ring() {
let nodes = spawn_nodes(N, Topology::Ring).await;
for node in &nodes {
assert_eq!(node.peers().await.unwrap().len(), 2);
}
}
#[tokio::test(max_threads = 1)]
async fn check_topology_mesh() {
let nodes = spawn_nodes(N, Topology::Mesh).await;
for node in &nodes {
assert_eq!(node.peers().await.unwrap().len(), N - 1);
}
}
#[tokio::test(max_threads = 1)]
async fn check_topology_star() {
let nodes = spawn_nodes(N, Topology::Star).await;
for (i, node) in nodes.iter().enumerate() {
if i == 0 {
assert_eq!(node.peers().await.unwrap().len(), N - 1);
} else {
assert_eq!(node.peers().await.unwrap().len(), 1);
}
}
}
}
|
use procon_reader::ProconReader;
use std::cmp::Reverse;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let s: Vec<u64> = rd.get_vec(n);
let t: Vec<u64> = rd.get_vec(n);
use std::collections::BinaryHeap;
let mut heap = BinaryHeap::new();
for i in 0..n {
heap.push(Reverse((t[i], i)));
}
let mut ans = vec![0; n];
while let Some(Reverse((t, i))) = heap.pop() {
if ans[i] >= 1 {
continue;
}
ans[i] = t;
heap.push(Reverse((t + s[i], (i + 1) % n)));
}
for ans in ans {
assert!(ans >= 1);
println!("{}", ans);
}
}
|
use super::VarResult;
use crate::ast::stat_expr_types::VarIndex;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::err_msgs::*;
use crate::helper::str_replace;
use crate::helper::{
ensure_srcs, ge1_param_i64, move_element, pine_ref_to_bool, pine_ref_to_f64,
pine_ref_to_f64_series, pine_ref_to_i64, pine_ref_to_i64_series, require_param,
};
use crate::runtime::context::{downcast_ctx, Ctx};
use crate::runtime::InputSrc;
use crate::types::{
downcast_pf_ref, int2float, Arithmetic, Callable, CallableFactory, Evaluate, EvaluateVal,
Float, Int, ParamCollectCall, PineRef, RefData, RuntimeErr, Series, SeriesCall, NA,
};
use std::rc::Rc;
pub fn swma_func<'a>(
source: RefData<Series<Float>>,
volume: RefData<Series<Int>>,
length: i64,
) -> Result<Float, RuntimeErr> {
let mut sum1 = 0f64;
let mut sum2 = 0f64;
for i in 0..length as usize {
match (source.index_value(i)?, volume.index_value(i)?) {
(Some(val), Some(vol)) => {
sum1 += val * vol as f64 / length as f64;
sum2 += vol as f64 / length as f64;
}
_ => {
return Ok(Float::from(None));
}
}
}
Ok(Some(sum1 / sum2))
}
#[derive(Debug, Clone, PartialEq)]
struct EmaVal {
volume_index: VarIndex,
}
impl EmaVal {
pub fn new() -> EmaVal {
EmaVal {
volume_index: VarIndex::new(0, 0),
}
}
}
impl<'a> SeriesCall<'a> for EmaVal {
fn step(
&mut self,
_ctx: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
_func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
ensure_srcs(_ctx, vec!["volume"], |indexs| {
self.volume_index = indexs[0];
});
move_tuplet!((source, length) = param);
let source = require_param("source", pine_ref_to_f64_series(source))?;
let length = ge1_param_i64("length", pine_ref_to_i64(length))?;
let volume = pine_ref_to_i64_series(_ctx.get_var(self.volume_index).clone()).unwrap();
let result = swma_func(source, volume, length)?;
Ok(PineRef::new(Series::from(result)))
}
fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> {
Box::new(self.clone())
}
}
pub fn declare_var<'a>() -> VarResult<'a> {
let value = PineRef::new(CallableFactory::new(|| {
Callable::new(
None,
Some(Box::new(ParamCollectCall::new_with_caller(Box::new(
EmaVal::new(),
)))),
)
}));
let func_type = FunctionTypes(vec![FunctionType::new((
vec![
("source", SyntaxType::float_series()),
("length", SyntaxType::int()),
],
SyntaxType::float_series(),
))]);
let syntax_type = SyntaxType::Function(Rc::new(func_type));
VarResult::new(value, syntax_type, "vwma")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::syntax_type::SyntaxType;
use crate::runtime::VarOperate;
use crate::runtime::{AnySeries, NoneCallback};
use crate::types::Series;
use crate::{LibInfo, PineParser, PineRunner};
// use crate::libs::{floor, exp, };
#[test]
fn vwma_test() {
let lib_info = LibInfo::new(
vec![declare_var()],
vec![
("close", SyntaxType::float_series()),
("volume", SyntaxType::int_series()),
],
);
let src = "m1 = vwma(close, 2)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![
(
"close",
AnySeries::from_float_vec(vec![
Some(6f64),
Some(12f64),
Some(12f64),
Some(6f64),
]),
),
(
"volume",
AnySeries::from_int_vec(vec![
Some(1i64),
Some(1i64),
Some(1i64),
Some(1i64),
]),
),
],
None,
)
.unwrap();
assert_eq!(
runner.get_context().move_var(VarIndex::new(0, 0)),
Some(PineRef::new(Series::from_vec(vec![
None,
Some(9f64),
Some(12f64),
Some(9f64)
])))
);
}
}
|
use super::{Register, State, Transition, Value};
use itertools::Itertools;
use pathfinding::directed::astar::astar;
use std::cmp::min;
// TODO: Caches results using normalized version of the problem.
impl State {
pub(crate) fn transition_to(&self, goal: &Self) -> Vec<Transition> {
assert!(self.reachable(goal));
// Find the optimal transition using pathfinder's A*
let mut nodes_explored = 0;
let (path, cost) = astar(
self,
|n| {
// println!(
// "Exploring from (node {}) (min_dist {}):\n{}",
// nodes_explored,
// n.min_distance(goal),
// n
// );
n.useful_transitions(goal)
.into_iter()
.filter_map(|t| {
nodes_explored += 1;
// TODO: lazily compute next state?
let mut new_state = n.clone();
t.apply(&mut new_state);
if new_state.is_valid() && new_state.reachable(goal) {
Some((new_state, t.cost()))
} else {
None
}
})
// TODO: Don't allocate
.collect::<Vec<_>>()
},
|n| n.min_distance(goal),
|n| n.satisfies(goal),
)
.expect("Could not find valid transition path");
println!("Nodes explored: {}", nodes_explored);
println!("Cost: {}", cost);
// Pathfinder gives a list of nodes visited, not the path taken.
// So take all the pairs of nodes and find the best transition
// between them.
let mut result = Vec::default();
for (from, to) in path.iter().tuple_windows() {
let mut cost = usize::max_value();
let mut best = None;
for transition in from.useful_transitions(goal) {
let mut dest = from.clone();
transition.apply(&mut dest);
if dest == *to && transition.cost() < cost {
cost = transition.cost();
best = Some(transition);
}
}
result.push(best.expect("Could not reproduce path"));
}
// Test admisability criterion along path
// #[cfg(debug)]
// test::test_admisability(self, goal, &result);
result
}
fn register_set_cost(&self, dest: Option<Register>, value: Value) -> usize {
use Transition::*;
use Value::*;
// No goal
if !value.is_specified() {
return 0;
}
// TODO: Copy does not take swaps into account
// Ignore References
// TODO: Copy for references if not in place
if let Reference { .. } = value {
// Assume the reference is available somewhere. If wo do Alloc,
// we need to subtract this cost.
if let Some(dest) = dest {
if let Reference { .. } = self.get_register(dest) {
// Assume it is the right one and already in place.
return 0;
} else {
return min(
Copy {
// TODO: It would be more accurate to use `dest` here,
// but that would be hard to undo when this thing gets
// replaced by an Alloc.
dest: Register(0),
source: Register(0),
}
.cost(),
Swap {
dest: Register(0),
source: Register(0),
}
.cost(),
);
}
}
return min(
Copy {
dest: Register(0),
source: Register(0),
}
.cost(),
Swap {
dest: Register(0),
source: Register(0),
}
.cost(),
);
}
// Compute best among a few strategies
let mut cost = usize::max_value();
// Try copy from registers
for source in (0..=15).map(Register) {
if value == self.get_register(source) {
cost = min(cost, match dest {
None => 0,
Some(dest) if dest == source => 0,
Some(dest) => min(Copy { dest, source }.cost(), Swap { dest, source }.cost()),
});
if cost == 0 {
return cost;
}
}
}
let dest = dest.unwrap_or(Register(0));
// Try literals
if let Literal(value) = value {
cost = min(cost, Set { dest, value }.cost());
}
// Try copy from allocations
let read_cost = Read {
dest,
source: Register(0),
offset: 0,
}
.cost();
if cost <= read_cost {
return cost;
}
for alloc in &self.allocations {
for alloc_val in alloc {
if *alloc_val == value {
return read_cost;
}
}
}
assert_ne!(cost, usize::max_value());
cost
}
pub(crate) fn min_distance(&self, goal: &Self) -> usize {
use Transition::*;
use Value::*;
// Compute minimum distance by taking the sum of the minimum cost to set
// each goal register from the current state.
// Note: this is not a perfect minimum: for example two `Set`
// transitions with identical `value` can be more expensive than
// a `Set` followed by `Copy`.
// Early exit with max distance if goal is unreachable.
if !self.reachable(goal) {
return usize::max_value();
}
let mut cost = 0;
// let mut constructed: Set<Value> = Set::default();
// TODO: Values only have to be Set or Read once, after that they can be Copy'd
// A Copy is not always better though.
// let get_cost = |dest, val| {
// let construct_cost = ;
// if constructed.contains(val) {
// if let Some(dest) = dest {
// min(construct_cost, Copy { dest, source }.cost())
// } else {
// 0
// }
// } else {
// self.register_set_cost(dest, *goal);
// }
// };
// Registers
for (i, (ours, goal)) in self.registers.iter().zip(goal.registers.iter()).enumerate() {
cost += self.register_set_cost(Some(Register(i as u8)), *goal);
}
// TODO: Flags
// Allocations
let write_cost = Write {
dest: Register(0),
offset: 0,
source: Register(0),
}
.cost();
let mut reused = 0;
for goal in &goal.allocations {
// Compute the cost of constructing it from scratch
let mut alloc_cost = Alloc {
dest: Register(0),
size: goal.len(),
}
.cost();
// Since Alloc is in place, we can undo one Copy
alloc_cost -= min(
Copy {
dest: Register(0),
source: Register(0),
}
.cost(),
Swap {
dest: Register(0),
source: Register(0),
}
.cost(),
);
for goal in goal.iter() {
if goal.is_specified() {
alloc_cost += write_cost + self.register_set_cost(None, *goal);
}
}
// See if we can change an existing allocation
let mut reuse_cost = usize::max_value();
for ours in &self.allocations {
if ours.len() != goal.len() {
continue;
}
let mut change_cost = 0;
for (ours, goal) in ours.iter().zip(goal.iter()) {
if !goal.is_specified() || ours == goal {
// Good as is
continue;
}
change_cost += write_cost + self.register_set_cost(None, *goal);
}
reuse_cost = min(reuse_cost, change_cost);
}
// Add best option to total cost
if reuse_cost <= alloc_cost {
cost += reuse_cost;
reused += 1;
} else {
cost += alloc_cost;
}
}
cost += (self.allocations.len() - reused) * Drop { dest: Register(0) }.cost();
cost
}
fn useful_transitions(&self, goal: &Self) -> Vec<Transition> {
let mut result = Vec::default();
// TODO: Filter out invalid transitions (which would lose references)
// TODO: No need to enumerate all cases of writing to an Unspecified, one
// should be sufficient.
// Generate Set transitions for each goal literal and register.
for value in goal.literals().into_iter() {
for dest in (0..=15).map(Register) {
let dest_val = self.get_register(dest);
if dest_val == goal.get_register(dest) {
// Don't overwrite already correct values
continue;
}
result.push(Transition::Set { dest, value });
}
}
// Copy and swap registers around
for source in (0..=15).map(Register) {
// No point in copying from unspecified regs
if !self.get_register(source).is_specified() {
continue;
}
// Generate moves and swaps between registers
for dest in (0..=15).map(Register) {
let dest_val = self.get_register(dest);
if dest_val == goal.get_register(dest) {
// Don't overwrite already correct values
continue;
}
// Copy to any reg
if source != dest {
result.push(Transition::Copy { dest, source });
}
// Swap two regs
if source < dest && dest_val.is_specified() {
result.push(Transition::Swap { dest, source });
}
}
// Generate reads and writes
if let Value::Reference {
index,
offset: base_offset,
} = self.get_register(source)
{
let values = &self.allocations[index];
for offset in (0..values.len()).map(|n| (n as isize) - base_offset) {
// TODO: Check if goal is specified?
for dest in (0..=15).map(Register) {
let dest_val = self.get_register(dest);
// Read if there is something there
if dest_val != goal.get_register(dest)
&& self.get_reference(source, offset).unwrap().is_specified()
{
result.push(Transition::Read {
dest,
source,
offset,
});
}
// Writes have source and dest flipped
if dest_val.is_specified() {
// TODO: Don't overwrite already correct values
result.push(Transition::Write {
dest: source,
offset,
source: dest,
});
}
}
}
}
}
// Allocate for goal sizes
for size in goal.alloc_sizes().into_iter() {
for dest in (0..=15).map(Register) {
result.push(Transition::Alloc { dest, size });
}
}
// Drop an existing reference
for dest in (0..=15).map(Register) {
if let Value::Reference { .. } = self.get_register(dest) {
result.push(Transition::Drop { dest });
}
}
result
}
}
#[cfg(test)]
mod test {
use super::{super::Allocation, *};
use proptest::strategy::Strategy;
#[test]
fn test_min_distance() {
use Transition::*;
use Value::*;
let mut initial = State::default();
initial.registers[0] = Symbol(5);
let mut goal = State::default();
goal.registers[0] = Literal(3);
goal.registers[1] = Reference {
index: 0,
offset: 0,
};
goal.allocations.push(Allocation(vec![Symbol(5)]));
let optimal_path = vec![
Alloc {
dest: Register(1),
size: 1,
},
Write {
dest: Register(1),
offset: 0,
source: Register(0),
},
Set {
dest: Register(0),
value: 3,
},
];
let optimal_cost = optimal_path.iter().map(|t| t.cost()).sum::<usize>();
test_admisability(&initial, &goal, &optimal_path);
let path = initial.transition_to(&goal);
let path_cost = optimal_path.iter().map(|t| t.cost()).sum::<usize>();
assert_eq!(optimal_cost, path_cost);
}
/// Provided a known best bath, test heuristic admisability.
fn test_admisability(initial: &State, goal: &State, path: &[Transition]) {
println!("Initial:\n{}", initial);
println!("Goal:\n{}", goal);
// Reconstruct intermediate states
let mut states = vec![initial.clone()];
for ts in path {
let mut next = states.last().unwrap().clone();
ts.apply(&mut next);
states.push(next);
println!(" {:7}: {:?}", ts.cost(), ts);
}
assert!(states.last().unwrap().satisfies(&goal));
// Check admisability: min_distance is always <= the real cost
// <https://en.wikipedia.org/wiki/Admissible_heuristic>
let mut overall_admisable = true;
for start in (0..states.len()) {
for end in (start..states.len()) {
let heuristic = states[start].min_distance(&states[end]);
let distance = path
.iter()
.skip(start)
.take(end - start)
.map(|t| t.cost())
.sum::<usize>();
let admisable = heuristic <= distance;
println!(
"{} - {}: {:7} {:7} {:5}",
start, end, heuristic, distance, admisable
);
overall_admisable &= admisable;
}
// Goal as target
let heuristic = states[start].min_distance(&goal);
let distance = path.iter().skip(start).map(|t| t.cost()).sum::<usize>();
let admisable = heuristic <= distance;
println!(
"{} - G: {:7} {:7} {:5}",
start, heuristic, distance, admisable
);
overall_admisable &= admisable;
}
assert!(overall_admisable);
}
// Check consistency
// <https://en.wikipedia.org/wiki/Consistent_heuristic>
// Take any pair of states, iterate all neighbouring states.
fn test_consistency(initial: &State, goal: &State) {
println!("Initial:\n{}", initial);
println!("Goal:\n{}", goal);
let mindist = initial.min_distance(goal);
let mut overal_consistent = true;
println!("Heuristic distance: {}", mindist);
for ts in initial.useful_transitions(goal) {
let mut neighbor = initial.clone();
ts.apply(&mut neighbor);
let cost = ts.cost();
let dist = neighbor.min_distance(goal);
let consistent = (cost + dist) >= mindist;
println!(" {:5} {:7} {:7}: {:?}", consistent, ts.cost(), dist, ts);
overal_consistent &= consistent;
}
assert!(overal_consistent);
}
#[test]
fn test_basic() {
use Transition::*;
use Value::*;
let mut initial = State::default();
initial.registers[0] = Symbol(1);
initial.registers[1] = Symbol(2);
initial.registers[2] = Symbol(3);
let mut goal = State::default();
goal.registers[0] = Reference {
index: 0,
offset: 0,
};
goal.registers[1] = Symbol(3);
goal.registers[2] = Literal(3);
goal.allocations
.push(Allocation(vec![Symbol(1), Symbol(2)]));
let path = initial.transition_to(&goal);
test_admisability(&initial, &goal, &path);
test_consistency(&initial, &goal);
}
#[test]
fn test_basic2() {
use Transition::*;
use Value::*;
let mut initial = State::default();
initial.registers[0] = Symbol(0);
initial.registers[1] = Symbol(1);
initial.registers[2] = Symbol(2);
initial.registers[3] = Symbol(3);
initial.registers[4] = Symbol(4);
let mut goal = State::default();
goal.registers[0] = Literal(0x0000000000100058);
goal.registers[1] = Symbol(1);
goal.registers[2] = Symbol(2);
goal.registers[3] = Reference {
index: 0,
offset: 0,
};
goal.allocations.push(Allocation(vec![
Literal(0x0000000000100058),
Symbol(3),
Symbol(4),
]));
let path = initial.transition_to(&goal);
test_admisability(&initial, &goal, &path);
test_consistency(&initial, &goal);
}
}
|
use crate::cache::ResponseCache;
use crate::error::Result;
use crate::proto::{Proto, Request};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::rc::Rc;
pub(super) struct Lighting {
ns: String,
proto: Rc<Proto>,
cache: Rc<ResponseCache>,
}
impl Lighting {
pub(super) fn new(ns: &str, proto: Rc<Proto>, cache: Rc<ResponseCache>) -> Lighting {
Lighting {
ns: String::from(ns),
cache,
proto,
}
}
pub(super) fn get_light_state(&self) -> Result<LightState> {
let request = Request::new(&self.ns, "get_light_state", None);
let response = if let Some(cache) = self.cache.as_ref() {
cache
.borrow_mut()
.try_get_or_insert_with(request, |r| self.proto.send_request(r))?
} else {
self.proto.send_request(&request)?
};
log::trace!("({}) {:?}", self.ns, response);
Ok(serde_json::from_value(response).unwrap_or_else(|err| {
panic!(
"invalid response from host with address {}: {}",
self.proto.host(),
err
)
}))
}
pub(super) fn set_light_state(&self, arg: Option<Value>) -> Result<()> {
if let Some(cache) = self.cache.as_ref() {
cache.borrow_mut().retain(|k, _| k.target != self.ns)
}
let response = self
.proto
.send_request(&Request::new(&self.ns, "transition_light_state", arg))
.map(|response| {
serde_json::from_value::<LightState>(response).unwrap_or_else(|err| {
panic!(
"invalid response from host with address {}: {}",
self.proto.host(),
err
)
})
})?;
log::trace!("({}) {:?}", self.ns, response);
Ok(())
}
}
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct LightState {
on_off: u64,
#[serde(flatten)]
hsv: Option<HSV>,
dft_on_state: Option<HSV>,
}
impl LightState {
pub(super) fn is_on(&self) -> bool {
self.on_off == 1
}
pub(super) fn hsv(&self) -> HSV {
if self.on_off == 1 {
self.hsv.as_ref().unwrap().clone()
} else {
self.dft_on_state.as_ref().unwrap().clone()
}
}
}
/// The HSV (Hue, Saturation, Value) state of the bulb.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HSV {
hue: u32,
saturation: u32,
brightness: u32,
color_temp: u32,
mode: Option<String>,
}
impl HSV {
/// Returns the `hue` (color portion) of the HSV model, expressed
/// as a number from 0 to 360 degrees.
pub fn hue(&self) -> u32 {
self.hue
}
/// Returns the `saturation` (amount of gray in particular color)
/// of the HSV model, expressed as a number from 0 to 100 percent.
pub fn saturation(&self) -> u32 {
self.saturation
}
/// Returns the `value` or `brightness` (intensity of the color)
/// of the HSV model, expressed as a number from 0 to 100 percent.
pub fn value(&self) -> u32 {
self.brightness
}
pub fn color_temp(&self) -> u32 {
self.color_temp
}
}
|
#![feature(extern_prelude)]
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde;
extern crate simple_server;
pub mod apilib {
pub mod transfer;
pub mod request;
pub mod response;
pub mod target;
#[cfg(test)]
mod tests;
}
|
use tui::layout::{Direction, Group, Rect, Size};
use tui::style::*;
use tui::widgets::*;
use components::App;
use models::{AppState, Mode};
use widgets::{self, ChatHistory};
use TerminalBackend;
pub fn render(app: &App, terminal: &mut TerminalBackend, size: &Rect) {
Group::default()
.direction(Direction::Horizontal)
.margin(0)
.sizes(&[Size::Percent(20), Size::Percent(80)])
.render(terminal, size, |terminal, chunks| {
render_sidebar(app.state(), terminal, &chunks[0]);
render_main(app.state(), terminal, &chunks[1]);
});
if app.state().current_mode() == &Mode::SelectChannel {
let mut selector_rect = size.clone();
// Pick the largest out of 50% and X cells in both directions, but also cap it to display
// size if it's smaller than the intended minimum.
selector_rect.width = (size.width / 2).max(40).min(size.width);
selector_rect.height = (size.height / 2).max(20).min(size.height);
// Center selector in the middle of parent size
selector_rect.x = (size.x + size.width / 2) - (selector_rect.width / 2);
selector_rect.y = (size.y + size.height / 2) - (selector_rect.height / 2);
render_channel_selector(&app, terminal, &selector_rect);
}
}
fn render_sidebar(state: &AppState, terminal: &mut TerminalBackend, rect: &Rect) {
let mut block = Block::default().borders(Borders::RIGHT);
block.render(terminal, rect);
widgets::ChannelList::new(&state.channels, state.selected_channel_id())
.render(terminal, &block.inner(rect));
}
fn render_main(state: &AppState, terminal: &mut TerminalBackend, rect: &Rect) {
Group::default()
.direction(Direction::Vertical)
.sizes(&[
Size::Fixed(1),
Size::Min(10),
Size::Fixed(1),
Size::Fixed(1),
])
.render(terminal, rect, |terminal, chunks| {
render_breadcrumbs(state, terminal, &chunks[0]);
render_history(state, terminal, &chunks[1]);
render_statusbar(state, terminal, &chunks[2]);
render_input(state, terminal, &chunks[3]);
});
}
fn render_breadcrumbs(state: &AppState, terminal: &mut TerminalBackend, rect: &Rect) {
match state.selected_channel() {
Some(channel) => {
let topic = match channel.topic_text() {
Some(text) => format!("{{fg=white {}}}", text),
None => String::from("{fg=gray No channel topic}"),
};
Paragraph::default()
.text(&format!(
"{{mod=bold {team}}} > {{mod=bold #{channel}}} [{topic}]",
team = state.team_name,
channel = channel.name(),
topic = topic
))
.style(Style::default().bg(Color::Gray).fg(Color::White))
.render(terminal, rect);
}
None => {
Paragraph::default()
.text(&format!("{} > (No channel selected)", state.team_name))
.style(Style::default().bg(Color::Gray).fg(Color::White))
.render(terminal, rect);
}
}
}
fn render_history(state: &AppState, terminal: &mut TerminalBackend, rect: &Rect) {
if rect.width < 2 {
return;
}
// Leave one width for scrollbar
let canvas = state.rendered_chat_canvas(rect.width - 1, rect.height);
ChatHistory::with_canvas(&canvas)
.scroll(state.current_history_scroll())
.render(terminal, rect);
}
fn render_statusbar(state: &AppState, terminal: &mut TerminalBackend, rect: &Rect) {
let (mode, mode_color) = match state.current_mode {
Mode::History => ("HISTORY", "bg=cyan;fg=black"),
Mode::SelectChannel => ("CHANNELS", "bg=black;fg=white"),
};
Paragraph::default()
.text(&format!(
"{{{mode_color} {mode}}} - [{offset}/{height}]",
mode = mode,
mode_color = mode_color,
offset = state.history_scroll,
height = state.max_history_scroll(),
))
.style(Style::default().bg(Color::Gray).fg(Color::White))
.render(terminal, rect);
}
fn render_input(_state: &AppState, terminal: &mut TerminalBackend, rect: &Rect) {
Paragraph::default()
.text("{fg=dark_gray Enter a reply...}")
.style(Style::default().bg(Color::Black).fg(Color::White))
.render(terminal, rect);
}
fn render_channel_selector(app: &App, terminal: &mut TerminalBackend, rect: &Rect) {
if rect.width <= 5 || rect.height <= 5 {
return;
}
let black_on_gray = Style::default().bg(Color::Gray).fg(Color::Black);
let white_on_black = Style::default().bg(Color::Black).fg(Color::White);
Block::default()
.title("Select channel")
.borders(Borders::ALL)
.style(black_on_gray)
.border_style(black_on_gray)
.title_style(black_on_gray)
.render(terminal, rect);
let input_rect = Rect::new(rect.left() + 1, rect.top() + 1, rect.width - 2, 1);
widgets::LineEdit::default()
.style(white_on_black)
.text(app.channel_selector.text())
.cursor_pos(app.channel_selector.cursor_pos())
.render(terminal, &input_rect);
let list_rect = Rect::new(
rect.left() + 1,
rect.top() + 3,
rect.width - 2,
rect.height - 4,
);
// SelectableList does not render background style.
// https://github.com/fdehau/tui-rs/issues/42
//
// Pad all items with spaces to achieve the same effect.
let matches: Vec<String> = app
.channel_selector
.top_matches(&app.state().channels, list_rect.height as usize)
.into_iter()
.map(|m| format!("#{:<1$}", m.channel.name(), list_rect.width as usize))
.collect();
SelectableList::default()
.block(
Block::default()
.borders(Borders::TOP)
.border_style(black_on_gray)
.style(black_on_gray),
)
.style(black_on_gray)
.highlight_style(white_on_black)
.items(&matches)
.select(app.channel_selector.selected_index(matches.len()))
.render(terminal, &list_rect);
}
|
use std::cmp::{max, min};
use regex::Regex;
fn main() {
let input:Result<_,_> = include_str!("input").lines().map(str::parse).collect();
let input: Vec<Action> = input.unwrap();
let part_one_input = input.iter().filter(|action| {
action.region.is_inside(Cuboid {
x: [-50, 50],
y: [-50, 50],
z: [-50, 50]
})
}).map(|x| *x).collect();
println!("Part one: {}", count_cubes(part_one_input));
println!("Part two: {}", count_cubes(input));
}
fn count_cubes(mut instructions: Vec<Action>) -> usize {
instructions.reverse();
instructions.iter().enumerate().filter(|(_, x)| x.on).map(|(i, action )| {
let regions_to_add = instructions[0..i].iter().fold(vec![action.region], |current_regions_to_add, region_to_not_add|
current_regions_to_add.into_iter().flat_map(|reg| reg.subtract(region_to_not_add.region)).collect()
);
regions_to_add.into_iter().map(|a| a.get_count()).sum::<usize>()
}).sum()
}
#[derive(Debug, Clone, Copy)]
struct Action {
on: bool,
region: Cuboid
}
#[derive(Debug, Clone, Copy)]
struct Cuboid {
x: [i128; 2],
y: [i128; 2],
z: [i128; 2]
}
impl Cuboid {
fn get_count(&self) -> usize {
((1 + self.x[1] - self.x[0])*(1 + self.y[1] - self.y[0])*(1 + self.z[1] - self.z[0])).try_into().unwrap()
}
fn is_valid(&self) -> bool {
self.x[0] <= self.x[1] && self.y[0] <= self.y[1] && self.z[0] <= self.z[1]
}
fn is_inside(&self, other: Cuboid) -> bool {
self.x[0] >= other.x[0] && self.x[1] <= other.x[1] &&
self.y[0] >= other.y[0] && self.y[1] <= other.y[1] &&
self.z[0] >= other.z[0] && self.z[1] <= other.z[1]
}
// ignores regions of other outside of self
fn subtract(&self, other: Cuboid) -> Vec<Cuboid>{
if other.x[0] > self.x[1] || other.x[1] < self.x[0] ||
other.y[0] > self.y[1] || other.y[1] < self.y[0] ||
other.z[0] > self.z[1] || other.z[1] < self.z[0] {
return vec!(*self);
};
[
Cuboid {
x: [self.x[0], other.x[0] - 1],
y: [self.y[0], self.y[1]],
z: [self.z[0], self.z[1]]
},
Cuboid {
x: [other.x[1] + 1, self.x[1]],
y: [self.y[0], self.y[1]],
z: [self.z[0], self.z[1]]
},
Cuboid {
x: [max(self.x[0], other.x[0]), min(self.x[1], other.x[1])],
y: [self.y[0], other.y[0] - 1],
z: [self.z[0], self.z[1]]
},
Cuboid {
x: [max(self.x[0], other.x[0]), min(self.x[1], other.x[1])],
y: [other.y[1] + 1, self.y[1]],
z: [self.z[0], self.z[1]]
},
Cuboid {
x: [max(self.x[0], other.x[0]), min(self.x[1], other.x[1])],
y: [max(self.y[0], other.y[0]), min(self.y[1], other.y[1])],
z: [self.z[0], other.z[0] - 1],
},
Cuboid {
x: [max(self.x[0], other.x[0]), min(self.x[1], other.x[1])],
y: [max(self.y[0], other.y[0]), min(self.y[1], other.y[1])],
z: [other.z[1] + 1, self.z[1]]
}
].into_iter().filter(|x| x.is_valid()).collect()
}
}
impl std::str::FromStr for Action {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let re = Regex::new(r"(on|off) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)").unwrap();
let caps = re.captures(s).unwrap();
let xs = [caps.get(2).unwrap().as_str().parse().unwrap(), caps.get(3).unwrap().as_str().parse().unwrap()];
let ys = [caps.get(4).unwrap().as_str().parse().unwrap(), caps.get(5).unwrap().as_str().parse().unwrap()];
let zs = [caps.get(6).unwrap().as_str().parse().unwrap(), caps.get(7).unwrap().as_str().parse().unwrap()];
Ok(Self {
on: caps.get(1).unwrap().as_str() == "on",
region: Cuboid {
x: [min(xs[0], xs[1]), max(xs[0], xs[1])],
y: [min(ys[0], ys[1]), max(ys[0], ys[1])],
z: [min(zs[0], zs[1]), max(zs[0], zs[1])]
}
})
}
}
|
struct ColumnIter<I> where I: Iterator {
iterators: Vec<I>
}
impl<I, T> Iterator for ColumnIter<I> where I: Iterator<Item=T> {
type Item = Vec<T>;
fn next(&mut self) -> Option<Self::Item> {
self.iterators.iter_mut().map(|iter| iter.next()).collect()
}
}
struct Image {
layers : Vec<Vec<u32>>,
width : usize
}
impl std::fmt::Display for Image {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for row in self.collapse().chunks(self.width) {
for pixel in row {
if *pixel == 1 {
write!(f, "☐")?;
} else {
write!(f, " ")?;
}
}
writeln!(f, "")?;
}
Ok(())
}
}
impl Image {
fn new(input: &'static str, width: usize, height: usize) -> Image {
Image {
layers : input.chars()
.map(|c| c.to_digit(10).unwrap())
.collect::<Vec<_>>()
.chunks(width * height)
.map(|c| c.to_vec())
.collect(),
width
}
}
fn collapse(&self) -> Vec<u32> {
let iterators : Vec<_> = (&self.layers).into_iter().map(|v| v.into_iter()).collect();
let column_iter = ColumnIter { iterators };
column_iter.map(|pixels| {
//find first non-transparent pixel
**(pixels.iter().filter(|p| ***p != 2).nth(0).unwrap())
}).collect()
}
fn get_layers(&self) -> &Vec<Vec<u32>> {
&self.layers
}
fn get_layer(&self, index: usize) -> &Vec<u32> {
assert!(index < self.layers.len());
&self.layers[index]
}
}
fn calc_part_1(image: &Image) -> u32 {
let (idx, _) = image.get_layers().iter().enumerate().map(|(i, layer)| {
(i, layer.iter().filter(|p| **p == 0).count())
}).min_by_key(|x| x.1).unwrap();
let fewest_0_layer = image.get_layer(idx);
fewest_0_layer.iter().filter(|p| **p == 1).count() as u32 *
fewest_0_layer.iter().filter(|p| **p == 2).count() as u32
}
fn main() {
let image = Image::new(include_str!("../input/day_8.txt"), 25, 6);
println!("Part 1 => {}", calc_part_1(&image));
println!("Part 2 =>\n{}", image);
}
#[test]
fn build_layers() {
let img = Image::new("123456789012", 3, 2);
assert_eq!(*img.get_layers(), vec!(vec!(1,2,3,4,5,6), vec!(7,8,9,0,1,2)));
}
#[test]
fn part_1_complete() {
let image = Image::new(include_str!("../input/day_8.txt"), 25, 6);
assert_eq!(calc_part_1(&image), 1920);
}
#[test]
fn part_2() {
let image = Image::new("0222112222120000", 2, 2);
assert_eq!(image.collapse(), vec!(0,1,1,0));
} |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
pub fn HcnCloseEndpoint(endpoint: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
pub fn HcnCloseGuestNetworkService(guestnetworkservice: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
pub fn HcnCloseLoadBalancer(loadbalancer: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
pub fn HcnCloseNamespace(namespace: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
pub fn HcnCloseNetwork(network: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnCreateEndpoint(network: *const ::core::ffi::c_void, id: *const ::windows_sys::core::GUID, settings: super::super::Foundation::PWSTR, endpoint: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnCreateGuestNetworkService(id: *const ::windows_sys::core::GUID, settings: super::super::Foundation::PWSTR, guestnetworkservice: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnCreateLoadBalancer(id: *const ::windows_sys::core::GUID, settings: super::super::Foundation::PWSTR, loadbalancer: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnCreateNamespace(id: *const ::windows_sys::core::GUID, settings: super::super::Foundation::PWSTR, namespace: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnCreateNetwork(id: *const ::windows_sys::core::GUID, settings: super::super::Foundation::PWSTR, network: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnDeleteEndpoint(id: *const ::windows_sys::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnDeleteGuestNetworkService(id: *const ::windows_sys::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnDeleteLoadBalancer(id: *const ::windows_sys::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnDeleteNamespace(id: *const ::windows_sys::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnDeleteNetwork(id: *const ::windows_sys::core::GUID, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnEnumerateEndpoints(query: super::super::Foundation::PWSTR, endpoints: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
pub fn HcnEnumerateGuestNetworkPortReservations(returncount: *mut u32, portentries: *mut *mut HCN_PORT_RANGE_ENTRY) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnEnumerateLoadBalancers(query: super::super::Foundation::PWSTR, loadbalancer: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnEnumerateNamespaces(query: super::super::Foundation::PWSTR, namespaces: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnEnumerateNetworks(query: super::super::Foundation::PWSTR, networks: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
pub fn HcnFreeGuestNetworkPortReservations(portentries: *mut HCN_PORT_RANGE_ENTRY);
#[cfg(feature = "Win32_Foundation")]
pub fn HcnModifyEndpoint(endpoint: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnModifyGuestNetworkService(guestnetworkservice: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnModifyLoadBalancer(loadbalancer: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnModifyNamespace(namespace: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnModifyNetwork(network: *const ::core::ffi::c_void, settings: super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnOpenEndpoint(id: *const ::windows_sys::core::GUID, endpoint: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnOpenLoadBalancer(id: *const ::windows_sys::core::GUID, loadbalancer: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnOpenNamespace(id: *const ::windows_sys::core::GUID, namespace: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnOpenNetwork(id: *const ::windows_sys::core::GUID, network: *mut *mut ::core::ffi::c_void, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnQueryEndpointProperties(endpoint: *const ::core::ffi::c_void, query: super::super::Foundation::PWSTR, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnQueryLoadBalancerProperties(loadbalancer: *const ::core::ffi::c_void, query: super::super::Foundation::PWSTR, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnQueryNamespaceProperties(namespace: *const ::core::ffi::c_void, query: super::super::Foundation::PWSTR, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnQueryNetworkProperties(network: *const ::core::ffi::c_void, query: super::super::Foundation::PWSTR, properties: *mut super::super::Foundation::PWSTR, errorrecord: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnRegisterGuestNetworkServiceCallback(guestnetworkservice: *const ::core::ffi::c_void, callback: HCN_NOTIFICATION_CALLBACK, context: *const ::core::ffi::c_void, callbackhandle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnRegisterServiceCallback(callback: HCN_NOTIFICATION_CALLBACK, context: *const ::core::ffi::c_void, callbackhandle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnReleaseGuestNetworkServicePortReservationHandle(portreservationhandle: super::super::Foundation::HANDLE) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnReserveGuestNetworkServicePort(guestnetworkservice: *const ::core::ffi::c_void, protocol: HCN_PORT_PROTOCOL, access: HCN_PORT_ACCESS, port: u16, portreservationhandle: *mut super::super::Foundation::HANDLE) -> ::windows_sys::core::HRESULT;
#[cfg(feature = "Win32_Foundation")]
pub fn HcnReserveGuestNetworkServicePortRange(guestnetworkservice: *const ::core::ffi::c_void, portcount: u16, portrangereservation: *mut HCN_PORT_RANGE_RESERVATION, portreservationhandle: *mut super::super::Foundation::HANDLE) -> ::windows_sys::core::HRESULT;
pub fn HcnUnregisterGuestNetworkServiceCallback(callbackhandle: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
pub fn HcnUnregisterServiceCallback(callbackhandle: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
}
pub type HCN_NOTIFICATIONS = i32;
pub const HcnNotificationInvalid: HCN_NOTIFICATIONS = 0i32;
pub const HcnNotificationNetworkPreCreate: HCN_NOTIFICATIONS = 1i32;
pub const HcnNotificationNetworkCreate: HCN_NOTIFICATIONS = 2i32;
pub const HcnNotificationNetworkPreDelete: HCN_NOTIFICATIONS = 3i32;
pub const HcnNotificationNetworkDelete: HCN_NOTIFICATIONS = 4i32;
pub const HcnNotificationNamespaceCreate: HCN_NOTIFICATIONS = 5i32;
pub const HcnNotificationNamespaceDelete: HCN_NOTIFICATIONS = 6i32;
pub const HcnNotificationGuestNetworkServiceCreate: HCN_NOTIFICATIONS = 7i32;
pub const HcnNotificationGuestNetworkServiceDelete: HCN_NOTIFICATIONS = 8i32;
pub const HcnNotificationNetworkEndpointAttached: HCN_NOTIFICATIONS = 9i32;
pub const HcnNotificationNetworkEndpointDetached: HCN_NOTIFICATIONS = 16i32;
pub const HcnNotificationGuestNetworkServiceStateChanged: HCN_NOTIFICATIONS = 17i32;
pub const HcnNotificationGuestNetworkServiceInterfaceStateChanged: HCN_NOTIFICATIONS = 18i32;
pub const HcnNotificationServiceDisconnect: HCN_NOTIFICATIONS = 16777216i32;
pub const HcnNotificationFlagsReserved: HCN_NOTIFICATIONS = -268435456i32;
#[cfg(feature = "Win32_Foundation")]
pub type HCN_NOTIFICATION_CALLBACK = ::core::option::Option<unsafe extern "system" fn(notificationtype: u32, context: *const ::core::ffi::c_void, notificationstatus: ::windows_sys::core::HRESULT, notificationdata: super::super::Foundation::PWSTR)>;
pub type HCN_PORT_ACCESS = i32;
pub const HCN_PORT_ACCESS_EXCLUSIVE: HCN_PORT_ACCESS = 1i32;
pub const HCN_PORT_ACCESS_SHARED: HCN_PORT_ACCESS = 2i32;
pub type HCN_PORT_PROTOCOL = i32;
pub const HCN_PORT_PROTOCOL_TCP: HCN_PORT_PROTOCOL = 1i32;
pub const HCN_PORT_PROTOCOL_UDP: HCN_PORT_PROTOCOL = 2i32;
pub const HCN_PORT_PROTOCOL_BOTH: HCN_PORT_PROTOCOL = 3i32;
#[repr(C)]
pub struct HCN_PORT_RANGE_ENTRY {
pub OwningPartitionId: ::windows_sys::core::GUID,
pub TargetPartitionId: ::windows_sys::core::GUID,
pub Protocol: HCN_PORT_PROTOCOL,
pub Priority: u64,
pub ReservationType: u32,
pub SharingFlags: u32,
pub DeliveryMode: u32,
pub StartingPort: u16,
pub EndingPort: u16,
}
impl ::core::marker::Copy for HCN_PORT_RANGE_ENTRY {}
impl ::core::clone::Clone for HCN_PORT_RANGE_ENTRY {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct HCN_PORT_RANGE_RESERVATION {
pub startingPort: u16,
pub endingPort: u16,
}
impl ::core::marker::Copy for HCN_PORT_RANGE_RESERVATION {}
impl ::core::clone::Clone for HCN_PORT_RANGE_RESERVATION {
fn clone(&self) -> Self {
*self
}
}
|
use std::fmt::{self, Display};
use std::str::FromStr;
use anyhow::bail;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Rcode {
NoError,
FormErr,
ServFail,
NXDomain,
NotImp,
Refused,
YXDomain,
YXRRset,
NXRRset,
NotAuth,
NotZone,
Reserved,
}
impl Rcode {
pub fn new(value: u8) -> Self {
match value {
0 => Rcode::NoError,
1 => Rcode::FormErr,
2 => Rcode::ServFail,
3 => Rcode::NXDomain,
4 => Rcode::NotImp,
5 => Rcode::Refused,
6 => Rcode::YXDomain,
7 => Rcode::YXRRset,
8 => Rcode::NXRRset,
9 => Rcode::NotAuth,
10 => Rcode::NotZone,
_ => Rcode::Reserved,
}
}
pub fn to_u8(self) -> u8 {
match self {
Rcode::NoError => 0,
Rcode::FormErr => 1,
Rcode::ServFail => 2,
Rcode::NXDomain => 3,
Rcode::NotImp => 4,
Rcode::Refused => 5,
Rcode::YXDomain => 6,
Rcode::YXRRset => 7,
Rcode::NXRRset => 8,
Rcode::NotAuth => 9,
Rcode::NotZone => 10,
Rcode::Reserved => 11,
}
}
pub fn to_str(self) -> &'static str {
match self {
Rcode::NoError => "NOERROR",
Rcode::FormErr => "FORMERR",
Rcode::ServFail => "SERVFAIL",
Rcode::NXDomain => "NXDOMAIN",
Rcode::NotImp => "NOTIMP",
Rcode::Refused => "REFUSED",
Rcode::YXDomain => "YXDOMAIN",
Rcode::YXRRset => "YXRRSET",
Rcode::NXRRset => "NXRRSET",
Rcode::NotAuth => "NOTAUTH",
Rcode::NotZone => "NOTZONE",
Rcode::Reserved => "RESERVED",
}
}
}
impl Display for Rcode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.to_str())
}
}
impl FromStr for Rcode {
type Err = anyhow::Error;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
match s.to_uppercase().as_ref() {
"NOERROR" => Ok(Rcode::NoError),
"FORMERR" => Ok(Rcode::FormErr),
"SERVFAIL" => Ok(Rcode::ServFail),
"NXDOMAIN" => Ok(Rcode::NXDomain),
"NOTIMP" => Ok(Rcode::NotImp),
"REFUSED" => Ok(Rcode::Refused),
"YXDOMAIN" => Ok(Rcode::YXDomain),
"YXRRSET" => Ok(Rcode::YXRRset),
"NXRRSET" => Ok(Rcode::NXRRset),
"NOTAUTH" => Ok(Rcode::NotAuth),
"NOTZONE" => Ok(Rcode::NotZone),
"RESERVED" => Ok(Rcode::Reserved),
_ => bail!("unknow rcode {}", s),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
pub fn test_rcode_equal() {
assert_eq!(Rcode::NoError.to_u8(), 0);
assert_eq!(Rcode::NoError.to_string(), "NOERROR");
}
#[test]
pub fn test_rcode_from_str() {
assert_eq!("noerror".parse::<Rcode>().unwrap(), Rcode::NoError);
assert_eq!("NOERROR".parse::<Rcode>().unwrap(), Rcode::NoError);
assert!("OERROR".parse::<Rcode>().is_err());
}
}
|
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::str;
use std::ffi::CStr;
use std::error::Error;
use std::str::from_utf8;
use cql_bindgen::cass_error_desc;
use cql_bindgen::CASS_ERROR_LIB_BAD_PARAMS;
use cql_bindgen::CASS_ERROR_LIB_NO_STREAMS;
use cql_bindgen::CASS_ERROR_LAST_ENTRY;
use cql_bindgen::CASS_ERROR_SSL_IDENTITY_MISMATCH;
use cql_bindgen::CASS_ERROR_SSL_INVALID_PEER_CERT;
use cql_bindgen::CASS_ERROR_SSL_NO_PEER_CERT;
use cql_bindgen::CASS_ERROR_SSL_INVALID_PRIVATE_KEY;
use cql_bindgen::CASS_ERROR_SSL_INVALID_CERT;
use cql_bindgen::CASS_ERROR_SSL_PROTOCOL_ERROR;
use cql_bindgen::CASS_ERROR_SERVER_UNPREPARED;
use cql_bindgen::CASS_ERROR_SERVER_ALREADY_EXISTS;
use cql_bindgen::CASS_ERROR_SERVER_CONFIG_ERROR;
use cql_bindgen::CASS_ERROR_SERVER_INVALID_QUERY;
use cql_bindgen::CASS_ERROR_SERVER_UNAUTHORIZED;
use cql_bindgen::CASS_ERROR_SERVER_SYNTAX_ERROR;
use cql_bindgen::CASS_ERROR_SERVER_READ_TIMEOUT;
use cql_bindgen::CASS_ERROR_SERVER_WRITE_TIMEOUT;
use cql_bindgen::CASS_ERROR_SERVER_TRUNCATE_ERROR;
use cql_bindgen::CASS_ERROR_SERVER_IS_BOOTSTRAPPING;
use cql_bindgen::CASS_ERROR_SERVER_OVERLOADED;
use cql_bindgen::CASS_ERROR_SERVER_UNAVAILABLE;
use cql_bindgen::CASS_ERROR_SERVER_BAD_CREDENTIALS;
use cql_bindgen::CASS_ERROR_SERVER_PROTOCOL_ERROR;
use cql_bindgen::CASS_ERROR_SERVER_SERVER_ERROR;
use cql_bindgen::CASS_ERROR_LIB_UNABLE_TO_CLOSE;
use cql_bindgen::CASS_ERROR_LIB_UNABLE_TO_CONNECT;
use cql_bindgen::CASS_ERROR_LIB_NOT_IMPLEMENTED;
use cql_bindgen::CASS_ERROR_LIB_NULL_VALUE;
use cql_bindgen::CASS_ERROR_LIB_UNABLE_TO_DETERMINE_PROTOCOL;
use cql_bindgen::CASS_ERROR_LIB_NAME_DOES_NOT_EXIST;
use cql_bindgen::CASS_ERROR_LIB_INVALID_STATEMENT_TYPE;
use cql_bindgen::CASS_ERROR_LIB_CALLBACK_ALREADY_SET;
use cql_bindgen::CASS_ERROR_LIB_UNABLE_TO_SET_KEYSPACE;
use cql_bindgen::CASS_ERROR_LIB_REQUEST_TIMED_OUT;
use cql_bindgen::CASS_ERROR_LIB_INVALID_VALUE_TYPE;
use cql_bindgen::CASS_ERROR_LIB_INVALID_ITEM_COUNT;
use cql_bindgen::CASS_ERROR_LIB_INDEX_OUT_OF_BOUNDS;
use cql_bindgen::CASS_ERROR_LIB_NO_HOSTS_AVAILABLE;
use cql_bindgen::CASS_ERROR_LIB_WRITE_ERROR;
use cql_bindgen::CASS_ERROR_LIB_NO_AVAILABLE_IO_THREAD;
use cql_bindgen::CASS_ERROR_LIB_REQUEST_QUEUE_FULL;
use cql_bindgen::CASS_ERROR_LIB_UNEXPECTED_RESPONSE;
use cql_bindgen::CASS_ERROR_LIB_HOST_RESOLUTION;
use cql_bindgen::CASS_ERROR_LIB_MESSAGE_ENCODE;
use cql_bindgen::CASS_ERROR_LIB_UNABLE_TO_INIT;
use cql_bindgen::CASS_OK;
use cql_bindgen::CassError as _CassError;
#[repr(C)]
pub enum CassErrorSource {
NONE = 0isize,
LIB = 1,
SERVER = 2,
SSL = 3,
COMPRESSION = 4,
}
pub struct CassError(_CassError);
impl Error for CassError {
fn description(&self) -> &str {
let c_buf: *const i8 = unsafe {
self.desc()
};
let buf: &[u8] = unsafe {
CStr::from_ptr(c_buf).to_bytes()
};
from_utf8(buf).unwrap()
}
}
impl Display for CassError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let c_buf: *const i8 = unsafe {
self.desc()
};
let buf: &[u8] = unsafe {
CStr::from_ptr(c_buf).to_bytes()
};
match str::from_utf8(buf) {
Ok(str_slice) => {
write!(f, "{}", str_slice)
}
Err(err) => panic!("unreachable? {:?}", err),
}
}
}
impl Debug for CassError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let c_buf: *const i8 = unsafe {
self.desc()
};
let buf: &[u8] = unsafe {
CStr::from_ptr(c_buf).to_bytes()
};
match str::from_utf8(buf) {
Ok(str_slice) => {
write!(f, "{:?}", str_slice)
}
Err(err) => panic!("unreachable? {:?}", err),
}
}
}
#[derive(Debug,Eq,PartialEq,Copy,Clone)]
#[repr(C)]
pub enum CassErrorTypes {
CASS_OK = 0,
LIB_BAD_PARAMS = 16777217,
LIB_NO_STREAMS = 16777218,
LIB_UNABLE_TO_INIT = 16777219,
LIB_MESSAGE_ENCODE = 16777220,
LIB_HOST_RESOLUTION = 16777221,
LIB_UNEXPECTED_RESPONSE = 16777222,
LIB_REQUEST_QUEUE_FULL = 16777223,
LIB_NO_AVAILABLE_IO_THREAD = 16777224,
LIB_WRITE_ERROR = 16777225,
LIB_NO_HOSTS_AVAILABLE = 16777226,
LIB_INDEX_OUT_OF_BOUNDS = 16777227,
LIB_INVALID_ITEM_COUNT = 16777228,
LIB_INVALID_VALUE_TYPE = 16777229,
LIB_REQUEST_TIMED_OUT = 16777230,
LIB_UNABLE_TO_SET_KEYSPACE = 16777231,
LIB_CALLBACK_ALREADY_SET = 16777232,
LIB_INVALID_STATEMENT_TYPE = 16777233,
LIB_NAME_DOES_NOT_EXIST = 16777234,
LIB_UNABLE_TO_DETERMINE_PROTOCOL = 16777235,
LIB_NULL_VALUE = 16777236,
LIB_NOT_IMPLEMENTED = 16777237,
LIB_UNABLE_TO_CONNECT = 16777238,
LIB_UNABLE_TO_CLOSE = 16777239,
SERVER_SERVER_ERROR = 33554432,
SERVER_PROTOCOL_ERROR = 33554442,
SERVER_BAD_CREDENTIALS = 33554688,
SERVER_UNAVAILABLE = 33558528,
SERVER_OVERLOADED = 33558529,
SERVER_IS_BOOTSTRAPPING = 33558530,
SERVER_TRUNCATE_ERROR = 33558531,
SERVER_WRITE_TIMEOUT = 33558784,
SERVER_READ_TIMEOUT = 33559040,
SERVER_SYNTAX_ERROR = 33562624,
SERVER_UNAUTHORIZED = 33562880,
SERVER_INVALID_QUERY = 33563136,
SERVER_CONFIG_ERROR = 33563392,
SERVER_ALREADY_EXISTS = 33563648,
SERVER_UNPREPARED = 33563904,
SSL_INVALID_CERT = 50331649,
SSL_INVALID_PRIVATE_KEY = 50331650,
SSL_NO_PEER_CERT = 50331651,
SSL_INVALID_PEER_CERT = 50331652,
SSL_IDENTITY_MISMATCH = 50331653,
LAST_ENTRY = 50331654,
}
impl CassError {
pub fn wrap<T>(&self, wrappee: T) -> Result<T, CassError> {
match self.0 {
CASS_OK => Ok(wrappee),
err => Err(CassError::build(err)),
}
}
pub fn build(val: u32) -> CassError {
match val {
0 => CassError(CASS_OK),
1 => CassError(CASS_ERROR_LIB_BAD_PARAMS),
2 => CassError(CASS_ERROR_LIB_NO_STREAMS),
3 => CassError(CASS_ERROR_LIB_UNABLE_TO_INIT),
4 => CassError(CASS_ERROR_LIB_MESSAGE_ENCODE),
5 => CassError(CASS_ERROR_LIB_HOST_RESOLUTION),
6 => CassError(CASS_ERROR_LIB_UNEXPECTED_RESPONSE),
7 => CassError(CASS_ERROR_LIB_REQUEST_QUEUE_FULL),
8 => CassError(CASS_ERROR_LIB_NO_AVAILABLE_IO_THREAD),
9 => CassError(CASS_ERROR_LIB_WRITE_ERROR),
10 | 16777226 => CassError(CASS_ERROR_LIB_NO_HOSTS_AVAILABLE),
11 => CassError(CASS_ERROR_LIB_INDEX_OUT_OF_BOUNDS),
12 => CassError(CASS_ERROR_LIB_INVALID_ITEM_COUNT),
13 => CassError(CASS_ERROR_LIB_INVALID_VALUE_TYPE),
14 => CassError(CASS_ERROR_LIB_REQUEST_TIMED_OUT),
15 => CassError(CASS_ERROR_LIB_UNABLE_TO_SET_KEYSPACE),
16 => CassError(CASS_ERROR_LIB_CALLBACK_ALREADY_SET),
17 => CassError(CASS_ERROR_LIB_INVALID_STATEMENT_TYPE),
18 => CassError(CASS_ERROR_LIB_NAME_DOES_NOT_EXIST),
19 => CassError(CASS_ERROR_LIB_UNABLE_TO_DETERMINE_PROTOCOL),
20 => CassError(CASS_ERROR_LIB_NULL_VALUE),
21 => CassError(CASS_ERROR_LIB_NOT_IMPLEMENTED),
22 => CassError(CASS_ERROR_LIB_UNABLE_TO_CONNECT),
23 => CassError(CASS_ERROR_LIB_UNABLE_TO_CLOSE),
33554432 => CassError(CASS_ERROR_SERVER_SERVER_ERROR),
33554442 => CassError(CASS_ERROR_SERVER_PROTOCOL_ERROR),
33554688 => CassError(CASS_ERROR_SERVER_BAD_CREDENTIALS),
33558528 => CassError(CASS_ERROR_SERVER_UNAVAILABLE),
33558529 => CassError(CASS_ERROR_SERVER_OVERLOADED),
33558530 => CassError(CASS_ERROR_SERVER_IS_BOOTSTRAPPING),
33558531 => CassError(CASS_ERROR_SERVER_TRUNCATE_ERROR),
33558784 => CassError(CASS_ERROR_SERVER_WRITE_TIMEOUT),
33559040 => CassError(CASS_ERROR_SERVER_READ_TIMEOUT),
33562624 => CassError(CASS_ERROR_SERVER_SYNTAX_ERROR),
33562880 => CassError(CASS_ERROR_SERVER_UNAUTHORIZED),
33563136 => CassError(CASS_ERROR_SERVER_INVALID_QUERY),
33563392 => CassError(CASS_ERROR_SERVER_CONFIG_ERROR),
33563648 => CassError(CASS_ERROR_SERVER_ALREADY_EXISTS),
33563904 => CassError(CASS_ERROR_SERVER_UNPREPARED),
50331649 => CassError(CASS_ERROR_SSL_INVALID_CERT),
50331650 => CassError(CASS_ERROR_SSL_INVALID_PRIVATE_KEY),
50331651 => CassError(CASS_ERROR_SSL_NO_PEER_CERT),
50331652 => CassError(CASS_ERROR_SSL_INVALID_PEER_CERT),
50331653 => CassError(CASS_ERROR_SSL_IDENTITY_MISMATCH),
50331654 => CassError(CASS_ERROR_SSL_PROTOCOL_ERROR),
50331655 => CassError(CASS_ERROR_LAST_ENTRY),
err_no => {
debug!("unhandled error number: {}", err_no);
CassError(err_no)
}
}
}
}
impl CassError {
pub unsafe fn desc(&self) -> *const i8 {
cass_error_desc(self.0)
}
pub fn debug(&self) {
println!("{:?}",self)
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::io;
#[fuchsia_async::run_singlethreaded]
async fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Usage: run_test_suite <test_url>\n");
eprintln!(
"<test_url> is the URL of the test component to run. It must be a component \
publishing the fuchsia.test.TestSuite protocol."
);
std::process::exit(1);
}
println!("\nRunning test '{}'", args[1]);
let mut stdout = io::stdout();
let result = run_test_suite_lib::run_test(args[1].clone(), &mut stdout).await;
if result.is_err() {
let err = result.unwrap_err();
println!("Test suite encountered error trying to run tests: {:?}", err);
std::process::exit(1);
}
let (outcome, executed, passed) = result.unwrap();
println!("\n{} out of {} tests passed...", passed.len(), executed.len());
println!("{} completed with outcome: {}", &args[1], outcome);
if outcome == run_test_suite_lib::TestOutcome::Passed {
std::process::exit(0);
}
std::process::exit(1);
}
|
use crate::{
builtins::{PyCode, PyDictRef},
compiler::{self, CompileError, CompileOpts},
convert::TryFromObject,
scope::Scope,
AsObject, PyObjectRef, PyRef, PyResult, VirtualMachine,
};
impl VirtualMachine {
pub fn compile(
&self,
source: &str,
mode: compiler::Mode,
source_path: String,
) -> Result<PyRef<PyCode>, CompileError> {
self.compile_with_opts(source, mode, source_path, self.compile_opts())
}
pub fn compile_with_opts(
&self,
source: &str,
mode: compiler::Mode,
source_path: String,
opts: CompileOpts,
) -> Result<PyRef<PyCode>, CompileError> {
compiler::compile(source, mode, source_path, opts).map(|code| self.ctx.new_code(code))
}
pub fn run_script(&self, scope: Scope, path: &str) -> PyResult<()> {
if get_importer(path, self)?.is_some() {
self.insert_sys_path(self.new_pyobj(path))?;
let runpy = self.import("runpy", None, 0)?;
let run_module_as_main = runpy.get_attr("_run_module_as_main", self)?;
run_module_as_main.call((identifier!(self, __main__).to_owned(), false), self)?;
return Ok(());
}
let dir = std::path::Path::new(path)
.parent()
.unwrap()
.to_str()
.unwrap();
self.insert_sys_path(self.new_pyobj(dir))?;
match std::fs::read_to_string(path) {
Ok(source) => {
self.run_code_string(scope, &source, path.to_owned())?;
}
Err(err) => {
error!("Failed reading file '{}': {}", path, err);
// TODO: Need to change to ExitCode or Termination
std::process::exit(1);
}
}
Ok(())
}
pub fn run_code_string(&self, scope: Scope, source: &str, source_path: String) -> PyResult {
let code_obj = self
.compile(source, compiler::Mode::Exec, source_path.clone())
.map_err(|err| self.new_syntax_error(&err, Some(source)))?;
// trace!("Code object: {:?}", code_obj.borrow());
scope.globals.set_item(
identifier!(self, __file__),
self.new_pyobj(source_path),
self,
)?;
self.run_code_obj(code_obj, scope)
}
pub fn run_block_expr(&self, scope: Scope, source: &str) -> PyResult {
let code_obj = self
.compile(source, compiler::Mode::BlockExpr, "<embedded>".to_owned())
.map_err(|err| self.new_syntax_error(&err, Some(source)))?;
// trace!("Code object: {:?}", code_obj.borrow());
self.run_code_obj(code_obj, scope)
}
}
fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> {
let path_importer_cache = vm.sys_module.get_attr("path_importer_cache", vm)?;
let path_importer_cache = PyDictRef::try_from_object(vm, path_importer_cache)?;
if let Some(importer) = path_importer_cache.get_item_opt(path, vm)? {
return Ok(Some(importer));
}
let path = vm.ctx.new_str(path);
let path_hooks = vm.sys_module.get_attr("path_hooks", vm)?;
let mut importer = None;
let path_hooks: Vec<PyObjectRef> = path_hooks.try_into_value(vm)?;
for path_hook in path_hooks {
match path_hook.call((path.clone(),), vm) {
Ok(imp) => {
importer = Some(imp);
break;
}
Err(e) if e.fast_isinstance(vm.ctx.exceptions.import_error) => continue,
Err(e) => return Err(e),
}
}
Ok(if let Some(imp) = importer {
let imp = path_importer_cache.get_or_insert(vm, path.into(), || imp.clone())?;
Some(imp)
} else {
None
})
}
|
use std::collections::HashSet;
use fileutil;
fn get_adjacent(heightmap: &Vec<Vec<i32>>, pos: (usize, usize)) -> HashSet<(usize, usize)> {
let deltas: Vec<(i32, i32)> = vec![(0, 1), (0, -1), (1, 0), (-1, 0)];
let (pos_y, pos_x) = pos;
let adj: HashSet<(usize, usize)> = deltas.iter()
.map(|(dy, dx)| (pos_y as i32 + dy, pos_x as i32 + dx))
.filter(|(y, x)|
0 <= *y && *y < heightmap.len() as i32 &&
0 <= *x && *x < heightmap[0].len() as i32
).map(|(y, x)| (y as usize, x as usize))
.collect();
adj
}
pub fn run() {
let heightmap: Vec<Vec<i32>> = fileutil::read_lines("data/2021/09.txt")
.unwrap()
.iter()
.map(|line|
line
.chars()
.map(|c| c.to_digit(10).unwrap() as i32).collect()
).collect();
let mut sum_risk_levels = 0;
let mut lowpoints: Vec<(usize, usize)> = vec![];
for i in 0..heightmap.len() as i32 {
for j in 0..heightmap[0].len() as i32 {
let cur_height = heightmap[i as usize][j as usize];
let is_lowpoint = get_adjacent(&heightmap, (i as usize, j as usize))
.iter()
.all(|(y, x)| heightmap[*y][*x] > cur_height);
if is_lowpoint {
let risk_level = cur_height + 1;
sum_risk_levels += risk_level;
lowpoints.push((i as usize, j as usize));
}
}
}
let mut stack: Vec<(usize, usize)> = vec![];
let mut visited: HashSet<(usize, usize)> = HashSet::new();
let mut basin_sizes: Vec<i32> = Vec::new();
for lowpoint in lowpoints {
let mut basin_size = 0;
stack.push(lowpoint);
while !stack.is_empty() {
let (cur_y, cur_x) = stack.pop().unwrap();
if visited.contains(&(cur_y, cur_x)) {
continue;
}
basin_size += 1;
visited.insert((cur_y, cur_x));
let cur_height = heightmap[cur_y][cur_x];
let adj = get_adjacent(&heightmap, (cur_y, cur_x));
for (adj_y, adj_x) in adj.difference(&visited) {
let adj_height = heightmap[*adj_y][*adj_x];
if cur_height < adj_height && adj_height != 9 {
stack.push((*adj_y, *adj_x));
}
}
}
basin_sizes.push(basin_size);
}
basin_sizes.sort();
basin_sizes.reverse();
let basin_mult = basin_sizes[0] * basin_sizes[1] * basin_sizes[2];
println!("{}", sum_risk_levels);
println!("{}", basin_mult);
} |
pub mod config;
pub mod network;
pub mod protobuf;
pub mod raft;
pub mod rpc_server;
pub mod shutdown;
pub mod state_machine;
pub mod storage;
|
mod queries;
use crate::{
snapshot_comparison::queries::TestQueries, try_run_influxql, try_run_sql, MiniCluster,
};
use arrow::record_batch::RecordBatch;
use arrow_flight::error::FlightError;
use arrow_util::test_util::{sort_record_batch, Normalizer, REGEX_UUID};
use influxdb_iox_client::format::influxql::{write_columnar, Options, TableBorders};
use once_cell::sync::Lazy;
use regex::{Captures, Regex};
use snafu::{OptionExt, ResultExt, Snafu};
use sqlx::types::Uuid;
use std::collections::HashMap;
use std::{
fmt::{Display, Formatter},
fs,
path::{Path, PathBuf},
};
use tonic::Code;
use self::queries::Query;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Could not read case file '{:?}': {}", path, source))]
ReadingCaseFile {
path: PathBuf,
source: std::io::Error,
},
#[snafu(context(false))]
MakingOutputPath { source: OutputPathError },
#[snafu(display("Could not write to output file '{:?}': {}", output_path, source))]
WritingToOutputFile {
output_path: PathBuf,
source: std::io::Error,
},
#[snafu(display("Could not read expected file '{:?}': {}", path, source))]
ReadingExpectedFile {
path: PathBuf,
source: std::io::Error,
},
#[snafu(display(
"Contents of output '{:?}' does not match contents of expected '{:?}'",
output_path,
expected_path,
))]
OutputMismatch {
output_path: PathBuf,
expected_path: PathBuf,
},
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Match the parquet directory names
/// For example, given
/// `51/216/1a3f45021a3f45021a3f45021a3f45021a3f45021a3f45021a3f45021a3f4502/1d325760-2b20-48de-ab48-2267b034133d.parquet`
///
/// matches `51/216/1a3f45021a3f45021a3f45021a3f45021a3f45021a3f45021a3f45021a3f4502`
pub static REGEX_DIRS: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"([0-9]+)/([0-9]+)/([0-9a-f]{64})"#).expect("directory regex"));
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Language {
#[default]
Sql,
InfluxQL,
}
impl Language {
fn normalize_results(&self, n: &Normalizer, results: Vec<RecordBatch>) -> Vec<String> {
match self {
Language::Sql => n.normalize_results(results),
Language::InfluxQL => {
let results = if n.sorted_compare && !results.is_empty() {
let schema = results[0].schema();
let batch = arrow::compute::concat_batches(&schema, &results)
.expect("concatenating batches");
vec![sort_record_batch(batch)]
} else {
results
};
let options = if n.no_table_borders {
Options {
borders: TableBorders::None,
}
} else {
Options::default()
};
let mut buf = Vec::<u8>::new();
write_columnar(&mut buf, &results, options).unwrap();
let mut seen: HashMap<String, u128> = HashMap::new();
unsafe { String::from_utf8_unchecked(buf) }
.trim()
.lines()
.map(|s| {
// replace any UUIDs
let s = REGEX_UUID.replace_all(s, |c: &Captures<'_>| {
let next = seen.len() as u128;
Uuid::from_u128(
*seen
.entry(c.get(0).unwrap().as_str().to_owned())
.or_insert(next),
)
.to_string()
});
let s = REGEX_DIRS.replace_all(&s, |_c: &Captures<'_>| {
// this ensures 15/232/5 is replaced with a string of a known width
// 1/1/1
["1", "1", "1"].join("/")
});
// Need to remove trailing spaces when using no_borders
let s = if n.no_table_borders {
s.trim_end()
} else {
s.as_ref()
};
s.to_string()
})
.collect::<Vec<_>>()
}
}
}
}
impl Display for Language {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Language::Sql => Display::fmt("SQL", f),
Language::InfluxQL => Display::fmt("InfluxQL", f),
}
}
}
pub async fn run(
cluster: &mut MiniCluster,
input_path: PathBuf,
setup_name: String,
contents: String,
language: Language,
) -> Result<()> {
// create output and expected output
let output_path = make_output_path(&input_path)?;
let expected_path = {
let mut p = input_path.clone();
let ext = p
.extension()
.expect("input path missing extension")
.to_str()
.expect("input path extension is not valid UTF-8");
p.set_extension(format!("{ext}.expected"));
p
};
println!("Running case in {input_path:?}");
println!(" writing output to {output_path:?}");
println!(" expected output in {expected_path:?}");
println!("Processing contents:\n{contents}");
let queries = TestQueries::from_lines(contents.lines(), language);
let mut output = vec![];
output.push(format!("-- Test Setup: {setup_name}"));
for q in queries.iter() {
output.push(format!("-- {}: {}", language, q.text()));
q.add_description(&mut output);
let results = run_query(cluster, q).await?;
output.extend(results);
}
fs::write(&output_path, output.join("\n")).context(WritingToOutputFileSnafu {
output_path: &output_path,
})?;
// Now, compare to expected results
let expected_data = fs::read_to_string(&expected_path).context(ReadingExpectedFileSnafu {
path: &expected_path,
})?;
let expected_contents: Vec<_> = expected_data.lines().map(|s| s.to_string()).collect();
if expected_contents != output {
let expected_path = make_absolute(&expected_path);
let output_path = make_absolute(&output_path);
if std::env::var("CI")
.map(|value| value == "true")
.unwrap_or(false)
{
// In CI, print out the contents because it's inconvenient to access the files and
// you're not going to update the files there.
println!("Expected output does not match actual output");
println!(
"Diff: \n\n{}",
String::from_utf8(
std::process::Command::new("diff")
.arg("-du")
.arg(&expected_path)
.arg(&output_path)
.output()
.unwrap()
.stdout
)
.unwrap()
);
} else {
// When you're not in CI, print out instructions for analyzing the content or updating
// the snapshot.
println!("Expected output does not match actual output");
println!(" expected output in {expected_path:?}");
println!(" actual output in {output_path:?}");
println!("Possibly helpful commands:");
println!(" # See diff");
println!(" diff -du {expected_path:?} {output_path:?}");
println!(" # Update expected");
println!(" cp -f {output_path:?} {expected_path:?}");
}
OutputMismatchSnafu {
output_path,
expected_path,
}
.fail()
} else {
Ok(())
}
}
#[derive(Debug, Snafu)]
pub enum OutputPathError {
#[snafu(display("Input path has no file stem: '{:?}'", path))]
NoFileStem { path: PathBuf },
#[snafu(display("Input path missing file extension: '{:?}'", path))]
MissingFileExt { path: PathBuf },
#[snafu(display("Input path has no parent?!: '{:?}'", path))]
NoParent { path: PathBuf },
}
/// Return output path for input path.
///
/// This converts `some/prefix/in/foo.sql` (or other file extensions) to `some/prefix/out/foo.sql.out`.
fn make_output_path(input: &Path) -> Result<PathBuf, OutputPathError> {
let stem = input.file_stem().context(NoFileStemSnafu { path: input })?;
let ext = input
.extension()
.context(MissingFileExtSnafu { path: input })?;
// go two levels up (from file to dir, from dir to parent dir)
let parent = input.parent().context(NoParentSnafu { path: input })?;
let parent = parent.parent().context(NoParentSnafu { path: parent })?;
let mut out = parent.to_path_buf();
// go one level down (from parent dir to out-dir)
out.push("out");
// make best effort attempt to create output directory if it
// doesn't exist (it does not on a fresh checkout)
if !out.exists() {
if let Err(e) = std::fs::create_dir(&out) {
panic!("Could not create output directory {out:?}: {e}");
}
}
// set file name and ext
out.push(stem);
out.set_extension(format!(
"{}.out",
ext.to_str().expect("extension is not valid UTF-8")
));
Ok(out)
}
/// Return the absolute path to `path`, regardless of if it exists on the local filesystem
fn make_absolute(path: &Path) -> PathBuf {
let mut absolute = std::env::current_dir().expect("cannot get current working directory");
absolute.extend(path);
absolute
}
async fn run_query(cluster: &MiniCluster, query: &Query) -> Result<Vec<String>> {
let (query_text, language) = (query.text(), query.language());
let result = match language {
Language::Sql => {
try_run_sql(
query_text,
cluster.namespace(),
cluster.querier().querier_grpc_connection(),
None,
true,
)
.await
}
Language::InfluxQL => {
try_run_influxql(
query_text,
cluster.namespace(),
cluster.querier().querier_grpc_connection(),
None,
)
.await
}
};
let batches = match result {
Ok((mut batches, schema)) => {
batches.push(RecordBatch::new_empty(schema));
batches
}
Err(influxdb_iox_client::flight::Error::ArrowFlightError(FlightError::Tonic(status)))
if status.code() == Code::InvalidArgument =>
{
return Ok(status.message().lines().map(str::to_string).collect())
}
Err(e) => panic!("error running query '{query_text}': {e}"),
};
Ok(query.normalize_results(batches, language))
}
|
use std::any::Any;
use crate::algebra::{Point2f, Mat2x2f};
use crate::canvas::Canvas;
use super::{GraphicObject};
#[derive(Clone, Debug)]
pub struct LineSegs2f {
pub vertices: Vec<Point2f>,
pub color: [f32; 4], // rgba
}
impl LineSegs2f {
pub fn new(vertices: Vec<Point2f>, color: [f32; 4]) -> LineSegs2f {
LineSegs2f { vertices, color }
}
pub fn from_floats(floats: Vec<f32>) -> LineSegs2f {
let mut vertices: Vec<Point2f> = Vec::new();
let mut iter = floats.iter();
let r = iter.next().unwrap();
let g = iter.next().unwrap();
let b = iter.next().unwrap();
let a = iter.next().unwrap();
let color: [f32; 4] = [*r, *g, *b, *a];
while match iter.next() {
Some(v1) => match iter.next() {
Some(v2) => {
vertices.push(Point2f::from_floats(*v1, *v2));
true
}
None => panic!("odd parse"),
},
None => false,
} {}
LineSegs2f::new(vertices, color)
}
#[inline]
pub fn shift(&self, dp: Point2f) -> LineSegs2f {
LineSegs2f {
vertices: self.vertices.iter().map(|x| *x + dp).collect(),
color: self.color,
}
}
#[inline]
fn wu(x1: f32, y1: f32, x2: f32, y2: f32, color: [f32; 4], canvas: &mut Canvas) {
let mut x1: i32 = (x1 * canvas.scaler) as i32;
let mut y1: i32 = (y1 * canvas.scaler) as i32;
let mut x2: i32 = (x2 * canvas.scaler) as i32;
let mut y2: i32 = (y2 * canvas.scaler) as i32;
let mut dx = x2 - x1;
let dy = y2 - y1;
canvas.set_color([color[0], color[1], color[2]]);
if dx == 0 {
if dy < 0 {
std::mem::swap(&mut y1, &mut y2);
}
for y in y1..y2 + 1 {
canvas.putpixel(x1, y, color[3]);
}
return;
}
if dy == 0 {
if dx < 0 {
std::mem::swap(&mut x1, &mut x2);
}
for x in x1..x2 + 1 {
canvas.putpixel(x, y1, color[3]);
}
return;
}
if dx == dy {
if dx < 0 {
x1 = x2;
y1 = y2;
dx = -dx;
}
for i in 0..dx + 1 {
canvas.putpixel(x1 + i, y1 + i, color[3]);
}
return;
}
if dx == -dy {
if dx < 0 {
x1 = x2;
y1 = y2;
dx = -dx;
}
for i in 0..dx + 1 {
canvas.putpixel(x1 + i, y1 - i, color[3]);
}
return;
}
let k = dy as f32 / dx as f32;
let mut e: f32 = 0.;
if dx + dy < 0 {
std::mem::swap(&mut x1, &mut x2);
std::mem::swap(&mut y1, &mut y2);
}
if k > 0. && k < 1. {
let mut py = y1;
for px in x1..x2 {
canvas.putpixel(px, py, color[3] * (1. - e));
canvas.putpixel(px, py + 1, color[3] * e);
e += k;
if e >= 1. {
py += 1;
e -= 1.;
}
}
} else if k > 1. {
let mut px = x1;
for py in y1..y2 {
canvas.putpixel(px, py, color[3] * (1. - e));
canvas.putpixel(px + 1, py, color[3] * e);
e += 1. / k;
if e >= 1. {
px += 1;
e -= 1.;
}
}
} else if k > -1. && k < 0. {
let mut py = y1;
for px in x1..x2 {
canvas.putpixel(px, py, color[3] * (1. + e));
canvas.putpixel(px, py - 1, color[3] * -e);
e += k;
if e <= -1. {
py -= 1;
e += 1.0;
}
}
} else if k < -1. {
let mut px = x2;
for py in (y1..y2).rev() {
canvas.putpixel(px, py, color[3] * (1. - e));
canvas.putpixel(px + 1, py, color[3] * e);
e += -1. / k;
if e >= 1. {
px += 1;
e -= 1.;
}
}
}
}
}
impl GraphicObject for LineSegs2f {
fn as_any(&self) -> &dyn Any {
self
}
fn shift(&self, dp: Point2f) -> Box<dyn GraphicObject> {
Box::new(self.shift(dp))
}
fn rotate(&self, rotate_mat: Mat2x2f) -> Box<dyn GraphicObject> {
Box::new(LineSegs2f {
vertices: self.vertices.iter().map(|x| rotate_mat * *x).collect(),
color: self.color,
})
}
fn zoom(&self, k: f32) -> Box<dyn GraphicObject> {
Box::new(LineSegs2f {
vertices: self.vertices.iter().map(|x| *x * k).collect(),
color: self.color,
})
}
fn shear(&self, k: f32) -> Box<dyn GraphicObject> {
Box::new(LineSegs2f {
vertices: self.vertices.iter().map(|x| Point2f::from_floats(x.x + k * x.y, x.y)).collect(),
color: self.color,
})
}
fn render(&self, mut canvas: &mut Canvas) {
let mut flag = false;
let mut x1: f32 = 0.; // convince compiler
let mut x2: f32;
let mut y1: f32 = 0.; // convince compiler
let mut y2: f32;
for vertex in self.vertices.iter() {
if !flag {
flag = true;
x1 = vertex.x;
y1 = vertex.y;
} else {
x2 = vertex.x;
y2 = vertex.y;
LineSegs2f::wu(x1, y1, x2, y2, self.color, &mut canvas);
x1 = x2;
y1 = y2;
}
}
}
}
|
use fuzzcheck::{DefaultMutator, Mutator};
use fuzzcheck_mutators_derive::make_mutator;
#[derive(Clone, DefaultMutator)]
enum NoAssociatedData {
#[ignore_variant]
A,
B,
#[ignore_variant]
C,
D,
E,
}
#[derive(Clone)]
enum WithIgnore<T> {
CanMutate(u8),
CannotMutate(CannotMutate),
X,
Y,
Z,
A { flag: bool, item: T },
}
#[derive(Clone)]
struct CannotMutate {}
make_mutator! {
name: WithIgnoreMutator,
recursive: false,
default: true,
type:
enum WithIgnore<T> {
CanMutate(u8),
#[ignore_variant]
CannotMutate(CannotMutate),
#[ignore_variant]
X,
#[ignore_variant]
Y,
#[ignore_variant]
Z,
#[ignore_variant]
A {
flag: bool,
item: T
}
}
}
#[test]
#[no_coverage]
fn test_compile() {
let m = WithIgnore::<bool>::default_mutator();
let _ = m.random_arbitrary(10.0);
}
|
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate slog;
use dotenv::dotenv;
use slog::Drain;
use slog_async;
use slog_term;
pub mod api;
pub mod core;
pub mod schema;
pub mod utils;
fn main() {
dotenv().ok();
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let logger = slog::Logger::root(drain, o!());
let mut rocket = rocket::ignite();
rocket = api::routes::fuel(rocket);
rocket = api::catchers::fuel(rocket);
rocket
.manage(utils::db::init_pool())
.manage(logger)
.launch();
}
|
use std::io;
use agent_simple::*;
pub mod agent_simple;
fn main() {
let secret_key: u64 = agent_get_secret_key().unwrap();
let mut buffer: String = String::new();
println!("Please input a 8 byte message");
let _ = io::stdin().read_line(&mut buffer);
let mut message = [0u8; 8];
for i in 0..8 {
if i < buffer.len() {
message[i] = buffer.as_bytes()[i];
}
}
let cipher_text: Vec<u8> = agent_encrypt(&message, &secret_key).unwrap();
let text: Vec<u8> = agent_decrypt(&cipher_text, &secret_key).unwrap();
assert!(message == &text[..]);
println!("message: {:?}", message);
println!("ciphertext: {:?}", cipher_text);
} |
use crate::{
event::{self, Event, LogEvent, Value},
transforms::{
regex_parser::{RegexParser, RegexParserConfig},
Transform,
},
};
use lazy_static::lazy_static;
use snafu::{OptionExt, Snafu};
use string_cache::DefaultAtom as Atom;
lazy_static! {
pub static ref MULTILINE_TAG: Atom = Atom::from("multiline_tag");
}
/// Parser for the CRI log format.
///
/// Expects logs to arrive in a CRI log format.
///
/// CRI log format ([documentation][cri_log_format]) is a simple
/// newline-separated text format. We rely on regular expressions to parse it.
///
/// Normalizes parsed data for consistency.
///
/// [cri_log_format]: https://github.com/kubernetes/community/blob/ee2abbf9dbfa4523b414f99a04ddc97bd38c74b2/contributors/design-proposals/node/kubelet-cri-logging.md
pub struct Cri {
// TODO: patch `RegexParser` to expose the concerete type on build.
regex_parser: Box<dyn Transform>,
}
impl Cri {
/// Create a new [`Cri`] parser.
pub fn new() -> Self {
let regex_parser = {
let mut rp_config = RegexParserConfig::default();
let pattern = r"^(?P<timestamp>.*) (?P<stream>(stdout|stderr)) (?P<multiline_tag>(P|F)) (?P<message>.*)$";
rp_config.patterns = vec![pattern.to_owned()];
rp_config.types.insert(
event::log_schema().timestamp_key().clone(),
"timestamp|%+".to_owned(),
);
RegexParser::build(&rp_config).expect("regexp patterns are static, should never fail")
};
Self { regex_parser }
}
}
impl Transform for Cri {
fn transform(&mut self, event: Event) -> Option<Event> {
let mut event = self.regex_parser.transform(event)?;
normalize_event(event.as_mut_log()).ok()?;
Some(event)
}
}
fn normalize_event(log: &mut LogEvent) -> Result<(), NormalizationError> {
// Detect if this is a partial event.
let multiline_tag = log
.remove(&MULTILINE_TAG)
.context(MultilineTagFieldMissing)?;
let multiline_tag = match multiline_tag {
Value::Bytes(val) => val,
_ => return Err(NormalizationError::MultilineTagValueUnexpectedType),
};
let is_partial = multiline_tag[0] == b'P';
// For partial messages add a partial event indicator.
if is_partial {
log.insert(event::PARTIAL_STR, true);
}
Ok(())
}
#[derive(Debug, Snafu)]
enum NormalizationError {
MultilineTagFieldMissing,
MultilineTagValueUnexpectedType,
}
#[cfg(test)]
pub mod tests {
use super::super::test_util;
use super::Cri;
use crate::event::LogEvent;
fn make_long_string(base: &str, len: usize) -> String {
base.chars().cycle().take(len).collect()
}
/// Shared test cases.
pub fn cases() -> Vec<(String, LogEvent)> {
vec![
(
"2016-10-06T00:17:09.669794202Z stdout F The content of the log entry 1".into(),
test_util::make_log_event(
"The content of the log entry 1",
"2016-10-06T00:17:09.669794202Z",
"stdout",
false,
),
),
(
"2016-10-06T00:17:09.669794202Z stdout P First line of log entry 2".into(),
test_util::make_log_event(
"First line of log entry 2",
"2016-10-06T00:17:09.669794202Z",
"stdout",
true,
),
),
(
"2016-10-06T00:17:09.669794202Z stdout P Second line of the log entry 2".into(),
test_util::make_log_event(
"Second line of the log entry 2",
"2016-10-06T00:17:09.669794202Z",
"stdout",
true,
),
),
(
"2016-10-06T00:17:10.113242941Z stderr F Last line of the log entry 2".into(),
test_util::make_log_event(
"Last line of the log entry 2",
"2016-10-06T00:17:10.113242941Z",
"stderr",
false,
),
),
// A part of the partial message with a realistic length.
(
[
r#"2016-10-06T00:17:10.113242941Z stdout P "#,
make_long_string("very long message ", 16 * 1024).as_str(),
]
.join(""),
test_util::make_log_event(
make_long_string("very long message ", 16 * 1024).as_str(),
"2016-10-06T00:17:10.113242941Z",
"stdout",
true,
),
),
]
}
#[test]
fn test_parsing() {
test_util::test_parser(Cri::new, cases());
}
}
|
extern crate serde;
extern crate oasis_core_runtime;
#[macro_use]
mod api;
pub use api::{Key, KeyValue, Transfer, UpdateRuntime, Withdraw};
|
use rand::Rng;
use std::cmp::Ordering;
use std::io::stdin;
// fn main() { // Function
// print!("Hello !") // Marco
// }
fn main() {
let secret_number = rand::thread_rng().gen_range(1, 101);
loop{ // Start a loop
println!("Guess the number");
println!("Enter your guess");
let mut guess = String::new();
stdin().read_line(&mut guess).expect("Failed to read line"); // Must always handle 'Result' using expect()
// let guess: u32 // annotate the variable type using :u32
// = guess // Variable Shadowing - same variable name is used for different data type
// .trim() // trim() -> removes the \n at the end on pressing Enter
// .parse() // parse the string to mentioned data type
// .expect("Please enter a number"); // handling 'Result' enum for two variants : [Ok and Err] Ok has the value Err has the error msg
// Better approach than above instead of expect()
let guess: u32 = match guess.trim().parse() { // Handle 'Result'
Ok(num) => num,
Err(_) => continue
};
println!("You Guessed : {}", &guess);
println!("The secret number is: {}", &secret_number);
match guess.cmp(&secret_number) {
// &mut guess also works. But why it works ??
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
|
/// Sets DSO as default logger.
#[macro_export]
macro_rules! set_log {
(periph: $uarte:ident,pin_number: $pin_number:expr,buf_size: $buf_size:expr,) => {
const _: () = {
use ::core::{cell::UnsafeCell, ptr::NonNull, slice};
use ::drone_core::log;
use ::drone_cortexm::reg;
use ::drone_nrf_map::periph::uarte::$uarte;
$crate::uarte_assert_taken!($uarte);
struct Logger;
#[repr(C, align(4))]
struct Buf(UnsafeCell<[u8; $buf_size]>);
static BUF: Buf = Buf(UnsafeCell::new([0; $buf_size]));
unsafe impl $crate::Logger for Logger {
type UarteMap = $uarte;
const BAUD_RATE: u32 = $crate::baud_rate(log::baud_rate!());
const BUF_SIZE: u32 = $buf_size;
const PIN_NUMBER: u32 = $pin_number;
#[inline]
fn buf() -> NonNull<u8> {
unsafe { NonNull::new_unchecked((&mut *BUF.0.get()).as_mut_ptr()) }
}
}
unsafe impl Sync for Buf {}
#[no_mangle]
extern "C" fn drone_log_is_enabled(port: u8) -> bool {
$crate::is_enabled::<Logger>(port)
}
#[no_mangle]
extern "C" fn drone_log_write_bytes(port: u8, buffer: *const u8, count: usize) {
$crate::write_bytes::<Logger>(port, unsafe { slice::from_raw_parts(buffer, count) })
}
#[no_mangle]
extern "C" fn drone_log_write_u8(port: u8, value: u8) {
$crate::write_bytes::<Logger>(port, &value.to_be_bytes())
}
#[no_mangle]
extern "C" fn drone_log_write_u16(port: u8, value: u16) {
$crate::write_bytes::<Logger>(port, &value.to_be_bytes())
}
#[no_mangle]
extern "C" fn drone_log_write_u32(port: u8, value: u32) {
$crate::write_bytes::<Logger>(port, &value.to_be_bytes())
}
#[no_mangle]
extern "C" fn drone_log_flush() {
$crate::flush::<Logger>();
}
};
};
}
|
use bit_vec::BitVec; // 0.5.1
fn main() {
let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
assert_eq!(bv.iter().filter(|x| *x).count(), 7);
assert_eq!(rank(&bv, 4), 3);
assert_eq!(bv.rank(4), 3);
}
fn rank(bv: &BitVec, i: usize) -> usize {
bv.iter().take(i).filter(|x| *x).count()
}
trait Rank {
fn rank(&self, i: usize) -> usize;
}
impl Rank for BitVec {
fn rank(&self, i: usize) -> usize {
self.iter().take(i).filter(|x| *x).count()
}
}
|
pub struct Solution;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: List,
}
type List = Option<Box<ListNode>>;
impl Solution {
pub fn swap_pairs(head: List) -> List {
let mut head = head;
let mut current = &mut head;
while current.is_some() && current.as_ref().unwrap().next.is_some() {
let mut x = current.take();
let mut y = x.as_mut().unwrap().next.take();
let z = y.as_mut().unwrap().next.take();
*current = y;
current = &mut current.as_mut().unwrap().next;
*current = x;
current = &mut current.as_mut().unwrap().next;
*current = z;
}
head
}
}
#[test]
fn test0024() {
fn cons(val: i32, next: List) -> List {
Some(Box::new(ListNode { val, next }))
}
assert_eq!(
Solution::swap_pairs(cons(1, cons(2, cons(3, cons(4, None))))),
cons(2, cons(1, cons(4, cons(3, None))))
);
}
|
#[macro_use]
extern crate glium;
extern crate alice;
extern crate rand;
use std::fs::File;
use std::io::Cursor;
use glium::{DisplayBuild, Surface};
use glium::glutin::{Event, ElementState, VirtualKeyCode, MouseScrollDelta, MouseButton};
use alice::model::rendering::{ModelRenderer, prepare_model};
use alice::model::{Model, Path, Point};
use alice::data::{Vec2, Vec3};
use rand::{thread_rng, Rng};
fn main() {
let display = glium::glutin::WindowBuilder::new()
.with_title(format!("Alice"))
.with_dimensions(1024, 768)
.with_vsync()
.build_glium()
.unwrap();
let window = display.get_window().unwrap();
let mut renderer = ModelRenderer::new(&display);
let model = if let Some(path) = std::env::args().nth(1) {
let file = File::open(path).unwrap();
let mut reader = alice::data::BinaryReader::new(file);
Model::read(&mut reader).unwrap()
} else {
let bytes = include_bytes!("cat.model");
let file: Cursor<&[u8]> = Cursor::new(bytes);
let mut reader = alice::data::BinaryReader::new(file);
Model::read(&mut reader).unwrap()
};
let mut wobble = WobbleModel::new(&model, 0.5, 0.95);
let mut x = 512.0;
let mut y = 384.0;
let mut scale = 1.0;
let mut mouse_pos = (0, 0);
loop {
let mut target = display.draw();
target.clear_color(0.02, 0.02, 0.02, 1.0);
let (w, h) = window.get_inner_size_points().unwrap();
renderer.set_size(w as f32, h as f32);
wobble.tick();
let model = prepare_model(&display, &wobble.model());
renderer.draw(&mut target, x, y, scale, &model);
target.finish().unwrap();
for ev in display.poll_events() {
match ev {
Event::Closed => return,
Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Escape)) => return,
Event::ReceivedCharacter(' ') => wobble.shuffle(10.0 / scale as f64),
Event::ReceivedCharacter('+') => scale *= 1.1,
Event::ReceivedCharacter('=') => scale *= 1.1,
Event::ReceivedCharacter('-') => scale /= 1.1,
Event::ReceivedCharacter('0') => {
x = w as f32 / 2.0;
y = h as f32 / 2.0;
scale = 1.0;
}
Event::MouseWheel(MouseScrollDelta::PixelDelta(dx, dy)) => {
x -= dx;
y += dy;
},
Event::MouseMoved(p) => mouse_pos = p,
Event::MouseInput(ElementState::Pressed, MouseButton::Left) => {
let f = window.hidpi_factor() as f64;
let (mx, my) = (mouse_pos.0 as f64 / f, h as f64 - mouse_pos.1 as f64 / f);
let (mx, my) = (mx - x as f64, my - y as f64);
let (mx, my) = (mx / scale as f64, my / scale as f64);
wobble.push((mx, my), 0.3, 100.0 / scale as f64)
},
_ => ()
}
}
}
}
struct WobbleModel {
spring: f64,
damping: f64,
paths: Vec<WobblePath>,
}
struct WobblePath {
colour: Vec3,
points: Vec<WobblePoint>
}
struct WobblePoint {
location: Vec2,
curve_bias: f64,
offset: Vec2,
velocity: Vec2
}
fn gauss(c: f64, x: f64) -> f64 {
(-x * x / (2.0 * c * c)).exp()
}
impl WobbleModel {
pub fn new(model: &Model, spring: f64, damping: f64) -> WobbleModel {
WobbleModel {
spring: spring,
damping: damping,
paths: model.paths
.iter()
.map(|path| WobblePath {
colour: path.colour,
points: path.points
.iter()
.map(|point| WobblePoint {
location: point.location,
curve_bias: point.curve_bias,
offset: (0.0, 0.0),
velocity: (0.0, 0.0)
})
.collect()
})
.collect()
}
}
pub fn model(&self) -> Model {
Model {
paths: self.paths
.iter()
.map(|path| Path {
colour: path.colour,
points: path.points
.iter()
.map(|point| {
let x = point.location.0 + point.offset.0;
let y = point.location.1 + point.offset.1;
Point {
location: (x, y),
curve_bias: point.curve_bias
}
})
.collect()
})
.collect()
}
}
pub fn shuffle(&mut self, v: f64) {
let mut rng = rand::thread_rng();
for path in self.paths.iter_mut() {
for point in path.points.iter_mut() {
point.velocity.0 += rng.gen_range(-v, v);
point.velocity.1 += rng.gen_range(-v, v);
}
}
}
pub fn push(&mut self, (x, y): Vec2, s: f64, w: f64) {
for path in self.paths.iter_mut() {
for point in path.points.iter_mut() {
let (px, py) = point.location;
let (dx, dy) = (px - x, py - y);
let d = (dx * dx + dy * dy).sqrt();
let d = s * gauss(w, d);
point.velocity.0 += d * dx;
point.velocity.1 += d * dy;
}
}
}
pub fn tick(&mut self) {
for path in self.paths.iter_mut() {
for point in path.points.iter_mut() {
let (mut ox, mut oy) = point.offset;
let (mut vx, mut vy) = point.velocity;
vx += -self.spring * ox;
vy += -self.spring * oy;
vx *= self.damping;
vy *= self.damping;
ox += vx;
oy += vy;
point.offset = (ox, oy);
point.velocity = (vx, vy);
}
}
}
}
|
use vec2d::*;
fn main() {
let mut v = matrix![[1, 2, 3], [4, 5, 6]];
//*v[0] = [5, 6];
//println!("v: {}, v.as_ptr(): {}", &v.v as *const )
println!("[[{}, {}], [{}, {}]]", v[0][0], v[0][1], v[1][0], v[1][1]);
} |
#![crate_name = "rho"]
extern crate ncurses;
mod host;
mod event;
mod client;
mod buffer;
use std::sync::Arc;
use std::sync::mpsc;
use std::sync::RwLock;
use std::sync::mpsc::{Receiver, Sender};
use host::Host;
use client::Client;
use buffer::Buffer;
use event::InputEvent;
use host::CursesHost;
pub use client::GenericClient;
pub struct Editor {
host: Host,
client: Client,
buffers: Arc<RwLock<Vec<Buffer>>>,
}
pub impl Editor {
pub fn new() {
let buffers = RwLock::new(vec![Buffer::new()]);
let (sender, recvr): (Sender<InputEvent>, Receiver<InputEvent>) = mpsc::channel();
let (host, client) = (CursesHost::new(buffers, sender), GenericClient::new(buffers,recvr));
}
pub fn run(&self) {
self.client.listen();
self.host.run();
}
}
|
extern crate jni;
extern crate qrcode;
extern crate sass_rs;
use jni::JNIEnv;
use jni::objects::{JClass, JString};
use jni::sys::jstring;
use pulldown_cmark::{html, Parser};
use qrcode::QrCode;
use sass_rs::{compile_file, Options};
use sass_rs::OutputStyle;
#[no_mangle]
#[allow(non_snake_case)]
pub extern "system" fn Java_io_github_ilaborie_slides2_kt_jvm_tools_Natives_markdownToHtml(
env: JNIEnv,
_class: JClass,
input: JString,
) -> jstring {
let input: String = env
.get_string(input)
.expect("Couldn't get java string!")
.into();
let parser = Parser::new(&input);
let mut html_buf = String::new();
html::push_html(&mut html_buf, parser);
env
.new_string(html_buf)
.expect("Couldn't create java string!")
.into_inner()
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "system" fn Java_io_github_ilaborie_slides2_kt_jvm_tools_Natives_qrCode(
env: JNIEnv,
_class: JClass,
input: JString,
) -> jstring {
let input: String = env
.get_string(input)
.expect("Couldn't get java string!")
.into();
let code = QrCode::new(input).unwrap();
let result = code.render()
.light_color("<span class=\"light\"></span>")
.dark_color("<span class=\"dark\"></span>")
.build();
env
.new_string(result)
.expect("Couldn't create java string!")
.into_inner()
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "system" fn Java_io_github_ilaborie_slides2_kt_jvm_tools_Natives_scssFileToCss(
env: JNIEnv,
_class: JClass,
input: JString,
) -> jstring {
let input: String = env
.get_string(input)
.expect("Couldn't get java string!")
.into();
let mut options = Options::default();
options.output_style = OutputStyle::Compressed;
let compiled = compile_file(&input, options)
.expect("Could not compile SCSS");
env
.new_string(compiled)
.expect("Couldn't create java string!")
.into_inner()
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {}
}
|
use openexr_sys as sys;
use crate::{
core::{
channel_list::{ChannelList, ChannelListRef, ChannelListRefMut},
cppstd::{
CppString, CppVectorFloat, CppVectorFloatRef, CppVectorFloatRefMut,
CppVectorString, CppVectorStringRef, CppVectorStringRefMut,
},
preview_image::{PreviewImage, PreviewImageRef, PreviewImageRefMut},
refptr::{OpaquePtr, Ref, RefMut},
tile_description::TileDescription,
Chromaticities, Compression, Envmap, LineOrder,
},
deep::DeepImageState,
};
use imath_traits::{Bound2, Matrix33, Matrix44, Vec2, Vec3};
use std::ffi::CStr;
#[repr(transparent)]
pub struct Attribute(pub(crate) *mut sys::Imf_Attribute_t);
pub trait TypedAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t;
}
// ----------------------------------------------------------------------------
// Box2iAttribute
#[repr(transparent)]
pub struct Box2iAttribute(pub(crate) *mut sys::Imf_Box2iAttribute_t);
unsafe impl OpaquePtr for Box2iAttribute {
type SysPointee = sys::Imf_Box2iAttribute_t;
type Pointee = Box2iAttribute;
}
pub type Box2iAttributeRef<'a, P = Box2iAttribute> = Ref<'a, P>;
pub type Box2iAttributeRefMut<'a, P = Box2iAttribute> = RefMut<'a, P>;
impl Box2iAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> Box2iAttribute
where
T: Bound2<i32>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_Box2iAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_Box2i_t,
)
.into_result()
.unwrap();
}
Box2iAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Bound2<i32>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_Box2iAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_Box2i_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Bound2<i32>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_Box2iAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_Box2i_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Box2iAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for Box2iAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_Box2iAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// Box2fAttribute
#[repr(transparent)]
pub struct Box2fAttribute(pub(crate) *mut sys::Imf_Box2fAttribute_t);
unsafe impl OpaquePtr for Box2fAttribute {
type SysPointee = sys::Imf_Box2fAttribute_t;
type Pointee = Box2fAttribute;
}
pub type Box2fAttributeRef<'a, P = Box2fAttribute> = Ref<'a, P>;
pub type Box2fAttributeRefMut<'a, P = Box2fAttribute> = RefMut<'a, P>;
impl Box2fAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> Box2fAttribute
where
T: Bound2<f32>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_Box2fAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_Box2f_t,
)
.into_result()
.unwrap();
}
Box2fAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Bound2<f32>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_Box2fAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_Box2f_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Bound2<f32>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_Box2fAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_Box2f_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_Box2fAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for Box2fAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_Box2fAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// IntAttribute
#[repr(transparent)]
pub struct IntAttribute(pub(crate) *mut sys::Imf_IntAttribute_t);
unsafe impl OpaquePtr for IntAttribute {
type SysPointee = sys::Imf_IntAttribute_t;
type Pointee = IntAttribute;
}
pub type IntAttributeRef<'a, P = IntAttribute> = Ref<'a, P>;
pub type IntAttributeRefMut<'a, P = IntAttribute> = RefMut<'a, P>;
impl IntAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: i32) -> IntAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_IntAttribute_from_value(&mut inner, &value)
.into_result()
.unwrap();
}
IntAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> &i32 {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_IntAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const i32)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut i32 {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_IntAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut i32)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_IntAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for IntAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_IntAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// FloatAttribute
#[repr(transparent)]
pub struct FloatAttribute(pub(crate) *mut sys::Imf_FloatAttribute_t);
unsafe impl OpaquePtr for FloatAttribute {
type SysPointee = sys::Imf_FloatAttribute_t;
type Pointee = FloatAttribute;
}
pub type FloatAttributeRef<'a, P = FloatAttribute> = Ref<'a, P>;
pub type FloatAttributeRefMut<'a, P = FloatAttribute> = RefMut<'a, P>;
impl FloatAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: f32) -> FloatAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_FloatAttribute_from_value(&mut inner, &value)
.into_result()
.unwrap();
}
FloatAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> &f32 {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_FloatAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const f32)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut f32 {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_FloatAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut f32)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_FloatAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for FloatAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_FloatAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// DoubleAttribute
#[repr(transparent)]
pub struct DoubleAttribute(pub(crate) *mut sys::Imf_DoubleAttribute_t);
unsafe impl OpaquePtr for DoubleAttribute {
type SysPointee = sys::Imf_DoubleAttribute_t;
type Pointee = DoubleAttribute;
}
pub type DoubleAttributeRef<'a, P = DoubleAttribute> = Ref<'a, P>;
pub type DoubleAttributeRefMut<'a, P = DoubleAttribute> = RefMut<'a, P>;
impl DoubleAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: f64) -> DoubleAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_DoubleAttribute_from_value(&mut inner, &value)
.into_result()
.unwrap();
}
DoubleAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> &f64 {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_DoubleAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const f64)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut f64 {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_DoubleAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut f64)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_DoubleAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for DoubleAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_DoubleAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// ChromaticitiesAttribute
#[repr(transparent)]
pub struct ChromaticitiesAttribute(
pub(crate) *mut sys::Imf_ChromaticitiesAttribute_t,
);
unsafe impl OpaquePtr for ChromaticitiesAttribute {
type SysPointee = sys::Imf_ChromaticitiesAttribute_t;
type Pointee = ChromaticitiesAttribute;
}
pub type ChromaticitiesAttributeRef<'a, P = ChromaticitiesAttribute> =
Ref<'a, P>;
pub type ChromaticitiesAttributeRefMut<'a, P = ChromaticitiesAttribute> =
RefMut<'a, P>;
impl ChromaticitiesAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &Chromaticities) -> ChromaticitiesAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_ChromaticitiesAttribute_from_value(&mut inner, value)
.into_result()
.unwrap();
}
ChromaticitiesAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> &Chromaticities {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_ChromaticitiesAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const Chromaticities)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut Chromaticities {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_ChromaticitiesAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut Chromaticities)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_ChromaticitiesAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for ChromaticitiesAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_ChromaticitiesAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// CompressionAttribute
#[repr(transparent)]
pub struct CompressionAttribute(
pub(crate) *mut sys::Imf_CompressionAttribute_t,
);
unsafe impl OpaquePtr for CompressionAttribute {
type SysPointee = sys::Imf_CompressionAttribute_t;
type Pointee = CompressionAttribute;
}
pub type CompressionAttributeRef<'a, P = CompressionAttribute> = Ref<'a, P>;
pub type CompressionAttributeRefMut<'a, P = CompressionAttribute> =
RefMut<'a, P>;
impl CompressionAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &Compression) -> CompressionAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_CompressionAttribute_from_value(
&mut inner,
value as *const Compression as *const sys::Imf_Compression,
)
.into_result()
.unwrap();
}
CompressionAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> Compression {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_CompressionAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
*(ptr as *const Compression)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut Compression {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_CompressionAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut Compression)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_CompressionAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for CompressionAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_CompressionAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// DeepImageStateAttribute
#[repr(transparent)]
pub struct DeepImageStateAttribute(
pub(crate) *mut sys::Imf_DeepImageStateAttribute_t,
);
unsafe impl OpaquePtr for DeepImageStateAttribute {
type SysPointee = sys::Imf_DeepImageStateAttribute_t;
type Pointee = DeepImageStateAttribute;
}
pub type DeepImageStateAttributeRef<'a, P = DeepImageStateAttribute> =
Ref<'a, P>;
pub type DeepImageStateAttributeRefMut<'a, P = DeepImageStateAttribute> =
RefMut<'a, P>;
impl DeepImageStateAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &DeepImageState) -> DeepImageStateAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_DeepImageStateAttribute_from_value(
&mut inner,
value as *const DeepImageState
as *const sys::Imf_DeepImageState,
)
.into_result()
.unwrap();
}
DeepImageStateAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> DeepImageState {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_DeepImageStateAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
*(ptr as *const DeepImageState)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut DeepImageState {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_DeepImageStateAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut DeepImageState)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_DeepImageStateAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for DeepImageStateAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_DeepImageStateAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// EnvmapAttribute
#[repr(transparent)]
pub struct EnvmapAttribute(pub(crate) *mut sys::Imf_EnvmapAttribute_t);
unsafe impl OpaquePtr for EnvmapAttribute {
type SysPointee = sys::Imf_EnvmapAttribute_t;
type Pointee = EnvmapAttribute;
}
pub type EnvmapAttributeRef<'a, P = EnvmapAttribute> = Ref<'a, P>;
pub type EnvmapAttributeRefMut<'a, P = EnvmapAttribute> = RefMut<'a, P>;
impl EnvmapAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &Envmap) -> EnvmapAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_EnvmapAttribute_from_value(
&mut inner,
value as *const Envmap as *const sys::Imf_Envmap,
)
.into_result()
.unwrap();
}
EnvmapAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> Envmap {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_EnvmapAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
*(ptr as *const Envmap)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut Envmap {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_EnvmapAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut Envmap)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_EnvmapAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for EnvmapAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_EnvmapAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// ChannelListAttribute
#[repr(transparent)]
pub struct ChannelListAttribute(
pub(crate) *mut sys::Imf_ChannelListAttribute_t,
);
unsafe impl OpaquePtr for ChannelListAttribute {
type SysPointee = sys::Imf_ChannelListAttribute_t;
type Pointee = ChannelListAttribute;
}
pub type ChannelListAttributeRef<'a, P = ChannelListAttribute> = Ref<'a, P>;
pub type ChannelListAttributeRefMut<'a, P = ChannelListAttribute> =
RefMut<'a, P>;
impl ChannelListAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &ChannelList) -> ChannelListAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_ChannelListAttribute_from_value(&mut inner, value.0)
.into_result()
.unwrap();
}
ChannelListAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> ChannelListRef {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_ChannelListAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
ChannelListRef::new(ptr)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> ChannelListRefMut {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_ChannelListAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
ChannelListRefMut::new(ptr)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_ChannelListAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for ChannelListAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_ChannelListAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// CppVectorFloatAttribute
#[repr(transparent)]
pub struct CppVectorFloatAttribute(
pub(crate) *mut sys::Imf_CppVectorFloatAttribute_t,
);
unsafe impl OpaquePtr for CppVectorFloatAttribute {
type SysPointee = sys::Imf_CppVectorFloatAttribute_t;
type Pointee = CppVectorFloatAttribute;
}
pub type CppVectorFloatAttributeRef<'a, P = CppVectorFloatAttribute> =
Ref<'a, P>;
pub type CppVectorFloatAttributeRefMut<'a, P = CppVectorFloatAttribute> =
RefMut<'a, P>;
impl CppVectorFloatAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &CppVectorFloat) -> CppVectorFloatAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_CppVectorFloatAttribute_from_value(&mut inner, value.0)
.into_result()
.unwrap();
}
CppVectorFloatAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> CppVectorFloatRef {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_CppVectorFloatAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
CppVectorFloatRef::new(ptr)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> CppVectorFloatRefMut {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_CppVectorFloatAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
CppVectorFloatRefMut::new(ptr)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_CppVectorFloatAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for CppVectorFloatAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_CppVectorFloatAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// CppVectorStringAttribute
#[repr(transparent)]
pub struct CppVectorStringAttribute(
pub(crate) *mut sys::Imf_CppVectorStringAttribute_t,
);
unsafe impl OpaquePtr for CppVectorStringAttribute {
type SysPointee = sys::Imf_CppVectorStringAttribute_t;
type Pointee = CppVectorStringAttribute;
}
pub type CppVectorStringAttributeRef<'a, P = CppVectorStringAttribute> =
Ref<'a, P>;
pub type CppVectorStringAttributeRefMut<'a, P = CppVectorStringAttribute> =
RefMut<'a, P>;
impl CppVectorStringAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &CppVectorString) -> CppVectorStringAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_CppVectorStringAttribute_from_value(&mut inner, value.0)
.into_result()
.unwrap();
}
CppVectorStringAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> CppVectorStringRef {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_CppVectorStringAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
CppVectorStringRef::new(ptr)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> CppVectorStringRefMut {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_CppVectorStringAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
CppVectorStringRefMut::new(ptr)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_CppVectorStringAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for CppVectorStringAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_CppVectorStringAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// CppStringAttribute
#[repr(transparent)]
pub struct CppStringAttribute(pub(crate) *mut sys::Imf_CppStringAttribute_t);
unsafe impl OpaquePtr for CppStringAttribute {
type SysPointee = sys::Imf_CppStringAttribute_t;
type Pointee = CppStringAttribute;
}
pub type CppStringAttributeRef<'a, P = CppStringAttribute> = Ref<'a, P>;
pub type CppStringAttributeRefMut<'a, P = CppStringAttribute> = RefMut<'a, P>;
impl CppStringAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &str) -> CppStringAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
let s = CppString::new(value);
sys::Imf_CppStringAttribute_from_value(&mut inner, s.0)
.into_result()
.unwrap();
}
CppStringAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> &str {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_CppStringAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
let mut cptr = std::ptr::null();
sys::std_string_c_str(ptr, &mut cptr);
CStr::from_ptr(cptr).to_str().unwrap()
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_CppStringAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for CppStringAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_CppStringAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// LineOrderAttribute
#[repr(transparent)]
pub struct LineOrderAttribute(pub(crate) *mut sys::Imf_LineOrderAttribute_t);
unsafe impl OpaquePtr for LineOrderAttribute {
type SysPointee = sys::Imf_LineOrderAttribute_t;
type Pointee = LineOrderAttribute;
}
pub type LineOrderAttributeRef<'a, P = LineOrderAttribute> = Ref<'a, P>;
pub type LineOrderAttributeRefMut<'a, P = LineOrderAttribute> = RefMut<'a, P>;
impl LineOrderAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &LineOrder) -> LineOrderAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_LineOrderAttribute_from_value(
&mut inner,
value as *const LineOrder as *const sys::Imf_LineOrder,
)
.into_result()
.unwrap();
}
LineOrderAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> LineOrder {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_LineOrderAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
*(ptr as *const LineOrder)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut LineOrder {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_LineOrderAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut LineOrder)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_LineOrderAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for LineOrderAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_LineOrderAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// M33fAttribute
#[repr(transparent)]
pub struct M33fAttribute(pub(crate) *mut sys::Imf_M33fAttribute_t);
unsafe impl OpaquePtr for M33fAttribute {
type SysPointee = sys::Imf_M33fAttribute_t;
type Pointee = M33fAttribute;
}
pub type M33fAttributeRef<'a, P = M33fAttribute> = Ref<'a, P>;
pub type M33fAttributeRefMut<'a, P = M33fAttribute> = RefMut<'a, P>;
impl M33fAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> M33fAttribute
where
T: Matrix33<f32>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_M33fAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_M33f_t,
)
.into_result()
.unwrap();
}
M33fAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Matrix33<f32>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_M33fAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_M33f_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Matrix33<f32>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_M33fAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_M33f_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_M33fAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
// ----------------------------------------------------------------------------
// M33dAttribute
#[repr(transparent)]
pub struct M33dAttribute(pub(crate) *mut sys::Imf_M33dAttribute_t);
unsafe impl OpaquePtr for M33dAttribute {
type SysPointee = sys::Imf_M33dAttribute_t;
type Pointee = M33dAttribute;
}
pub type M33dAttributeRef<'a, P = M33dAttribute> = Ref<'a, P>;
pub type M33dAttributeRefMut<'a, P = M33dAttribute> = RefMut<'a, P>;
impl M33dAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> M33dAttribute
where
T: Matrix33<f64>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_M33dAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_M33d_t,
)
.into_result()
.unwrap();
}
M33dAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Matrix33<f64>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_M33dAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_M33d_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Matrix33<f64>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_M33dAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_M33d_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_M33dAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for M33dAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_M33dAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// M44fAttribute
#[repr(transparent)]
pub struct M44fAttribute(pub(crate) *mut sys::Imf_M44fAttribute_t);
unsafe impl OpaquePtr for M44fAttribute {
type SysPointee = sys::Imf_M44fAttribute_t;
type Pointee = M44fAttribute;
}
pub type M44fAttributeRef<'a, P = M44fAttribute> = Ref<'a, P>;
pub type M44fAttributeRefMut<'a, P = M44fAttribute> = RefMut<'a, P>;
impl M44fAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> M44fAttribute
where
T: Matrix44<f32>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_M44fAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_M44f_t,
)
.into_result()
.unwrap();
}
M44fAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Matrix44<f32>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_M44fAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_M44f_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Matrix44<f32>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_M44fAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_M44f_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_M44fAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for M44fAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_M44fAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// M44dAttribute
#[repr(transparent)]
pub struct M44dAttribute(pub(crate) *mut sys::Imf_M44dAttribute_t);
unsafe impl OpaquePtr for M44dAttribute {
type SysPointee = sys::Imf_M44dAttribute_t;
type Pointee = M44dAttribute;
}
pub type M44dAttributeRef<'a, P = M44dAttribute> = Ref<'a, P>;
pub type M44dAttributeRefMut<'a, P = M44dAttribute> = RefMut<'a, P>;
impl M44dAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> M44dAttribute
where
T: Matrix44<f64>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_M44dAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_M44d_t,
)
.into_result()
.unwrap();
}
M44dAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Matrix44<f64>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_M44dAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_M44d_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Matrix44<f64>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_M44dAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_M44d_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_M44dAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for M44dAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_M44dAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// PreviewImageAttribute
#[repr(transparent)]
pub struct PreviewImageAttribute(
pub(crate) *mut sys::Imf_PreviewImageAttribute_t,
);
unsafe impl OpaquePtr for PreviewImageAttribute {
type SysPointee = sys::Imf_PreviewImageAttribute_t;
type Pointee = PreviewImageAttribute;
}
pub type PreviewImageAttributeRef<'a, P = PreviewImageAttribute> = Ref<'a, P>;
pub type PreviewImageAttributeRefMut<'a, P = PreviewImageAttribute> =
RefMut<'a, P>;
impl PreviewImageAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &PreviewImage) -> PreviewImageAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_PreviewImageAttribute_from_value(&mut inner, value.0)
.into_result()
.unwrap();
}
PreviewImageAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> PreviewImageRef {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_PreviewImageAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
PreviewImageRef::new(ptr)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> PreviewImageRefMut {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_PreviewImageAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
PreviewImageRefMut::new(ptr)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_PreviewImageAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for PreviewImageAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_PreviewImageAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// TileDescriptionAttribute
#[repr(transparent)]
pub struct TileDescriptionAttribute(
pub(crate) *mut sys::Imf_TileDescriptionAttribute_t,
);
unsafe impl OpaquePtr for TileDescriptionAttribute {
type SysPointee = sys::Imf_TileDescriptionAttribute_t;
type Pointee = TileDescriptionAttribute;
}
pub type TileDescriptionAttributeRef<'a, P = TileDescriptionAttribute> =
Ref<'a, P>;
pub type TileDescriptionAttributeRefMut<'a, P = TileDescriptionAttribute> =
RefMut<'a, P>;
impl TileDescriptionAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value(value: &TileDescription) -> TileDescriptionAttribute {
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_TileDescriptionAttribute_from_value(
&mut inner,
&(*value).into(),
)
.into_result()
.unwrap();
}
TileDescriptionAttribute(inner)
}
/// Access to the contained value
pub fn value(&self) -> &TileDescription {
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_TileDescriptionAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const TileDescription)
}
}
/// Mutable access to the contained value
pub fn value_mut(&mut self) -> &mut TileDescription {
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_TileDescriptionAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut TileDescription)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_TileDescriptionAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for TileDescriptionAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_TileDescriptionAttribute_t
as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// V2iAttribute
#[repr(transparent)]
pub struct V2iAttribute(pub(crate) *mut sys::Imf_V2iAttribute_t);
unsafe impl OpaquePtr for V2iAttribute {
type SysPointee = sys::Imf_V2iAttribute_t;
type Pointee = V2iAttribute;
}
pub type V2iAttributeRef<'a, P = V2iAttribute> = Ref<'a, P>;
pub type V2iAttributeRefMut<'a, P = V2iAttribute> = RefMut<'a, P>;
impl V2iAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> V2iAttribute
where
T: Vec2<i32>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_V2iAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_V2i_t,
)
.into_result()
.unwrap();
}
V2iAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Vec2<i32>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_V2iAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_V2i_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Vec2<i32>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_V2iAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_V2i_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_V2iAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for V2iAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_V2iAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// V2fAttribute
#[repr(transparent)]
pub struct V2fAttribute(pub(crate) *mut sys::Imf_V2fAttribute_t);
unsafe impl OpaquePtr for V2fAttribute {
type SysPointee = sys::Imf_V2fAttribute_t;
type Pointee = V2fAttribute;
}
pub type V2fAttributeRef<'a, P = V2fAttribute> = Ref<'a, P>;
pub type V2fAttributeRefMut<'a, P = V2fAttribute> = RefMut<'a, P>;
impl V2fAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> V2fAttribute
where
T: Vec2<f32>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_V2fAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_V2f_t,
)
.into_result()
.unwrap();
}
V2fAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Vec2<f32>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_V2fAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_V2f_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Vec2<f32>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_V2fAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_V2f_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_V2fAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for V2fAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_V2fAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// V2dAttribute
#[repr(transparent)]
pub struct V2dAttribute(pub(crate) *mut sys::Imf_V2dAttribute_t);
unsafe impl OpaquePtr for V2dAttribute {
type SysPointee = sys::Imf_V2dAttribute_t;
type Pointee = V2dAttribute;
}
pub type V2dAttributeRef<'a, P = V2dAttribute> = Ref<'a, P>;
pub type V2dAttributeRefMut<'a, P = V2dAttribute> = RefMut<'a, P>;
impl V2dAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> V2dAttribute
where
T: Vec2<f64>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_V2dAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_V2d_t,
)
.into_result()
.unwrap();
}
V2dAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Vec2<f64>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_V2dAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_V2d_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Vec2<f64>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_V2dAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_V2d_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_V2dAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for V2dAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_V2dAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// V3iAttribute
#[repr(transparent)]
pub struct V3iAttribute(pub(crate) *mut sys::Imf_V3iAttribute_t);
unsafe impl OpaquePtr for V3iAttribute {
type SysPointee = sys::Imf_V3iAttribute_t;
type Pointee = V3iAttribute;
}
pub type V3iAttributeRef<'a, P = V3iAttribute> = Ref<'a, P>;
pub type V3iAttributeRefMut<'a, P = V3iAttribute> = RefMut<'a, P>;
impl V3iAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> V3iAttribute
where
T: Vec3<i32>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_V3iAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_V3i_t,
)
.into_result()
.unwrap();
}
V3iAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Vec3<i32>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_V3iAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_V3i_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Vec3<i32>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_V3iAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_V3i_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_V3iAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for V3iAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_V3iAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// V3fAttribute
#[repr(transparent)]
pub struct V3fAttribute(pub(crate) *mut sys::Imf_V3fAttribute_t);
unsafe impl OpaquePtr for V3fAttribute {
type SysPointee = sys::Imf_V3fAttribute_t;
type Pointee = V3fAttribute;
}
pub type V3fAttributeRef<'a, P = V3fAttribute> = Ref<'a, P>;
pub type V3fAttributeRefMut<'a, P = V3fAttribute> = RefMut<'a, P>;
impl V3fAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> V3fAttribute
where
T: Vec3<f32>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_V3fAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_V3f_t,
)
.into_result()
.unwrap();
}
V3fAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Vec3<f32>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_V3fAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_V3f_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Vec3<f32>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_V3fAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_V3f_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_V3fAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for V3fAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_V3fAttribute_t as *const sys::Imf_Attribute_t
}
}
// ----------------------------------------------------------------------------
// V3dAttribute
#[repr(transparent)]
pub struct V3dAttribute(pub(crate) *mut sys::Imf_V3dAttribute_t);
unsafe impl OpaquePtr for V3dAttribute {
type SysPointee = sys::Imf_V3dAttribute_t;
type Pointee = V3dAttribute;
}
pub type V3dAttributeRef<'a, P = V3dAttribute> = Ref<'a, P>;
pub type V3dAttributeRefMut<'a, P = V3dAttribute> = RefMut<'a, P>;
impl V3dAttribute {
/// Create a new attribute wrapping the given value
pub fn from_value<T>(value: &T) -> V3dAttribute
where
T: Vec3<f64>,
{
let mut inner = std::ptr::null_mut();
unsafe {
sys::Imf_V3dAttribute_from_value(
&mut inner,
value as *const T as *const sys::Imath_V3d_t,
)
.into_result()
.unwrap();
}
V3dAttribute(inner)
}
/// Access to the contained value
pub fn value<T>(&self) -> &T
where
T: Vec3<f64>,
{
let mut ptr = std::ptr::null();
unsafe {
sys::Imf_V3dAttribute_value_const(self.0, &mut ptr)
.into_result()
.unwrap();
&*(ptr as *const sys::Imath_V3d_t as *const T)
}
}
/// Mutable access to the contained value
pub fn value_mut<T>(&mut self) -> &mut T
where
T: Vec3<f64>,
{
let mut ptr = std::ptr::null_mut();
unsafe {
sys::Imf_V3dAttribute_value(self.0, &mut ptr)
.into_result()
.unwrap();
&mut *(ptr as *mut sys::Imath_V3d_t as *mut T)
}
}
/// Get this attribute's type name
pub fn type_name(&self) -> &str {
unsafe {
let mut ptr = std::ptr::null();
sys::Imf_V3dAttribute_typeName(self.0, &mut ptr)
.into_result()
.unwrap();
std::ffi::CStr::from_ptr(ptr)
.to_str()
.expect("Invalid UTF-8")
}
}
}
impl TypedAttribute for V3dAttribute {
fn as_attribute_ptr(&self) -> *const sys::Imf_Attribute_t {
self.0 as *const sys::Imf_V3dAttribute_t as *const sys::Imf_Attribute_t
}
}
|
// Copyright 2020 IOTA Stiftung
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
use bee_signing::ternary::wots::{normalize, NormalizeError};
use bee_ternary::{T1B1Buf, TryteBuf};
#[test]
fn invalid_message_length() {
let hash = TryteBuf::try_from_str("CEFLDDLMF9TO9ZLLTYXINXPYZHEFTXKWKWZXEIUD")
.unwrap()
.as_trits()
.encode::<T1B1Buf>();
assert_eq!(
normalize(&hash).err(),
Some(NormalizeError::InvalidMessageLength(hash.len()))
);
}
#[test]
fn input_output() {
let tests = [
(
"YSQMIFUQFJNLFAPAETRWNWUX9LSTTCERCIOBDZIDHVRVNPQNHTSNWYKSRFDOCQGXFTJY9HIGNND9RBHYF",
"MJQMIFUQFJNLFAPAETRWNWUX9LSMMMMMDIOBDZIDHVRVNPQNHTSNWYHSRFDOCQGXFTJY9HIGNND9RBHYF",
),
(
"FLMLSYHTEIXHEKZKABOVAZBEZNRAAM99KYXHR9IZZTF9DXNS9GNZDEZZACQTS9EPYNZYUFWFVQS9UOGFR",
"NNHLSYHTEIXHEKZKABOVAZBEZNRTAM99KYXHR9IZZTF9DXNS9GNZDEMMMMMBS9EPYNZYUFWFVQS9UOGFR",
),
(
"U9NWKLJUSHCVUDVJRFMCIZHUDMPLBZFTPCTOMKVGTEIRDSTBFDAOYIGEWSAXEZUFXO9HMDGKRH9ZJEJSY",
"NNNNFLJUSHCVUDVJRFMCIZHUDMPFBZFTPCTOMKVGTEIRDSTBFDAOYINNRSAXEZUFXO9HMDGKRH9ZJEJSY",
),
(
"TDA9LYGIE9OVLYGRAVHWYXPXNJMRZAMALYVJNRJP9SC9KYYSHIBHJVSOQIOKNYCNYYAPIUNXLDBWROWKN",
"NZA9LYGIE9OVLYGRAVHWYXPXNJMNNUMALYVJNRJP9SC9KYYSHIBHJVMMMMBKNYCNYYAPIUNXLDBWROWKN",
),
(
"OYXALGQ9HQVKD9FPNDZXNUHT9WGHKVNXJRLTMYQFUKEITR9KPSIVGTBFC9DKSN9GDJJJYSPJYXISGPZCN",
"MEXALGQ9HQVKD9FPNDZXNUHT9WGYKVNXJRLTMYQFUKEITR9KPSIVGTNEC9DKSN9GDJJJYSPJYXISGPZCN",
),
(
"INQE9N9JPQPS9JOEQGZGJYRSJBILNRLE9DAZVVVVFCZNAZERHWXXPTBUUIPZJYQGBPKYC9AEFMJN9RSAC",
"MMUE9N9JPQPS9JOEQGZGJYRSJBIMMBLE9DAZVVVVFCZNAZERHWXXPTYUUIPZJYQGBPKYC9AEFMJN9RSAC",
),
(
"DAXOGMLCVIGJWBTMFLBZLRVD9ZLJUQLSJGJF9XAAGVKQSHTSTQXJAWOJROXDBOWUYIF9JASOCIXFPWTIR",
"NNNNNTLCVIGJWBTMFLBZLRVD9ZLEUQLSJGJF9XAAGVKQSHTSTQXJAWMMHOXDBOWUYIF9JASOCIXFPWTIR",
),
(
"UVIQJKFZDPZVCNLTQWUNLWXSGFIOMD9DYHOMAJZDNW9ONSLRNZCBZAKNHLDJLHBIMCPNHRCCBWBSRSUBB",
"LVIQJKFZDPZVCNLTQWUNLWXSGFIMME9DYHOMAJZDNW9ONSLRNZCBZANNZLDJLHBIMCPNHRCCBWBSRSUBB",
),
(
"WDVGEKTJYIHISJXHFLRFGTLPNUDTWBKTSKNLJXO9JUUHBOZAU9G9MLVZEDZILUIDYTPKCLDHPYNEJ9YJN",
"NNNOEKTJYIHISJXHFLRFGTLPNUDNOBKTSKNLJXO9JUUHBOZAU9G9MLNNTDZILUIDYTPKCLDHPYNEJ9YJN",
),
(
"XHGMBGNQOLRRCPWRZTQJEWYOEMVISGVUXCTIWCFMXWNYBKFVXPUJOPWGQZQXTYNJZUQXCQTIZFXSXOTEX",
"MMMMKGNQOLRRCPWRZTQJEWYOEMVMLGVUXCTIWCFMXWNYBKFVXPUJOPMMMMMYTYNJZUQXCQTIZFXSXOTEX",
),
];
for test in tests.iter() {
let input_trits = TryteBuf::try_from_str(test.0).unwrap().as_trits().encode::<T1B1Buf>();
let output_trits = TryteBuf::try_from_str(test.1).unwrap().as_trits().encode::<T1B1Buf>();
let normalized_trits = normalize(&input_trits).unwrap().encode::<T1B1Buf>();
assert_eq!(output_trits, normalized_trits);
}
}
|
use crate::expiring_hash_map::ExpiringHashMap;
use crate::{
event::{self, Event},
sinks::util::{
encoding::{EncodingConfigWithDefault, EncodingConfiguration},
StreamSink,
},
template::Template,
topology::config::{DataType, SinkConfig, SinkContext, SinkDescription},
};
use async_trait::async_trait;
use bytes::Bytes;
use futures::pin_mut;
use futures::stream::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
use tokio::{
fs::{self, File},
io::AsyncWriteExt,
};
mod bytes_path;
use bytes_path::BytesPath;
use super::streaming_sink::{self, StreamingSink};
#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct FileSinkConfig {
pub path: Template,
pub idle_timeout_secs: Option<u64>,
#[serde(
default,
skip_serializing_if = "crate::serde::skip_serializing_if_default"
)]
pub encoding: EncodingConfigWithDefault<Encoding>,
}
inventory::submit! {
SinkDescription::new_without_default::<FileSinkConfig>("file")
}
#[derive(Deserialize, Serialize, Debug, Eq, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum Encoding {
Text,
Ndjson,
}
impl Default for Encoding {
fn default() -> Self {
Encoding::Text
}
}
#[typetag::serde(name = "file")]
impl SinkConfig for FileSinkConfig {
fn build(&self, cx: SinkContext) -> crate::Result<(super::RouterSink, super::Healthcheck)> {
let sink = FileSink::new(&self);
let sink = streaming_sink::compat::adapt_to_topology(sink);
let sink = StreamSink::new(sink, cx.acker());
Ok((Box::new(sink), Box::new(futures01::future::ok(()))))
}
fn input_type(&self) -> DataType {
DataType::Log
}
fn sink_type(&self) -> &'static str {
"file"
}
}
#[derive(Debug)]
pub struct FileSink {
path: Template,
encoding: EncodingConfigWithDefault<Encoding>,
idle_timeout: Duration,
files: ExpiringHashMap<Bytes, File>,
}
impl FileSink {
pub fn new(config: &FileSinkConfig) -> Self {
Self {
path: config.path.clone(),
encoding: config.encoding.clone(),
idle_timeout: Duration::from_secs(config.idle_timeout_secs.unwrap_or(30)),
files: ExpiringHashMap::default(),
}
}
/// Uses pass the `event` to `self.path` template to obtain the file path
/// to store the event as.
fn partition_event(&mut self, event: &Event) -> Option<bytes::Bytes> {
let bytes = match self.path.render(event) {
Ok(b) => b,
Err(missing_keys) => {
warn!(
message = "Keys do not exist on the event. Dropping event.",
?missing_keys
);
return None;
}
};
Some(bytes)
}
fn deadline_at(&self) -> Instant {
Instant::now()
.checked_add(self.idle_timeout)
.expect("unable to compute next deadline")
}
async fn run(&mut self, input: impl Stream<Item = Event> + Send + Sync) -> crate::Result<()> {
pin_mut!(input);
loop {
tokio::select! {
event = input.next() => {
match event {
None => {
// If we got `None` - terminate the processing.
debug!(message = "Receiver exhausted, terminating the processing loop.");
break;
}
Some(event) => self.process_event(event).await,
}
}
result = self.files.next_expired(), if !self.files.is_empty() => {
match result {
// We do not poll map when it's empty, so we should
// never reach this branch.
None => unreachable!(),
Some(Ok((mut expired_file, path))) => {
// We got an expired file. All we really want is to
// flush and close it.
if let Err(error) = expired_file.flush().await {
error!(message = "Failed to flush file.", ?path, %error);
}
drop(expired_file); // ignore close error
}
Some(Err(error)) => error!(
message = "An error occured while expiring a file.",
%error,
),
}
}
}
}
Ok(())
}
async fn process_event(&mut self, event: Event) {
let path = match self.partition_event(&event) {
Some(path) => path,
None => {
// We weren't able to find the path to use for the
// file.
// This is already logged at `partition_event`, so
// here we just skip the event.
return;
}
};
let next_deadline = self.deadline_at();
trace!(message = "Computed next deadline.", ?next_deadline, ?path);
let file = if let Some(file) = self.files.reset_at(&path, next_deadline) {
trace!(message = "Working with an already opened file.", ?path);
file
} else {
trace!(message = "Opening new file.", ?path);
let file = match open_file(BytesPath::new(path.clone())).await {
Ok(file) => file,
Err(error) => {
// We coundn't open the file for this event.
// Maybe other events will work though! Just log
// the error and skip this event.
error!(message = "Unable to open the file.", ?path, %error);
return;
}
};
self.files.insert_at(path.clone(), file, next_deadline);
self.files.get_mut(&path).unwrap()
};
trace!(message = "Writing an event to file.", ?path);
if let Err(error) = write_event_to_file(file, event, &self.encoding).await {
error!(message = "Failed to write file.", ?path, %error);
}
}
}
async fn open_file(path: impl AsRef<std::path::Path>) -> std::io::Result<File> {
let parent = path.as_ref().parent();
if let Some(parent) = parent {
fs::create_dir_all(parent).await?;
}
fs::OpenOptions::new()
.read(false)
.write(true)
.create(true)
.append(true)
.open(path)
.await
}
pub fn encode_event(encoding: &EncodingConfigWithDefault<Encoding>, mut event: Event) -> Vec<u8> {
encoding.apply_rules(&mut event);
let log = event.into_log();
match encoding.codec() {
Encoding::Ndjson => serde_json::to_vec(&log).expect("Unable to encode event as JSON."),
Encoding::Text => log
.get(&event::log_schema().message_key())
.map(|v| v.to_string_lossy().into_bytes())
.unwrap_or_default(),
}
}
async fn write_event_to_file(
file: &mut File,
event: Event,
encoding: &EncodingConfigWithDefault<Encoding>,
) -> Result<(), std::io::Error> {
let mut buf = encode_event(encoding, event);
buf.push(b'\n');
file.write_all(&buf[..]).await
}
#[async_trait]
impl StreamingSink for FileSink {
async fn run(
&mut self,
input: impl Stream<Item = Event> + Send + Sync + 'static,
) -> crate::Result<()> {
FileSink::run(self, input).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
event,
test_util::{
self, lines_from_file, random_events_with_stream, random_lines_with_stream, temp_dir,
temp_file,
},
};
use futures::stream;
use std::convert::TryInto;
#[test]
fn single_partition() {
test_util::trace_init();
let template = temp_file();
let config = FileSinkConfig {
path: template.clone().try_into().unwrap(),
idle_timeout_secs: None,
encoding: Encoding::Text.into(),
};
let mut sink = FileSink::new(&config);
let (input, _) = random_lines_with_stream(100, 64);
let events = stream::iter(input.clone().into_iter().map(Event::from));
let mut rt = crate::test_util::runtime();
let _ = rt
.block_on_std(async move { sink.run(events).await })
.unwrap();
let output = lines_from_file(template);
for (input, output) in input.into_iter().zip(output) {
assert_eq!(input, output);
}
}
#[test]
fn many_partitions() {
test_util::trace_init();
let directory = temp_dir();
let mut template = directory.to_string_lossy().to_string();
template.push_str("/{{level}}s-{{date}}.log");
trace!(message = "Template", %template);
let config = FileSinkConfig {
path: template.try_into().unwrap(),
idle_timeout_secs: None,
encoding: Encoding::Text.into(),
};
let mut sink = FileSink::new(&config);
let (mut input, _) = random_events_with_stream(32, 8);
input[0].as_mut_log().insert("date", "2019-26-07");
input[0].as_mut_log().insert("level", "warning");
input[1].as_mut_log().insert("date", "2019-26-07");
input[1].as_mut_log().insert("level", "error");
input[2].as_mut_log().insert("date", "2019-26-07");
input[2].as_mut_log().insert("level", "warning");
input[3].as_mut_log().insert("date", "2019-27-07");
input[3].as_mut_log().insert("level", "error");
input[4].as_mut_log().insert("date", "2019-27-07");
input[4].as_mut_log().insert("level", "warning");
input[5].as_mut_log().insert("date", "2019-27-07");
input[5].as_mut_log().insert("level", "warning");
input[6].as_mut_log().insert("date", "2019-28-07");
input[6].as_mut_log().insert("level", "warning");
input[7].as_mut_log().insert("date", "2019-29-07");
input[7].as_mut_log().insert("level", "error");
let events = stream::iter(input.clone().into_iter());
let mut rt = crate::test_util::runtime();
let _ = rt
.block_on_std(async move { sink.run(events).await })
.unwrap();
let output = vec![
lines_from_file(&directory.join("warnings-2019-26-07.log")),
lines_from_file(&directory.join("errors-2019-26-07.log")),
lines_from_file(&directory.join("warnings-2019-27-07.log")),
lines_from_file(&directory.join("errors-2019-27-07.log")),
lines_from_file(&directory.join("warnings-2019-28-07.log")),
lines_from_file(&directory.join("errors-2019-29-07.log")),
];
assert_eq!(
input[0].as_log()[&event::log_schema().message_key()],
From::<&str>::from(&output[0][0])
);
assert_eq!(
input[1].as_log()[&event::log_schema().message_key()],
From::<&str>::from(&output[1][0])
);
assert_eq!(
input[2].as_log()[&event::log_schema().message_key()],
From::<&str>::from(&output[0][1])
);
assert_eq!(
input[3].as_log()[&event::log_schema().message_key()],
From::<&str>::from(&output[3][0])
);
assert_eq!(
input[4].as_log()[&event::log_schema().message_key()],
From::<&str>::from(&output[2][0])
);
assert_eq!(
input[5].as_log()[&event::log_schema().message_key()],
From::<&str>::from(&output[2][1])
);
assert_eq!(
input[6].as_log()[&event::log_schema().message_key()],
From::<&str>::from(&output[4][0])
);
assert_eq!(
input[7].as_log()[&event::log_schema().message_key()],
From::<&str>::from(&output[5][0])
);
}
#[tokio::test]
async fn reopening() {
use pretty_assertions::assert_eq;
test_util::trace_init();
let template = temp_file();
let config = FileSinkConfig {
path: template.clone().try_into().unwrap(),
idle_timeout_secs: Some(1),
encoding: Encoding::Text.into(),
};
let mut sink = FileSink::new(&config);
let (mut input, _) = random_lines_with_stream(10, 64);
let (mut tx, rx) = tokio::sync::mpsc::channel(1);
let _ = tokio::spawn(async move { sink.run(rx).await });
// send initial payload
for line in input.clone() {
tx.send(Event::from(line)).await.unwrap();
}
// wait for file to go idle and be closed
tokio::time::delay_for(Duration::from_secs(2)).await;
// trigger another write
let last_line = "i should go at the end";
tx.send(Event::from(last_line)).await.unwrap();
input.push(String::from(last_line));
// wait for another flush
tokio::time::delay_for(Duration::from_secs(1)).await;
// make sure we appended instead of overwriting
let output = lines_from_file(template);
assert_eq!(input, output);
}
}
|
/*
* hurl (https://hurl.dev)
* Copyright (C) 2020 Orange
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
extern crate reqwest;
use std::fmt;
use serde::{Deserialize, Serialize};
pub enum Encoding {
Utf8,
Latin1,
}
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match self {
Encoding::Utf8 => "utf8",
Encoding::Latin1 => "iso8859-1"
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Url {
pub scheme: String,
pub host: String,
pub port: Option<u16>,
pub path: String,
pub query_string: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Header {
pub name: String,
pub value: String,
}
pub fn get_header_value(headers: Vec<Header>, name: &str) -> Option<String> {
for header in headers {
if header.name.as_str() == name {
return Some(header.value);
}
}
None
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Param {
pub name: String,
pub value: String,
}
pub fn encode_form_params(params: Vec<Param>) -> Vec<u8> {
params
.iter()
//.map(|p| format!("{}={}", p.name, utf8_percent_encode(p.value.as_str(), FRAGMENT)))
.map(|p| format!("{}={}", p.name, url_encode(p.value.clone())))
.collect::<Vec<_>>()
.join("&")
.into_bytes()
}
fn url_encode(s: String) -> String {
const MAX_CHAR_VAL: u32 = std::char::MAX as u32;
let mut buff = [0; 4];
s.chars()
.map(|ch| {
match ch as u32 {
0..=47 | 58..=64 | 91..=96 | 123..=MAX_CHAR_VAL => {
ch.encode_utf8(&mut buff);
buff[0..ch.len_utf8()].iter().map(|&byte| format!("%{:x}", byte)).collect::<String>()
}
_ => ch.to_string(),
}
})
.collect::<String>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encode_form_params() {
assert_eq!(
encode_form_params(vec![
Param {
name: String::from("param1"),
value: String::from("value1"),
},
Param {
name: String::from("param2"),
value: String::from(""),
}
]),
vec![
112, 97, 114, 97, 109, 49, 61, 118, 97, 108, 117, 101, 49, 38, 112, 97, 114, 97, 109,
50, 61
]
);
assert_eq!(
std::str::from_utf8(&encode_form_params(vec![
Param { name: String::from("param1"), value: String::from("value1") },
Param { name: String::from("param2"), value: String::from("") },
Param { name: String::from("param3"), value: String::from("a=b") },
Param { name: String::from("param4"), value: String::from("a%3db") },
])).unwrap(),
"param1=value1¶m2=¶m3=a%3db¶m4=a%253db"
);
}
}
|
use crate::memory::Memory;
pub struct ROM {
data: Vec<u8>,
}
impl ROM {
pub fn new(data: &[u8]) -> Self {
Self {
data: data.to_owned()
}
}
}
impl Memory for ROM {
#[inline]
fn get_u8(&self, addr: u16) -> u8 {
self.data[addr as usize]
}
#[inline]
fn set_u8(&mut self, _addr: u16, _value: u8) {
// DO NOTHING
}
}
|
use crate::Error;
use futures::FutureExt;
use std::{
cmp,
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use tokio::time::{delay_for, Delay};
use tower03::{retry::Policy, timeout::error::Elapsed};
pub enum RetryAction {
/// Indicate that this request should be retried with a reason
Retry(String),
/// Indicate that this request should not be retried with a reason
DontRetry(String),
/// Indicate that this request should not be retried but the request was successful
Successful,
}
pub trait RetryLogic: Clone {
type Error: std::error::Error + Send + Sync + 'static;
type Response;
fn is_retriable_error(&self, error: &Self::Error) -> bool;
fn should_retry_response(&self, _response: &Self::Response) -> RetryAction {
// Treat the default as the request is successful
RetryAction::Successful
}
}
#[derive(Debug, Clone)]
pub struct FixedRetryPolicy<L> {
remaining_attempts: usize,
previous_duration: Duration,
current_duration: Duration,
max_duration: Duration,
logic: L,
}
pub struct RetryPolicyFuture<L: RetryLogic> {
delay: Delay,
policy: FixedRetryPolicy<L>,
}
impl<L: RetryLogic> FixedRetryPolicy<L> {
pub fn new(
remaining_attempts: usize,
initial_backoff: Duration,
max_duration: Duration,
logic: L,
) -> Self {
FixedRetryPolicy {
remaining_attempts,
previous_duration: Duration::from_secs(0),
current_duration: initial_backoff,
max_duration,
logic,
}
}
fn advance(&self) -> FixedRetryPolicy<L> {
let next_duration: Duration = self.previous_duration + self.current_duration;
FixedRetryPolicy {
remaining_attempts: self.remaining_attempts - 1,
previous_duration: self.current_duration,
current_duration: cmp::min(next_duration, self.max_duration),
max_duration: self.max_duration,
logic: self.logic.clone(),
}
}
fn backoff(&self) -> Duration {
self.current_duration
}
fn build_retry(&self) -> RetryPolicyFuture<L> {
let policy = self.advance();
let delay = delay_for(self.backoff());
debug!(message = "retrying request.", delay_ms = %self.backoff().as_millis());
RetryPolicyFuture { delay, policy }
}
}
impl<Req, Res, L> Policy<Req, Res, Error> for FixedRetryPolicy<L>
where
Req: Clone,
L: RetryLogic<Response = Res>,
{
type Future = RetryPolicyFuture<L>;
fn retry(&self, _: &Req, result: Result<&Res, &Error>) -> Option<Self::Future> {
match result {
Ok(response) => {
if self.remaining_attempts == 0 {
error!("retries exhausted");
return None;
}
match self.logic.should_retry_response(response) {
RetryAction::Retry(reason) => {
warn!(message = "retrying after response.", %reason);
Some(self.build_retry())
}
RetryAction::DontRetry(reason) => {
warn!(message = "request is not retryable; dropping the request.", %reason);
None
}
RetryAction::Successful => None,
}
}
Err(error) => {
if self.remaining_attempts == 0 {
error!(message = "retries exhausted.", %error);
return None;
}
if let Some(expected) = error.downcast_ref::<L::Error>() {
if self.logic.is_retriable_error(expected) {
warn!("retrying after error: {}", expected);
Some(self.build_retry())
} else {
error!(message = "encountered non-retriable error.", %error);
None
}
} else if error.downcast_ref::<Elapsed>().is_some() {
warn!("request timedout.");
Some(self.build_retry())
} else {
warn!(message = "unexpected error type.", %error);
None
}
}
}
}
fn clone_request(&self, request: &Req) -> Option<Req> {
Some(request.clone())
}
}
// Safety: `L` is never pinned and we use no unsafe pin projections
// therefore this safe.
impl<L: RetryLogic> Unpin for RetryPolicyFuture<L> {}
impl<L: RetryLogic> Future for RetryPolicyFuture<L> {
type Output = FixedRetryPolicy<L>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
futures::ready!(self.delay.poll_unpin(cx));
Poll::Ready(self.policy.clone())
}
}
impl RetryAction {
pub fn is_retryable(&self) -> bool {
if let RetryAction::Retry(_) = &self {
true
} else {
false
}
}
pub fn is_not_retryable(&self) -> bool {
if let RetryAction::DontRetry(_) = &self {
true
} else {
false
}
}
pub fn is_successful(&self) -> bool {
if let RetryAction::Successful = &self {
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::trace_init;
use std::{fmt, time::Duration};
use tokio::time;
use tokio_test::{assert_pending, assert_ready_err, assert_ready_ok, task};
use tower03::retry::RetryLayer;
use tower_test03::{assert_request_eq, mock};
#[tokio::test]
async fn service_error_retry() {
time::pause();
trace_init();
let policy = FixedRetryPolicy::new(
5,
Duration::from_secs(1),
Duration::from_secs(10),
SvcRetryLogic,
);
let (mut svc, mut handle) = mock::spawn_layer(RetryLayer::new(policy));
assert_ready_ok!(svc.poll_ready());
let fut = svc.call("hello");
let mut fut = task::spawn(fut);
assert_request_eq!(handle, "hello").send_error(Error(true));
assert_pending!(fut.poll());
time::advance(Duration::from_secs(2)).await;
assert_pending!(fut.poll());
assert_request_eq!(handle, "hello").send_response("world");
assert_eq!(fut.await.unwrap(), "world");
}
#[tokio::test]
async fn service_error_no_retry() {
trace_init();
let policy = FixedRetryPolicy::new(
5,
Duration::from_secs(1),
Duration::from_secs(10),
SvcRetryLogic,
);
let (mut svc, mut handle) = mock::spawn_layer(RetryLayer::new(policy));
assert_ready_ok!(svc.poll_ready());
let mut fut = task::spawn(svc.call("hello"));
assert_request_eq!(handle, "hello").send_error(Error(false));
assert_ready_err!(fut.poll());
}
#[tokio::test]
async fn timeout_error() {
time::pause();
trace_init();
let policy = FixedRetryPolicy::new(
5,
Duration::from_secs(1),
Duration::from_secs(10),
SvcRetryLogic,
);
let (mut svc, mut handle) = mock::spawn_layer(RetryLayer::new(policy));
assert_ready_ok!(svc.poll_ready());
let mut fut = task::spawn(svc.call("hello"));
assert_request_eq!(handle, "hello").send_error(tower03::timeout::error::Elapsed::new());
assert_pending!(fut.poll());
time::advance(Duration::from_secs(2)).await;
assert_pending!(fut.poll());
assert_request_eq!(handle, "hello").send_response("world");
assert_eq!(fut.await.unwrap(), "world");
}
#[test]
fn backoff_grows_to_max() {
let mut policy = FixedRetryPolicy::new(
10,
Duration::from_secs(1),
Duration::from_secs(10),
SvcRetryLogic,
);
assert_eq!(Duration::from_secs(1), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(1), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(2), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(3), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(5), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(8), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(10), policy.backoff());
policy = policy.advance();
assert_eq!(Duration::from_secs(10), policy.backoff());
}
#[derive(Debug, Clone)]
struct SvcRetryLogic;
impl RetryLogic for SvcRetryLogic {
type Error = Error;
type Response = &'static str;
fn is_retriable_error(&self, error: &Self::Error) -> bool {
error.0
}
}
#[derive(Debug)]
struct Error(bool);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "error")
}
}
impl std::error::Error for Error {}
}
|
pub const MAP_WIDTH: usize = 80;
pub const MAP_HEIGHT: usize = 50;
pub const MAP_TOTAL_DIMENSION: usize = MAP_WIDTH * MAP_HEIGHT;
pub const COORDINATE_X: i32 = 79;
pub const COORDINATE_Y: i32 = 49;
pub const MAX_ROOMS: i32 = 30;
pub const MIN_SIZE_ROOM: i32 = 6;
pub const MAX_SIZE_ROOM: i32 = 10;
pub const VISIBLE_TILES_RANGE: i32 = 8;
|
#[doc = "Reader of register SRGPIO"]
pub type R = crate::R<u32, super::SRGPIO>;
#[doc = "Writer for register SRGPIO"]
pub type W = crate::W<u32, super::SRGPIO>;
#[doc = "Register SRGPIO `reset()`'s with value 0"]
impl crate::ResetValue for super::SRGPIO {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `R0`"]
pub type R0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R0`"]
pub struct R0_W<'a> {
w: &'a mut W,
}
impl<'a> R0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `R1`"]
pub type R1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R1`"]
pub struct R1_W<'a> {
w: &'a mut W,
}
impl<'a> R1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `R2`"]
pub type R2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R2`"]
pub struct R2_W<'a> {
w: &'a mut W,
}
impl<'a> R2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `R3`"]
pub type R3_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R3`"]
pub struct R3_W<'a> {
w: &'a mut W,
}
impl<'a> R3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `R4`"]
pub type R4_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R4`"]
pub struct R4_W<'a> {
w: &'a mut W,
}
impl<'a> R4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `R5`"]
pub type R5_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R5`"]
pub struct R5_W<'a> {
w: &'a mut W,
}
impl<'a> R5_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `R6`"]
pub type R6_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R6`"]
pub struct R6_W<'a> {
w: &'a mut W,
}
impl<'a> R6_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `R7`"]
pub type R7_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R7`"]
pub struct R7_W<'a> {
w: &'a mut W,
}
impl<'a> R7_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `R8`"]
pub type R8_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R8`"]
pub struct R8_W<'a> {
w: &'a mut W,
}
impl<'a> R8_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `R9`"]
pub type R9_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R9`"]
pub struct R9_W<'a> {
w: &'a mut W,
}
impl<'a> R9_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `R10`"]
pub type R10_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R10`"]
pub struct R10_W<'a> {
w: &'a mut W,
}
impl<'a> R10_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `R11`"]
pub type R11_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R11`"]
pub struct R11_W<'a> {
w: &'a mut W,
}
impl<'a> R11_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `R12`"]
pub type R12_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R12`"]
pub struct R12_W<'a> {
w: &'a mut W,
}
impl<'a> R12_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `R13`"]
pub type R13_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R13`"]
pub struct R13_W<'a> {
w: &'a mut W,
}
impl<'a> R13_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `R14`"]
pub type R14_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R14`"]
pub struct R14_W<'a> {
w: &'a mut W,
}
impl<'a> R14_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
impl R {
#[doc = "Bit 0 - GPIO Port A Software Reset"]
#[inline(always)]
pub fn r0(&self) -> R0_R {
R0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - GPIO Port B Software Reset"]
#[inline(always)]
pub fn r1(&self) -> R1_R {
R1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - GPIO Port C Software Reset"]
#[inline(always)]
pub fn r2(&self) -> R2_R {
R2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - GPIO Port D Software Reset"]
#[inline(always)]
pub fn r3(&self) -> R3_R {
R3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - GPIO Port E Software Reset"]
#[inline(always)]
pub fn r4(&self) -> R4_R {
R4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - GPIO Port F Software Reset"]
#[inline(always)]
pub fn r5(&self) -> R5_R {
R5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - GPIO Port G Software Reset"]
#[inline(always)]
pub fn r6(&self) -> R6_R {
R6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - GPIO Port H Software Reset"]
#[inline(always)]
pub fn r7(&self) -> R7_R {
R7_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - GPIO Port J Software Reset"]
#[inline(always)]
pub fn r8(&self) -> R8_R {
R8_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - GPIO Port K Software Reset"]
#[inline(always)]
pub fn r9(&self) -> R9_R {
R9_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - GPIO Port L Software Reset"]
#[inline(always)]
pub fn r10(&self) -> R10_R {
R10_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - GPIO Port M Software Reset"]
#[inline(always)]
pub fn r11(&self) -> R11_R {
R11_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - GPIO Port N Software Reset"]
#[inline(always)]
pub fn r12(&self) -> R12_R {
R12_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - GPIO Port P Software Reset"]
#[inline(always)]
pub fn r13(&self) -> R13_R {
R13_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - GPIO Port Q Software Reset"]
#[inline(always)]
pub fn r14(&self) -> R14_R {
R14_R::new(((self.bits >> 14) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - GPIO Port A Software Reset"]
#[inline(always)]
pub fn r0(&mut self) -> R0_W {
R0_W { w: self }
}
#[doc = "Bit 1 - GPIO Port B Software Reset"]
#[inline(always)]
pub fn r1(&mut self) -> R1_W {
R1_W { w: self }
}
#[doc = "Bit 2 - GPIO Port C Software Reset"]
#[inline(always)]
pub fn r2(&mut self) -> R2_W {
R2_W { w: self }
}
#[doc = "Bit 3 - GPIO Port D Software Reset"]
#[inline(always)]
pub fn r3(&mut self) -> R3_W {
R3_W { w: self }
}
#[doc = "Bit 4 - GPIO Port E Software Reset"]
#[inline(always)]
pub fn r4(&mut self) -> R4_W {
R4_W { w: self }
}
#[doc = "Bit 5 - GPIO Port F Software Reset"]
#[inline(always)]
pub fn r5(&mut self) -> R5_W {
R5_W { w: self }
}
#[doc = "Bit 6 - GPIO Port G Software Reset"]
#[inline(always)]
pub fn r6(&mut self) -> R6_W {
R6_W { w: self }
}
#[doc = "Bit 7 - GPIO Port H Software Reset"]
#[inline(always)]
pub fn r7(&mut self) -> R7_W {
R7_W { w: self }
}
#[doc = "Bit 8 - GPIO Port J Software Reset"]
#[inline(always)]
pub fn r8(&mut self) -> R8_W {
R8_W { w: self }
}
#[doc = "Bit 9 - GPIO Port K Software Reset"]
#[inline(always)]
pub fn r9(&mut self) -> R9_W {
R9_W { w: self }
}
#[doc = "Bit 10 - GPIO Port L Software Reset"]
#[inline(always)]
pub fn r10(&mut self) -> R10_W {
R10_W { w: self }
}
#[doc = "Bit 11 - GPIO Port M Software Reset"]
#[inline(always)]
pub fn r11(&mut self) -> R11_W {
R11_W { w: self }
}
#[doc = "Bit 12 - GPIO Port N Software Reset"]
#[inline(always)]
pub fn r12(&mut self) -> R12_W {
R12_W { w: self }
}
#[doc = "Bit 13 - GPIO Port P Software Reset"]
#[inline(always)]
pub fn r13(&mut self) -> R13_W {
R13_W { w: self }
}
#[doc = "Bit 14 - GPIO Port Q Software Reset"]
#[inline(always)]
pub fn r14(&mut self) -> R14_W {
R14_W { w: self }
}
}
|
use std::io::Read;
fn read<T: std::str::FromStr>() -> T {
let token: String = std::io::stdin()
.bytes()
.map(|c| c.ok().unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().unwrap()
}
fn main() {
let ha: i32 = read();
let hb: i32 = read();
let hc: i32 = read();
let mut v = vec![(ha, 'A'), (hb, 'B'), (hc, 'C')];
v.sort_by(|x, y| y.0.cmp(&x.0));
v.iter().map(|(_, c)| c).for_each(|c| println!("{}", c));
}
|
// https://leetcode-cn.com/problems/maximal-rectangle/
// 解法 https://segmentfault.com/a/1190000003498304
pub struct Solution {}
mod q84;
impl Solution {
pub fn maximal_rectangle(matrix: Vec<Vec<char>>) -> i32 {
let mut result = 0;
let y_len = matrix.first().unwrap_or(&vec![]).len();
matrix.iter().enumerate().for_each(|(idx, arr)| {
let mut heights: Vec<i32> = vec![0; y_len];
arr.iter().enumerate().for_each(|(idy, _)| {
for i in (0..=idx).rev() {
if matrix[i][idy] == '0' {
break;
} else {
heights[idy] += 1;
};
}
});
result = q84::Solution::largest_rectangle_area(heights).max(result);
});
return result;
}
}
fn main() {
let matrix = vec![
vec!['1', '0', '1', '0', '0'],
vec!['1', '0', '1', '1', '1'],
vec!['1', '1', '1', '1', '1'],
vec!['1', '0', '0', '1', '0'],
];
let res = Solution::maximal_rectangle(matrix);
println!("{}", res);
}
|
use super::parse::AST;
use super::parse::Node;
use super::parse::Operator;
use super::parse::Leaf;
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Value {
Register(usize),
Immediate(i32),
Label(usize),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Statement {
pub op: Operator,
pub ret: Option<usize>,
pub args: Vec<Value>
}
#[derive(Debug, Clone, PartialEq)]
pub struct BasicBlock {
pub statements: Vec<Statement>,
pub nexts: Vec<usize>
}
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
pub name: String,
pub args: Vec<String>,
pub retnum: usize,
pub basicblocks: Vec<BasicBlock>
}
#[derive(Debug, Clone, PartialEq)]
pub struct Program {
pub funcs: HashMap<String, Function>
}
fn expression(ast: &AST, program: &Program,
vars: &HashMap<String, usize>, statements: &mut Vec<Statement>,
regcount: usize)
-> Option<Value> {
match ast {
AST::Node(node) => {
match node.op {
Operator::Call{name:ref funcname} => {
match program.funcs.get(funcname) {
Some(func) => {
if node.children.len() != func.args.len() {
println!("Function {} expected {} args, but {} provided",
funcname, func.args.len(), node.children.len());
return None;
}
}
None => {
println!("Undefined function {}", funcname);
}
}
}
Operator::Add => {
if node.children.len() != 2 {
println!("Add operation take 2 args, but {} provided",
node.children.len());
return None;
}
}
Operator::Sub => {
if node.children.len() != 2 {
println!("Sub operation take 2 args, but {} provided",
node.children.len());
return None;
}
}
Operator::Multiply => {
if node.children.len() != 2 {
println!("Multiply operation take 2 args, but {} provided",
node.children.len());
return None;
}
}
Operator::Division => {
if node.children.len() != 2 {
println!("Division operation take 2 args, but {} provided",
node.children.len());
return None;
}
}
Operator::Modulo => {
if node.children.len() != 2 {
println!("Modulo operation take 2 args, but {} provided",
node.children.len());
return None;
}
}
Operator::LessThan => {
if node.children.len() != 2 {
println!("LessThan operation take 2 args, but {} provided",
node.children.len());
return None;
}
}
Operator::Greater => {
if node.children.len() != 2 {
println!("Greater operation take 2 args, but {} provided",
node.children.len());
return None;
}
}
Operator::Equal => {
if node.children.len() != 2 {
println!("Equal operation take 2 args, but {} provided",
node.children.len());
return None;
}
}
_ => {
println!("Unsupported operation {:?}", node.op);
return None
}
}
let mut id_vec = Vec::new();
for child in &node.children {
let id = expression(&child, program, vars, statements, regcount)?;
id_vec.push(id);
}
let id = statements.len() + regcount;
statements.push(Statement {
op: node.op.clone(),
ret: Some(id),
args: id_vec
});
Some(Value::Register(id))
}
AST::Leaf(leaf) => {
match leaf {
Leaf::Identifier(name) => {
match vars.get(name) {
Some(id) => {
Some(Value::Register(*id))
}
None => {
println!("Undefined variable {}", name);
None
}
}
}
Leaf::Constant(imm) => {
Some(Value::Immediate(*imm))
}
}
}
}
}
fn substitute(children: &Vec<AST>, program: &Program,
vars: &mut HashMap<String, usize>,
statements: &mut Vec<Statement>, regcount: usize)
-> Option<Value> {
match &children[0] {
AST::Leaf(leaf) => {
match leaf {
Leaf::Identifier(lhs) => {
if vars.contains_key(lhs) {
println!("Variable {} is already defined.", lhs);
return None;
}
let exp_id = expression(&children[1], program, vars,
statements, regcount)?;
let id = statements.len() + regcount;
statements.push(Statement {
op: Operator::Substitute,
ret: Some(id),
args: vec![exp_id; 1]
});
vars.insert(lhs.to_string(), id);
Some(Value::Register(id))
}
Leaf::Constant(constant) => {
println!("Unexpected constant {}, expected identifier", constant);
None
}
}
}
AST::Node(_node) => {
println!("Unexpected Node, expected identifier or constant");
None
}
}
}
fn call(name: &str, children: &Vec<AST>, program: &Program,
vars: &HashMap<String, usize>, statements: &mut Vec<Statement>,
regcount: usize)
-> Option<Value> {
match program.funcs.get(name) {
Some(func) => {
if func.args.len() != children.len() {
println!("Function {}: expected {} args, but {} provided",
name, func.args.len(), children.len());
return None;
}
let mut id_vec = Vec::new();
for child in children {
let id = expression(child, program, vars, statements,
regcount)?;
id_vec.push(id);
}
let id = statements.len();
statements.push(Statement {
op: Operator::Call{name:name.to_string()},
ret: Some(id),
args: id_vec
});
Some(Value::Register(id))
}
None => {
println!("Function {} is not defined.", name);
None
}
}
}
fn if_op(children: &Vec<AST>, program: &Program,
vars: &mut HashMap<String, usize>, basicblocks: &mut Vec<BasicBlock>,
regcount: usize) -> bool {
if children.len() < 2 {
println!("If need 2 or 3 children");
return false;
}
let id = match expression(&children[0], program, vars,
&mut basicblocks.last_mut().unwrap().statements,
regcount) {
Some(id) => id,
None => {
println!("Invalid expression");
return false
}
};
let newregcount = regcount + basicblocks.last().unwrap().statements.len();
let index = match statement(&children[1], program, vars, newregcount) {
Some(vb) => {
basicblocks.last_mut().unwrap().statements.push(Statement {
op: Operator::If,
ret: None,
args: vec![id]
});
let offset = basicblocks.len();
basicblocks.last_mut().unwrap().nexts.push(offset);
for b in vb {
let mut nexts = Vec::new();
for bid in b.nexts {
nexts.push(bid + offset);
}
basicblocks.push(BasicBlock {
statements: b.statements,
nexts
});
}
let jump_to = basicblocks.len();
basicblocks.get_mut(offset-1).unwrap().nexts.push(jump_to);
basicblocks.len() - 1
}
None => {
println!("Invalid statements");
println!("{:?}", children[1]);
return false
}
};
if children.len() == 3 {
match statement(&children[2], program, vars, newregcount) {
Some(vb) => {
basicblocks.last_mut().unwrap().statements.push(Statement {
op: Operator::Jump,
ret: None,
args: Vec::new()
});
let offset = basicblocks.len();
for b in vb {
let mut nexts = Vec::new();
for bid in b.nexts {
nexts.push(bid + offset);
}
basicblocks.push(BasicBlock {
statements: b.statements,
nexts
});
}
let jump_to = basicblocks.len();
basicblocks.get_mut(offset-1).unwrap().nexts.push(jump_to);
}
None => {
println!("Invalid statements");
return false
}
}
}
let jump_to = basicblocks.len();
basicblocks.last_mut().unwrap().nexts.push(jump_to);
basicblocks.push(BasicBlock {
statements: Vec::new(),
nexts: Vec::new()
});
true
}
fn return_op(children: &Vec<AST>, program: &Program,
vars: &mut HashMap<String, usize>, statements: &mut Vec<Statement>,
regcount: usize) -> bool {
let mut vec_id = Vec::new();
for child in children {
let id = match expression(child, program, vars,
statements, regcount) {
Some(id) => id,
None => {
println!("Invalid expression");
return false
}
};
vec_id.push(id);
}
statements.push(Statement {
op: Operator::Return,
ret: None,
args: vec_id
});
true
}
fn statement_impl(ast: &AST, program: &Program,
vars: &mut HashMap<String, usize>,
basicblocks: &mut Vec<BasicBlock>, regcount: usize)
-> bool {
match ast {
AST::Node(node) => {
match node.op {
Operator::Substitute => {
substitute(&node.children, program, vars,
&mut basicblocks.last_mut().unwrap().statements,
regcount).is_some()
}
Operator::Call{ref name} => {
call(&name, &node.children, program, vars,
&mut basicblocks.last_mut().unwrap().statements,
regcount).is_some()
}
Operator::If => {
if_op(&node.children, program, vars, basicblocks, regcount)
}
Operator::Return => {
return_op(&node.children, program, vars,
&mut basicblocks.last_mut().unwrap().statements,
regcount)
}
_ => {
println!("Unknwon operator: {:?}", node.op);
false
}
}
}
AST::Leaf(_leaf) => {
println!("Invalid identifier or constant");
false
}
}
}
fn statement(ast: &AST, program: &Program,
vars: &mut HashMap<String, usize>, regcount: usize)
-> Option<Vec<BasicBlock>> {
let mut basicblocks = vec![BasicBlock {
statements: Vec::new(),
nexts: Vec::new()
}];
match ast {
AST::Node(node) => {
match node.op {
Operator::Statement => {
for child in &node.children {
if !statement_impl(&child, program, vars, &mut basicblocks, regcount) {
return None;
}
}
Some(basicblocks)
}
_ => {
println!("Unexpected operator: {:?}, expected Statement", node.op);
None
}
}
}
AST::Leaf(_leaf) => {
println!("Invalid identifier or constant");
None
}
}
}
fn pre_declare_function(node: &Node, program: &Program) -> Option<Function> {
match node.op {
Operator::FunctionDeclare{ref name, ref args, retnum} => {
Some(Function { name: name.to_string(), args: args.to_vec(), retnum, basicblocks: Vec::new() })
}
_ => {
println!("Unexpected operator: {:?}, expected FunctionDeclare", node.op);
None
}
}
}
fn function(node: &Node, program: &Program) -> Option<Function> {
match node.op {
Operator::FunctionDeclare{ref name, ref args, retnum} => {
let mut vars = HashMap::<String, usize>::new();
for (i, arg) in args.iter().enumerate() {
vars.insert(arg.to_string(), i);
}
let regcount = args.len();
match statement(&node.children[0], program, &mut vars, regcount) {
Some(mut basicblocks) => {
if retnum == 0 && name != "main" {
basicblocks.last_mut().unwrap().statements.push(Statement {
op: Operator::Return,
ret: None,
args: Vec::new()
});
}
Some(Function { name: name.to_string(), args: args.to_vec(), retnum, basicblocks })
}
None => {
println!("Invalid statements");
None
}
}
}
_ => {
println!("Unexpected operator: {:?}, expected FunctionDeclare", node.op);
None
}
}
}
fn pre_declare(ast: &AST, program: &mut Program) -> bool {
match ast {
AST::Node(node) => {
match pre_declare_function(node, program) {
Some(func) => {
program.funcs.insert(func.name.clone(), func);
true
}
None => {
println!("Invalid function declare");
false
}
}
}
AST::Leaf(_leaf) => {
println!("Invalid identifier or constant");
false
}
}
}
fn declare(ast: &AST, program: &mut Program) -> bool {
match ast {
AST::Node(node) => {
match function(node, program) {
Some(func) => {
program.funcs.insert(func.name.clone(), func);
true
}
None => {
println!("Invalid function declare");
false
}
}
}
AST::Leaf(_leaf) => {
println!("Invalid identifier or constant");
false
}
}
}
impl Program {
fn new() -> Program {
let getnum = Function {
name: "getnum".to_string(),
args: Vec::new(),
retnum: 1,
basicblocks: Vec::new()
};
let getchar = Function {
name: "getchar".to_string(),
args: Vec::new(),
retnum: 1,
basicblocks: Vec::new()
};
let putnum = Function {
name: "putnum".to_string(),
args: vec!["x".to_string()],
retnum: 0,
basicblocks: Vec::new()
};
let putchar = Function {
name: "putchar".to_string(),
args: vec!["x".to_string()],
retnum: 0,
basicblocks: Vec::new()
};
let halt = Function {
name: "halt".to_string(),
args: Vec::new(),
retnum: 0,
basicblocks: Vec::new()
};
let mut funcs = HashMap::<String, Function>::new();
funcs.insert(getnum.name.clone(), getnum);
funcs.insert(getchar.name.clone(), getchar);
funcs.insert(putnum.name.clone(), putnum);
funcs.insert(putchar.name.clone(), putchar);
funcs.insert(halt.name.clone(), halt);
Program { funcs }
}
}
pub fn generate(ast: &AST) -> Option<Program> {
let mut program = Program::new();
match ast {
AST::Node(node) => {
match node.op {
Operator::Declare => {
for child in &node.children {
if !pre_declare(child, &mut program) {
return None;
}
}
for child in &node.children {
if !declare(child, &mut program) {
return None;
}
}
Some(program)
}
_ => {
println!("Unexpected operator {:?}, expected Declare", node.op);
None
}
}
}
AST::Leaf(_leaf) => {
println!("Invalid identifier or constant");
None
}
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Access control register"]
pub acr: ACR,
#[doc = "0x04 - Program/erase control register"]
pub pecr: PECR,
#[doc = "0x08 - Power down key register"]
pub pdkeyr: PDKEYR,
#[doc = "0x0c - Program/erase key register"]
pub pekeyr: PEKEYR,
#[doc = "0x10 - Program memory key register"]
pub prgkeyr: PRGKEYR,
#[doc = "0x14 - Option byte key register"]
pub optkeyr: OPTKEYR,
#[doc = "0x18 - Status register"]
pub sr: SR,
#[doc = "0x1c - Option byte register"]
pub optr: OPTR,
#[doc = "0x20 - Write Protection Register 1"]
pub wrprot1: WRPROT1,
_reserved9: [u8; 92usize],
#[doc = "0x80 - Write Protection Register 2"]
pub wrprot2: WRPROT2,
}
#[doc = "Access control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [acr](acr) module"]
pub type ACR = crate::Reg<u32, _ACR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ACR;
#[doc = "`read()` method returns [acr::R](acr::R) reader structure"]
impl crate::Readable for ACR {}
#[doc = "`write(|w| ..)` method takes [acr::W](acr::W) writer structure"]
impl crate::Writable for ACR {}
#[doc = "Access control register"]
pub mod acr;
#[doc = "Program/erase control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pecr](pecr) module"]
pub type PECR = crate::Reg<u32, _PECR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PECR;
#[doc = "`read()` method returns [pecr::R](pecr::R) reader structure"]
impl crate::Readable for PECR {}
#[doc = "`write(|w| ..)` method takes [pecr::W](pecr::W) writer structure"]
impl crate::Writable for PECR {}
#[doc = "Program/erase control register"]
pub mod pecr;
#[doc = "Power down key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pdkeyr](pdkeyr) module"]
pub type PDKEYR = crate::Reg<u32, _PDKEYR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PDKEYR;
#[doc = "`write(|w| ..)` method takes [pdkeyr::W](pdkeyr::W) writer structure"]
impl crate::Writable for PDKEYR {}
#[doc = "Power down key register"]
pub mod pdkeyr;
#[doc = "Program/erase key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pekeyr](pekeyr) module"]
pub type PEKEYR = crate::Reg<u32, _PEKEYR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PEKEYR;
#[doc = "`write(|w| ..)` method takes [pekeyr::W](pekeyr::W) writer structure"]
impl crate::Writable for PEKEYR {}
#[doc = "Program/erase key register"]
pub mod pekeyr;
#[doc = "Program memory key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [prgkeyr](prgkeyr) module"]
pub type PRGKEYR = crate::Reg<u32, _PRGKEYR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PRGKEYR;
#[doc = "`write(|w| ..)` method takes [prgkeyr::W](prgkeyr::W) writer structure"]
impl crate::Writable for PRGKEYR {}
#[doc = "Program memory key register"]
pub mod prgkeyr;
#[doc = "Option byte key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optkeyr](optkeyr) module"]
pub type OPTKEYR = crate::Reg<u32, _OPTKEYR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTKEYR;
#[doc = "`write(|w| ..)` method takes [optkeyr::W](optkeyr::W) writer structure"]
impl crate::Writable for OPTKEYR {}
#[doc = "Option byte key register"]
pub mod optkeyr;
#[doc = "Status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sr](sr) module"]
pub type SR = crate::Reg<u32, _SR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SR;
#[doc = "`read()` method returns [sr::R](sr::R) reader structure"]
impl crate::Readable for SR {}
#[doc = "`write(|w| ..)` method takes [sr::W](sr::W) writer structure"]
impl crate::Writable for SR {}
#[doc = "Status register"]
pub mod sr;
#[doc = "Option byte register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optr](optr) module"]
pub type OPTR = crate::Reg<u32, _OPTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTR;
#[doc = "`read()` method returns [optr::R](optr::R) reader structure"]
impl crate::Readable for OPTR {}
#[doc = "Option byte register"]
pub mod optr;
#[doc = "Write Protection Register 1\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wrprot1](wrprot1) module"]
pub type WRPROT1 = crate::Reg<u32, _WRPROT1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WRPROT1;
#[doc = "`read()` method returns [wrprot1::R](wrprot1::R) reader structure"]
impl crate::Readable for WRPROT1 {}
#[doc = "Write Protection Register 1"]
pub mod wrprot1;
#[doc = "Write Protection Register 2\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wrprot2](wrprot2) module"]
pub type WRPROT2 = crate::Reg<u32, _WRPROT2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WRPROT2;
#[doc = "`read()` method returns [wrprot2::R](wrprot2::R) reader structure"]
impl crate::Readable for WRPROT2 {}
#[doc = "Write Protection Register 2"]
pub mod wrprot2;
|
use super::Visibility;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
pub struct UpdateEvent {
/// Whether the user has the overlay enabled or disabled. If the overlay
/// is disabled, all the functionality of the SDK will still work. The
/// calls will instead focus the Discord client and show the modal there
/// instead of in application.
pub enabled: bool,
/// Whether the overlay is visible or not.
#[serde(rename = "locked")]
pub visible: Visibility,
}
#[derive(Debug)]
pub enum OverlayEvent {
Update(UpdateEvent),
}
|
#![crate_id(name="cksum", vers="1.0.0", author="Michael Gehring")]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
use std::io::{BufferedReader, EndOfFile, File, IoError, IoResult, print};
use std::io::stdio::stdin;
#[path="../common/util.rs"]
mod util;
static NAME : &'static str = "cksum";
static VERSION : &'static str = "1.0.0";
fn crc_update(mut crc: u32, input: u8) -> u32 {
crc ^= input as u32 << 24;
for _ in range(0u, 8) {
if crc & 0x80000000 != 0 {
crc <<= 1;
crc ^= 0x04c11db7;
} else {
crc <<= 1;
}
}
crc
}
fn crc_final(mut crc: u32, mut length: uint) -> u32 {
while length != 0 {
crc = crc_update(crc, length as u8);
length >>= 8;
}
!crc
}
fn cksum(fname: &str) -> IoResult<(u32, uint)> {
let mut crc = 0u32;
let mut size = 0u;
let mut rd = try!(open_file(fname));
loop {
match rd.read_byte() {
Ok(b) => {
crc = crc_update(crc, b);
size += 1;
}
Err(err) => {
return match err {
IoError{kind: k, ..} if k == EndOfFile => Ok((crc_final(crc, size), size)),
_ => Err(err),
}
}
}
}
}
fn open_file(name: &str) -> IoResult<Box<Reader>> {
match name {
"-" => Ok(box stdin() as Box<Reader>),
_ => {
let f = try!(File::open(&Path::new(name)));
Ok(box BufferedReader::new(f) as Box<Reader>)
}
}
}
pub fn uumain(args: Vec<String>) -> int {
let opts = [
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) => m,
Err(err) => fail!("{}", err),
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS] [FILE]...", NAME);
println!("");
print(getopts::usage("Print CRC and size for each file.", opts.as_slice()).as_slice());
return 0;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
let files = matches.free;
if files.is_empty() {
match cksum("-") {
Ok((crc, size)) => println!("{} {}", crc, size),
Err(err) => {
show_error!("{}", err);
return 2;
}
}
return 0;
}
let mut exit_code = 0;
for fname in files.iter() {
match cksum(fname.as_slice()) {
Ok((crc, size)) => println!("{} {} {}", crc, size, fname),
Err(err) => {
show_error!("'{}' {}", fname, err);
exit_code = 2;
}
}
}
exit_code
}
|
use crate::dto::Link;
use std::collections::HashMap;
use quick_xml::Reader;
use quick_xml::events::Event;
use crate::parser::ParsingState::{Skipping, ReadingSnippet, ReadingTitle, ReadingPaging};
use std::io::BufReader;
use std::convert::TryFrom;
use std::borrow::Cow;
pub struct Html<'a>(pub &'a [u8]);
#[derive(Default)]
pub struct Links {
pub links: Vec<Link>,
pub paging: Option<Paging>,
}
#[derive(Debug, Default, PartialEq)]
pub struct Paging {
pub s: i32,
pub dc: i32,
}
#[derive(Debug, PartialEq)]
enum ParsingState {
Skipping,
ReadingTitle,
ReadingSnippet,
ReadingPaging { paging: Paging },
}
impl<'a> TryFrom<Html<'a>> for Links {
type Error = String;
fn try_from(html: Html<'a>) -> Result<Self, Self::Error> {
let mut links = vec![];
let mut reader = Reader::from_reader(BufReader::new(html.0));
reader.check_end_names(false); // to support unclosed tags like <br>
reader.expand_empty_elements(true); // to support self-closing tags like <input>
let mut state = Skipping;
let mut url = None;
let mut title = String::with_capacity(75);
let mut snippet = String::with_capacity(400);
//FIXME restrict buffer length (with BufReader buffer capacity?)
let mut buf = Vec::new();
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => {
let tag_name = reader.decode(e.local_name());
// all needed information is in <a> and <input> tags
if !(tag_name == "a" || tag_name == "input") {
continue;
}
let attrs: HashMap<Cow<str>, String> = e.attributes()
.filter_map(|attr| {
attr.ok().and_then(|a| {
let key = reader.decode(a.key);
let value = reader.decode(a.value.as_ref());
//FIXME how do I not allocate here?
Some((key, (*value).to_owned()))
})
}).collect();
if let Some(c) = attrs.get("class") {
match c.as_ref() {
"result__a" => {
url = attrs.get("href").cloned();
state = ReadingTitle;
}
"result__snippet" => {
state = ReadingSnippet;
}
_ => {}
}
}
// parse paging info
if tag_name == "input" {
let type_and_value =
(attrs.get("type").map(String::as_str),
attrs.get("value").map(String::as_str));
if let (Some("submit"), Some("Next")) = type_and_value {
state = ReadingPaging {
paging: Paging { s: 0, dc: 0 }
}
};
if let Some(n) = attrs.get("name") {
// assuming the input fields are always in the same order
match n.as_ref() {
"s" => {
let value = attrs
.get("value")
.ok_or_else(|| "No value")?
.parse()
.map_err(|_| "Can't parse [input.name=\"s\"] value")?;
if let ReadingPaging { ref mut paging } = state {
paging.s = value;
};
}
"dc" => {
let value = attrs
.get("value")
.ok_or_else(|| "No value")?
.parse()
.map_err(|_| "Can't parse [input.name=\"dc\"] value")?;
if let ReadingPaging { ref mut paging } = state {
paging.dc = value;
}
}
_ => {}
};
}
}
}
// title and snippet may be split into multiple tags (e.g. <b>)
Ok(Event::Text(ref bytes)) if state == ReadingTitle => {
let next_part = reader.decode(bytes);
title.push_str(next_part.as_ref());
}
Ok(Event::Text(ref bytes)) if state == ReadingSnippet => {
let next_part = reader.decode(bytes);
snippet.push_str(next_part.as_ref());
}
Ok(Event::End(ref e)) => {
let tag_name = reader.decode(e.local_name());
if "a" == tag_name.as_ref() {
if state == ReadingSnippet {
links.push(Link {
//TODO should I clone?
url: url.clone().unwrap(),
title: title.clone(),
snippet: snippet.clone(),
});
url = None;
title = String::with_capacity(75);
snippet = String::with_capacity(400);
}
state = Skipping;
}
}
Ok(Event::Eof) => break,//TODO I can stop parsing way earlier than EOF
_ => {}
}
}
let paging = match state {
ReadingPaging { paging } => Some(paging),
_ => None
};
//TODO produce Err if this is not a valid results page
Ok(Links {
links: links.to_owned(),
paging,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_no_links() {
let html = Html(
br#"
<div class="results">
</div>
"#
);
let links = Links::try_from(html).unwrap().links;
assert_eq!(0, links.len())
}
#[test]
fn parses_one_link() {
let html = Html(
br#"
<div class="results">
<div class="result">
<a class="result__a" href="https://link.com">Link</a>
<a class="result__snippet">Snippet</a>
</div>
</div>
"#
);
let links = Links::try_from(html).unwrap().links;
assert_eq!(1, links.len());
let link = links.first().unwrap();
assert_eq!("Link", link.title);
assert_eq!("https://link.com", link.url);
assert_eq!("Snippet", link.snippet);
}
#[test]
fn parses_multiple_links() {
let html = Html(
br#"
<div class="results">
<div class="result">
<a class="result__a" href="https://link1.com">Link 1</a>
<a class="result__snippet">Snippet 1</a>
</div>
<div class="result">
<a class="result__a" href="https://link2.com">Link 2</a>
<a class="result__snippet">Snippet 2</a>
</div>
</div>
"#
);
let links = Links::try_from(html).unwrap().links;
assert_eq!(2, links.len());
let link1 = &links[0];
assert_eq!("Link 1", link1.title);
assert_eq!("https://link1.com", link1.url);
assert_eq!("Snippet 1", link1.snippet);
let link2 = &links[1];
assert_eq!("Link 2", link2.title);
assert_eq!("https://link2.com", link2.url);
assert_eq!("Snippet 2", link2.snippet);
}
#[test]
fn handles_inner_snippet_tags() {
let html = Html(
br#"
<div class="results">
<div class="result">
<a class="result__a" href="https://link.com">Link</a>
<a class="result__snippet">A <b>snippet</b> with some inner tags</a>
</div>
</div>
"#
);
let links = Links::try_from(html).unwrap().links;
assert_eq!(1, links.len());
//TODO add assertions after designing the handling of the bold text
}
#[test]
fn parses_next_paging() {
let html = Html(
br#"
<div class="results">
<div class="result">
<a class="result__a" href="https://link.com">Link</a>
<a class="result__snippet">A <b>snippet</b> with some inner tags</a>
</div>
<div class="nav-link">
<input type="submit" value="Next">
<input type="hidden" name="q" value="test">
<input type="hidden" name="s" value="30">
<input type="hidden" name="dc" value="29">
</div>
</div>
"#
);
let paging = Links::try_from(html).unwrap().paging.unwrap();
assert_eq!(30, paging.s);
assert_eq!(29, paging.dc);
}
#[test]
fn parses_prev_and_next_paging() {
let html = Html(
br#"
<div class="results">
<div class="result">
<a class="result__a" href="https://link.com">Link</a>
<a class="result__snippet">A <b>snippet</b> with some inner tags</a>
</div>
<div class="nav-link">
<input type="submit" value="Previous">
<input type="hidden" name="q" value="test">
<input type="hidden" name="s" value="0">
<input type="hidden" name="dc" value="-31">
</div>
<div class="nav-link">
<input type="submit" value="Next">
<input type="hidden" name="q" value="test">
<input type="hidden" name="s" value="80">
<input type="hidden" name="dc" value="79">
</div>
</div>
"#
);
let paging = Links::try_from(html).unwrap().paging.unwrap();
assert_eq!(80, paging.s);
assert_eq!(79, paging.dc);
}
#[test]
fn parses_no_paging_from_the_last_page() {
let html = Html(
br#"
<div class="results">
<div class="result">
<a class="result__a" href="https://link.com">Link</a>
<a class="result__snippet">A <b>snippet</b> with some inner tags</a>
</div>
<div class="nav-link">
<input type="submit" value="Previous">
<input type="hidden" name="q" value="test">
<input type="hidden" name="s" value="0">
<input type="hidden" name="dc" value="-31">
</div>
</div>
"#
);
let paging = Links::try_from(html).unwrap().paging;
assert_eq!(None, paging);
}
}
|
use cgmath::{
BaseFloat, EuclideanSpace, InnerSpace, Matrix3, Point2, Point3, SquareMatrix, Transform,
Vector3, Zero,
};
use collision::primitive::*;
use collision::{Aabb, Aabb2, Aabb3, Bound, ComputeBound, Primitive, Union};
use super::{Inertia, Mass, Material, PartialCrossProduct};
use collide::CollisionShape;
/// Describe a shape with volume
///
/// ### Type parameters:
///
/// - `I`: Inertia type, see `Inertia` for more information
pub trait Volume<S, I> {
/// Compute the mass of the shape based on its material
fn get_mass(&self, material: &Material) -> Mass<S, I>;
}
impl<S> Volume<S, S> for Circle<S>
where
S: BaseFloat + Inertia,
{
fn get_mass(&self, material: &Material) -> Mass<S, S> {
use std::f64::consts::PI;
let pi = S::from(PI).unwrap();
let mass = pi * self.radius * self.radius * material.density();
let inertia = mass * self.radius * self.radius / (S::one() + S::one());
Mass::new_with_inertia(mass, inertia)
}
}
impl<S> Volume<S, S> for Rectangle<S>
where
S: BaseFloat + Inertia,
{
fn get_mass(&self, material: &Material) -> Mass<S, S> {
let b: Aabb2<S> = self.compute_bound();
let mass = b.volume() * material.density();
let inertia =
mass * (b.dim().x * b.dim().x + b.dim().y * b.dim().y) / S::from(12.).unwrap();
Mass::new_with_inertia(mass, inertia)
}
}
impl<S> Volume<S, S> for Square<S>
where
S: BaseFloat + Inertia,
{
fn get_mass(&self, material: &Material) -> Mass<S, S> {
let b: Aabb2<S> = self.compute_bound();
let mass = b.volume() * material.density();
let inertia =
mass * (b.dim().x * b.dim().x + b.dim().y * b.dim().y) / S::from(12.).unwrap();
Mass::new_with_inertia(mass, inertia)
}
}
impl<S> Volume<S, S> for ConvexPolygon<S>
where
S: BaseFloat + Inertia,
{
fn get_mass(&self, material: &Material) -> Mass<S, S> {
let mut area = S::zero();
let mut denom = S::zero();
for i in 0..self.vertices.len() {
let j = if i == self.vertices.len() - 1 {
0
} else {
i + 1
};
let p0 = self.vertices[i].to_vec();
let p1 = self.vertices[j].to_vec();
let a = p0.cross(&p1).abs();
let b = p0.dot(p0) + p0.dot(p1) + p1.dot(p1);
denom += a * b;
area += a;
}
let mass = area * S::from(0.5).unwrap() * material.density();
let inertia = mass / S::from(6.).unwrap() * denom / area;
Mass::new_with_inertia(mass, inertia)
}
}
impl<S> Volume<S, Matrix3<S>> for Sphere<S>
where
S: BaseFloat,
{
fn get_mass(&self, material: &Material) -> Mass<S, Matrix3<S>> {
use std::f64::consts::PI;
let pi = S::from(PI).unwrap();
let mass = S::from(4. / 3.).unwrap()
* pi
* self.radius
* self.radius
* self.radius
* material.density();
let inertia = S::from(2. / 5.).unwrap() * mass * self.radius * self.radius;
Mass::new_with_inertia(mass, Matrix3::from_value(inertia))
}
}
impl<S> Volume<S, Matrix3<S>> for Cuboid<S>
where
S: BaseFloat,
{
fn get_mass(&self, material: &Material) -> Mass<S, Matrix3<S>> {
let b: Aabb3<S> = self.compute_bound();
let mass = b.volume() * material.density();
let x2 = b.dim().x * b.dim().x;
let y2 = b.dim().y * b.dim().y;
let z2 = b.dim().z * b.dim().z;
let mnorm = mass / S::from(12.).unwrap();
let inertia = Matrix3::from_diagonal(Vector3::new(y2 + z2, x2 + z2, x2 + y2) * mnorm);
Mass::new_with_inertia(mass, inertia)
}
}
impl<S> Volume<S, Matrix3<S>> for Cube<S>
where
S: BaseFloat,
{
fn get_mass(&self, material: &Material) -> Mass<S, Matrix3<S>> {
let b: Aabb3<S> = self.compute_bound();
let mass = b.volume() * material.density();
let x2 = b.dim().x * b.dim().x;
let y2 = b.dim().y * b.dim().y;
let z2 = b.dim().z * b.dim().z;
let mnorm = mass / S::from(12.).unwrap();
let inertia = Matrix3::from_diagonal(Vector3::new(y2 + z2, x2 + z2, x2 + y2) * mnorm);
Mass::new_with_inertia(mass, inertia)
}
}
fn poly_sub_expr_calc<S>(w0: S, w1: S, w2: S) -> (S, S, S, S, S, S)
where
S: BaseFloat,
{
let t0 = w0 + w1;
let t1 = w0 * w0;
let t2 = t1 + t0 * w1;
let f1 = t0 + w2;
let f2 = t2 + w2 * f1;
let f3 = w0 * t0 + w1 * t2 + w2 * f2;
(
f1,
f2,
f3,
f2 + w0 * (f1 + w0),
f2 + w1 * (f1 + w1),
f2 + w2 * (f1 + w2),
)
}
const ONE_6: f64 = 1. / 6.;
const ONE_24: f64 = 1. / 24.;
const ONE_60: f64 = 1. / 60.;
const ONE_120: f64 = 1. / 120.;
const POLY_SCALE: [f64; 10] = [
ONE_6, ONE_24, ONE_24, ONE_24, ONE_60, ONE_60, ONE_60, ONE_120, ONE_120, ONE_120,
];
impl<S> Volume<S, Matrix3<S>> for ConvexPolyhedron<S>
where
S: BaseFloat,
{
// Volume of tetrahedron is 1/6 * a.cross(b).dot(c) where a = B - C, b = A - C, c = Origin - C
// Sum for all faces
fn get_mass(&self, material: &Material) -> Mass<S, Matrix3<S>> {
let mut intg: [S; 10] = [S::zero(); 10];
for (p0, p1, p2) in self.faces_iter() {
let v1 = p1 - p0; // a1, b1, c1
let v2 = p2 - p0; // a2, b2, c2
let d = v1.cross(v2); // d0, d1, d2
let (f1x, f2x, f3x, g0x, g1x, g2x) = poly_sub_expr_calc(p0.x, p1.x, p2.x);
let (_, f2y, f3y, g0y, g1y, g2y) = poly_sub_expr_calc(p0.y, p1.y, p2.y);
let (_, f2z, f3z, g0z, g1z, g2z) = poly_sub_expr_calc(p0.z, p1.z, p2.z);
intg[0] += d.x * f1x;
intg[1] += d.x * f2x;
intg[2] += d.y * f2y;
intg[3] += d.z * f2z;
intg[4] += d.x * f3x;
intg[5] += d.y * f3y;
intg[6] += d.z * f3z;
intg[7] += d.x * (p0.y * g0x + p1.y * g1x + p2.y * g2x);
intg[8] += d.y * (p0.z * g0y + p1.z * g1y + p2.z * g2y);
intg[9] += d.z * (p0.x * g0z + p1.x * g1z + p2.x * g2z);
}
for i in 0..10 {
intg[i] *= S::from(POLY_SCALE[i]).unwrap();
}
let cm = Point3::new(intg[1] / intg[0], intg[2] / intg[0], intg[3] / intg[0]);
let mut inertia = Matrix3::zero();
inertia.x.x = intg[5] + intg[6] - intg[0] * (cm.y * cm.y + cm.z * cm.z);
inertia.y.y = intg[4] + intg[6] - intg[0] * (cm.x * cm.x + cm.z * cm.z);
inertia.z.z = intg[4] + intg[5] - intg[0] * (cm.x * cm.x + cm.y * cm.y);
inertia.x.y = -(intg[7] - intg[0] * cm.x * cm.y);
inertia.y.z = -(intg[8] - intg[0] * cm.y * cm.z);
inertia.x.z = -(intg[9] - intg[0] * cm.x * cm.z);
Mass::new_with_inertia(
intg[0] * material.density(),
inertia * material.density::<S>(),
)
}
}
impl<S> Volume<S, S> for Primitive2<S>
where
S: BaseFloat + Inertia,
{
fn get_mass(&self, material: &Material) -> Mass<S, S> {
use collision::primitive::Primitive2::*;
match *self {
Particle(_) | Line(_) => Mass::new(material.density()),
Circle(ref circle) => circle.get_mass(material),
Rectangle(ref rectangle) => rectangle.get_mass(material),
Square(ref square) => square.get_mass(material),
ConvexPolygon(ref polygon) => polygon.get_mass(material),
}
}
}
impl<S> Volume<S, Matrix3<S>> for Capsule<S>
where
S: BaseFloat,
{
fn get_mass(&self, material: &Material) -> Mass<S, Matrix3<S>> {
use std::f64::consts::PI;
let pi = S::from(PI).unwrap();
let rsq = self.radius() * self.radius();
let hsq = self.height() * self.height();
let two = S::one() + S::one();
let three = two + S::one();
let four = two + two;
let five = three + two;
let eight = five + three;
let twelve = eight + four;
let c_m = pi * rsq * self.height() * material.density();
let h_m = pi * two / three * rsq * self.radius() * material.density();
let mass = c_m + two * h_m;
let c_i_xz = hsq / twelve + rsq / four;
let h_i_xz = rsq * two / five + hsq / two + self.height() * self.radius() * three / eight;
let i_xz = c_m * c_i_xz + h_m * h_i_xz * two;
let i_y = c_m * rsq / two + h_m * rsq * four / five;
let inertia = Matrix3::from_diagonal(Vector3::new(i_xz, i_y, i_xz));
Mass::new_with_inertia(mass, inertia)
}
}
impl<S> Volume<S, Matrix3<S>> for Cylinder<S>
where
S: BaseFloat,
{
fn get_mass(&self, material: &Material) -> Mass<S, Matrix3<S>> {
use std::f64::consts::PI;
let pi = S::from(PI).unwrap();
let rsq = self.radius() * self.radius();
let volume = pi * rsq * self.height();
let mass = volume * material.density();
let two = S::one() + S::one();
let three = S::one() + two;
let twelve = three * two * two;
let i_y = mass * rsq / two;
let i_xz = mass / twelve * (three * rsq + self.height() * self.height());
let inertia = Matrix3::from_diagonal(Vector3::new(i_xz, i_y, i_xz));
Mass::new_with_inertia(mass, inertia)
}
}
impl<S> Volume<S, Matrix3<S>> for Primitive3<S>
where
S: BaseFloat,
{
fn get_mass(&self, material: &Material) -> Mass<S, Matrix3<S>> {
use collision::primitive::Primitive3::*;
match *self {
Particle(_) | Quad(_) => Mass::new(material.density()),
Sphere(ref sphere) => sphere.get_mass(material),
Cuboid(ref cuboid) => cuboid.get_mass(material),
Cube(ref cube) => cube.get_mass(material),
Capsule(ref capsule) => capsule.get_mass(material),
Cylinder(ref cylinder) => cylinder.get_mass(material),
ConvexPolyhedron(ref polyhedra) => polyhedra.get_mass(material),
}
}
}
// Composite inertia : sum(I_i + M_i * d_i^2)
// I_i : Inertia of primitive with index i
// M_i : Mass of primitive with index i
// d_i : Offset from composite center of mass to primitive center of mass
impl<S, P, T, B, Y> Volume<S, S> for CollisionShape<P, T, B, Y>
where
S: BaseFloat + Inertia,
P: Volume<S, S> + Primitive<Point = Point2<S>> + ComputeBound<B>,
B: Bound<Point = Point2<S>> + Clone + Union<B, Output = B>,
T: Transform<Point2<S>>,
Y: Default,
{
fn get_mass(&self, material: &Material) -> Mass<S, S> {
let (mass, inertia) = self
.primitives()
.iter()
.map(|p| (p.0.get_mass(material), &p.1))
.fold((S::zero(), S::zero()), |(a_m, a_i), (m, t)| {
(a_m + m.mass(), a_i + m.local_inertia() + m.mass() * d2(t))
});
Mass::new_with_inertia(mass, inertia)
}
}
fn d2<S, T>(t: &T) -> S
where
S: BaseFloat,
T: Transform<Point2<S>>,
{
let p = t.transform_point(Point2::origin()).to_vec();
p.dot(p)
}
impl<S, P, T, B, Y> Volume<S, Matrix3<S>> for CollisionShape<P, T, B, Y>
where
S: BaseFloat,
P: Volume<S, Matrix3<S>> + Primitive<Point = Point3<S>> + ComputeBound<B>,
B: Bound<Point = Point3<S>> + Clone + Union<B, Output = B>,
T: Transform<Point3<S>>,
Y: Default,
{
fn get_mass(&self, material: &Material) -> Mass<S, Matrix3<S>> {
let (mass, inertia) = self
.primitives()
.iter()
.map(|p| (p.0.get_mass(material), &p.1))
.fold((S::zero(), Matrix3::zero()), |(a_m, a_i), (m, t)| {
(a_m + m.mass(), a_i + m.local_inertia() + d3(t) * m.mass())
});
Mass::new_with_inertia(mass, inertia)
}
}
fn d3<S, T>(t: &T) -> Matrix3<S>
where
S: BaseFloat,
T: Transform<Point3<S>>,
{
let o = t.transform_point(Point3::origin()).to_vec();
let d2 = o.magnitude2();
let mut j = Matrix3::from_value(d2);
j.x += o * -o.x;
j.y += o * -o.y;
j.z += o * -o.z;
j
}
|
//! File checksum computing and checksum file writing.
use std::{
borrow::Cow,
fs::File,
io::{self, Write},
path::{Path, PathBuf},
};
use rayon::{iter::ParallelIterator, prelude::ParallelBridge};
use sha2::{Digest, Sha256};
use crate::error::Error;
pub trait Checksum {
/// compute the hash of the file pointed by the filepath by using [io::copy] between a file handler and the hasher.
/// As such, it shouldn't make the program go OOM with big files, but it has not been tested.
/// Can return an error if there has been problems regarding IO.
#[inline]
fn get_hash<R>(reader: &mut R, hasher: &mut Sha256) -> Result<String, Error>
where
R: std::io::Read,
{
io::copy(reader, hasher)?;
let result = format!("{:x}", hasher.finalize_reset());
Ok(result)
}
/// corpus/lang/lang_part_x.jsonl
#[inline]
fn get_hash_path(src: &Path, hasher: &mut Sha256) -> Result<String, Error> {
let mut f = File::open(src)?;
Self::get_hash(&mut f, hasher)
}
/// this should operate on the wide-level.
fn checksum_folder(src: &Path, num_threads: usize) -> Result<(), Error> {
if num_threads != 1 {
rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build_global()?;
}
if src.is_file() {
// TODO #86442 merged
// return Err(io::Error::new(
// io::ErrorKind::IsADirectory,
// format!("{}", src),
// ));
error!("Checksum only works on folders!");
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{:?}", src)).into());
}
let language_dirs = std::fs::read_dir(src)?.filter_map(|entry| {
// check entry validity
let entry = match entry {
Ok(e) => e.path(),
Err(e) => {
error!("error with directory entry {:?}", e);
return None;
}
};
// filter out files
if !entry.is_dir() {
warn!("{:?} is not a directory: ignoring checksum op", entry);
None
} else {
Some(entry)
}
});
let language_dirs_par = language_dirs.par_bridge();
language_dirs_par.for_each(|language_dir| match Self::get_write_hashes(&language_dir) {
Ok(_) => (),
Err(e) => error!("Error with directory {:?}: {:?}", language_dir, e),
});
Ok(())
}
#[inline]
/// convinience function for checksum_folder
/// TODO: move out of trait
fn get_write_hashes(src: &Path) -> Result<(), Error> {
debug!("Getting hashes for {:?}", src);
let hashes = Self::checksum_lang(src)?;
let checksum_filepath = src.to_path_buf().join("checksum.sha256");
debug!("writing checksums in {:?}", checksum_filepath);
let mut checksum_file = File::create(&checksum_filepath)?;
Self::write_checksum(&mut checksum_file, hashes)?;
Ok(())
}
fn write_checksum<W: Write>(
writer: &mut W,
hashes: Vec<(PathBuf, String)>,
) -> Result<(), Error> {
for (path, hash) in hashes {
if let Some(filename) = path.file_name() {
let filename = if let Some(filename_string) = filename.to_str() {
Cow::from(filename_string)
} else {
let filename_string = filename.to_string_lossy();
warn!(
"could not convert path to string: {:?}, using {} in replacement.",
filename, filename_string
);
filename_string
};
writeln!(writer, "{} {}", hash, filename)?;
} else {
warn!("Could not get filename for {:?}: ignoring in checksum. Add manually if necessary.", path);
}
}
Ok(())
}
/// this should operate on lang-level
fn checksum_lang(src: &Path) -> Result<Vec<(PathBuf, String)>, Error> {
let mut hasher = Sha256::new();
let mut hashes = Vec::new();
for filepath in std::fs::read_dir(src)? {
let filepath = filepath?.path();
debug!("hashing {:?}", filepath);
let hash = Self::get_hash_path(&filepath, &mut hasher)?;
hashes.push((filepath, hash));
}
Ok(hashes)
}
}
#[cfg(test)]
mod tests {
use sha2::Digest;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use tempfile::TempDir;
use sha2::Sha256;
use crate::error::Error;
use crate::ops::Checksum;
fn gen_dummy_corpus() -> Result<TempDir, Error> {
let corpus_dir = tempfile::tempdir().unwrap();
let (langs, contents): (Vec<&str>, Vec<&str>) = [
("fr", r#"{{"content":"foo_french"}}"#),
("en", r#"{{"content":"foo_english"}}"#),
("de", r#"{{"content":"foo_german"}}"#),
("es", r#"{{"content":"foo_spanish"}}"#),
]
.iter()
.cloned()
.unzip();
for (lang, content) in langs.iter().zip(contents.iter()) {
let path = corpus_dir.path();
let lang_dir = path.join(lang);
std::fs::create_dir(&lang_dir)?;
let lang_text_file = lang_dir.clone().join(format!("{lang}.jsonl"));
let mut f = File::create(&lang_text_file)?;
write!(&mut f, "{content}")?;
}
Ok(corpus_dir)
}
#[test]
fn test_write_checksum() {
struct DummyChecksum;
impl Checksum for DummyChecksum {}
let hashes = vec![
(PathBuf::from("fr.txt"), "hash_for_fr.txt".to_string()),
(PathBuf::from("en.txt"), "hash_for_en.txt".to_string()),
(PathBuf::from("es.txt"), "hash_for_es.txt".to_string()),
(PathBuf::from("de.txt"), "hash_for_de.txt".to_string()),
];
let expected = "hash_for_fr.txt fr.txt
hash_for_en.txt en.txt
hash_for_es.txt es.txt
hash_for_de.txt de.txt
";
let mut checksum_writer = Vec::new();
DummyChecksum::write_checksum(&mut checksum_writer, hashes).unwrap();
let checksum_string = String::from_utf8(checksum_writer).unwrap();
assert_eq!(expected, &checksum_string);
}
#[test]
fn test_get_write_hashes() -> Result<(), Error> {
struct DummyChecksum;
impl Checksum for DummyChecksum {}
let lang = tempfile::tempdir()?;
let lang_corpus = lang.path().join("fr.txt");
let text = "foo bar baz quux";
let mut f = File::create(&lang_corpus)?;
f.write(text.as_bytes())?;
DummyChecksum::get_write_hashes(lang.path())?;
let checksum_file = lang.path().join("checksum.sha256");
let checksums = std::fs::read_to_string(&checksum_file)?;
let mut x = checksums.split(' ').take(2);
let (checksum, filename) = (x.next(), x.next());
let mut hasher = Sha256::new();
hasher.update(text.as_bytes());
let expected_checksum = format!("{:x}", hasher.finalize_reset());
let expected_filename = "fr.txt\n";
assert_eq!(checksum.unwrap(), &expected_checksum);
assert_eq!(filename.unwrap(), expected_filename);
Ok(())
}
#[test]
fn test_checksum_lang() -> Result<(), Error> {
struct DummyChecksum;
impl Checksum for DummyChecksum {}
let corpus_dir = tempfile::tempdir().unwrap();
let (langs, contents): (Vec<&str>, Vec<&str>) = [
("fr", r#"{{"content":"foo_french"}}"#),
("en", r#"{{"content":"foo_english"}}"#),
("de", r#"{{"content":"foo_german"}}"#),
("es", r#"{{"content":"foo_spanish"}}"#),
]
.iter()
.cloned()
.unzip();
for (lang, content) in langs.iter().zip(contents.iter()) {
let path = corpus_dir.path();
let lang_dir = path.join(lang);
std::fs::create_dir(&lang_dir)?;
let lang_text_file = lang_dir.clone().join(format!("{lang}.jsonl"));
let mut f = File::create(&lang_text_file)?;
write!(&mut f, "{content}")?;
}
for (lang, content) in langs.iter().zip(contents) {
// corpora are not split, so there's only one file (hence [0]). We then take the hash (hence .1)
let hash = &DummyChecksum::checksum_lang(&corpus_dir.path().join(lang))?[0].1;
let expected = {
let mut hasher = Sha256::new();
let mut reader = content.as_bytes();
DummyChecksum::get_hash(&mut reader, &mut hasher)?
};
assert_eq!(hash, &expected);
}
Ok(())
}
#[test]
fn test_checksum_folder() -> Result<(), Error> {
struct DummyChecksum;
impl Checksum for DummyChecksum {}
let corpus_dir = tempfile::tempdir().unwrap();
let (langs, contents): (Vec<&str>, Vec<&str>) = [
("fr", r#"{{"content":"foo_french"}}"#),
("en", r#"{{"content":"foo_english"}}"#),
("de", r#"{{"content":"foo_german"}}"#),
("es", r#"{{"content":"foo_spanish"}}"#),
]
.iter()
.cloned()
.unzip();
for (lang, content) in langs.iter().zip(contents.iter()) {
let path = corpus_dir.path();
let lang_dir = path.join(lang);
std::fs::create_dir(&lang_dir)?;
let lang_text_file = lang_dir.clone().join(format!("{lang}.jsonl"));
let mut f = File::create(&lang_text_file)?;
write!(&mut f, "{content}")?;
}
let corpus_path = corpus_dir.path();
DummyChecksum::checksum_folder(corpus_path, 1)?;
for dir in std::fs::read_dir(&corpus_path)? {
let dir = dir?;
let mut hashes: Vec<(_, _)> = Vec::new();
let mut hashes_from_files: Vec<(_, _)> = Vec::new();
let mut hasher = Sha256::new();
for language_dir in std::fs::read_dir(dir.path())? {
let language_dir = language_dir?;
let current_path = language_dir.path();
let extension = current_path.extension().and_then(|x| x.to_str());
match extension {
None => (),
Some("jsonl") => {
let hash = DummyChecksum::get_hash_path(¤t_path, &mut hasher)?;
let filename = current_path.clone();
let filename = filename.file_name().map(|f| f.to_owned());
let filename = filename.unwrap().into_string();
hashes.push((filename.unwrap(), hash));
}
Some("sha256") => {
let checksums = std::fs::read_to_string(current_path)?;
let parts: Vec<String> = checksums
.split(' ')
.take(2)
.map(|x| x.to_string())
.collect();
let hash = parts[0].clone();
let filename = parts[1].clone().replace('\n', "");
hashes_from_files.push((filename, hash));
}
_ => (),
}
}
assert_eq!(hashes, hashes_from_files);
}
Ok(())
}
}
|
use std::{error, fmt};
use std::str::Utf8Error;
use std::string::FromUtf8Error;
pub static SIZE_MASKS: [u8; 9] = [
0b00000000,
0b10000000,
0b11000000,
0b11100000,
0b11110000,
0b11111000,
0b11111100,
0b11111110,
0b11111111
];
/// Simple error type returned either by the `Decoder` or `Encoder`
#[derive(Debug)]
pub enum Error {
Utf8Encoding,
ReadingOutOfBounds,
BufferNotEmpty,
InvalidData,
}
impl error::Error for Error {
fn description(&self) -> &str {
use Error::*;
match *self {
Utf8Encoding => "Couldn't decode UTF-8 string",
ReadingOutOfBounds => "Attempted to read out of bounds",
BufferNotEmpty => "There is still data to read",
InvalidData => "Data does not match requested type",
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))
}
}
impl From<Utf8Error> for Error {
fn from(_: Utf8Error) -> Error {
Error::Utf8Encoding
}
}
impl From<FromUtf8Error> for Error {
fn from(_: FromUtf8Error) -> Error {
Error::Utf8Encoding
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
|
use std::result;
#[derive(Debug)]
pub enum SeriesError {
Error,
}
type Result<T> = result::Result<T, SeriesError>;
pub fn lsp(s: &str, length: usize) -> Result<u32> {
if length == 0 {
return Ok(1);
}
let digits = parse_input(s, length)?;
digits
.windows(length)
.map(|w| w.iter().product())
.max()
.ok_or(SeriesError::Error)
}
fn parse_input(s: &str, length: usize) -> Result<Vec<u32>> {
if length > s.len() {
return Err(SeriesError::Error);
}
// mut + for to avoid walking the string twice
let mut digits = Vec::new();
for c in s.chars() {
match c.to_digit(10) {
Some(n) => digits.push(n),
None => return Err(SeriesError::Error),
}
}
Ok(digits)
}
|
mod exit;
mod queue;
use std::arch::global_asm;
use std::cell::{OnceCell, UnsafeCell};
use std::mem;
use std::ptr;
use std::sync::{
atomic::{AtomicI32, AtomicU64, Ordering},
Arc,
};
use std::thread::{self, ThreadId};
use firefly_rt::function::{DynamicCallee, ModuleFunctionArity};
use firefly_rt::process::{Process, ProcessStatus};
use firefly_rt::term::{OpaqueTerm, Pid, ProcessId};
use self::queue::RunQueue;
#[thread_local]
pub static CURRENT_PROCESS: UnsafeCell<Option<Arc<Process>>> = UnsafeCell::new(None);
#[thread_local]
pub static CURRENT_SCHEDULER: OnceCell<Scheduler> = OnceCell::new();
/// Returns a reference to the scheduler for the current thread
pub fn with_current<F, R>(fun: F) -> R
where
F: FnOnce(&Scheduler) -> R,
{
fun(CURRENT_SCHEDULER.get().unwrap())
}
/// Initializes the scheduler for the current thread, if not already initialized,
/// returning a reference to it
pub fn init<'a>() -> bool {
CURRENT_SCHEDULER.get_or_init(|| Scheduler::new().unwrap());
true
}
/// Applies the currently executing process to the given function
pub fn with_current_process<F, R>(fun: F) -> R
where
F: FnOnce(&Process) -> R,
{
let p = unsafe { (&*CURRENT_PROCESS.get()).as_deref().unwrap() };
fun(p)
}
struct SchedulerData {
process: Arc<Process>,
registers: UnsafeCell<CalleeSavedRegisters>,
}
impl SchedulerData {
fn new(process: Arc<Process>) -> Self {
Self {
process,
registers: UnsafeCell::new(Default::default()),
}
}
#[allow(dead_code)]
fn pid(&self) -> Pid {
Pid::Local {
id: self.process.pid(),
}
}
fn registers(&self) -> &CalleeSavedRegisters {
unsafe { &*self.registers.get() }
}
fn registers_mut(&self) -> &mut CalleeSavedRegisters {
unsafe { &mut *self.registers.get() }
}
}
unsafe impl Send for SchedulerData {}
unsafe impl Sync for SchedulerData {}
pub struct Scheduler {
pub id: ThreadId,
// References are always 64-bits even on 32-bit platforms
#[allow(dead_code)]
next_reference_id: AtomicU64,
// In this runtime, we aren't doing work-stealing, so the run queue
// is never accessed by any other thread
run_queue: UnsafeCell<RunQueue>,
prev: UnsafeCell<Option<Arc<SchedulerData>>>,
current: UnsafeCell<Arc<SchedulerData>>,
halt_code: AtomicI32,
}
// This guarantee holds as long as `init` and `current` are only
// ever accessed by the scheduler when scheduling
unsafe impl Sync for Scheduler {}
impl Scheduler {
/// Creates a new scheduler with the default configuration
fn new() -> anyhow::Result<Self> {
let id = thread::current().id();
// The root process is how the scheduler gets time for itself,
// and is also how we know when to shutdown the scheduler due
// to termination of all its processes
let root = {
let process = Arc::new(Process::new(
None,
ProcessId::next(),
"root:init/0".parse().unwrap(),
));
unsafe {
process.set_status(ProcessStatus::Running);
}
let mut registers = CalleeSavedRegisters::default();
unsafe {
registers.set(1, 0x0u64);
}
Arc::new(SchedulerData {
process,
registers: UnsafeCell::new(registers),
})
};
// The scheduler starts with the root process running
Ok(Self {
id,
next_reference_id: AtomicU64::new(0),
run_queue: UnsafeCell::new(RunQueue::default()),
prev: UnsafeCell::new(None),
current: UnsafeCell::new(root),
halt_code: AtomicI32::new(0),
})
}
fn parent(&self) -> ProcessId {
self.current().process.pid()
}
fn prev(&self) -> &SchedulerData {
unsafe { (&*self.prev.get()).as_deref().unwrap() }
}
fn prev_mut(&self) -> &mut SchedulerData {
unsafe {
(&mut *self.prev.get())
.as_mut()
.map(|prev| Arc::get_mut(prev).unwrap())
.unwrap()
}
}
fn take_prev(&self) -> Arc<SchedulerData> {
unsafe { (&mut *self.prev.get()).take().unwrap() }
}
fn current(&self) -> &SchedulerData {
unsafe { &*self.current.get() }
}
fn current_mut(&self) -> &mut SchedulerData {
unsafe { Arc::get_mut(&mut *self.current.get()).unwrap() }
}
pub fn current_process(&self) -> Arc<Process> {
self.current().process.clone()
}
/// Swaps the prev and current scheduler data in-place and updates CURRENT_PROCESS
///
/// This is intended for use when yielding to the scheduler
fn swap_current(&self) {
// Here, `prev` is the previously suspended process, and `current` is
// the process currently in the process of yielding. We need to set the
// yielding process status to Runnable and reschedule it for later, if applicable
let prev = self.prev_mut();
let proc = prev.process.clone();
let current = self.current_mut();
unsafe {
let prev_status = current.process.status();
if prev_status == ProcessStatus::Running {
current.process.set_status(ProcessStatus::Runnable);
}
}
mem::swap(prev, current);
let _ = unsafe { (&mut *CURRENT_PROCESS.get()).replace(proc) };
}
/// Swaps the current scheduler data with the one provided, and updates CURRENT_PROCESS
///
/// This is intended for use when swapping from the scheduler to a process, and as such,
/// it requires that `prev` contains None when this is called
fn swap_with(&self, new: Arc<SchedulerData>) {
assert!(unsafe { (&mut *self.prev.get()).replace(new).is_none() });
self.swap_current()
}
/// Returns true if the root process (scheduler) is running
#[allow(dead_code)]
fn is_root(&self) -> bool {
unsafe { (&*self.prev.get()).is_none() }
}
pub(super) fn spawn_init(&self) -> anyhow::Result<Arc<Process>> {
// The init process is the actual "root" Erlang process, it acts
// as the entry point for the program from Erlang's perspective,
// and is responsible for starting/stopping the system in Erlang.
//
// If this process exits, the scheduler terminates
let mfa: ModuleFunctionArity = "init:start/0".parse().unwrap();
//let init_fn = function::find_symbol(&mfa).expect("unable to locate init:start/0 function!");
let init_fn = crate::init::start as DynamicCallee;
let process = Arc::new(Process::new(Some(self.parent()), ProcessId::next(), mfa));
let data = Arc::new(SchedulerData::new(process));
Self::runnable(&data, init_fn);
Ok(self.schedule(data))
}
fn schedule(&self, data: Arc<SchedulerData>) -> Arc<Process> {
let handle = data.process.clone();
let rq = unsafe { &mut *self.run_queue.get() };
rq.schedule(data);
handle
}
#[inline]
pub(super) fn run_once(&self) -> bool {
// The scheduler will yield to a process to execute
self.scheduler_yield()
}
fn runnable(scheduler: &SchedulerData, init_fn: DynamicCallee) {
#[derive(Copy, Clone)]
struct StackPointer(*mut u64);
impl StackPointer {
#[inline(always)]
unsafe fn push(&mut self, value: u64) {
self.0 = self.0.offset(-1);
ptr::write(self.0, value);
}
}
// Write the return function and init function to the end of the stack,
// when execution resumes, the pointer before the stack pointer will be
// used as the return address - the first time that will be the init function.
//
// When execution returns from the init function, then it will return via
// `process_return`, which will return to the scheduler and indicate that
// the process exited. The nature of the exit is indicated by error state
// in the process itself
unsafe {
scheduler.process.set_status(ProcessStatus::Runnable);
let stack = scheduler.process.stack();
let registers = scheduler.registers_mut();
// This can be used to push items on the process
// stack before it starts executing. For now that
// is not being done
let mut sp = StackPointer(stack.top as *mut u64);
// Make room for the CFA above the frame pointer, and add padding so
// stack alignment of 16 bytes is preserved
sp.push(0);
sp.push(0);
// Write stack/frame pointer initial values
registers.set_stack_pointer(sp.0 as u64);
registers.set_frame_pointer(sp.0 as u64);
// TODO: Set up for closures
// If the init function is a closure, place it in
// the first callee-save register, which will be moved to
// the first argument register (e.g. %rsi) by swap_stack for
// the call to the entry point
registers.set(0, OpaqueTerm::NONE);
// This is used to indicate to swap_stack that this process
// is being swapped to for the first time, which allows the
// function to perform some initial one-time setup to link
// call frames for the unwinder and call the entry point
registers.set(1, FIRST_SWAP);
// The function that swap_stack will call as entry
registers.set(2, init_fn as u64);
}
}
// TODO: Request application master termination for controlled shutdown
// This request will always come from the thread which spawned the application
// master, i.e. the "main" scheduler thread
//
// Returns `Ok(())` if shutdown was successful, `Err(anyhow::Error)` if something
// went wrong during shutdown, and it was not able to complete normally
pub(super) fn shutdown(&self) -> std::process::ExitCode {
use std::process::ExitCode;
if self.halt_code.load(Ordering::Relaxed) == 0 {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}
pub(super) fn process_yield(&self) -> bool {
// Swap back to the scheduler, which is currently "suspended" in `prev`.
// When `swap_stack` is called it will look like a return from the last call
// to `swap_stack` from the scheduler loop.
//
// This function will appear to return normally to the caller if the process
// that yielded is rescheduled
let prev = unsafe { (&*(self.prev.get())).as_deref().unwrap().registers() };
let current = unsafe { (&*(self.current.get())).registers_mut() };
unsafe {
swap_stack(current, prev, FIRST_SWAP);
}
true
}
/// This function performs two roles, albeit virtually identical:
///
/// First, this function is called by the scheduler to resume execution
/// of a process pulled from the run queue. It does so using its "root"
/// process as its context.
///
/// Second, this function is called by a process when it chooses to
/// yield back to the scheduler. In this case, the scheduler "root"
/// process is swapped in, so the scheduler has a chance to do its
/// auxilary tasks, after which the scheduler will call it again to
/// swap in a new process.
fn scheduler_yield(&self) -> bool {
loop {
let next = {
let rq = unsafe { &mut *self.run_queue.get() };
rq.next()
};
match next {
Some(scheduler_data) => {
// Found a process to schedule
unsafe {
// The swap takes care of setting up the to-be-scheduled process
// as the current process, and swaps to its stack. The code below
// is executed when that process has yielded and we're resetting
// the state of the scheduler such that the "current process" is
// the scheduler itself
self.swap_process(scheduler_data);
}
// When we reach here, the process has yielded
// back to the scheduler, and is still marked
// as the current process. We need to handle
// swapping it out with the scheduler process
// and handling its exit, if exiting
self.swap_current();
// At this point, `prev` is the process which just yielded
let prev = self.take_prev();
match prev.process.status() {
ProcessStatus::Running => {
let rq = unsafe { &mut *self.run_queue.get() };
rq.reschedule(prev);
}
ProcessStatus::Exiting => {
self.halt_code.store(0, Ordering::Relaxed);
// Process has exited normally, we're done with it
}
ProcessStatus::Errored(exception) => {
exit::log_exit(&prev.process, exception);
self.halt_code.store(1, Ordering::Relaxed);
}
other => assert_eq!(other, ProcessStatus::Running),
}
// When reached, either the process scheduled is the root process,
// or the process is exiting and we called .reduce(); either way we're
// returning to the main scheduler loop to check for signals, etc.
break true;
}
None => {
// No more processes to schedule, we're done
break false;
}
}
}
}
/// This function takes care of coordinating the scheduling of a new
/// process/descheduling of the current process.
///
/// - Updating process status
/// - Updating reduction count based on accumulated reductions during execution
/// - Resetting reduction counter for next process
/// - Handling exiting processes (logging/propagating)
///
/// Once that is complete, it swaps to the new process stack via `swap_stack`,
/// at which point execution resumes where the newly scheduled process left
/// off previously, or in its init function.
unsafe fn swap_process(&self, new: Arc<SchedulerData>) {
// Mark the new process as Running
new.process.set_status(ProcessStatus::Running);
self.swap_with(new);
let prev = self.prev();
let new = self.current();
// Execute the swap
//
// When swapping to the root process, we effectively return from here, which
// will unwind back to the main scheduler loop in `lib.rs`.
//
// When swapping to a newly spawned process, we return "into"
// its init function, or put another way, we jump to its
// function prologue. In this situation, all of the saved registers
// except %rsp and %rbp will be zeroed. %rsp is set during the call
// to `spawn`, but %rbp is set to the current %rbp value to ensure
// that stack traces link the new stack to the frame in which execution
// started
//
// When swapping to a previously spawned process, we return to the end
// of `process_yield`, which is what the process last called before the
// scheduler was swapped in.
swap_stack(prev.registers_mut(), new.registers(), FIRST_SWAP);
}
}
#[derive(Default, Debug)]
#[repr(C)]
#[cfg(all(unix, target_arch = "x86_64"))]
struct CalleeSavedRegisters {
pub rsp: u64,
pub r15: u64,
pub r14: u64,
pub r13: u64,
pub r12: u64,
pub rbx: u64,
pub rbp: u64,
}
#[cfg(target_arch = "x86_64")]
impl CalleeSavedRegisters {
#[inline(always)]
unsafe fn set<T: Copy>(&mut self, index: isize, value: T) {
let base = std::ptr::addr_of!(self.rbp);
let base = base.offset((-index) - 2) as *mut T;
base.write(value);
}
#[inline(always)]
unsafe fn set_stack_pointer(&mut self, value: u64) {
self.rsp = value;
}
#[inline(always)]
unsafe fn set_frame_pointer(&mut self, value: u64) {
self.rbp = value;
}
}
#[derive(Debug, Default)]
#[repr(C)]
#[cfg(all(unix, target_arch = "aarch64"))]
struct CalleeSavedRegisters {
pub sp: u64,
pub x29: u64,
pub x28: u64,
pub x27: u64,
pub x26: u64,
pub x25: u64,
pub x24: u64,
pub x23: u64,
pub x22: u64,
pub x21: u64,
pub x20: u64,
pub x19: u64,
}
#[cfg(target_arch = "aarch64")]
impl CalleeSavedRegisters {
#[inline(always)]
unsafe fn set<T: Copy>(&mut self, index: isize, value: T) {
let base = std::ptr::addr_of!(self.x19);
let base = base.offset(-index) as *mut T;
base.write(value);
}
#[inline(always)]
unsafe fn set_stack_pointer(&mut self, value: u64) {
self.sp = value;
}
#[inline(always)]
unsafe fn set_frame_pointer(&mut self, value: u64) {
self.x29 = value;
}
}
const FIRST_SWAP: u64 = 0xdeadbeef;
extern "C-unwind" {
#[link_name = "__firefly_swap_stack"]
fn swap_stack(
prev: *mut CalleeSavedRegisters,
new: *const CalleeSavedRegisters,
first_swap: u64,
);
}
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
global_asm!(include_str!("swap_stack/swap_stack_linux_x86_64.s"));
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
global_asm!(include_str!("swap_stack/swap_stack_macos_x86_64.s"));
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
global_asm!(include_str!("swap_stack/swap_stack_macos_aarch64.s"));
|
use net::{
packets::*,
tokio::{self, net::TcpListener},
ReadResponse, RemoteConnection,
};
use async_channel::Sender;
pub async fn server(
addr: &'static str,
read_buf_sender: Sender<(ReadBuffer, Sender<WriteBuf>)>,
) -> Result<(), Box<std::io::Error>> {
let listener = TcpListener::bind(addr).await?;
info!("Started server on {}...", addr);
loop {
let (socket, other_addr) = listener.accept().await?;
let (mut socket_read, mut socket_write) = socket.into_split();
let buf_sender = read_buf_sender.clone();
let (write_buf_sender, write_buf_reciever) = async_channel::unbounded::<WriteBuf>();
tokio::spawn(async move {
info!("Client connected from {}", other_addr);
if let Err(_) = buf_sender
.send((ReadBuffer::new(vec![0, 0]), write_buf_sender.clone()))
.await
{
info!("receiver dropped");
return;
}
let mut buffer = vec![0; 10000];
loop {
match RemoteConnection::read_length(&mut buffer, &mut socket_read).await {
ReadResponse::Ok(len) => {
info!("Recieved message: {:?}", &buffer[0..len]);
if let Err(_) = buf_sender
.send((
ReadBuffer::new(buffer[0..len].to_vec()),
write_buf_sender.clone(),
))
.await
{
info!("receiver dropped");
return;
}
}
ReadResponse::Disconnected => break,
ReadResponse::Error => return,
ReadResponse::PacketLengthTooLong => {
error!("Packet length more than buffer length");
write_buf_sender.clone().send(WriteBuf::new_server_packet(
ServerPacket::PacketLengthInvalid,
).push("Packet length (first 2 bytes) exeeds maximum allowed on this server".to_string())).await.unwrap();
}
}
}
});
tokio::spawn(async move {
while let Ok(mut x) = write_buf_reciever.recv().await {
RemoteConnection::socket_write(&mut x, &mut socket_write).await;
}
});
}
}
|
mod resolve;
mod tree;
mod validate;
pub use tree::*;
use crate::errors::ErrorCx;
use crate::flatten::ResolverContext;
use crate::source_file::FileMap;
use annotate_snippets::snippet::{Annotation, AnnotationType, Snippet};
pub use resolve::dummy_span;
pub use validate::{eval_term, eval_type};
pub fn resolve_library(
srcs: &FileMap,
ctx: ResolverContext,
deps: &Libraries,
) -> Result<Library, Vec<Snippet>> {
Library::from_files(ctx, deps)
.map_err(|errs| errs.into_iter().map(|err| err.into_snippet(srcs)).collect())
}
pub fn add_library(errors: &mut ErrorCx, libs: &mut Libraries, lib: Library) {
if let Err(name) = libs.add_library(lib) {
errors.push(Snippet {
title: Some(Annotation {
label: Some(format!("multiple libraries with name {}", name)),
id: None,
annotation_type: AnnotationType::Error,
}),
footer: vec![],
slices: vec![],
});
}
}
pub fn validate_latest_library(srcs: &FileMap, errors: &mut ErrorCx, libs: &Libraries) {
let validator = validate::Validator::new(libs);
for err in validator.run() {
errors.push(err.into_snippet(srcs));
}
}
|
use cid::Cid;
use core::convert::TryFrom;
use core::ops::Range;
use crate::file::reader::{FileContent, FileReader, Traversal};
use crate::file::{FileReadFailed, Metadata};
use crate::pb::{merkledag::PBLink, FlatUnixFs};
use crate::InvalidCidInLink;
/// IdleFileVisit represents a prepared file visit over a tree. The user has to know the CID and be
/// able to get the block for the visit.
///
/// **Note**: For easier to use interface, you should consider using `ipfs_unixfs::walk::Walker`.
/// It uses `IdleFileVisit` and `FileVisit` internally but has a better API.
#[derive(Default, Debug)]
pub struct IdleFileVisit {
range: Option<Range<u64>>,
}
type FileVisitResult<'a> = (&'a [u8], u64, Metadata, Option<FileVisit>);
impl IdleFileVisit {
/// Target range represents the target byte range of the file we are interested in visiting.
pub fn with_target_range(self, range: Range<u64>) -> Self {
Self { range: Some(range) }
}
/// Begins the visitation by processing the first block to be visited.
///
/// Returns (on success) a tuple of file bytes, total file size, any metadata associated, and
/// optionally a `FileVisit` to continue the walk.
pub fn start(self, block: &'_ [u8]) -> Result<FileVisitResult<'_>, FileReadFailed> {
let fr = FileReader::from_block(block)?;
self.start_from_reader(fr, &mut None)
}
pub(crate) fn start_from_parsed<'a>(
self,
block: FlatUnixFs<'a>,
cache: &'_ mut Option<Cache>,
) -> Result<FileVisitResult<'a>, FileReadFailed> {
let fr = FileReader::from_parsed(block)?;
self.start_from_reader(fr, cache)
}
fn start_from_reader<'a>(
self,
fr: FileReader<'a>,
cache: &'_ mut Option<Cache>,
) -> Result<FileVisitResult<'a>, FileReadFailed> {
let metadata = fr.as_ref().to_owned();
let (content, traversal) = fr.content();
match content {
FileContent::Bytes(content) => {
let block = 0..content.len() as u64;
let content = maybe_target_slice(content, &block, self.range.as_ref());
Ok((content, traversal.file_size(), metadata, None))
}
FileContent::Links(iter) => {
// we need to select suitable here
let mut links = cache.take().unwrap_or_default().inner;
let pending = iter.enumerate().filter_map(|(i, (link, range))| {
if !block_is_in_target_range(&range, self.range.as_ref()) {
return None;
}
Some(to_pending(i, link, range))
});
for item in pending {
links.push(item?);
}
// order is reversed to consume them in the depth first order
links.reverse();
if links.is_empty() {
*cache = Some(links.into());
Ok((&[][..], traversal.file_size(), metadata, None))
} else {
Ok((
&[][..],
traversal.file_size(),
metadata,
Some(FileVisit {
pending: links,
state: traversal,
range: self.range,
}),
))
}
}
}
}
}
/// Optional cache for datastructures which can be re-used without re-allocation between walks of
/// different files.
#[derive(Default)]
pub struct Cache {
inner: Vec<(Cid, Range<u64>)>,
}
impl From<Vec<(Cid, Range<u64>)>> for Cache {
fn from(mut inner: Vec<(Cid, Range<u64>)>) -> Self {
inner.clear();
Cache { inner }
}
}
/// FileVisit represents an ongoing visitation over an UnixFs File tree.
///
/// The file visitor does **not** implement size validation of merkledag links at the moment. This
/// could be implmented with generational storage and it would require an u64 per link.
///
/// **Note**: For easier to use interface, you should consider using `ipfs_unixfs::walk::Walker`.
/// It uses `IdleFileVisit` and `FileVisit` internally but has a better API.
#[derive(Debug)]
pub struct FileVisit {
/// The internal cache for pending work. Order is such that the next is always the last item,
/// so it can be popped. This currently does use a lot of memory for very large files.
///
/// One workaround would be to transform excess links to relative links to some block of a Cid.
pending: Vec<(Cid, Range<u64>)>,
/// Target range, if any. Used to filter the links so that we will only visit interesting
/// parts.
range: Option<Range<u64>>,
state: Traversal,
}
impl FileVisit {
/// Access hashes of all pending links for prefetching purposes. The block for the first item
/// returned by this method is the one which needs to be processed next with `continue_walk`.
///
/// Returns tuple of the next Cid which needs to be processed and an iterator over the
/// remaining.
pub fn pending_links(&self) -> (&Cid, impl Iterator<Item = &Cid>) {
let mut iter = self.pending.iter().rev().map(|(link, _)| link);
let first = iter
.next()
.expect("the presence of links has been validated");
(first, iter)
}
/// Continues the walk with the data for the first `pending_link` key.
///
/// Returns on success a tuple of bytes and new version of `FileVisit` to continue the visit,
/// when there is something more to visit.
pub fn continue_walk<'a>(
mut self,
next: &'a [u8],
cache: &mut Option<Cache>,
) -> Result<(&'a [u8], Option<Self>), FileReadFailed> {
let traversal = self.state;
let (_, range) = self
.pending
.pop()
.expect("User called continue_walk there must have been a next link");
// interesting, validation doesn't trigger if the range is the same?
let fr = traversal.continue_walk(next, &range)?;
let (content, traversal) = fr.content();
match content {
FileContent::Bytes(content) => {
let content = maybe_target_slice(content, &range, self.range.as_ref());
if !self.pending.is_empty() {
self.state = traversal;
Ok((content, Some(self)))
} else {
*cache = Some(self.pending.into());
Ok((content, None))
}
}
FileContent::Links(iter) => {
let before = self.pending.len();
for (i, (link, range)) in iter.enumerate() {
if !block_is_in_target_range(&range, self.range.as_ref()) {
continue;
}
self.pending.push(to_pending(i, link, range)?);
}
// reverse to keep the next link we need to traverse as last, where pop() operates.
(&mut self.pending[before..]).reverse();
self.state = traversal;
Ok((&[][..], Some(self)))
}
}
}
/// Returns the total size of the file in bytes.
pub fn file_size(&self) -> u64 {
self.state.file_size()
}
}
impl AsRef<Metadata> for FileVisit {
fn as_ref(&self) -> &Metadata {
self.state.as_ref()
}
}
fn to_pending(
nth: usize,
link: PBLink<'_>,
range: Range<u64>,
) -> Result<(Cid, Range<u64>), FileReadFailed> {
let hash = link.Hash.as_deref().unwrap_or_default();
match Cid::try_from(hash) {
Ok(cid) => Ok((cid, range)),
Err(e) => Err(FileReadFailed::InvalidCid(InvalidCidInLink::from((
nth, link, e,
)))),
}
}
/// Returns true if the blocks byte offsets are interesting for our target range, false otherwise.
/// If there is no target, all blocks are of interest.
fn block_is_in_target_range(block: &Range<u64>, target: Option<&Range<u64>>) -> bool {
use core::cmp::{max, min};
if let Some(target) = target {
max(block.start, target.start) <= min(block.end, target.end)
} else {
true
}
}
/// Whenever we propagate the content from the tree upwards, we need to make sure it's inside the
/// range we were originally interested in.
fn maybe_target_slice<'a>(
content: &'a [u8],
block: &Range<u64>,
target: Option<&Range<u64>>,
) -> &'a [u8] {
if let Some(target) = target {
target_slice(content, block, target)
} else {
content
}
}
fn target_slice<'a>(content: &'a [u8], block: &Range<u64>, target: &Range<u64>) -> &'a [u8] {
use core::cmp::min;
if !block_is_in_target_range(block, Some(target)) {
// defaulting to empty slice is good, and similar to the "cat" HTTP API operation.
&[][..]
} else {
let start;
let end;
// FIXME: these must have bugs and must be possible to simplify
if target.start < block.start {
// we mostly need something before
start = 0;
end = (min(target.end, block.end) - block.start) as usize;
} else if target.end > block.end {
// we mostly need something after
start = (target.start - block.start) as usize;
end = (min(target.end, block.end) - block.start) as usize;
} else {
// inside
start = (target.start - block.start) as usize;
end = start + (target.end - target.start) as usize;
}
&content[start..end]
}
}
#[cfg(test)]
mod tests {
use super::target_slice;
#[test]
#[allow(clippy::type_complexity)]
fn slice_for_target() {
use core::ops::Range;
// turns out these examples are not easy to determine at all
// writing out the type here avoids &b""[..] inside the array.
let cases: &[(&[u8], u64, Range<u64>, &[u8])] = &[
// xxxx xxxx cont ent_
// ^^^^ ^^^^
(b"content_", 8, 0..8, b""),
// xxxx xxxx cont ent_
// ^^^^ ^^^^ ^
(b"content_", 8, 0..9, b"c"),
// xxxx xxxx cont ent_
// ^^^ ^^^^ ^^^^ ^^^^ ...
(b"content_", 8, 1..20, b"content_"),
// xxxx xxxx cont ent_
// ^ ^^^^ ^^^^ ...
(b"content_", 8, 7..20, b"content_"),
// xxxx xxxx cont ent_
// ^^^^ ^^^^ ...
(b"content_", 8, 8..20, b"content_"),
// xxxx xxxx cont ent_
// ^^^ ^^^^ ...
(b"content_", 8, 9..20, b"ontent_"),
// xxxx xxxx cont ent_
// ^ ...
(b"content_", 8, 15..20, b"_"),
// xxxx xxxx cont ent_ yyyy
// ^^^^
(b"content_", 8, 16..20, b""),
];
for (block_data, block_offset, target_range, expected) in cases {
let block_range = *block_offset..(block_offset + block_data.len() as u64);
let sliced = target_slice(block_data, &block_range, target_range);
assert_eq!(
sliced, *expected,
"slice {:?} of block {:?}",
target_range, block_range
);
}
}
}
|
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Start UART receiver"]
pub tasks_startrx: TASKS_STARTRX,
#[doc = "0x04 - Stop UART receiver"]
pub tasks_stoprx: TASKS_STOPRX,
#[doc = "0x08 - Start UART transmitter"]
pub tasks_starttx: TASKS_STARTTX,
#[doc = "0x0c - Stop UART transmitter"]
pub tasks_stoptx: TASKS_STOPTX,
_reserved4: [u8; 28usize],
#[doc = "0x2c - Flush RX FIFO into RX buffer"]
pub tasks_flushrx: TASKS_FLUSHRX,
_reserved5: [u8; 208usize],
#[doc = "0x100 - CTS is activated (set low). Clear To Send."]
pub events_cts: EVENTS_CTS,
#[doc = "0x104 - CTS is deactivated (set high). Not Clear To Send."]
pub events_ncts: EVENTS_NCTS,
#[doc = "0x108 - Data received in RXD (but potentially not yet transferred to Data RAM)"]
pub events_rxdrdy: EVENTS_RXDRDY,
_reserved8: [u8; 4usize],
#[doc = "0x110 - Receive buffer is filled up"]
pub events_endrx: EVENTS_ENDRX,
_reserved9: [u8; 8usize],
#[doc = "0x11c - Data sent from TXD"]
pub events_txdrdy: EVENTS_TXDRDY,
#[doc = "0x120 - Last TX byte transmitted"]
pub events_endtx: EVENTS_ENDTX,
#[doc = "0x124 - Error detected"]
pub events_error: EVENTS_ERROR,
_reserved12: [u8; 28usize],
#[doc = "0x144 - Receiver timeout"]
pub events_rxto: EVENTS_RXTO,
_reserved13: [u8; 4usize],
#[doc = "0x14c - UART receiver has started"]
pub events_rxstarted: EVENTS_RXSTARTED,
#[doc = "0x150 - UART transmitter has started"]
pub events_txstarted: EVENTS_TXSTARTED,
_reserved15: [u8; 4usize],
#[doc = "0x158 - Transmitter stopped"]
pub events_txstopped: EVENTS_TXSTOPPED,
_reserved16: [u8; 164usize],
#[doc = "0x200 - Shortcut register"]
pub shorts: SHORTS,
_reserved17: [u8; 252usize],
#[doc = "0x300 - Enable or disable interrupt"]
pub inten: INTEN,
#[doc = "0x304 - Enable interrupt"]
pub intenset: INTENSET,
#[doc = "0x308 - Disable interrupt"]
pub intenclr: INTENCLR,
_reserved20: [u8; 372usize],
#[doc = "0x480 - Error source Note : this register is read / write one to clear."]
pub errorsrc: ERRORSRC,
_reserved21: [u8; 124usize],
#[doc = "0x500 - Enable UART"]
pub enable: ENABLE,
_reserved22: [u8; 4usize],
#[doc = "0x508 - Unspecified"]
pub psel: PSEL,
_reserved23: [u8; 12usize],
#[doc = "0x524 - Baud rate. Accuracy depends on the HFCLK source selected."]
pub baudrate: BAUDRATE,
_reserved24: [u8; 12usize],
#[doc = "0x534 - RXD EasyDMA channel"]
pub rxd: RXD,
_reserved25: [u8; 4usize],
#[doc = "0x544 - TXD EasyDMA channel"]
pub txd: TXD,
_reserved26: [u8; 28usize],
#[doc = "0x56c - Configuration of parity and hardware flow control"]
pub config: CONFIG,
}
#[doc = r" Register block"]
#[repr(C)]
pub struct PSEL {
#[doc = "0x00 - Pin select for RTS signal"]
pub rts: self::psel::RTS,
#[doc = "0x04 - Pin select for TXD signal"]
pub txd: self::psel::TXD,
#[doc = "0x08 - Pin select for CTS signal"]
pub cts: self::psel::CTS,
#[doc = "0x0c - Pin select for RXD signal"]
pub rxd: self::psel::RXD,
}
#[doc = r" Register block"]
#[doc = "Unspecified"]
pub mod psel;
#[doc = r" Register block"]
#[repr(C)]
pub struct RXD {
#[doc = "0x00 - Data pointer"]
pub ptr: self::rxd::PTR,
#[doc = "0x04 - Maximum number of bytes in receive buffer"]
pub maxcnt: self::rxd::MAXCNT,
#[doc = "0x08 - Number of bytes transferred in the last transaction"]
pub amount: self::rxd::AMOUNT,
}
#[doc = r" Register block"]
#[doc = "RXD EasyDMA channel"]
pub mod rxd;
#[doc = r" Register block"]
#[repr(C)]
pub struct TXD {
#[doc = "0x00 - Data pointer"]
pub ptr: self::txd::PTR,
#[doc = "0x04 - Maximum number of bytes in transmit buffer"]
pub maxcnt: self::txd::MAXCNT,
#[doc = "0x08 - Number of bytes transferred in the last transaction"]
pub amount: self::txd::AMOUNT,
}
#[doc = r" Register block"]
#[doc = "TXD EasyDMA channel"]
pub mod txd;
#[doc = "Start UART receiver"]
pub struct TASKS_STARTRX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start UART receiver"]
pub mod tasks_startrx;
#[doc = "Stop UART receiver"]
pub struct TASKS_STOPRX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop UART receiver"]
pub mod tasks_stoprx;
#[doc = "Start UART transmitter"]
pub struct TASKS_STARTTX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Start UART transmitter"]
pub mod tasks_starttx;
#[doc = "Stop UART transmitter"]
pub struct TASKS_STOPTX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Stop UART transmitter"]
pub mod tasks_stoptx;
#[doc = "Flush RX FIFO into RX buffer"]
pub struct TASKS_FLUSHRX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Flush RX FIFO into RX buffer"]
pub mod tasks_flushrx;
#[doc = "CTS is activated (set low). Clear To Send."]
pub struct EVENTS_CTS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "CTS is activated (set low). Clear To Send."]
pub mod events_cts;
#[doc = "CTS is deactivated (set high). Not Clear To Send."]
pub struct EVENTS_NCTS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "CTS is deactivated (set high). Not Clear To Send."]
pub mod events_ncts;
#[doc = "Data received in RXD (but potentially not yet transferred to Data RAM)"]
pub struct EVENTS_RXDRDY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Data received in RXD (but potentially not yet transferred to Data RAM)"]
pub mod events_rxdrdy;
#[doc = "Receive buffer is filled up"]
pub struct EVENTS_ENDRX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Receive buffer is filled up"]
pub mod events_endrx;
#[doc = "Data sent from TXD"]
pub struct EVENTS_TXDRDY {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Data sent from TXD"]
pub mod events_txdrdy;
#[doc = "Last TX byte transmitted"]
pub struct EVENTS_ENDTX {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Last TX byte transmitted"]
pub mod events_endtx;
#[doc = "Error detected"]
pub struct EVENTS_ERROR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Error detected"]
pub mod events_error;
#[doc = "Receiver timeout"]
pub struct EVENTS_RXTO {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Receiver timeout"]
pub mod events_rxto;
#[doc = "UART receiver has started"]
pub struct EVENTS_RXSTARTED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "UART receiver has started"]
pub mod events_rxstarted;
#[doc = "UART transmitter has started"]
pub struct EVENTS_TXSTARTED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "UART transmitter has started"]
pub mod events_txstarted;
#[doc = "Transmitter stopped"]
pub struct EVENTS_TXSTOPPED {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Transmitter stopped"]
pub mod events_txstopped;
#[doc = "Shortcut register"]
pub struct SHORTS {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Shortcut register"]
pub mod shorts;
#[doc = "Enable or disable interrupt"]
pub struct INTEN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable or disable interrupt"]
pub mod inten;
#[doc = "Enable interrupt"]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable interrupt"]
pub mod intenset;
#[doc = "Disable interrupt"]
pub struct INTENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Disable interrupt"]
pub mod intenclr;
#[doc = "Error source Note : this register is read / write one to clear."]
pub struct ERRORSRC {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Error source Note : this register is read / write one to clear."]
pub mod errorsrc;
#[doc = "Enable UART"]
pub struct ENABLE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Enable UART"]
pub mod enable;
#[doc = "Baud rate. Accuracy depends on the HFCLK source selected."]
pub struct BAUDRATE {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Baud rate. Accuracy depends on the HFCLK source selected."]
pub mod baudrate;
#[doc = "Configuration of parity and hardware flow control"]
pub struct CONFIG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Configuration of parity and hardware flow control"]
pub mod config;
|
#[doc = "Reader of register ROUTELOC2"]
pub type R = crate::R<u32, super::ROUTELOC2>;
#[doc = "Writer for register ROUTELOC2"]
pub type W = crate::W<u32, super::ROUTELOC2>;
#[doc = "Register ROUTELOC2 `reset()`'s with value 0"]
impl crate::ResetValue for super::ROUTELOC2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "I/O Location\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CH8LOC_A {
#[doc = "0: Location 0"]
LOC0 = 0,
#[doc = "1: Location 1"]
LOC1 = 1,
#[doc = "2: Location 2"]
LOC2 = 2,
#[doc = "3: Location 3"]
LOC3 = 3,
#[doc = "4: Location 4"]
LOC4 = 4,
#[doc = "5: Location 5"]
LOC5 = 5,
#[doc = "6: Location 6"]
LOC6 = 6,
#[doc = "7: Location 7"]
LOC7 = 7,
#[doc = "8: Location 8"]
LOC8 = 8,
#[doc = "9: Location 9"]
LOC9 = 9,
#[doc = "10: Location 10"]
LOC10 = 10,
}
impl From<CH8LOC_A> for u8 {
#[inline(always)]
fn from(variant: CH8LOC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CH8LOC`"]
pub type CH8LOC_R = crate::R<u8, CH8LOC_A>;
impl CH8LOC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CH8LOC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CH8LOC_A::LOC0),
1 => Val(CH8LOC_A::LOC1),
2 => Val(CH8LOC_A::LOC2),
3 => Val(CH8LOC_A::LOC3),
4 => Val(CH8LOC_A::LOC4),
5 => Val(CH8LOC_A::LOC5),
6 => Val(CH8LOC_A::LOC6),
7 => Val(CH8LOC_A::LOC7),
8 => Val(CH8LOC_A::LOC8),
9 => Val(CH8LOC_A::LOC9),
10 => Val(CH8LOC_A::LOC10),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LOC0`"]
#[inline(always)]
pub fn is_loc0(&self) -> bool {
*self == CH8LOC_A::LOC0
}
#[doc = "Checks if the value of the field is `LOC1`"]
#[inline(always)]
pub fn is_loc1(&self) -> bool {
*self == CH8LOC_A::LOC1
}
#[doc = "Checks if the value of the field is `LOC2`"]
#[inline(always)]
pub fn is_loc2(&self) -> bool {
*self == CH8LOC_A::LOC2
}
#[doc = "Checks if the value of the field is `LOC3`"]
#[inline(always)]
pub fn is_loc3(&self) -> bool {
*self == CH8LOC_A::LOC3
}
#[doc = "Checks if the value of the field is `LOC4`"]
#[inline(always)]
pub fn is_loc4(&self) -> bool {
*self == CH8LOC_A::LOC4
}
#[doc = "Checks if the value of the field is `LOC5`"]
#[inline(always)]
pub fn is_loc5(&self) -> bool {
*self == CH8LOC_A::LOC5
}
#[doc = "Checks if the value of the field is `LOC6`"]
#[inline(always)]
pub fn is_loc6(&self) -> bool {
*self == CH8LOC_A::LOC6
}
#[doc = "Checks if the value of the field is `LOC7`"]
#[inline(always)]
pub fn is_loc7(&self) -> bool {
*self == CH8LOC_A::LOC7
}
#[doc = "Checks if the value of the field is `LOC8`"]
#[inline(always)]
pub fn is_loc8(&self) -> bool {
*self == CH8LOC_A::LOC8
}
#[doc = "Checks if the value of the field is `LOC9`"]
#[inline(always)]
pub fn is_loc9(&self) -> bool {
*self == CH8LOC_A::LOC9
}
#[doc = "Checks if the value of the field is `LOC10`"]
#[inline(always)]
pub fn is_loc10(&self) -> bool {
*self == CH8LOC_A::LOC10
}
}
#[doc = "Write proxy for field `CH8LOC`"]
pub struct CH8LOC_W<'a> {
w: &'a mut W,
}
impl<'a> CH8LOC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CH8LOC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Location 0"]
#[inline(always)]
pub fn loc0(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC0)
}
#[doc = "Location 1"]
#[inline(always)]
pub fn loc1(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC1)
}
#[doc = "Location 2"]
#[inline(always)]
pub fn loc2(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC2)
}
#[doc = "Location 3"]
#[inline(always)]
pub fn loc3(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC3)
}
#[doc = "Location 4"]
#[inline(always)]
pub fn loc4(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC4)
}
#[doc = "Location 5"]
#[inline(always)]
pub fn loc5(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC5)
}
#[doc = "Location 6"]
#[inline(always)]
pub fn loc6(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC6)
}
#[doc = "Location 7"]
#[inline(always)]
pub fn loc7(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC7)
}
#[doc = "Location 8"]
#[inline(always)]
pub fn loc8(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC8)
}
#[doc = "Location 9"]
#[inline(always)]
pub fn loc9(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC9)
}
#[doc = "Location 10"]
#[inline(always)]
pub fn loc10(self) -> &'a mut W {
self.variant(CH8LOC_A::LOC10)
}
#[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 & !0x3f) | ((value as u32) & 0x3f);
self.w
}
}
#[doc = "I/O Location\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CH9LOC_A {
#[doc = "0: Location 0"]
LOC0 = 0,
#[doc = "1: Location 1"]
LOC1 = 1,
#[doc = "2: Location 2"]
LOC2 = 2,
#[doc = "3: Location 3"]
LOC3 = 3,
#[doc = "4: Location 4"]
LOC4 = 4,
#[doc = "5: Location 5"]
LOC5 = 5,
#[doc = "6: Location 6"]
LOC6 = 6,
#[doc = "7: Location 7"]
LOC7 = 7,
#[doc = "8: Location 8"]
LOC8 = 8,
#[doc = "9: Location 9"]
LOC9 = 9,
#[doc = "10: Location 10"]
LOC10 = 10,
#[doc = "11: Location 11"]
LOC11 = 11,
#[doc = "12: Location 12"]
LOC12 = 12,
#[doc = "13: Location 13"]
LOC13 = 13,
#[doc = "14: Location 14"]
LOC14 = 14,
#[doc = "15: Location 15"]
LOC15 = 15,
#[doc = "16: Location 16"]
LOC16 = 16,
}
impl From<CH9LOC_A> for u8 {
#[inline(always)]
fn from(variant: CH9LOC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CH9LOC`"]
pub type CH9LOC_R = crate::R<u8, CH9LOC_A>;
impl CH9LOC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CH9LOC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CH9LOC_A::LOC0),
1 => Val(CH9LOC_A::LOC1),
2 => Val(CH9LOC_A::LOC2),
3 => Val(CH9LOC_A::LOC3),
4 => Val(CH9LOC_A::LOC4),
5 => Val(CH9LOC_A::LOC5),
6 => Val(CH9LOC_A::LOC6),
7 => Val(CH9LOC_A::LOC7),
8 => Val(CH9LOC_A::LOC8),
9 => Val(CH9LOC_A::LOC9),
10 => Val(CH9LOC_A::LOC10),
11 => Val(CH9LOC_A::LOC11),
12 => Val(CH9LOC_A::LOC12),
13 => Val(CH9LOC_A::LOC13),
14 => Val(CH9LOC_A::LOC14),
15 => Val(CH9LOC_A::LOC15),
16 => Val(CH9LOC_A::LOC16),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LOC0`"]
#[inline(always)]
pub fn is_loc0(&self) -> bool {
*self == CH9LOC_A::LOC0
}
#[doc = "Checks if the value of the field is `LOC1`"]
#[inline(always)]
pub fn is_loc1(&self) -> bool {
*self == CH9LOC_A::LOC1
}
#[doc = "Checks if the value of the field is `LOC2`"]
#[inline(always)]
pub fn is_loc2(&self) -> bool {
*self == CH9LOC_A::LOC2
}
#[doc = "Checks if the value of the field is `LOC3`"]
#[inline(always)]
pub fn is_loc3(&self) -> bool {
*self == CH9LOC_A::LOC3
}
#[doc = "Checks if the value of the field is `LOC4`"]
#[inline(always)]
pub fn is_loc4(&self) -> bool {
*self == CH9LOC_A::LOC4
}
#[doc = "Checks if the value of the field is `LOC5`"]
#[inline(always)]
pub fn is_loc5(&self) -> bool {
*self == CH9LOC_A::LOC5
}
#[doc = "Checks if the value of the field is `LOC6`"]
#[inline(always)]
pub fn is_loc6(&self) -> bool {
*self == CH9LOC_A::LOC6
}
#[doc = "Checks if the value of the field is `LOC7`"]
#[inline(always)]
pub fn is_loc7(&self) -> bool {
*self == CH9LOC_A::LOC7
}
#[doc = "Checks if the value of the field is `LOC8`"]
#[inline(always)]
pub fn is_loc8(&self) -> bool {
*self == CH9LOC_A::LOC8
}
#[doc = "Checks if the value of the field is `LOC9`"]
#[inline(always)]
pub fn is_loc9(&self) -> bool {
*self == CH9LOC_A::LOC9
}
#[doc = "Checks if the value of the field is `LOC10`"]
#[inline(always)]
pub fn is_loc10(&self) -> bool {
*self == CH9LOC_A::LOC10
}
#[doc = "Checks if the value of the field is `LOC11`"]
#[inline(always)]
pub fn is_loc11(&self) -> bool {
*self == CH9LOC_A::LOC11
}
#[doc = "Checks if the value of the field is `LOC12`"]
#[inline(always)]
pub fn is_loc12(&self) -> bool {
*self == CH9LOC_A::LOC12
}
#[doc = "Checks if the value of the field is `LOC13`"]
#[inline(always)]
pub fn is_loc13(&self) -> bool {
*self == CH9LOC_A::LOC13
}
#[doc = "Checks if the value of the field is `LOC14`"]
#[inline(always)]
pub fn is_loc14(&self) -> bool {
*self == CH9LOC_A::LOC14
}
#[doc = "Checks if the value of the field is `LOC15`"]
#[inline(always)]
pub fn is_loc15(&self) -> bool {
*self == CH9LOC_A::LOC15
}
#[doc = "Checks if the value of the field is `LOC16`"]
#[inline(always)]
pub fn is_loc16(&self) -> bool {
*self == CH9LOC_A::LOC16
}
}
#[doc = "Write proxy for field `CH9LOC`"]
pub struct CH9LOC_W<'a> {
w: &'a mut W,
}
impl<'a> CH9LOC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CH9LOC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Location 0"]
#[inline(always)]
pub fn loc0(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC0)
}
#[doc = "Location 1"]
#[inline(always)]
pub fn loc1(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC1)
}
#[doc = "Location 2"]
#[inline(always)]
pub fn loc2(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC2)
}
#[doc = "Location 3"]
#[inline(always)]
pub fn loc3(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC3)
}
#[doc = "Location 4"]
#[inline(always)]
pub fn loc4(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC4)
}
#[doc = "Location 5"]
#[inline(always)]
pub fn loc5(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC5)
}
#[doc = "Location 6"]
#[inline(always)]
pub fn loc6(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC6)
}
#[doc = "Location 7"]
#[inline(always)]
pub fn loc7(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC7)
}
#[doc = "Location 8"]
#[inline(always)]
pub fn loc8(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC8)
}
#[doc = "Location 9"]
#[inline(always)]
pub fn loc9(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC9)
}
#[doc = "Location 10"]
#[inline(always)]
pub fn loc10(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC10)
}
#[doc = "Location 11"]
#[inline(always)]
pub fn loc11(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC11)
}
#[doc = "Location 12"]
#[inline(always)]
pub fn loc12(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC12)
}
#[doc = "Location 13"]
#[inline(always)]
pub fn loc13(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC13)
}
#[doc = "Location 14"]
#[inline(always)]
pub fn loc14(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC14)
}
#[doc = "Location 15"]
#[inline(always)]
pub fn loc15(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC15)
}
#[doc = "Location 16"]
#[inline(always)]
pub fn loc16(self) -> &'a mut W {
self.variant(CH9LOC_A::LOC16)
}
#[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 & !(0x3f << 8)) | (((value as u32) & 0x3f) << 8);
self.w
}
}
#[doc = "I/O Location\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CH10LOC_A {
#[doc = "0: Location 0"]
LOC0 = 0,
#[doc = "1: Location 1"]
LOC1 = 1,
#[doc = "2: Location 2"]
LOC2 = 2,
#[doc = "3: Location 3"]
LOC3 = 3,
#[doc = "4: Location 4"]
LOC4 = 4,
#[doc = "5: Location 5"]
LOC5 = 5,
}
impl From<CH10LOC_A> for u8 {
#[inline(always)]
fn from(variant: CH10LOC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CH10LOC`"]
pub type CH10LOC_R = crate::R<u8, CH10LOC_A>;
impl CH10LOC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CH10LOC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CH10LOC_A::LOC0),
1 => Val(CH10LOC_A::LOC1),
2 => Val(CH10LOC_A::LOC2),
3 => Val(CH10LOC_A::LOC3),
4 => Val(CH10LOC_A::LOC4),
5 => Val(CH10LOC_A::LOC5),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LOC0`"]
#[inline(always)]
pub fn is_loc0(&self) -> bool {
*self == CH10LOC_A::LOC0
}
#[doc = "Checks if the value of the field is `LOC1`"]
#[inline(always)]
pub fn is_loc1(&self) -> bool {
*self == CH10LOC_A::LOC1
}
#[doc = "Checks if the value of the field is `LOC2`"]
#[inline(always)]
pub fn is_loc2(&self) -> bool {
*self == CH10LOC_A::LOC2
}
#[doc = "Checks if the value of the field is `LOC3`"]
#[inline(always)]
pub fn is_loc3(&self) -> bool {
*self == CH10LOC_A::LOC3
}
#[doc = "Checks if the value of the field is `LOC4`"]
#[inline(always)]
pub fn is_loc4(&self) -> bool {
*self == CH10LOC_A::LOC4
}
#[doc = "Checks if the value of the field is `LOC5`"]
#[inline(always)]
pub fn is_loc5(&self) -> bool {
*self == CH10LOC_A::LOC5
}
}
#[doc = "Write proxy for field `CH10LOC`"]
pub struct CH10LOC_W<'a> {
w: &'a mut W,
}
impl<'a> CH10LOC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CH10LOC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Location 0"]
#[inline(always)]
pub fn loc0(self) -> &'a mut W {
self.variant(CH10LOC_A::LOC0)
}
#[doc = "Location 1"]
#[inline(always)]
pub fn loc1(self) -> &'a mut W {
self.variant(CH10LOC_A::LOC1)
}
#[doc = "Location 2"]
#[inline(always)]
pub fn loc2(self) -> &'a mut W {
self.variant(CH10LOC_A::LOC2)
}
#[doc = "Location 3"]
#[inline(always)]
pub fn loc3(self) -> &'a mut W {
self.variant(CH10LOC_A::LOC3)
}
#[doc = "Location 4"]
#[inline(always)]
pub fn loc4(self) -> &'a mut W {
self.variant(CH10LOC_A::LOC4)
}
#[doc = "Location 5"]
#[inline(always)]
pub fn loc5(self) -> &'a mut W {
self.variant(CH10LOC_A::LOC5)
}
#[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 & !(0x3f << 16)) | (((value as u32) & 0x3f) << 16);
self.w
}
}
#[doc = "I/O Location\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CH11LOC_A {
#[doc = "0: Location 0"]
LOC0 = 0,
#[doc = "1: Location 1"]
LOC1 = 1,
#[doc = "2: Location 2"]
LOC2 = 2,
#[doc = "3: Location 3"]
LOC3 = 3,
#[doc = "4: Location 4"]
LOC4 = 4,
#[doc = "5: Location 5"]
LOC5 = 5,
}
impl From<CH11LOC_A> for u8 {
#[inline(always)]
fn from(variant: CH11LOC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CH11LOC`"]
pub type CH11LOC_R = crate::R<u8, CH11LOC_A>;
impl CH11LOC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CH11LOC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CH11LOC_A::LOC0),
1 => Val(CH11LOC_A::LOC1),
2 => Val(CH11LOC_A::LOC2),
3 => Val(CH11LOC_A::LOC3),
4 => Val(CH11LOC_A::LOC4),
5 => Val(CH11LOC_A::LOC5),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LOC0`"]
#[inline(always)]
pub fn is_loc0(&self) -> bool {
*self == CH11LOC_A::LOC0
}
#[doc = "Checks if the value of the field is `LOC1`"]
#[inline(always)]
pub fn is_loc1(&self) -> bool {
*self == CH11LOC_A::LOC1
}
#[doc = "Checks if the value of the field is `LOC2`"]
#[inline(always)]
pub fn is_loc2(&self) -> bool {
*self == CH11LOC_A::LOC2
}
#[doc = "Checks if the value of the field is `LOC3`"]
#[inline(always)]
pub fn is_loc3(&self) -> bool {
*self == CH11LOC_A::LOC3
}
#[doc = "Checks if the value of the field is `LOC4`"]
#[inline(always)]
pub fn is_loc4(&self) -> bool {
*self == CH11LOC_A::LOC4
}
#[doc = "Checks if the value of the field is `LOC5`"]
#[inline(always)]
pub fn is_loc5(&self) -> bool {
*self == CH11LOC_A::LOC5
}
}
#[doc = "Write proxy for field `CH11LOC`"]
pub struct CH11LOC_W<'a> {
w: &'a mut W,
}
impl<'a> CH11LOC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CH11LOC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Location 0"]
#[inline(always)]
pub fn loc0(self) -> &'a mut W {
self.variant(CH11LOC_A::LOC0)
}
#[doc = "Location 1"]
#[inline(always)]
pub fn loc1(self) -> &'a mut W {
self.variant(CH11LOC_A::LOC1)
}
#[doc = "Location 2"]
#[inline(always)]
pub fn loc2(self) -> &'a mut W {
self.variant(CH11LOC_A::LOC2)
}
#[doc = "Location 3"]
#[inline(always)]
pub fn loc3(self) -> &'a mut W {
self.variant(CH11LOC_A::LOC3)
}
#[doc = "Location 4"]
#[inline(always)]
pub fn loc4(self) -> &'a mut W {
self.variant(CH11LOC_A::LOC4)
}
#[doc = "Location 5"]
#[inline(always)]
pub fn loc5(self) -> &'a mut W {
self.variant(CH11LOC_A::LOC5)
}
#[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 & !(0x3f << 24)) | (((value as u32) & 0x3f) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:5 - I/O Location"]
#[inline(always)]
pub fn ch8loc(&self) -> CH8LOC_R {
CH8LOC_R::new((self.bits & 0x3f) as u8)
}
#[doc = "Bits 8:13 - I/O Location"]
#[inline(always)]
pub fn ch9loc(&self) -> CH9LOC_R {
CH9LOC_R::new(((self.bits >> 8) & 0x3f) as u8)
}
#[doc = "Bits 16:21 - I/O Location"]
#[inline(always)]
pub fn ch10loc(&self) -> CH10LOC_R {
CH10LOC_R::new(((self.bits >> 16) & 0x3f) as u8)
}
#[doc = "Bits 24:29 - I/O Location"]
#[inline(always)]
pub fn ch11loc(&self) -> CH11LOC_R {
CH11LOC_R::new(((self.bits >> 24) & 0x3f) as u8)
}
}
impl W {
#[doc = "Bits 0:5 - I/O Location"]
#[inline(always)]
pub fn ch8loc(&mut self) -> CH8LOC_W {
CH8LOC_W { w: self }
}
#[doc = "Bits 8:13 - I/O Location"]
#[inline(always)]
pub fn ch9loc(&mut self) -> CH9LOC_W {
CH9LOC_W { w: self }
}
#[doc = "Bits 16:21 - I/O Location"]
#[inline(always)]
pub fn ch10loc(&mut self) -> CH10LOC_W {
CH10LOC_W { w: self }
}
#[doc = "Bits 24:29 - I/O Location"]
#[inline(always)]
pub fn ch11loc(&mut self) -> CH11LOC_W {
CH11LOC_W { w: self }
}
}
|
use serde_derive::Deserialize;
use super::{parse_to_config_file, ConfigStructure, Flattenable};
use crate::sort;
use crate::CONFIG_FILE;
const fn default_true() -> bool {
true
}
const fn default_scroll_offset() -> usize {
6
}
const fn default_max_preview_size() -> u64 {
2 * 1024 * 1024 // 2 MB
}
const fn default_column_ratio() -> (usize, usize, usize) {
(1, 3, 4)
}
#[derive(Clone, Debug, Deserialize)]
struct SortRawOption {
#[serde(default)]
show_hidden: bool,
#[serde(default = "default_true")]
directories_first: bool,
#[serde(default)]
case_sensitive: bool,
#[serde(default)]
reverse: bool,
}
impl SortRawOption {
pub fn into_sort_option(self, sort_method: sort::SortType) -> sort::SortOption {
sort::SortOption {
show_hidden: self.show_hidden,
directories_first: self.directories_first,
case_sensitive: self.case_sensitive,
reverse: self.reverse,
sort_method,
}
}
}
impl std::default::Default for SortRawOption {
fn default() -> Self {
SortRawOption {
show_hidden: bool::default(),
directories_first: default_true(),
case_sensitive: bool::default(),
reverse: bool::default(),
}
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct LllRawConfig {
#[serde(default = "default_scroll_offset")]
scroll_offset: usize,
#[serde(default = "default_max_preview_size")]
max_preview_size: u64,
column_ratio: Option<[usize; 3]>,
sort_method: Option<String>,
#[serde(default)]
sort_option: SortRawOption,
}
impl Flattenable<LllConfig> for LllRawConfig {
fn flatten(self) -> LllConfig {
let column_ratio = match self.column_ratio {
Some(s) => (s[0], s[1], s[2]),
_ => default_column_ratio(),
};
let sort_method = match self.sort_method {
Some(s) => match sort::SortType::parse(s.as_str()) {
Some(s) => s,
None => sort::SortType::Natural,
},
None => sort::SortType::Natural,
};
let sort_option = self.sort_option.into_sort_option(sort_method);
LllConfig {
scroll_offset: self.scroll_offset,
max_preview_size: self.max_preview_size,
column_ratio,
sort_option,
}
}
}
#[derive(Debug, Clone)]
pub struct LllConfig {
pub scroll_offset: usize,
pub max_preview_size: u64,
pub sort_option: sort::SortOption,
pub column_ratio: (usize, usize, usize),
}
impl ConfigStructure for LllConfig {
fn get_config() -> Self {
parse_to_config_file::<LllRawConfig, LllConfig>(CONFIG_FILE)
.unwrap_or_else(LllConfig::default)
}
}
impl std::default::Default for LllConfig {
fn default() -> Self {
let sort_option = sort::SortOption::default();
LllConfig {
scroll_offset: default_scroll_offset(),
max_preview_size: default_max_preview_size(),
sort_option,
column_ratio: default_column_ratio(),
}
}
}
|
use std::env;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Need to provide a search term :)");
process::exit(1);
}
if let Err(e) = wikit::run(args) {
println!("Application error: {}", e);
process::exit(1);
}
}
|
mod apu;
mod cpu;
mod gamepad;
mod gui;
mod ines;
mod kevtris;
mod mapper;
mod png;
mod ppu;
mod record;
use std::env;
fn main() {
let mut cpu = cpu::Cpu::new();
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
let filename = &args[1];
let file = ines::File::read(filename);
cpu.load_game(file);
cpu.reset();
cpu.ppu.build_ntsc_palette();
gui::execute(&mut cpu);
} else {
cpu::Cpu::kevtris_nestest();
}
}
|
#[doc = "Reader of register PPSSI"]
pub type R = crate::R<u32, super::PPSSI>;
#[doc = "Reader of field `P0`"]
pub type P0_R = crate::R<bool, bool>;
#[doc = "Reader of field `P1`"]
pub type P1_R = crate::R<bool, bool>;
#[doc = "Reader of field `P2`"]
pub type P2_R = crate::R<bool, bool>;
#[doc = "Reader of field `P3`"]
pub type P3_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - SSI Module 0 Present"]
#[inline(always)]
pub fn p0(&self) -> P0_R {
P0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - SSI Module 1 Present"]
#[inline(always)]
pub fn p1(&self) -> P1_R {
P1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - SSI Module 2 Present"]
#[inline(always)]
pub fn p2(&self) -> P2_R {
P2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - SSI Module 3 Present"]
#[inline(always)]
pub fn p3(&self) -> P3_R {
P3_R::new(((self.bits >> 3) & 0x01) != 0)
}
}
|
use thiserror::Error;
use crate::direction::Direction;
#[derive(Debug, Error)]
pub enum DecodeError {
#[error("incomplete op (opcode={opcode:#04x})")]
Incomplete { opcode: u8 },
#[error("undefined op (opcode={opcode:#04x})")]
Undefined { opcode: u8 },
}
pub type DecodeResult<T> = Result<T, DecodeError>;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Op {
Move(Direction),
Jump(u8),
SetSleepTimer(u8),
LoopBegin(u8),
LoopEnd,
ShootDirection(Direction),
SetSprite(u8),
SetHomingTimer(u8),
SetInversion(bool, bool),
SetPosition(u8, u8),
// これらは全てオペコード 0xA1。
// ザコの場合、(0xA1, 0x01..=0xFF) で被弾時のジャンプ先を設定し、(0xA1, 0x00) で設定解除。
// ボスの場合、(0xA1, 0x00..=0xFF) でHPを設定。
SetJumpOnDamage(u8),
UnsetJumpOnDamage,
SetHealth(u8),
IncrementSprite,
DecrementSprite,
SetPart(u8),
RandomizeX(u8),
RandomizeY(u8),
BccX(u8),
BcsX(u8),
BccY(u8),
BcsY(u8),
// オペコード 0xC0..=0xCF は全て同じ機能と思われる。
ShootAim(u8),
RestoreMusic,
PlaySound(u8),
}
impl Op {
pub fn new_move(dir: Direction) -> Self {
Self::Move(dir)
}
pub fn new_jump(addr: u8) -> Self {
Self::Jump(addr)
}
pub fn new_set_sleep_timer(idx: u8) -> Self {
assert!((0..=0xF).contains(&idx));
Self::SetSleepTimer(idx)
}
pub fn new_loop_begin(idx: u8) -> Self {
assert!((0..=0xF).contains(&idx));
assert_ne!(idx, 1);
Self::LoopBegin(idx)
}
pub fn new_loop_end() -> Self {
Self::LoopEnd
}
pub fn new_shoot_direction(dir: Direction) -> Self {
assert!((0..=0xF).contains(&dir.index()));
Self::ShootDirection(dir)
}
pub fn new_set_sprite(idx: u8) -> Self {
assert!((0..=0xF).contains(&idx));
Self::SetSprite(idx)
}
pub fn new_set_homing_timer(idx: u8) -> Self {
assert!((0..=0xF).contains(&idx));
Self::SetHomingTimer(idx)
}
pub fn new_set_inversion(inv_x: bool, inv_y: bool) -> Self {
Self::SetInversion(inv_x, inv_y)
}
pub fn new_set_position(x: u8, y: u8) -> Self {
Self::SetPosition(x, y)
}
pub fn new_set_jump_on_damage(addr: u8) -> Self {
assert_ne!(addr, 0);
Self::SetJumpOnDamage(addr)
}
pub fn new_unset_jump_on_damage() -> Self {
Self::UnsetJumpOnDamage
}
pub fn new_set_health(health: u8) -> Self {
Self::SetHealth(health)
}
pub fn new_increment_sprite() -> Self {
Self::IncrementSprite
}
pub fn new_decrement_sprite() -> Self {
Self::DecrementSprite
}
pub fn new_set_part(part: u8) -> Self {
Self::SetPart(part)
}
pub fn new_randomize_x(mask: u8) -> Self {
Self::RandomizeX(mask)
}
pub fn new_randomize_y(mask: u8) -> Self {
Self::RandomizeY(mask)
}
pub fn new_bcc_x(addr: u8) -> Self {
Self::BccX(addr)
}
pub fn new_bcs_x(addr: u8) -> Self {
Self::BcsX(addr)
}
pub fn new_bcc_y(addr: u8) -> Self {
Self::BccY(addr)
}
pub fn new_bcs_y(addr: u8) -> Self {
Self::BcsY(addr)
}
pub fn new_shoot_aim(unused: u8) -> Self {
assert!((0..=0xF).contains(&unused));
Self::ShootAim(unused)
}
pub fn new_restore_music() -> Self {
Self::RestoreMusic
}
pub fn new_play_sound(sound: u8) -> Self {
assert!((1..=0xF).contains(&sound));
Self::PlaySound(sound)
}
pub fn len(self) -> usize {
match self {
Self::Move(..) => 1,
Self::Jump(..) => 2,
Self::SetSleepTimer(..) => 1,
Self::LoopBegin(..) => 1,
Self::LoopEnd => 1,
Self::ShootDirection(..) => 1,
Self::SetSprite(..) => 1,
Self::SetHomingTimer(..) => 1,
Self::SetInversion(..) => 1,
Self::SetPosition(..) => 3,
Self::SetJumpOnDamage(..) => 2,
Self::UnsetJumpOnDamage => 2,
Self::SetHealth(..) => 2,
Self::IncrementSprite => 1,
Self::DecrementSprite => 1,
Self::SetPart(..) => 2,
Self::RandomizeX(..) => 2,
Self::RandomizeY(..) => 2,
Self::BccX(..) => 2,
Self::BcsX(..) => 2,
Self::BccY(..) => 2,
Self::BcsY(..) => 2,
Self::ShootAim(..) => 1,
Self::RestoreMusic => 1,
Self::PlaySound(..) => 1,
}
}
pub fn addr_destination(self) -> Option<u8> {
match self {
Self::Jump(addr) => Some(addr),
Self::SetJumpOnDamage(addr) => Some(addr),
Self::BccX(addr) => Some(addr),
Self::BcsX(addr) => Some(addr),
Self::BccY(addr) => Some(addr),
Self::BcsY(addr) => Some(addr),
_ => None,
}
}
pub fn decode(buf: &[u8]) -> DecodeResult<Self> {
assert!(!buf.is_empty());
let opcode = buf[0];
macro_rules! ensure_buf_len {
($len:expr) => {{
if buf.len() < $len {
return Err(DecodeError::Incomplete { opcode });
}
}};
}
match opcode {
0x00..=0x3F => Ok(Self::new_move(Direction::new(opcode))),
0x40 => {
ensure_buf_len!(2);
let addr = buf[1];
Ok(Self::new_jump(addr))
}
0x41..=0x4F => Ok(Self::new_set_sleep_timer(opcode & 0xF)),
0x50 | 0x52..=0x5F => Ok(Self::new_loop_begin(opcode & 0xF)),
0x51 => Ok(Self::new_loop_end()),
0x60..=0x6F => Ok(Self::new_shoot_direction(Direction::new(opcode & 0xF))),
0x70..=0x7F => Ok(Self::new_set_sprite(opcode & 0xF)),
0x80..=0x8F => Ok(Self::new_set_homing_timer(opcode & 0xF)),
0x90..=0x93 => Ok(Self::new_set_inversion(
(opcode & 1) != 0,
(opcode & 2) != 0,
)),
0xA0 => {
ensure_buf_len!(3);
let x = buf[1];
let y = buf[2];
Ok(Self::new_set_position(x, y))
}
// バイナリを見ただけでは set_jump_on_damage, set_health のどちらなのか判別できない。
// とりあえず前者だと仮定し、判別はクライアント側に任せる。
0xA1 => {
ensure_buf_len!(2);
let addr = buf[1];
if addr == 0 {
Ok(Self::new_unset_jump_on_damage())
} else {
Ok(Self::new_set_jump_on_damage(addr))
}
}
0xA2 => Ok(Self::new_increment_sprite()),
0xA3 => Ok(Self::new_decrement_sprite()),
0xA4 => {
ensure_buf_len!(2);
let part = buf[1];
Ok(Self::new_set_part(part))
}
0xA5 => {
ensure_buf_len!(2);
let mask = buf[1];
Ok(Self::new_randomize_x(mask))
}
0xA6 => {
ensure_buf_len!(2);
let mask = buf[1];
Ok(Self::new_randomize_y(mask))
}
0xB0 => {
ensure_buf_len!(2);
let addr = buf[1];
Ok(Self::new_bcc_x(addr))
}
0xB1 => {
ensure_buf_len!(2);
let addr = buf[1];
Ok(Self::new_bcs_x(addr))
}
0xB2 => {
ensure_buf_len!(2);
let addr = buf[1];
Ok(Self::new_bcc_y(addr))
}
0xB3 => {
ensure_buf_len!(2);
let addr = buf[1];
Ok(Self::new_bcs_y(addr))
}
0xC0..=0xCF => Ok(Self::new_shoot_aim(opcode & 0xF)),
0xF0 => Ok(Self::new_restore_music()),
0xF1..=0xFF => Ok(Self::new_play_sound(opcode & 0xF)),
_ => Err(DecodeError::Undefined { opcode }),
}
}
pub fn encode(self, buf: &mut [u8]) {
match self {
Self::Move(dir) => buf[0] = dir.index(),
Self::Jump(addr) => {
buf[0] = 0x40;
buf[1] = addr;
}
Self::SetSleepTimer(idx) => buf[0] = 0x40 | idx,
Self::LoopBegin(idx) => buf[0] = 0x50 | idx,
Self::LoopEnd => buf[0] = 0x51,
Self::ShootDirection(dir) => buf[0] = 0x60 | dir.index(),
Self::SetSprite(idx) => buf[0] = 0x70 | idx,
Self::SetHomingTimer(idx) => buf[0] = 0x80 | idx,
Self::SetInversion(inv_x, inv_y) => {
buf[0] = 0x90 | u8::from(inv_x) | (u8::from(inv_y) << 1);
}
Self::SetPosition(x, y) => {
buf[0] = 0xA0;
buf[1] = x;
buf[2] = y;
}
Self::SetJumpOnDamage(addr) => {
buf[0] = 0xA1;
buf[1] = addr;
}
Self::UnsetJumpOnDamage => {
buf[0] = 0xA1;
buf[1] = 0;
}
Self::SetHealth(health) => {
buf[0] = 0xA1;
buf[1] = health;
}
Self::IncrementSprite => buf[0] = 0xA2,
Self::DecrementSprite => buf[0] = 0xA3,
Self::SetPart(part) => {
buf[0] = 0xA4;
buf[1] = part;
}
Self::RandomizeX(mask) => {
buf[0] = 0xA5;
buf[1] = mask;
}
Self::RandomizeY(mask) => {
buf[0] = 0xA6;
buf[1] = mask;
}
Self::BccX(addr) => {
buf[0] = 0xB0;
buf[1] = addr;
}
Self::BcsX(addr) => {
buf[0] = 0xB1;
buf[1] = addr;
}
Self::BccY(addr) => {
buf[0] = 0xB2;
buf[1] = addr;
}
Self::BcsY(addr) => {
buf[0] = 0xB3;
buf[1] = addr;
}
Self::ShootAim(unused) => buf[0] = 0xC0 | unused,
Self::RestoreMusic => buf[0] = 0xF0,
Self::PlaySound(sound) => buf[0] = 0xF0 | sound,
}
}
}
|
use proconio::{input, marker::Usize1};
fn dfs(i: usize, g: &Vec<Vec<usize>>, seen: &mut Vec<bool>) {
seen[i] = true;
for &j in &g[i] {
if seen[j] {
continue;
}
dfs(j, g, seen);
}
}
fn main() {
input! {
n: usize,
m: usize,
edges: [(Usize1, Usize1); m],
};
let mut g = vec![vec![]; n];
for (u, v) in edges {
g[u].push(v);
g[v].push(u);
}
let mut seen = vec![false; n];
let mut ans = 0;
for i in 0..n {
if seen[i] {
continue;
}
ans += 1;
dfs(i, &g, &mut seen);
}
println!("{}", ans);
}
|
use crate::dtos::{SurveyDTO, SurveyDTOs};
/// A trait that provides a collection like abstraction over read only database access.
///
/// Generic T is likely a DTO used for pure data transfer to an external caller,
/// whether that's via a REST controller or over gRPC as a proto type etc.
pub trait SurveyDTOReadRepository {
/// Error type that likely corresponds to an underlying database error.
type Error: 'static + std::error::Error + std::fmt::Display + Send;
/// Returns the SurveyDTO corresponding to the supplied key as an owned type.
///
/// # Failure case
///
/// If we fail to communicate with the underlying storage, then an error is returned.
fn get_survey_for_author(&mut self, id: &String, author: &String) -> Result<Option<SurveyDTO>, Self::Error>;
/// Returns a `Vec<ListViewSurveyDTO>`, based on the supplied `page_num` and `page_size`.
/// The page_num should start at 1, but is up to the implementer to design as they see fit.
/// This is returned as a unique type because the inner `ListViewSurveyDTO` is trimmed down,
/// and intended for a list view where questions and choices aren't necessary data.
///
/// # Failure case
///
/// If we fail to communicate with the underlying storage, then an error is returned.
fn get_surveys_by_author(&mut self, author: &String) -> Result<Option<SurveyDTOs>, Self::Error>;
}
|
fn main() {
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
println!("{}", user1.email);
println!("{}", user1.username);
println!("{}", user1.active);
println!("{}", user1.sign_in_count);
// To edit a struct, it needs to be mutable
let mut user2 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
user2.email = String::from("anotheremail@example.com");
println!("{}", user2.email);
println!("{}", user2.username);
println!("{}", user2.active);
println!("{}", user2.sign_in_count);
fn build_user(email: String, username: String) -> User {
User {
email,
username,
active: true,
sign_in_count: 1,
}
}
let user3 = build_user(String::from("email"), String::from("username"));
println!("{}", user3.email);
println!("{}", user3.username);
println!("{}", user3.active);
println!("{}", user3.sign_in_count);
// We can also create new structs based on an other one
let user4 = User {
email: String::from("another@example.com"),
username: String::from("anotherusername567"),
..user1
};
println!("{}", user4.email);
println!("{}", user4.username);
println!("{}", user4.active);
println!("{}", user4.sign_in_count);
// Tuple structs can be used when we don't want to have specific variable names
struct Color(i32, i32, i32);
let black = Color(0, 0, 0);
println!("{}", black.0);
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {:?}", rect1);
// New line between each field
println!("rect1 is {:#?}", rect1);
// To define a method for the structure
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
println!("The area of the rectangle is {} square pixels.", rect1.area());
fn area2(rect: &Rectangle) -> u32 {
&rect.width * &rect.height
}
println!("The area of the rectangle is {} square pixels.", area2(&rect1));
// We can have multiple impl blocks
impl Rectangle {
// Here is a constructor
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
}
let square = Rectangle::square(10);
println!("The area of the square is {} square pixels.", square.area());
}
|
use super::layer::Layer;
pub struct Network {
layers: Vec<Layer>,
}
impl Network {
pub fn new(layout: Vec<u32>) -> Network {
let mut layers = Vec::with_capacity(layout.len());
for (index, nb_neurons) in layout.into_iter().enumerate() {
layers.push(Layer::new(nb_neurons, find_previous_layer(&layers, index)));
}
Network {
layers,
}
}
pub fn predict(&mut self, inputs: Vec<f32>) -> Vec<f32> {
self.layers.get(0).expect("Network has no layer ?!").set_input_value(inputs);
for layer in self.layers.iter_mut().skip(1) {
layer.compute_layer();
}
self.layers.last().unwrap().get_values()
}
}
// -------
// HELPERS
// -------
fn find_previous_layer(layers: &Vec<Layer>, index: usize) -> Option<&Layer> {
match index {
0 => None,
i => layers.get(i - 1),
}
}
|
extern crate rayon;
extern crate rand;
extern crate statrs;
extern crate petgraph;
extern crate vec_graph;
extern crate gurobi;
extern crate capngraph;
extern crate bit_set;
extern crate docopt;
#[macro_use]
extern crate slog;
extern crate slog_stream;
extern crate slog_term;
extern crate slog_json;
extern crate serde;
extern crate serde_json;
extern crate bincode;
#[macro_use]
extern crate serde_derive;
extern crate rand_mersenne_twister;
#[cfg(test)]
#[macro_use]
extern crate quickcheck;
use std::fs::File;
use std::cell::RefCell;
use petgraph::prelude::*;
use rayon::prelude::*;
use petgraph::visit::EdgeFiltered;
use petgraph::algo::bellman_ford;
use slog::{Logger, DrainExt};
use statrs::distribution::Uniform;
use rand::Rng;
use rand::distributions::IndependentSample;
use bit_set::BitSet;
use rand_mersenne_twister::{MTRng64, mersenne};
use serde_json::to_string as json_string;
use bincode::{Infinite, deserialize_from as bin_read_from};
#[cfg_attr(rustfmt, rustfmt_skip)]
const USAGE: &str = "
Run the E-EXACT IP. Be warned that THIS IS VERY SLOW. Only run on small datasets.
Only the IC model is supported.
See https://arxiv.org/abs/1701.08462 for exact definition of this IP.
Usage:
e-exact <graph> IC <k> <samples> [options]
e-exact (-h | --help)
Options:
-h --help Show this screen.
--log <logfile> Log to given file.
--threads <threads> Number of threads to use.
--costs <path> Path to costs file.
--benefits <path> Path to benefits file.
";
#[derive(Debug, Serialize, Deserialize)]
struct Args {
arg_graph: String,
arg_k: usize,
arg_samples: usize,
flag_log: Option<String>,
flag_threads: Option<usize>,
flag_costs: Option<String>,
flag_benefits: Option<String>,
}
thread_local!(static RNG: RefCell<MTRng64> = RefCell::new(mersenne()));
type CostVec = Vec<f64>;
type BenVec = Vec<f64>;
type InfGraph = Graph<(), f32>;
type Sample = BitSet;
type Cycle = Vec<EdgeIndex>;
type CycleVec = Vec<Cycle>;
fn sample<R: Rng>(rng: &mut R, g: &InfGraph) -> Sample {
let uniform = Uniform::new(0.0, 1.0).expect("Unable to construct uniform dist (?!?!?)");
let mut sample = Sample::default();
for edge in g.edge_references() {
if uniform.ind_sample(rng) < *edge.weight() as f64 {
sample.insert(edge.id().index());
}
}
sample
}
fn ip(g: &InfGraph,
samples: &Vec<Sample>,
sample_cycles: &Vec<CycleVec>,
k: usize,
benefits: Option<&BenVec>,
costs: Option<&CostVec>,
threads: usize,
log: Logger)
-> Result<(Vec<usize>, Vec<Vec<bool>>), String> {
use gurobi::*;
let mut env = Env::new();
env.set_threads(threads)?;
let mut model = Model::new(&env)?;
model.set_objective_type(ObjectiveType::Maximize)?;
#[allow(non_snake_case)]
let T = samples.len() as f64;
info!(log, "building IP");
let s = g.node_indices()
.map(|u| {
model.add_var(benefits.as_ref().map(|b| b[u.index()]).unwrap_or(1.0),
VariableType::Binary)
.unwrap()
})
.collect::<Vec<_>>();
let inv = g.node_indices().collect::<Vec<_>>();
// cardinality constraint
model.add_con(costs.map(|c| Constraint::build().weighted_sum(&s, c).is_less_than(k as f64))
.unwrap_or_else(|| Constraint::build().sum(&s).is_less_than(k as f64)))?;
let mut ys = Vec::with_capacity(samples.len());
for (sample, cycles) in samples.iter().zip(sample_cycles) {
let y = g.edge_references()
.map(|e| {
model.add_var(benefits.as_ref().map(|b| b[e.target().index()]).unwrap_or(1.0) / T,
VariableType::Binary)
.unwrap()
})
.collect::<Vec<_>>();
debug!(log, "adding edge connectivity constraints");
for eref in g.edge_references() {
let con = Constraint::build()
.sum(g.edges_directed(eref.source(), Incoming)
.filter(|e| sample.contains(e.id().index()))
.map(|e| y[e.id().index()]))
.plus(s[eref.source().index()], 1.0)
.plus(y[eref.id().index()], -1.0)
.is_greater_than(0.0);
model.add_con(con)?;
}
debug!(log, "adding node connectivity constraints");
for v in g.node_indices() {
let con = Constraint::build()
.sum(g.edges_directed(v, Incoming)
.filter(|e| sample.contains(e.id().index()))
.map(|e| y[e.id().index()]))
.plus(s[v.index()], 1.0)
.is_less_than(1.0);
model.add_con(con)?;
}
debug!(log, "adding {} cycle constraints", cycles.len());
for cycle in cycles {
let con = Constraint::build()
.sum(cycle.iter().map(|e| y[e.index()]))
.is_less_than(cycle.len() as f64 - 1.0);
model.add_con(con)?;
}
ys.push(y);
}
let sol = model.optimize()?;
info!(log, "found solution"; "value" => sol.value()?);
Ok((sol.variables(s[0], s[s.len() - 1])?
.iter()
.enumerate()
.filter_map(|(i, &f)| if f == 1.0 { Some(inv[i].index()) } else { None })
.collect(),
ys.into_iter()
.map(|y| {
sol.variables(y[0], y[y.len() - 1]).unwrap().iter().map(|&v| v == 1.0).collect()
})
.collect()))
}
fn e_exact(g: &InfGraph,
samples: &Vec<Sample>,
k: usize,
benefits: Option<BenVec>,
costs: Option<CostVec>,
threads: usize,
log: Logger)
-> Result<Vec<usize>, String> {
let cycles = vec![vec![]; samples.len()];
loop {
let (soln, active_edges) = ip(&g,
&samples,
&cycles,
k,
benefits.as_ref(),
costs.as_ref(),
threads,
log.new(o!("section" => "ip")))?;
let mut added_cycles = false;
'cycle: for active in active_edges {
let gp = EdgeFiltered::from_fn(&g, |e| active[e.id().index()]);
for u in g.node_indices() {
let (weights, _) = bellman_ford(&gp, u).unwrap();
for v in g.edges_directed(u, Incoming)
.filter(|e| active[e.id().index()])
.map(|e| e.source()) {
if weights[v.index()].is_finite() {
panic!("cycle found! {:?} {} -- cycle handling is NOT implemented since I haven't yet needed it", v, weights[v.index()]);
}
}
}
}
if !added_cycles {
return Ok(soln);
}
}
}
fn main() {
let args: Args = docopt::Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
if let Some(threads) = args.flag_threads {
rayon::initialize(rayon::Configuration::new().num_threads(threads)).unwrap();
}
let log =
match args.flag_log {
Some(ref filename) => slog::Logger::root(slog::Duplicate::new(slog_term::streamer().color().compact().build(),
slog_stream::stream(File::create(filename).unwrap(), slog_json::default())).fuse(), o!("version" => env!("CARGO_PKG_VERSION"))),
None => {
slog::Logger::root(slog_term::streamer().color().compact().build().fuse(),
o!("version" => env!("CARGO_PKG_VERSION")))
}
};
info!(log, "parameters"; "args" => json_string(&args).unwrap());
info!(log, "loading graph"; "path" => args.arg_graph);
let g = capngraph::load_graph(args.arg_graph.as_str()).expect("Unable to load graph.");
let costs: Option<CostVec> = args.flag_costs
.as_ref()
.map(|path| bin_read_from(&mut File::open(path).unwrap(), Infinite).unwrap());
let bens: Option<BenVec> = args.flag_benefits
.as_ref()
.map(|path| bin_read_from(&mut File::open(path).unwrap(), Infinite).unwrap());
let samples = (0..args.arg_samples)
.into_par_iter()
.map(|_| RNG.with(|r| sample(&mut *r.borrow_mut(), &g)))
.collect::<Vec<_>>();
let soln = e_exact(&g,
&samples,
args.arg_k,
bens,
costs,
args.flag_threads.unwrap_or(1),
log.new(o!("section" => "e-exact")))
.unwrap();
info!(log, "optimal solution"; "seeds" => json_string(&soln).unwrap());
}
|
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
/// The command line arguments
#[derive(Debug, Deserialize, Serialize, StructOpt)]
#[serde(rename_all = "snake_case")]
pub enum Args {
/// Generate random bytes from /dev/nsm
Rand {
#[structopt(name = "number-of-bytes")]
number: u8,
},
/// Sign an attestation document
Attestation {
/// Base64Url encoded
#[structopt(long)]
nonce: Option<String>,
/// Base64Url encoded
#[structopt(long)]
public_key: Option<String>,
/// Base64Url encoded
#[structopt(long, name = "user-data")]
user_data: Option<String>,
},
/// Run this process as long running process
/// instead of run a single command and exit
Server {
#[structopt(name = "unix-socket-path")]
/// The unix socket to listen on
socket: String,
},
/// Read data from PlatformConfigurationRegister at index
DescribePcr {
#[structopt(name = "pcr-index")]
/// index of the PCR to describe
index: u16,
},
/// Extend PlatformConfigurationRegister at index with data
ExtendPcr {
#[structopt(short, long, name = "pcr-index")]
/// Index the PCR to extend
index: u16,
#[structopt(long, name = "data")]
/// Data to extend it with
data: String,
},
/// Lock PlatformConfigurationRegister at index from further modifications
LockPcr {
#[structopt(name = "pcr-index")]
/// Index to lock
index: u16,
},
/// Lock PlatformConfigurationRegisters at indexes [0, range) from further modifications
LockPcrs {
#[structopt(name = "pcr-range")]
/// Number of PCRs to lock, starting from index 0
range: u16,
},
/// Return capabilities and version of the connected NitroSecureModule.
/// Clients are recommended to decode major_version and minor_version first,
/// and use an appropriate structure to hold this data,
/// or fail if the version is not supported.
DescribeNsm,
}
|
fn solve(num_recipes: usize) -> String {
let mut recipes: Vec<usize> = vec![3, 7];
let mut current_recipes: Vec<usize> = vec![0, 1];
while recipes.len() < num_recipes + 10 {
let sum = (¤t_recipes)
.into_iter()
.map(|i| recipes[*i])
.sum::<usize>();
recipes.append(&mut sum.to_string()
.chars()
.map(|d| d.to_digit(10).unwrap() as usize)
.collect());
current_recipes = current_recipes
.into_iter()
.map(|i| (i + recipes[i] + 1) % recipes.len())
.collect();
}
recipes[num_recipes..(num_recipes + 10)]
.into_iter()
.map(|n| ((n + 48) as u8) as char)
.collect::<String>()
}
fn main() {
println!("{}", solve(84601));
}
#[test]
fn test_14() {
assert_eq!(solve(9), "5158916779".to_owned());
assert_eq!(solve(5), "0124515891".to_owned());
assert_eq!(solve(18), "9251071085".to_owned());
assert_eq!(solve(2018), "5941429882".to_owned());
}
|
extern crate testing_tutorial;
use testing_tutorial::add_three_times_four;
#[test]
fn math_checks_out() {
let result = add_three_times_four(5i);
assert_eq!(32i, result);
} |
//! Helper functions for multipart support
use headers::{ContentType, HeaderMap, HeaderMapExt};
use mime;
/// Utility function to get the multipart boundary marker (if any) from the Headers.
pub fn boundary(headers: &HeaderMap) -> Option<String> {
headers.typed_get::<ContentType>().and_then(|content_type| {
if mime.type_() == mime::MULTIPART && mime.subtype() == mime::FORM_DATA {
mime.get_param(mime::BOUNDARY).map(|x| x.to_string())
} else {
None
}
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.