text stringlengths 8 4.13M |
|---|
use std::error::Error;
use std::fs::File;
use std::io::Write;
use flate2::read::GzDecoder;
use log::error;
pub use analysis::execute_analysis;
pub use query::execute_query;
pub use statistics::execute_statistics;
use crate::csv::csv_data::{CsvData, CsvStream};
use crate::db::Rows;
mod analysis;
mod query;
mod statistics;
mod util;
pub struct Options {
pub delimiter: char,
pub trim: bool,
pub textonly: bool,
}
fn csv_data_from_mime_type(
filename: &str,
mime_type: &str,
options: &Options,
) -> Result<CsvData, Box<dyn Error>> {
if mime_type == "application/gzip" {
let reader = File::open(filename)?;
let d = GzDecoder::new(reader);
CsvData::from_reader(d, filename, options.delimiter, options.trim)
} else if mime_type == "text/plain" {
CsvData::from_filename(filename, options.delimiter, options.trim)
} else {
let error_format = format!("Unsupported MIME type {} for file {}", mime_type, filename);
error!("{}", error_format);
Err(error_format.into())
}
}
trait ReadAndSeek: std::io::Read + std::io::Seek {}
fn csv_stream_from_mime_type(
filename: &str,
mime_type: &str,
options: &Options,
) -> Result<CsvStream<File>, Box<dyn Error>> {
if mime_type == "text/plain" {
let reader = File::open(filename)?;
CsvStream::from_reader(reader, filename, options.delimiter, options.trim)
} else {
let error_format = format!("Unsupported MIME type {} for file {}", mime_type, filename);
error!("{}", error_format);
Err(error_format.into())
}
}
///Writes a set of rows to STDOUT
pub fn write_to_stdout(results: Rows) -> Result<(), Box<dyn Error>> {
let stdout = std::io::stdout();
let lock = stdout.lock();
let mut buf = std::io::BufWriter::new(lock);
for result in results {
buf.write_all(result.join(",").as_str().as_bytes())?;
buf.write_all(b"\n")?;
}
Ok(())
}
///Writes a set of rows to STDOUT, with the header included
pub fn write_to_stdout_with_header(results: Rows, header: &[String]) -> Result<(), Box<dyn Error>> {
let header = header.join(",");
println!("{}", header);
write_to_stdout(results)
}
|
use std::error::Error;
use std::fmt::Display;
use std::fmt;
use std::io::Write;
use termcolor::BufferWriter;
use termcolor::ColorChoice;
use termcolor::ColorSpec;
use termcolor::Color;
use termcolor::WriteColor;
#[derive(Debug)]
pub struct HttpError {
pub code: u16,
pub url: String,
}
impl HttpError {
pub fn new(code: u16, url: String) -> Self {
Self { code, url }
}
}
#[derive(Debug)]
pub enum HnError {
// Error used when parsing of an HTML document fails
HtmlParsingError,
// Error used when program attempts to invoke an action requiring authentication,
// but is not authenticated
UnauthenticatedError,
// Error used when a client fails to authenticate
AuthenticationError,
// Error raised from a failure during an HTTP request/response
HttpError(HttpError),
// Error raised from Network connectivity problems
NetworkError(Option<Box<dyn Error>>),
// Error from incorrect Argument configuration from the user
ArgumentError(Option<&'static str>),
// Error due to inability to Serialize or Deserialize data with respect to a type.
SerializationError(Option<&'static str>)
}
impl Display for HnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
HnError::HtmlParsingError => {
write!(f, "There was a problem parsing HTML data. This is an internal library error.")
},
HnError::UnauthenticatedError => {
write!(f, "An unauthenticated client attempted an action requiring authentication.")
}
HnError::AuthenticationError => {
write!(f, "A Hacker News client failed to authenticate.")
}
HnError::HttpError(http_err) => {
write!(f, "Unsuccesful HTTP response code, url '{}', code '{}'",
http_err.url,
http_err.code,
)
},
HnError::NetworkError(src) => {
match src {
Some(src) => write!(f, "Failed to make network request. {}", src.to_string()),
None => write!(f, "Failed to make network request."),
}
},
HnError::ArgumentError(msg) => {
match msg {
None => write!(f, "Incorrect argument configuration."),
Some(msg) => write!(f, "Incorrect argument configuration. {}.", msg),
}
}
HnError::SerializationError(msg) => {
match msg {
Some(msg) => write!(f, "Failed to serialize/deseralize data structure. {}.", msg),
None => write!(f, "Failed to serialize/deseralize data structure."),
}
}
}
}
}
impl HnError {
pub fn variant_str(&self) -> &'static str {
match self {
HnError::HtmlParsingError => "HtmlParsingError",
HnError::UnauthenticatedError => "UnauthenticatedError",
HnError::AuthenticationError => "AuthenticationError",
HnError::HttpError(_http_err) => "HttpError",
HnError::NetworkError(_source) => "NetworkErr",
HnError::ArgumentError(_msg) => "ArgumentError",
HnError::SerializationError(_msg) => "SerializationError",
}
}
}
struct Colorizer {
// use_stderr: bool,
// use_color: bool,
// pieces: Vec<String, Style>
pieces: Vec<(String, Style)>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Style {
Good,
Warning,
Error,
Hint,
Default,
}
impl Default for Style {
fn default() -> Self {
Self::Default
}
}
impl Colorizer {
pub fn print(&self) -> Result<(), Box<dyn std::error::Error>> {
let writer = BufferWriter::stdout(ColorChoice::Always);
let mut buffer = writer.buffer();
for piece in self.pieces.iter() {
let mut color = ColorSpec::new();
match piece.1 {
Style::Good => {
color.set_fg(Some(Color::Green));
},
Style::Warning => {
color.set_fg(Some(Color::Yellow));
},
Style::Error => {
color.set_fg(Some(Color::Red));
color.set_bold(true);
},
Style::Hint => {
color.set_dimmed(true);
color.set_italic(true);
},
Style::Default => {}
}
buffer.set_color(&color)?;
buffer.write_all(piece.0.as_bytes())?;
buffer.reset()?;
}
writer.print(&buffer)?;
Ok(())
}
}
impl HnError {
pub fn formatted_print(&self) {
let mut colorizer = Colorizer {
pieces: vec![],
};
colorizer.pieces.push(("error: ".to_string(), Style::Error));
colorizer.pieces.push((format!("{}\n", self), Style::Default));
colorizer.pieces.push((format!("{}\n", self.variant_str()), Style::Hint));
if let Err(_err) = colorizer.print() {
log::error!("Failed formatted color print of {}", self);
eprintln!("error: {}", self);
}
}
}
impl Error for HnError {}
|
fn unannotated_literals() -> u8 {
let _x: i64 = 123;
let _x: u32 = 88;
42
}
|
//! Implementation of Hybrid Logical Clocks
//!
//! HLC timestamps blend the best attributes of traditional wall-clock timestamps and
//! vector clocks. They are close to traditional wall-clock timestamps but the sub-millisecond
//! bits of the timestamp are dropped in favor of a logical clock that provides happened-before
//! guarantees for related timestamps. Full details may be found in the following paper
//! https://cse.buffalo.edu/tech-reports/2014-04.pdf
//!
use std::fmt;
use std::convert::From;
extern crate time;
/// Provides a HLC Clock that uses the normal system clock.
///
/// Implemented in terms of time::get_time()
pub mod system_clock {
use super::Clock;
/// Returns system time in milleseconds since Jan 1 1970
pub fn system_time_ms() -> u64 {
let t = time::get_time();
t.sec as u64 * 1000 + t.nsec as u64 / 1000000
}
/// Returns a new Clock instance that uses the normal system clock
pub fn new() -> Clock<fn() -> u64> {
Clock::new(system_time_ms)
}
}
/// Represents a stateful HLC clock.
pub struct Clock<T>
where T: FnMut() -> u64
{
get_wall_time_ms: T,
last: Timestamp
}
impl<T> Clock<T>
where T: FnMut() -> u64
{
pub fn new(f: T) -> Clock<T> {
Clock {
get_wall_time_ms: f,
last : Timestamp(0)
}
}
/// Returns a Timestamp that is guaranteed to be larger than any previous timestamps passed
/// to the update() method.
pub fn now(&mut self) -> Timestamp {
let now_ms = (self.get_wall_time_ms)();
if now_ms > self.last.wall_time_ms() {
self.last.set(now_ms, 0);
} else {
match self.last.logical().checked_add(1) {
Some(l) => self.last.set_logical(l),
None => {
self.last.set(self.last.wall_time_ms() + 1, 0);
}
}
}
Timestamp(self.last.0)
}
/// Updates the internal state of the clock and ensures that all timestamps returned by the
/// now method will come after this time.
pub fn update(&mut self, ts: &Timestamp) {
// TODO: Detect runaway clocks and handle them gracefully
if ts.wall_time_ms() > self.last.wall_time_ms() {
self.last.0 = ts.0;
}
else if ts.wall_time_ms() == self.last.wall_time_ms() {
if ts.logical() > self.last.logical() {
self.last.set_logical(ts.logical());
}
}
}
}
/// Represents an HLC Timestamp
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
pub struct Timestamp(u64);
impl Timestamp {
pub fn from(ts: u64) -> Timestamp {
Timestamp(ts)
}
pub fn to_u64(&self) -> u64 {
self.0
}
pub fn wall_time_ms(&self) -> u64 {
self.0 >> 16
}
pub fn logical(&self) -> u16 {
(self.0 & 0xFFFFu64) as u16
}
fn set_logical(&mut self, l: u16) {
self.0 = (self.0 & !0xFFFFu64) | l as u64
}
fn set(&mut self, wall_ms: u64, l: u16) {
self.0 = wall_ms << 16 | l as u64
}
}
impl From<u64> for Timestamp {
fn from(ts: u64) -> Self {
Timestamp::from(ts)
}
}
impl From<Timestamp> for u64 {
fn from(ts: Timestamp) -> Self {
ts.to_u64()
}
}
impl fmt::Display for Timestamp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Timestamp({},{})", self.wall_time_ms(), self.logical())
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use super::*;
fn ts(wall: u64, logical: u16) -> Timestamp {
Timestamp(wall << 16 | logical as u64)
}
#[test]
fn compare() {
assert!(Timestamp::from(0x2u64) > Timestamp::from(0x1u64));
assert!(Timestamp::from(0x1u64) == Timestamp::from(0x1u64));
assert!(Timestamp::from(0x1u64) != Timestamp::from(0x2u64));
assert!(Timestamp::from(0x10001u64) == Timestamp::from(0x10001u64));
assert!(Timestamp::from(0x20001u64) > Timestamp::from(0x10001u64));
assert!(Timestamp::from(0x20001u64) > Timestamp::from(0x10002u64));
}
#[test]
fn update() {
let v = Cell::new(0u64);
let mut c = Clock::new(|| v.get());
assert_eq!(c.now(), ts(0, 1));
assert_eq!(c.now(), ts(0, 2));
v.set(1u64);
assert_eq!(c.now(), ts(1, 0));
assert_eq!(c.now(), ts(1, 1));
c.update( &ts(1, 3));
assert_eq!(c.now(), ts(1, 4));
c.update( &ts(3, 3));
assert_eq!(c.now(), ts(3, 4));
v.set(5u64);
assert_eq!(c.now(), ts(5, 0));
}
#[test]
fn overflow() {
let v = Cell::new(0u64);
let mut c = Clock::new(|| v.get());
assert_eq!(c.now(), ts(0, 1));
c.update( &ts(0, u16::max_value()));
assert_eq!(c.now(), ts(1, 0));
}
} |
//! Module for [`MonotonicMap`].
use super::clear::Clear;
/// A map-like interface which in reality only stores one value at a time. The keys must be
/// monotonically increasing (i.e. timestamps). For Hydroflow, this allows state to be stored which
/// resets each tick by using the tick counter as the key. In the generic `Map` case it can be
/// swapped out for a true map to allow processing of multiple ticks of data at once.
#[derive(Clone, Debug)]
pub struct MonotonicMap<K, V>
where
K: PartialOrd,
{
key: Option<K>,
val: V,
}
impl<K, V> Default for MonotonicMap<K, V>
where
K: PartialOrd,
V: Default,
{
fn default() -> Self {
Self {
key: None,
val: Default::default(),
}
}
}
impl<K, V> MonotonicMap<K, V>
where
K: PartialOrd,
{
/// Creates a new `MonotonicMap` initialized with the given value. The
/// vaue will be `Clear`ed before it is accessed.
pub fn new_init(val: V) -> Self {
Self { key: None, val }
}
/// Inserts the value using the function if new `key` is strictly later than the current key.
pub fn get_mut_with(&mut self, key: K, init: impl FnOnce() -> V) -> &mut V {
if self.key.as_ref().map_or(true, |old_key| old_key < &key) {
self.key = Some(key);
self.val = (init)();
}
&mut self.val
}
// /// Returns the value for the monotonically increasing key, or `None` if
// /// the key has already passed.
// pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
// if self
// .key
// .as_ref()
// .map_or(true, |old_key| old_key <= &key)
// {
// self.key = Some(key);
// Some(&mut self.val)
// } else {
// None
// }
// }
}
impl<K, V> MonotonicMap<K, V>
where
K: PartialOrd,
V: Default,
{
/// Gets a mutable reference to the inner value. If `key` is strictly later than the existing
/// key, the value will be reset to `Default::default`.
pub fn get_mut_default(&mut self, key: K) -> &mut V {
self.get_mut_with(key, Default::default)
}
}
impl<K, V> MonotonicMap<K, V>
where
K: PartialOrd,
V: Clear,
{
/// Gets a mutable reference to the inner value. If `key` is strictly later than the existing
/// key, the value will be cleared via the [`Clear`] trait.
pub fn get_mut_clear(&mut self, key: K) -> &mut V {
if self.key.as_ref().map_or(true, |old_key| old_key < &key) {
self.key = Some(key);
self.val.clear();
}
&mut self.val
}
}
|
pub const P_KEY_FILE: &str = "/.lockbox/public_key";
pub const S_KEY_FILE: &str = "/.lockbox/secret_key";
pub const NONCE_FILE: &str = "/.lockbox/nonce";
pub const DATABASE_FILE: &str = "/.lockbox/passwords.db";
|
use anyhow::{anyhow, Result};
use hwloc::{ObjectType, Topology, TopologyObject};
/// Bind the current thread to a single CPU core.
pub fn bind_to_single_core() -> Result<()> {
let mut topo = Topology::new();
let mut cpuset = last_core(&mut topo)?
.cpuset()
.ok_or(anyhow!("empty CPU set"))?;
cpuset.singlify();
Ok(())
}
/// Helper method to find the last core.
fn last_core(topo: &mut Topology) -> Result<&TopologyObject> {
let core_depth = topo.depth_or_below_for_type(&ObjectType::Core).unwrap();
let all_cores = topo.objects_at_depth(core_depth);
all_cores.last().cloned().ok_or(anyhow!("no cores found"))
}
|
/// # Panics
///
/// If string is empty.
fn first_char(string: &str) -> char {
string.chars().next().unwrap()
}
/// # Panics
///
/// If string is empty.
fn first_and_last_char(string: &str) -> (char, char) {
(
first_char(string),
first_char(string.rmatches(|_: char| true).next().unwrap()),
)
}
struct Pokemon {
name: &'static str,
first: char,
last: char,
}
impl Pokemon {
fn new(name: &'static str) -> Pokemon {
let (first, last) = first_and_last_char(name);
Pokemon { name, first, last }
}
}
#[derive(Default)]
struct App {
max_path_length: usize,
max_path_length_count: usize,
max_path_example: Vec<&'static str>,
pokemon: Vec<Pokemon>,
}
impl App {
fn search(&mut self, offset: usize) {
if offset > self.max_path_length {
self.max_path_length = offset;
self.max_path_length_count = 1;
} else if offset == self.max_path_length {
self.max_path_length_count += 1;
self.max_path_example.clear();
self.max_path_example.extend(
self.pokemon[0..offset]
.iter()
.map(|Pokemon { name, .. }| *name),
);
}
let last_char = self.pokemon[offset - 1].last;
for i in offset..self.pokemon.len() {
if self.pokemon[i].first == last_char {
self.pokemon.swap(offset, i);
self.search(offset + 1);
self.pokemon.swap(offset, i);
}
}
}
}
fn main() {
let pokemon_names = [
"audino",
"bagon",
"baltoy",
"banette",
"bidoof",
"braviary",
"bronzor",
"carracosta",
"charmeleon",
"cresselia",
"croagunk",
"darmanitan",
"deino",
"emboar",
"emolga",
"exeggcute",
"gabite",
"girafarig",
"gulpin",
"haxorus",
"heatmor",
"heatran",
"ivysaur",
"jellicent",
"jumpluff",
"kangaskhan",
"kricketune",
"landorus",
"ledyba",
"loudred",
"lumineon",
"lunatone",
"machamp",
"magnezone",
"mamoswine",
"nosepass",
"petilil",
"pidgeotto",
"pikachu",
"pinsir",
"poliwrath",
"poochyena",
"porygon2",
"porygonz",
"registeel",
"relicanth",
"remoraid",
"rufflet",
"sableye",
"scolipede",
"scrafty",
"seaking",
"sealeo",
"silcoon",
"simisear",
"snivy",
"snorlax",
"spoink",
"starly",
"tirtouga",
"trapinch",
"treecko",
"tyrogue",
"vigoroth",
"vulpix",
"wailord",
"wartortle",
"whismur",
"wingull",
"yamask",
];
let mut app = App {
pokemon: pokemon_names
.iter()
.map(|name| Pokemon::new(name))
.collect(),
..App::default()
};
for i in 0..app.pokemon.len() {
app.pokemon.swap(0, i);
app.search(1);
app.pokemon.swap(0, i);
}
println!("Maximum path length: {}", app.max_path_length);
println!("Paths of that length: {}", app.max_path_length_count);
println!(
"Example path of that length: {}",
app.max_path_example.join(" "),
);
} |
use super::core::*;
use assembly_core::nom::{
combinator::{cond, map_opt, map_res},
multi::{fold_many_m_n, length_count},
number::complete::{le_f32, le_u32, le_u8},
sequence::tuple,
IResult,
};
use assembly_core::parser::{
parse_object_id, parse_object_template, parse_quat, parse_quat_wxyz, parse_u32_wstring,
parse_u8_bool, parse_u8_wstring, parse_vec3f, parse_world_id,
};
use num_traits::FromPrimitive;
use std::collections::HashMap;
use std::convert::TryFrom;
pub fn parse_zone_paths_version(input: &[u8]) -> IResult<&[u8], ZonePathsVersion> {
map_opt(le_u32, ZonePathsVersion::from_u32)(input)
}
pub fn parse_path_version(input: &[u8]) -> IResult<&[u8], PathVersion> {
map_opt(le_u32, PathVersion::from_u32)(input)
}
pub fn parse_path_type(input: &[u8]) -> IResult<&[u8], PathType> {
map_opt(le_u32, PathType::from_u32)(input)
}
pub fn parse_path_composition(input: &[u8]) -> IResult<&[u8], PathComposition> {
map_opt(le_u32, PathComposition::from_u32)(input)
}
pub fn parse_path_data_movement(input: &[u8]) -> IResult<&[u8], PathDataMovement> {
Ok((input, PathDataMovement {}))
}
pub fn parse_path_data_moving_platform(
version: PathVersion,
) -> fn(&[u8]) -> IResult<&[u8], PathDataMovingPlatform> {
fn pre_v13(i: &[u8]) -> IResult<&[u8], PathDataMovingPlatform> {
Ok((i, PathDataMovingPlatform::PreV13))
}
fn v13_to_17(i: &[u8]) -> IResult<&[u8], PathDataMovingPlatform> {
let (i, platform_travel_sound) = parse_u8_wstring(i)?;
Ok((
i,
PathDataMovingPlatform::V13ToV17 {
platform_travel_sound,
},
))
}
fn post_v18(i: &[u8]) -> IResult<&[u8], PathDataMovingPlatform> {
let (i, something) = le_u8(i)?;
Ok((i, PathDataMovingPlatform::PostV18 { something }))
}
match version.id() {
0..=12 => pre_v13,
13..=17 => v13_to_17,
_ => post_v18,
}
}
pub fn parse_property_rental_time_unit(input: &[u8]) -> IResult<&[u8], PropertyRentalTimeUnit> {
map_opt(le_u32, PropertyRentalTimeUnit::from_u32)(input)
}
pub fn parse_property_achievement_required(
input: &[u8],
) -> IResult<&[u8], PropertyAchievementRequired> {
map_opt(le_u32, PropertyAchievementRequired::from_u32)(input)
}
pub fn parse_path_data_property(input: &[u8]) -> IResult<&[u8], PathDataProperty> {
let (input, value_1) = le_u32(input)?;
let (input, price) = le_u32(input)?;
let (input, rental_time) = le_u32(input)?;
let (input, associated_map) = parse_world_id(input)?;
let (input, value_2) = le_u32(input)?;
let (input, display_name) = parse_u8_wstring(input)?;
let (input, display_description) = parse_u32_wstring(input)?;
let (input, value_3) = le_u32(input)?;
let (input, clone_limit) = le_u32(input)?;
let (input, reputation_multiplier) = le_f32(input)?;
let (input, rental_time_unit) = parse_property_rental_time_unit(input)?;
let (input, achievement_required) = parse_property_achievement_required(input)?;
let (input, player_zone_coordinate) = parse_vec3f(input)?;
let (input, max_build_height) = le_f32(input)?;
Ok((
input,
PathDataProperty {
value_1,
price,
rental_time,
associated_map,
value_2,
display_name,
display_description,
value_3,
clone_limit,
reputation_multiplier,
rental_time_unit,
achievement_required,
player_zone_coordinate,
max_build_height,
},
))
}
pub fn parse_path_data_camera<'a>(
version: PathVersion,
) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], PathDataCamera> {
let mut v1_parser = cond(version.min(14), le_u8);
move |i: &'a [u8]| {
let (i, next_path) = parse_u8_wstring(i)?;
let (i, value_1) = v1_parser(i)?;
Ok((i, PathDataCamera { next_path, value_1 }))
}
}
pub fn parse_path_data_spawner(input: &[u8]) -> IResult<&[u8], PathDataSpawner> {
let (input, spawned_lot) = parse_object_template(input)?;
let (input, respawn_time) = le_u32(input)?;
let (input, max_to_spawn) = le_u32(input)?;
let (input, min_to_spawn) = le_u32(input)?;
let (input, spawner_obj_id) = parse_object_id(input)?;
let (input, activate_network_on_load) = parse_u8_bool(input)?;
Ok((
input,
PathDataSpawner {
spawned_lot,
respawn_time,
max_to_spawn,
min_to_spawn,
spawner_obj_id,
activate_network_on_load,
},
))
}
pub fn parse_path_data_showcase(input: &[u8]) -> IResult<&[u8], PathDataShowcase> {
Ok((input, PathDataShowcase {}))
}
pub fn parse_path_data_race(input: &[u8]) -> IResult<&[u8], PathDataRace> {
Ok((input, PathDataRace {}))
}
pub fn parse_path_data_rail(input: &[u8]) -> IResult<&[u8], PathDataRail> {
Ok((input, PathDataRail {}))
}
pub fn parse_path_waypoint_data_movement(input: &[u8]) -> IResult<&[u8], PathWaypointDataMovement> {
let (input, config) = parse_waypoint_config(input)?;
Ok((input, PathWaypointDataMovement { config }))
}
pub fn parse_path_waypoint_data_moving_platform_sounds(
input: &[u8],
) -> IResult<&[u8], PathWaypointDataMovingPlatformSounds> {
let (input, depart_sound) = parse_u8_wstring(input)?;
let (input, arrive_sound) = parse_u8_wstring(input)?;
Ok((
input,
PathWaypointDataMovingPlatformSounds {
depart_sound,
arrive_sound,
},
))
}
pub fn parse_path_waypoint_data_moving_platform<'a>(
version: PathVersion,
) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], PathWaypointDataMovingPlatform> {
let mut sounds_parser = cond(
version.min(13),
parse_path_waypoint_data_moving_platform_sounds,
);
move |input: &'a [u8]| {
let (input, rotation) = parse_quat(input)?;
let (input, lock_player) = parse_u8_bool(input)?;
let (input, speed) = le_f32(input)?;
let (input, wait) = le_f32(input)?;
let (input, sounds) = sounds_parser(input)?;
Ok((
input,
PathWaypointDataMovingPlatform {
rotation,
lock_player,
speed,
wait,
sounds,
},
))
}
}
pub fn parse_path_waypoint_data_property(input: &[u8]) -> IResult<&[u8], PathWaypointDataProperty> {
Ok((input, PathWaypointDataProperty {}))
}
pub fn parse_path_waypoint_data_camera(input: &[u8]) -> IResult<&[u8], PathWaypointDataCamera> {
let (input, rotation) = parse_quat(input)?;
let (input, time) = le_f32(input)?;
let (input, value_5) = le_f32(input)?;
let (input, tension) = le_f32(input)?;
let (input, continuity) = le_f32(input)?;
let (input, bias) = le_f32(input)?;
Ok((
input,
PathWaypointDataCamera {
rotation,
time,
value_5,
tension,
continuity,
bias,
},
))
}
pub fn parse_path_waypoint_data_spawner(input: &[u8]) -> IResult<&[u8], PathWaypointDataSpawner> {
let (input, rotation) = parse_quat(input)?;
let (input, config) = parse_waypoint_config(input)?;
Ok((input, PathWaypointDataSpawner { rotation, config }))
}
pub fn parse_path_waypoint_data_showcase(input: &[u8]) -> IResult<&[u8], PathWaypointDataShowcase> {
Ok((input, PathWaypointDataShowcase {}))
}
pub fn parse_path_waypoint_data_race(input: &[u8]) -> IResult<&[u8], PathWaypointDataRace> {
let (input, rotation) = parse_quat(input)?;
let (input, value_1) = le_u8(input)?;
let (input, value_2) = le_u8(input)?;
let (input, value_3) = le_f32(input)?;
let (input, value_4) = le_f32(input)?;
let (input, value_5) = le_f32(input)?;
Ok((
input,
PathWaypointDataRace {
rotation,
value_1,
value_2,
value_3,
value_4,
value_5,
},
))
}
fn parse_path_waypoint_variant_movement(
input: &[u8],
) -> IResult<&[u8], PathWaypointVariantMovement> {
let (input, position) = parse_vec3f(input)?;
let (input, data) = parse_path_waypoint_data_movement(input)?;
Ok((input, PathWaypointVariantMovement { position, data }))
}
fn parse_path_variant_movement(
input: &[u8],
header: PathHeader,
) -> IResult<&[u8], PathVariantMovement> {
let (input, path_data) = parse_path_data_movement(input)?;
let (input, waypoints) = length_count(le_u32, parse_path_waypoint_variant_movement)(input)?;
Ok((
input,
PathVariantMovement {
header,
path_data,
waypoints,
},
))
}
fn parse_path_waypoint_variant_moving_platform<'a>(
version: PathVersion,
) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], PathWaypointVariantMovingPlatform> {
let mut inner = parse_path_waypoint_data_moving_platform(version);
move |i: &'a [u8]| {
let (i, position) = parse_vec3f(i)?;
let (i, data) = inner(i)?;
Ok((i, PathWaypointVariantMovingPlatform { position, data }))
}
}
fn parse_path_variant_moving_platform(
input: &[u8],
header: PathHeader,
) -> IResult<&[u8], PathVariantMovingPlatform> {
let (input, path_data) = parse_path_data_moving_platform(header.version)(input)?;
let (input, waypoints) = length_count(
le_u32,
parse_path_waypoint_variant_moving_platform(header.version),
)(input)?;
Ok((
input,
PathVariantMovingPlatform {
header,
path_data,
waypoints,
},
))
}
fn parse_path_waypoint_variant_property(
input: &[u8],
) -> IResult<&[u8], PathWaypointVariantProperty> {
let (input, position) = parse_vec3f(input)?;
let (input, data) = parse_path_waypoint_data_property(input)?;
Ok((input, PathWaypointVariantProperty { position, data }))
}
fn parse_path_variant_property(
input: &[u8],
header: PathHeader,
) -> IResult<&[u8], PathVariantProperty> {
let (input, path_data) = parse_path_data_property(input)?;
let (input, waypoints) = length_count(le_u32, parse_path_waypoint_variant_property)(input)?;
Ok((
input,
PathVariantProperty {
header,
path_data,
waypoints,
},
))
}
fn parse_path_waypoint_variant_camera(input: &[u8]) -> IResult<&[u8], PathWaypointVariantCamera> {
let (input, position) = parse_vec3f(input)?;
let (input, data) = parse_path_waypoint_data_camera(input)?;
Ok((input, PathWaypointVariantCamera { position, data }))
}
fn parse_path_variant_camera(
input: &[u8],
header: PathHeader,
) -> IResult<&[u8], PathVariantCamera> {
let (input, path_data) = parse_path_data_camera(header.version)(input)?;
let (input, waypoints) = length_count(le_u32, parse_path_waypoint_variant_camera)(input)?;
Ok((
input,
PathVariantCamera {
header,
path_data,
waypoints,
},
))
}
fn parse_path_waypoint_variant_spawner(input: &[u8]) -> IResult<&[u8], PathWaypointVariantSpawner> {
let (input, position) = parse_vec3f(input)?;
let (input, data) = parse_path_waypoint_data_spawner(input)?;
Ok((input, PathWaypointVariantSpawner { position, data }))
}
fn parse_path_variant_spawner(
input: &[u8],
header: PathHeader,
) -> IResult<&[u8], PathVariantSpawner> {
let (input, path_data) = parse_path_data_spawner(input)?;
let (input, waypoints) = length_count(le_u32, parse_path_waypoint_variant_spawner)(input)?;
Ok((
input,
PathVariantSpawner {
header,
path_data,
waypoints,
},
))
}
fn parse_path_waypoint_variant_showcase(
input: &[u8],
) -> IResult<&[u8], PathWaypointVariantShowcase> {
let (input, position) = parse_vec3f(input)?;
let (input, data) = parse_path_waypoint_data_showcase(input)?;
Ok((input, PathWaypointVariantShowcase { position, data }))
}
fn parse_path_variant_showcase(
input: &[u8],
header: PathHeader,
) -> IResult<&[u8], PathVariantShowcase> {
let (input, path_data) = parse_path_data_showcase(input)?;
let (input, waypoints) = length_count(le_u32, parse_path_waypoint_variant_showcase)(input)?;
Ok((
input,
PathVariantShowcase {
header,
path_data,
waypoints,
},
))
}
fn parse_path_waypoint_variant_race(input: &[u8]) -> IResult<&[u8], PathWaypointVariantRace> {
let (input, position) = parse_vec3f(input)?;
let (input, data) = parse_path_waypoint_data_race(input)?;
Ok((input, PathWaypointVariantRace { position, data }))
}
fn parse_path_variant_race(input: &[u8], header: PathHeader) -> IResult<&[u8], PathVariantRace> {
let (input, path_data) = parse_path_data_race(input)?;
let (input, waypoints) = length_count(le_u32, parse_path_waypoint_variant_race)(input)?;
Ok((
input,
PathVariantRace {
header,
path_data,
waypoints,
},
))
}
fn parse_path_waypoint_variant_rail(input: &[u8]) -> IResult<&[u8], PathWaypointVariantRail> {
let (input, position) = parse_vec3f(input)?;
let (input, rotation) = parse_quat_wxyz(input)?;
let (input, config) = parse_waypoint_config(input)?;
Ok((
input,
PathWaypointVariantRail {
position,
data: PathWaypointDataRail {
rotation,
speed: None,
config,
},
},
))
}
fn parse_path_waypoint_variant_rail_17(input: &[u8]) -> IResult<&[u8], PathWaypointVariantRail> {
let (input, position) = parse_vec3f(input)?;
let (input, rotation) = parse_quat_wxyz(input)?;
let (input, speed) = le_f32(input)?;
let (input, config) = parse_waypoint_config(input)?;
Ok((
input,
PathWaypointVariantRail {
position,
data: PathWaypointDataRail {
rotation,
speed: Some(speed),
config,
},
},
))
}
fn parse_path_variant_rail(input: &[u8], header: PathHeader) -> IResult<&[u8], PathVariantRail> {
let version = header.version;
let waypoint_parser = if version.min(17) {
parse_path_waypoint_variant_rail_17
} else {
parse_path_waypoint_variant_rail
};
let (input, path_data) = parse_path_data_rail(input)?;
let (input, waypoints) = length_count(le_u32, waypoint_parser)(input)?;
Ok((
input,
PathVariantRail {
header,
path_data,
waypoints,
},
))
}
fn parse_path_data(inp: &[u8], path_type: PathType, header: PathHeader) -> IResult<&[u8], Path> {
match path_type {
PathType::Movement => {
let (inp, var) = parse_path_variant_movement(inp, header)?;
Ok((inp, Path::Movement(var)))
}
PathType::MovingPlatform => {
let (inp, var) = parse_path_variant_moving_platform(inp, header)?;
Ok((inp, Path::MovingPlatform(var)))
}
PathType::Property => {
let (inp, var) = parse_path_variant_property(inp, header)?;
Ok((inp, Path::Property(var)))
}
PathType::Camera => {
let (inp, var) = parse_path_variant_camera(inp, header)?;
Ok((inp, Path::Camera(var)))
}
PathType::Spawner => {
let (inp, var) = parse_path_variant_spawner(inp, header)?;
Ok((inp, Path::Spawner(var)))
}
PathType::Showcase => {
let (inp, var) = parse_path_variant_showcase(inp, header)?;
Ok((inp, Path::Showcase(var)))
}
PathType::Race => {
let (inp, var) = parse_path_variant_race(inp, header)?;
Ok((inp, Path::Race(var)))
}
PathType::Rail => {
let (inp, var) = parse_path_variant_rail(inp, header)?;
Ok((inp, Path::Rail(var)))
}
}
}
pub fn parse_path(input: &[u8]) -> IResult<&[u8], Path> {
let (input, version) = parse_path_version(input)?;
let (input, path_name) = parse_u8_wstring(input)?;
let (input, path_type) = parse_path_type(input)?;
let (input, value_1) = le_u32(input)?;
let (input, path_composition) = parse_path_composition(input)?;
let header = PathHeader {
version,
path_name,
value_1,
path_composition,
};
parse_path_data(input, path_type, header)
}
pub fn parse_waypoint_config_entry(input: &[u8]) -> IResult<&[u8], (String, String)> {
tuple((parse_u8_wstring, parse_u8_wstring))(input)
}
fn extend_config_map(
mut map: HashMap<String, String>,
entry: (String, String),
) -> HashMap<String, String> {
map.insert(entry.0, entry.1);
map
}
pub fn parse_waypoint_config(input: &[u8]) -> IResult<&[u8], WaypointConfig> {
let (input, count) = map_res(le_u32, usize::try_from)(input)?;
fold_many_m_n(
count,
count,
parse_waypoint_config_entry,
HashMap::new,
extend_config_map,
)(input)
}
pub fn parse_zone_paths(input: &[u8]) -> IResult<&[u8], ZonePaths> {
let (input, version) = parse_zone_paths_version(input)?;
let (input, paths) = length_count(le_u32, parse_path)(input)?;
Ok((input, ZonePaths { version, paths }))
}
|
// This file is part of Substrate.
// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::config::TaskExecutor;
use crate::task_manager::TaskManager;
use futures::{future::FutureExt, pin_mut, select};
use parking_lot::Mutex;
use std::{any::Any, sync::Arc, time::Duration};
use tracing_subscriber::{layer::{SubscriberExt, Context}, Layer};
use tracing::{subscriber::Subscriber, span::{Attributes, Id, Record, Span}, event::Event};
use sc_telemetry::TelemetrySpan;
#[derive(Clone, Debug)]
struct DropTester(Arc<Mutex<usize>>);
struct DropTesterRef(DropTester);
impl DropTester {
fn new() -> DropTester {
DropTester(Arc::new(Mutex::new(0)))
}
fn new_ref(&self) -> DropTesterRef {
*self.0.lock() += 1;
DropTesterRef(self.clone())
}
}
impl PartialEq<usize> for DropTester {
fn eq(&self, other: &usize) -> bool {
&*self.0.lock() == other
}
}
impl Drop for DropTesterRef {
fn drop(&mut self) {
*(self.0).0.lock() -= 1;
}
}
#[test]
fn ensure_drop_tester_working() {
let drop_tester = DropTester::new();
assert_eq!(drop_tester, 0);
let drop_tester_ref_1 = drop_tester.new_ref();
assert_eq!(drop_tester, 1);
let drop_tester_ref_2 = drop_tester.new_ref();
assert_eq!(drop_tester, 2);
drop(drop_tester_ref_1);
assert_eq!(drop_tester, 1);
drop(drop_tester_ref_2);
assert_eq!(drop_tester, 0);
}
async fn run_background_task(_keep_alive: impl Any) {
loop {
tokio::time::delay_for(Duration::from_secs(1)).await;
}
}
async fn run_background_task_blocking(duration: Duration, _keep_alive: impl Any) {
loop {
// block for X sec (not interruptible)
std::thread::sleep(duration);
// await for 1 sec (interruptible)
tokio::time::delay_for(Duration::from_secs(1)).await;
}
}
fn new_task_manager(task_executor: TaskExecutor) -> TaskManager {
TaskManager::new(task_executor, None, None).unwrap()
}
#[test]
fn ensure_tasks_are_awaited_on_shutdown() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let task_manager = new_task_manager(task_executor);
let spawn_handle = task_manager.spawn_handle();
let drop_tester = DropTester::new();
spawn_handle.spawn("task1", run_background_task(drop_tester.new_ref()));
spawn_handle.spawn("task2", run_background_task(drop_tester.new_ref()));
assert_eq!(drop_tester, 2);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 2);
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
#[test]
fn ensure_keep_alive_during_shutdown() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let mut task_manager = new_task_manager(task_executor);
let spawn_handle = task_manager.spawn_handle();
let drop_tester = DropTester::new();
task_manager.keep_alive(drop_tester.new_ref());
spawn_handle.spawn("task1", run_background_task(()));
assert_eq!(drop_tester, 1);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 1);
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
#[test]
fn ensure_blocking_futures_are_awaited_on_shutdown() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let task_manager = new_task_manager(task_executor);
let spawn_handle = task_manager.spawn_handle();
let drop_tester = DropTester::new();
spawn_handle.spawn(
"task1",
run_background_task_blocking(Duration::from_secs(3), drop_tester.new_ref()),
);
spawn_handle.spawn(
"task2",
run_background_task_blocking(Duration::from_secs(3), drop_tester.new_ref()),
);
assert_eq!(drop_tester, 2);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 2);
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
#[test]
fn ensure_no_task_can_be_spawn_after_terminate() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let mut task_manager = new_task_manager(task_executor);
let spawn_handle = task_manager.spawn_handle();
let drop_tester = DropTester::new();
spawn_handle.spawn("task1", run_background_task(drop_tester.new_ref()));
spawn_handle.spawn("task2", run_background_task(drop_tester.new_ref()));
assert_eq!(drop_tester, 2);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 2);
task_manager.terminate();
spawn_handle.spawn("task3", run_background_task(drop_tester.new_ref()));
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
#[test]
fn ensure_task_manager_future_ends_when_task_manager_terminated() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let mut task_manager = new_task_manager(task_executor);
let spawn_handle = task_manager.spawn_handle();
let drop_tester = DropTester::new();
spawn_handle.spawn("task1", run_background_task(drop_tester.new_ref()));
spawn_handle.spawn("task2", run_background_task(drop_tester.new_ref()));
assert_eq!(drop_tester, 2);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 2);
task_manager.terminate();
runtime.block_on(task_manager.future()).expect("future has ended without error");
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
#[test]
fn ensure_task_manager_future_ends_with_error_when_essential_task_fails() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let mut task_manager = new_task_manager(task_executor);
let spawn_handle = task_manager.spawn_handle();
let spawn_essential_handle = task_manager.spawn_essential_handle();
let drop_tester = DropTester::new();
spawn_handle.spawn("task1", run_background_task(drop_tester.new_ref()));
spawn_handle.spawn("task2", run_background_task(drop_tester.new_ref()));
assert_eq!(drop_tester, 2);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 2);
spawn_essential_handle.spawn("task3", async { panic!("task failed") });
runtime.block_on(task_manager.future()).expect_err("future()'s Result must be Err");
assert_eq!(drop_tester, 2);
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
#[test]
fn ensure_children_tasks_ends_when_task_manager_terminated() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let mut task_manager = new_task_manager(task_executor.clone());
let child_1 = new_task_manager(task_executor.clone());
let spawn_handle_child_1 = child_1.spawn_handle();
let child_2 = new_task_manager(task_executor.clone());
let spawn_handle_child_2 = child_2.spawn_handle();
task_manager.add_child(child_1);
task_manager.add_child(child_2);
let spawn_handle = task_manager.spawn_handle();
let drop_tester = DropTester::new();
spawn_handle.spawn("task1", run_background_task(drop_tester.new_ref()));
spawn_handle.spawn("task2", run_background_task(drop_tester.new_ref()));
spawn_handle_child_1.spawn("task3", run_background_task(drop_tester.new_ref()));
spawn_handle_child_2.spawn("task4", run_background_task(drop_tester.new_ref()));
assert_eq!(drop_tester, 4);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 4);
task_manager.terminate();
runtime.block_on(task_manager.future()).expect("future has ended without error");
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
#[test]
fn ensure_task_manager_future_ends_with_error_when_childs_essential_task_fails() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let mut task_manager = new_task_manager(task_executor.clone());
let child_1 = new_task_manager(task_executor.clone());
let spawn_handle_child_1 = child_1.spawn_handle();
let spawn_essential_handle_child_1 = child_1.spawn_essential_handle();
let child_2 = new_task_manager(task_executor.clone());
let spawn_handle_child_2 = child_2.spawn_handle();
task_manager.add_child(child_1);
task_manager.add_child(child_2);
let spawn_handle = task_manager.spawn_handle();
let drop_tester = DropTester::new();
spawn_handle.spawn("task1", run_background_task(drop_tester.new_ref()));
spawn_handle.spawn("task2", run_background_task(drop_tester.new_ref()));
spawn_handle_child_1.spawn("task3", run_background_task(drop_tester.new_ref()));
spawn_handle_child_2.spawn("task4", run_background_task(drop_tester.new_ref()));
assert_eq!(drop_tester, 4);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 4);
spawn_essential_handle_child_1.spawn("task5", async { panic!("task failed") });
runtime.block_on(task_manager.future()).expect_err("future()'s Result must be Err");
assert_eq!(drop_tester, 4);
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
#[test]
fn ensure_task_manager_future_continues_when_childs_not_essential_task_fails() {
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor: TaskExecutor = (move |future, _| handle.spawn(future).map(|_| ())).into();
let mut task_manager = new_task_manager(task_executor.clone());
let child_1 = new_task_manager(task_executor.clone());
let spawn_handle_child_1 = child_1.spawn_handle();
let child_2 = new_task_manager(task_executor.clone());
let spawn_handle_child_2 = child_2.spawn_handle();
task_manager.add_child(child_1);
task_manager.add_child(child_2);
let spawn_handle = task_manager.spawn_handle();
let drop_tester = DropTester::new();
spawn_handle.spawn("task1", run_background_task(drop_tester.new_ref()));
spawn_handle.spawn("task2", run_background_task(drop_tester.new_ref()));
spawn_handle_child_1.spawn("task3", run_background_task(drop_tester.new_ref()));
spawn_handle_child_2.spawn("task4", run_background_task(drop_tester.new_ref()));
assert_eq!(drop_tester, 4);
// allow the tasks to even start
runtime.block_on(async { tokio::time::delay_for(Duration::from_secs(1)).await });
assert_eq!(drop_tester, 4);
spawn_handle_child_1.spawn("task5", async { panic!("task failed") });
runtime.block_on(async {
let t1 = task_manager.future().fuse();
let t2 = tokio::time::delay_for(Duration::from_secs(3)).fuse();
pin_mut!(t1, t2);
select! {
res = t1 => panic!("task should not have stopped: {:?}", res),
_ = t2 => {},
}
});
assert_eq!(drop_tester, 4);
runtime.block_on(task_manager.clean_shutdown());
assert_eq!(drop_tester, 0);
}
struct TestLayer {
spans_entered: Arc<Mutex<Vec<String>>>,
spans: Arc<Mutex<std::collections::HashMap<Id, String>>>,
}
impl<S: Subscriber> Layer<S> for TestLayer {
fn new_span(&self, attrs: &Attributes<'_>, id: &Id, _ctx: Context<S>) {
self.spans.lock().insert(id.clone(), attrs.metadata().name().to_string());
}
fn on_record(&self, _: &Id, _: &Record<'_>, _: Context<S>) {}
fn on_event(&self, _: &Event<'_>, _: Context<S>) {}
fn on_enter(&self, span: &Id, _: Context<S>) {
let name = self.spans.lock().get(span).unwrap().clone();
self.spans_entered.lock().push(name);
}
fn on_exit(&self, _: &Id, _: Context<S>) {}
fn on_close(&self, _: Id, _: Context<S>) {}
}
type TestSubscriber = tracing_subscriber::layer::Layered<
TestLayer,
tracing_subscriber::fmt::Subscriber
>;
fn setup_subscriber() -> (
TestSubscriber,
Arc<Mutex<Vec<String>>>,
) {
let spans_entered = Arc::new(Mutex::new(Default::default()));
let layer = TestLayer {
spans: Arc::new(Mutex::new(Default::default())),
spans_entered: spans_entered.clone(),
};
let subscriber = tracing_subscriber::fmt().finish().with(layer);
(subscriber, spans_entered)
}
#[test]
fn telemetry_span_is_forwarded_to_task() {
let (subscriber, spans_entered) = setup_subscriber();
let _sub_guard = tracing::subscriber::set_global_default(subscriber);
let telemetry_span = TelemetrySpan::new();
let span = tracing::info_span!("test");
let _enter = span.enter();
let mut runtime = tokio::runtime::Runtime::new().unwrap();
let handle = runtime.handle().clone();
let task_executor = TaskExecutor::from(move |fut, _| handle.spawn(fut).map(|_| ()));
let task_manager = TaskManager::new(task_executor, None, Some(telemetry_span.clone())).unwrap();
let (sender, receiver) = futures::channel::oneshot::channel();
let spawn_handle = task_manager.spawn_handle();
let span = span.clone();
task_manager.spawn_handle().spawn(
"test",
async move {
assert_eq!(span, Span::current());
spawn_handle.spawn("test-nested", async move {
assert_eq!(span, Span::current());
sender.send(()).unwrap();
}.boxed());
}.boxed(),
);
// We need to leave exit the span here. If tokio is not running with multithreading, this
// would lead to duplicate spans being "active" and forwarding the wrong one.
drop(_enter);
runtime.block_on(receiver).unwrap();
runtime.block_on(task_manager.clean_shutdown());
drop(runtime);
let spans = spans_entered.lock();
// We entered the telemetry span and the "test" in the future, the nested future and
// the "test" span outside of the future. So, we should have recorded 3 spans.
assert_eq!(5, spans.len());
assert_eq!(spans[0], "test");
assert_eq!(spans[1], telemetry_span.span().metadata().unwrap().name());
assert_eq!(spans[2], "test");
assert_eq!(spans[3], telemetry_span.span().metadata().unwrap().name());
assert_eq!(spans[4], "test");
}
|
// Vicfred
// https://atcoder.jp/contests/abc128/tasks/abc128_b
// implementation, sorting
use std::io;
use std::cmp::Ordering;
#[derive(Eq,PartialEq)]
struct Restaurant {
name: String,
score: i64,
index: i64,
}
impl PartialOrd for Restaurant {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if self.name == other.name {
Some(self.score.cmp(&other.score).reverse())
} else {
Some(self.name.cmp(&other.name))
}
}
}
impl Ord for Restaurant {
fn cmp(&self, other: &Restaurant) -> Ordering {
if self.name == other.name {
self.score.cmp(&other.score).reverse()
} else {
self.name.cmp(&other.name)
}
}
}
impl Restaurant {
fn new(name: String, score: i64, index: i64) -> Self {
Self{name, score, index}
}
}
fn main() {
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.unwrap();
let n = n.trim().parse::<i64>().unwrap();
let mut restaurants = Vec::<Restaurant>::new();
for idx in 1..n+1 {
let mut line = String::new();
io::stdin()
.read_line(&mut line)
.unwrap();
let words: Vec<&str> =
line
.split_whitespace()
.collect();
let name = words[0].to_string();
let score: i64 = words[1].parse().unwrap();
restaurants.push(Restaurant::new(name, score, idx));
}
restaurants.sort();
for item in restaurants {
println!("{}", item.index);
}
}
|
#[doc = "Register `RCC_APB4RSTCLRR` reader"]
pub type R = crate::R<RCC_APB4RSTCLRR_SPEC>;
#[doc = "Register `RCC_APB4RSTCLRR` writer"]
pub type W = crate::W<RCC_APB4RSTCLRR_SPEC>;
#[doc = "Field `LTDCRST` reader - LTDCRST"]
pub type LTDCRST_R = crate::BitReader;
#[doc = "Field `LTDCRST` writer - LTDCRST"]
pub type LTDCRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DSIRST` reader - DSIRST"]
pub type DSIRST_R = crate::BitReader;
#[doc = "Field `DSIRST` writer - DSIRST"]
pub type DSIRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DDRPERFMRST` reader - DDRPERFMRST"]
pub type DDRPERFMRST_R = crate::BitReader;
#[doc = "Field `DDRPERFMRST` writer - DDRPERFMRST"]
pub type DDRPERFMRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USBPHYRST` reader - USBPHYRST"]
pub type USBPHYRST_R = crate::BitReader;
#[doc = "Field `USBPHYRST` writer - USBPHYRST"]
pub type USBPHYRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - LTDCRST"]
#[inline(always)]
pub fn ltdcrst(&self) -> LTDCRST_R {
LTDCRST_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 4 - DSIRST"]
#[inline(always)]
pub fn dsirst(&self) -> DSIRST_R {
DSIRST_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 8 - DDRPERFMRST"]
#[inline(always)]
pub fn ddrperfmrst(&self) -> DDRPERFMRST_R {
DDRPERFMRST_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 16 - USBPHYRST"]
#[inline(always)]
pub fn usbphyrst(&self) -> USBPHYRST_R {
USBPHYRST_R::new(((self.bits >> 16) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - LTDCRST"]
#[inline(always)]
#[must_use]
pub fn ltdcrst(&mut self) -> LTDCRST_W<RCC_APB4RSTCLRR_SPEC, 0> {
LTDCRST_W::new(self)
}
#[doc = "Bit 4 - DSIRST"]
#[inline(always)]
#[must_use]
pub fn dsirst(&mut self) -> DSIRST_W<RCC_APB4RSTCLRR_SPEC, 4> {
DSIRST_W::new(self)
}
#[doc = "Bit 8 - DDRPERFMRST"]
#[inline(always)]
#[must_use]
pub fn ddrperfmrst(&mut self) -> DDRPERFMRST_W<RCC_APB4RSTCLRR_SPEC, 8> {
DDRPERFMRST_W::new(self)
}
#[doc = "Bit 16 - USBPHYRST"]
#[inline(always)]
#[must_use]
pub fn usbphyrst(&mut self) -> USBPHYRST_W<RCC_APB4RSTCLRR_SPEC, 16> {
USBPHYRST_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "This register is used to release the reset of the corresponding peripheral. Writing has no effect, reading will return the effective values of the corresponding bits. Writing a releases the reset of the corresponding peripheral.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_apb4rstclrr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_apb4rstclrr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RCC_APB4RSTCLRR_SPEC;
impl crate::RegisterSpec for RCC_APB4RSTCLRR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rcc_apb4rstclrr::R`](R) reader structure"]
impl crate::Readable for RCC_APB4RSTCLRR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rcc_apb4rstclrr::W`](W) writer structure"]
impl crate::Writable for RCC_APB4RSTCLRR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RCC_APB4RSTCLRR to value 0"]
impl crate::Resettable for RCC_APB4RSTCLRR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
#[derive(VulkanoShader)]
#[ty = "vertex"]
#[src = "
#version 450
layout(set = 0, binding = 0) uniform Matrix {
mat4 matrix;
} matrix;
layout(location = 0) in vec2 pos;
layout(location = 1) in vec2 uv;
layout(location = 2) in vec4 col;
layout(location = 0) out vec2 f_uv;
layout(location = 1) out vec4 f_color;
void main() {
f_uv = uv;
f_color = col / 255.0;
gl_Position = matrix.matrix * vec4(pos.xy, 0, 1);
gl_Position.y = - gl_Position.y;
}
"]
struct _Dummy;
|
use crate::vmcmd::*;
use std::io::Write;
use std::fs::File;
pub struct Assembler {
filename : String,
label_index : u32,
assembly : String,
label_counter: usize,
no_comment : bool,
current_fnc : String,
}
impl Assembler {
pub fn new(filename: String, no_comment: bool) -> Assembler {
Assembler {
assembly : String::from(format!("\n//\n// Translation unit: {}\n//\n", filename)),
label_counter: 0,
label_index : 0,
current_fnc : String::new(),
filename,
no_comment
}
}
pub fn convert(&mut self, cmd_list: Vec<VMCmd>) -> String {
for cmd in cmd_list.iter() {
self.translate_cmd(cmd);
}
return String::from(&self.assembly);
}
fn translate_cmd(&mut self, cmd: &VMCmd) {
match cmd {
VMCmd::Add(_) => self.commit_binary_operation("D+M", "add"),
VMCmd::Sub(_) => self.commit_binary_operation("M-D", "sub"),
VMCmd::Or(_) => self.commit_binary_operation("M|D", "or"),
VMCmd::And(_) => self.commit_binary_operation("M&D", "and"),
VMCmd::Neg(_) => self.commit_unary_operation("-M", "neg"),
VMCmd::Not(_) => self.commit_unary_operation("!M", "not"),
VMCmd::Eq(_) => self.commit_comparison("JEQ", "eq"),
VMCmd::Gt(_) => self.commit_comparison("JGT", "gt"),
VMCmd::Lt(_) => self.commit_comparison("JLT", "lt"),
VMCmd::Push(push, line) => self.commit_push(push, *line),
VMCmd::Pop(pop, line) => self.commit_pop(pop, *line),
VMCmd::Label(label, _) => self.commit_label(label),
VMCmd::Goto(label, _) => self.commit_goto(label),
VMCmd::IfGoto(label, _) => self.commit_if_goto(label),
VMCmd::Function(fct_cmd, line) => self.commit_function_declaration(fct_cmd, *line),
VMCmd::Call(call_cmd, _) => self.commit_function_call(call_cmd),
VMCmd::Return(_) => self.commit_return(),
}
}
fn commit(&mut self, s: &str) {
self.assembly.push_str(s);
self.assembly.push('\n');
}
fn commit_comment(&mut self, comment: &str) {
if !self.no_comment {
self.commit(&format!("\n// {}", comment));
}
}
fn commit_d_to_register(&mut self, reg: &str) {
self.commit(&format!("@{}", reg));
self.commit("M=D");
}
fn commit_register_to_d(&mut self, reg: &str) {
self.commit(&format!("@{}", reg));
self.commit("D=M");
}
fn commit_const_to_d(&mut self, value: i16) {
self.commit(&format!("@{}", value));
self.commit("D=A");
}
fn commit_stack_to_d(&mut self) {
self.commit("@SP");
self.commit("A=M");
self.commit("D=M");
}
fn commit_d_to_stack(&mut self) {
self.commit("@SP");
self.commit("A=M");
self.commit("M=D");
}
fn commit_decrement_stack(&mut self) {
self.commit("@SP");
self.commit("M=M-1");
}
fn commit_increment_stack(&mut self) {
self.commit("@SP");
self.commit("M=M+1");
}
fn commit_register_to_stack(&mut self, reg: &str){
self.commit(&format!("@{}", reg));
self.commit("D=M");
self.commit_d_to_stack();
self.commit_increment_stack();
}
fn commit_binary_operation(&mut self, operation: &str, comment: &str) {
self.commit_comment(comment);
self.commit("@SP");
self.commit("AM=M-1");
self.commit("D=M");
self.commit("A=A-1");
self.commit(&format!("M={}", operation));
}
fn commit_unary_operation(&mut self, operation: &str, comment: &str) {
self.commit_comment(comment);
self.commit("@SP");
self.commit("A=M-1");
self.commit(&format!("M={}", operation));
}
fn commit_comparison(&mut self, operation: &str, comment: &str) {
// first, do D == stack[n-1] - stack[n]
let true_label = format!(
"__{}_TRUE_{}_{}__",
operation, self.filename, self.label_counter
);
let false_label = format!(
"__{}_FALSE_{}_{}__",
operation, self.filename, self.label_counter
);
self.commit_binary_operation("M-D", comment);
self.commit("D=M");
self.commit(&format!("@{}", true_label));
self.commit(&format!("D;{}", operation));
self.commit("@SP");
self.commit("A=M-1");
self.commit("M=0");
self.commit(&format!("@{}", false_label));
self.commit("0;JMP");
self.commit(&format!("({})", true_label));
self.commit("@SP");
self.commit("A=M-1");
self.commit("M=-1");
self.commit(&format!("({})", false_label));
self.label_counter += 1;
}
fn commit_push(&mut self, cmd: &PushCmd, line_number: u32) {
self.commit_comment(&format!("push {} {}", cmd.segment, cmd.value));
match cmd.segment.as_ref() {
"local" | "argument" | "this" | "that" => {
let register = match cmd.segment.as_ref() {
"local" => "LCL",
"argument" => "ARG",
"this" => "THIS",
"that" => "THAT",
_ => panic!(
"Error at line {} : \"push {} {}\" -- Unknown segment {}",
line_number, cmd.segment, cmd.value, cmd.value
),
};
self.commit(&format!("@{}", register));
self.commit("D=M");
self.commit(&format!("@{}", cmd.value));
self.commit("A=D+A");
self.commit("D=M");
self.commit_d_to_stack();
self.commit_increment_stack();
}
"constant" => {
self.commit_const_to_d(cmd.value);
self.commit_d_to_stack();
self.commit_increment_stack();
}
"static" => {
self.commit(&format!("@_static_{}_{}", self.filename, cmd.value));
self.commit("D=M");
self.commit_d_to_stack();
self.commit_increment_stack();
}
"pointer" => {
let register = match cmd.value {
0 => "THIS",
1 => "THAT",
_ => panic!("Wrong pointer value {}, line {}", cmd.value, line_number),
};
self.commit(&format!("@{}", register));
self.commit("D=M");
self.commit_d_to_stack();
self.commit_increment_stack();
}
"temp" => {
// RAM[5-12]
assert!(
0 < cmd.value && cmd.value < 9,
"Error at line {} : \"push temp {}\" -- Temp value {} overflow",
line_number,
cmd.value,
cmd.value
);
self.commit(&format!("@{}", cmd.value + 5));
self.commit("D=M");
self.commit_d_to_stack();
self.commit_increment_stack();
}
_ => panic!("Unknown segment : {}, line {}", cmd.segment, line_number),
}
}
fn commit_pop(&mut self, cmd: &PopCmd, line_number: u32) {
self.commit_comment(&format!("pop {} {}", cmd.segment, cmd.value));
match cmd.segment.as_ref() {
"temp" => {
self.commit_const_to_d(5);
self.commit(&format!("@{}", cmd.value));
self.commit("D=D+A");
self.commit_d_to_register("R13");
self.commit_decrement_stack();
self.commit_stack_to_d();
self.commit("@R13");
self.commit("A=M");
self.commit("M=D");
}
"static" => {
self.commit_decrement_stack();
self.commit_stack_to_d();
self.commit(&format!("@_static_{}_{}", self.filename, cmd.value));
self.commit("M=D");
}
"local" | "argument" | "this" | "that" => {
let register = match cmd.segment.as_ref() {
"local" => "LCL",
"argument" => "ARG",
"this" => "THIS",
"that" => "THAT",
_ => panic!(
"Error at line {} : \"push {} {}\" -- Unknown segment {}",
line_number, cmd.segment, cmd.value, cmd.value
),
};
self.commit_register_to_d(register);
self.commit(&format!("@{}", cmd.value));
self.commit("D=D+A");
self.commit_d_to_register("R13");
self.commit_decrement_stack();
self.commit_stack_to_d();
self.commit("@R13");
self.commit("A=M");
self.commit("M=D");
}
"pointer" => {
let register = match cmd.value {
0 => "THIS",
1 => "THAT",
_ => panic!("Wrong pointer value {}, line {}", cmd.value, line_number),
};
self.commit_decrement_stack();
self.commit_stack_to_d();
self.commit(&format!("@{}", register));
self.commit("M=D");
}
"constant" => {
panic!(
"Error at line {} : \"pop constant {}\" -- pop constant not authorized.",
line_number, cmd.value
)
}
_ => {
panic!(
"Error at line {} : \"pop {} {}\" -- Segment {} not recognized.",
line_number, cmd.segment, cmd.value, cmd.segment
)
}
}
}
fn commit_label(&mut self, label: &str){
self.commit(&format!("({})", label));
}
fn commit_goto(&mut self, label: &str){
self.commit_comment(&format!("goto {}", label));
self.commit(&format!("@{}", label));
self.commit("0; JMP");
}
fn commit_if_goto(&mut self, label: &str) {
self.commit_comment(&format!("if-goto {}", label));
self.commit_decrement_stack();
self.commit_stack_to_d();
self.commit(&format!("@{}", label));
self.commit("D; JNE");
}
fn commit_function_declaration(&mut self, fnc_cmd: &FunctionCmd, line_number: u32){
self.current_fnc = String::from(&fnc_cmd.function_name);
self.commit_comment(&format!("declaration of fn {}_{}",fnc_cmd.function_name, fnc_cmd.local_args));
let fnc_label = get_function_label(&fnc_cmd.function_name);
self.commit(&format!("({})", fnc_label));
for _ in 0..fnc_cmd.local_args{
self.commit_push(&PushCmd{
segment: String::from("constant"),
value: 0
}, line_number);
}
}
fn commit_function_call(&mut self, call_cmd: &CallCmd){
self.commit_comment(&format!("call of fn {}.{} {}", self.filename, call_cmd.function_name, call_cmd.args));
let func_label = get_function_label(&call_cmd.function_name);
let return_address = format!("__{}_{}$return.{}__", self.filename, call_cmd.function_name, self.label_index);
// Push return-address
self.commit(&format!("@{}", return_address));
self.commit("D=A");
self.commit_d_to_stack();
self.commit_increment_stack();
// Save caller's frame
self.commit_register_to_stack("LCL");
self.commit_register_to_stack("ARG");
self.commit_register_to_stack("THIS");
self.commit_register_to_stack("THAT");
// ARG = SP-n-5
self.commit_register_to_d("SP");
self.commit("@5");
self.commit("D=D-A");
self.commit(&format!("@{}", call_cmd.args));
self.commit("D=D-A");
self.commit_d_to_register("ARG");
// LCL = SP
self.commit_register_to_d("SP");
self.commit_d_to_register("LCL");
// goto called function
self.commit(&format!("@{}", func_label));
self.commit("0;JMP");
// set return address label
self.commit_label(&return_address);
self.label_index += 1;
}
fn commit_return(&mut self){
self.commit_comment(&format!("Return from {}", self.current_fnc));
// FRAME (R13) = LCL
self.commit_register_to_d("LCL");
self.commit_d_to_register("R13");
// Return address (R14) = *(FRAME-5)
self.commit_restore_frame_to_register(5, "R14");
// Pop the top-most value of the stack to *ARG, to set the return value of the function
self.commit_comment("Pop return value to *ARG");
self.commit_decrement_stack();
self.commit_stack_to_d();
self.commit("@ARG");
self.commit("A=M");
self.commit("M=D");
// SP = ARG+1
self.commit_comment("Restore stack");
self.commit("@ARG");
self.commit("D=M+1");
self.commit_d_to_register("SP");
// Restore caller's frame
self.commit_comment("Restore frame");
self.commit_restore_frame_to_register(1, "THAT");
self.commit_restore_frame_to_register(2, "THIS");
self.commit_restore_frame_to_register(3, "ARG");
self.commit_restore_frame_to_register(4, "LCL");
// GOTO stored return address
self.commit_comment("Goto stored return address");
self.commit_register_to_d("R14");
self.commit("A=D");
self.commit("0;JMP");
}
fn commit_restore_frame_to_register(&mut self, frame_idx: usize, register: &str) {
// register = *(FRAME - frame_idx)
self.commit_register_to_d("R13");
self.commit(&format!("@{}", frame_idx));
self.commit("D=D-A"); // D=FRAME-idx
self.commit("A=D");
self.commit("D=M"); // D = *(FRAME-idx)
self.commit_d_to_register(register);
}
pub fn commit_bootstrap(&mut self, output_file: &mut File){
self.commit_const_to_d(256);
self.commit_d_to_register("SP");
self.commit_function_call(&CallCmd{
function_name: String::from("Sys.init"),
args: 0
});
output_file.write_all(self.assembly.as_bytes())
.expect("Unable to write bootstrap code to file");
}
}
fn get_function_label(fct_name: &str) -> String{
return format!("__{}__", fct_name);
}
|
use crate::arch::read_clock_counter;
pub struct StopWatch {
current: u64,
}
impl StopWatch {
pub fn start() -> StopWatch {
let current = read_clock_counter();
StopWatch { current }
}
pub fn lap_time(&mut self, title: &'static str) {
let current = read_clock_counter();
trace!("profiler: {} counts ({})", current - self.current, title,);
self.current = current;
}
}
|
use std::fmt;
/// paramType represents a SCTP INIT/INITACK parameter
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(C)]
pub(crate) enum ParamType {
HeartbeatInfo = 1,
/// Heartbeat Info [RFCRFC4960]
Ipv4Addr = 5,
/// IPv4 IP [RFCRFC4960]
Ipv6Addr = 6,
/// IPv6 IP [RFCRFC4960]
StateCookie = 7,
/// State Cookie [RFCRFC4960]
UnrecognizedParam = 8,
/// Unrecognized Parameters [RFCRFC4960]
CookiePreservative = 9,
/// Cookie Preservative [RFCRFC4960]
HostNameAddr = 11,
/// Host Name IP [RFCRFC4960]
SupportedAddrTypes = 12,
/// Supported IP Types [RFCRFC4960]
OutSsnResetReq = 13,
/// Outgoing SSN Reset Request Parameter [RFCRFC6525]
IncSsnResetReq = 14,
/// Incoming SSN Reset Request Parameter [RFCRFC6525]
SsnTsnResetReq = 15,
/// SSN/TSN Reset Request Parameter [RFCRFC6525]
ReconfigResp = 16,
/// Re-configuration Response Parameter [RFCRFC6525]
AddOutStreamsReq = 17,
/// Add Outgoing Streams Request Parameter [RFCRFC6525]
AddIncStreamsReq = 18,
/// Add Incoming Streams Request Parameter [RFCRFC6525]
Random = 32770,
/// Random (0x8002) [RFCRFC4805]
ChunkList = 32771,
/// Chunk List (0x8003) [RFCRFC4895]
ReqHmacAlgo = 32772,
/// Requested HMAC Algorithm Parameter (0x8004) [RFCRFC4895]
Padding = 32773,
/// Padding (0x8005)
SupportedExt = 32776,
/// Supported Extensions (0x8008) [RFCRFC5061]
ForwardTsnSupp = 49152,
/// Forward TSN supported (0xC000) [RFCRFC3758]
AddIpAddr = 49153,
/// Add IP IP (0xC001) [RFCRFC5061]
DelIpaddr = 49154,
/// Delete IP IP (0xC002) [RFCRFC5061]
ErrClauseInd = 49155,
/// Error Cause Indication (0xC003) [RFCRFC5061]
SetPriAddr = 49156,
/// Set Primary IP (0xC004) [RFCRFC5061]
SuccessInd = 49157,
/// Success Indication (0xC005) [RFCRFC5061]
AdaptLayerInd = 49158,
/// Adaptation Layer Indication (0xC006) [RFCRFC5061]
Unknown,
}
impl Default for ParamType {
fn default() -> Self {
ParamType::Unknown
}
}
impl fmt::Display for ParamType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match *self {
ParamType::HeartbeatInfo => "Heartbeat Info",
ParamType::Ipv4Addr => "IPv4 IP",
ParamType::Ipv6Addr => "IPv6 IP",
ParamType::StateCookie => "State Cookie",
ParamType::UnrecognizedParam => "Unrecognized Parameters",
ParamType::CookiePreservative => "Cookie Preservative",
ParamType::HostNameAddr => "Host Name IP",
ParamType::SupportedAddrTypes => "Supported IP Types",
ParamType::OutSsnResetReq => "Outgoing SSN Reset Request Parameter",
ParamType::IncSsnResetReq => "Incoming SSN Reset Request Parameter",
ParamType::SsnTsnResetReq => "SSN/TSN Reset Request Parameter",
ParamType::ReconfigResp => "Re-configuration Response Parameter",
ParamType::AddOutStreamsReq => "Add Outgoing Streams Request Parameter",
ParamType::AddIncStreamsReq => "Add Incoming Streams Request Parameter",
ParamType::Random => "Random",
ParamType::ChunkList => "Chunk List",
ParamType::ReqHmacAlgo => "Requested HMAC Algorithm Parameter",
ParamType::Padding => "Padding",
ParamType::SupportedExt => "Supported Extensions",
ParamType::ForwardTsnSupp => "Forward TSN supported",
ParamType::AddIpAddr => "Add IP IP",
ParamType::DelIpaddr => "Delete IP IP",
ParamType::ErrClauseInd => "Error Cause Indication",
ParamType::SetPriAddr => "Set Primary IP",
ParamType::SuccessInd => "Success Indication",
ParamType::AdaptLayerInd => "Adaptation Layer Indication",
_ => "Unknown ParamType",
};
write!(f, "{}", s)
}
}
impl From<u16> for ParamType {
fn from(v: u16) -> ParamType {
match v {
1 => ParamType::HeartbeatInfo,
5 => ParamType::Ipv4Addr,
6 => ParamType::Ipv6Addr,
7 => ParamType::StateCookie,
8 => ParamType::UnrecognizedParam,
9 => ParamType::CookiePreservative,
11 => ParamType::HostNameAddr,
12 => ParamType::SupportedAddrTypes,
13 => ParamType::OutSsnResetReq,
14 => ParamType::IncSsnResetReq,
15 => ParamType::SsnTsnResetReq,
16 => ParamType::ReconfigResp,
17 => ParamType::AddOutStreamsReq,
18 => ParamType::AddIncStreamsReq,
32770 => ParamType::Random,
32771 => ParamType::ChunkList,
32772 => ParamType::ReqHmacAlgo,
32773 => ParamType::Padding,
32776 => ParamType::SupportedExt,
49152 => ParamType::ForwardTsnSupp,
49153 => ParamType::AddIpAddr,
49154 => ParamType::DelIpaddr,
49155 => ParamType::ErrClauseInd,
49156 => ParamType::SetPriAddr,
49157 => ParamType::SuccessInd,
_ => ParamType::Unknown,
}
}
}
|
#![allow(dead_code)]
#![allow(unused_variables)]
mod basis;
use crate::basis::stack_heap;
use crate::basis::control_flow;
use crate::basis::data_structure;
use crate::basis::std_collections;
use crate::basis::characters;
use crate::basis::functions;
use crate::basis::traits;
use crate::basis::variable_access;
use crate::basis::circular_reference;
use crate::basis::miscl;
use crate::basis::async_rust;
use crate::basis::advanced_type;
use crate::basis::closure_test;
use crate::basis::smart_pointer;
use crate::basis::concurrency_test;
use std::mem;
const MEANING_A:u8 = 42; //Global, no fixed address in memory. because they’re inlined to each place they’re used.
static mut Z:i32 = 323; //Global, aren’t inlined upon use
fn operators()
{
let mut a = 2+3*4;
println!("{}", a);
a -=2;
println!("remainder of {} / {} = {}", a, 3, (a%3));
let a_cubed = i32::pow(a, 3);
println!("{}", a_cubed);
let b =2.5;
let b_cubed = f64::powi(b, 3);
let b_to_pi = f64::powf(b, std::f64::consts::PI);
println!("{} cubed = {}, {}^pi = {}", b, b_cubed, b, b_to_pi);
}
fn scope_and_shadow()
{
let a = 123;
let a = 122;
{
let b = 456;
println!("inside b = {}\n", b);
let a = 938;
println!("inside a = {}\n", a);
}
println!("outside a = {}\n", a);
}
fn global_var()
{
println!("= {}", MEANING_A);
println!("= {}", unsafe { Z });
unsafe
{
Z = 4343;
println!("= {}", Z);
}
}
#[tokio::main]
async fn main() {
concurrency_test::concurrency_test();
smart_pointer::smart_pointer_test();
closure_test::closure_test();
advanced_type::advanced_type();
async_rust::async_rust();
miscl::miscl();
circular_reference::circular_reference();
variable_access::variable_access();
traits::traits();
functions::functions();
characters::characters();
std_collections::std_collect();
data_structure::data_structure();
control_flow::control_flow();
stack_heap::stack_and_heap();
global_var();
scope_and_shadow();
let a:u8 = 123; // 0 .. 256
let b:i8 = 123; //-128 .. 127
println!("a = {}", a);
println!("Hello, world!");
let mut c = 12;
println!("c = {}", c);
c = 1334534353;
println!("c = {}, size = {} bytes", c, mem::size_of_val(&c));
c = -1;
println!("c = {}, after modifying size = {} bytes", c, mem::size_of_val(&c));
let z:isize = 123; // isize/usize
let size_of_z = mem::size_of_val(&z);
println!("z = {}, takes up {} bytes, {}-bit os", z, size_of_z, size_of_z*8);
let d:char = 'x';
println!("d = {}, size = {} bytes", d, mem::size_of_val(&d));
let e:f32 = 2.3; // double precision
println!("e = {}, size = {} bytes", e, mem::size_of_val(&e));
operators();
}
|
use super::*;
use crate::gc::Address;
use std::collections::HashSet;
pub struct HeapBlock {
cell_size: usize,
free_list: *mut FreeListEntry,
bitset: HashSet<Address>,
cursor: Address,
pub next: Address,
pub prev: Address,
storage: u8,
}
impl HeapBlock {
pub fn sweep(&mut self) -> bool {
let mut all_free = true;
let mut free_list: *mut FreeListEntry = std::ptr::null_mut();
let mut seen = HashSet::new();
self.for_each_cell_mut(|this, cell_addr| unsafe {
if this.is_marked(cell_addr) {
let mut cell = Ref {
ptr: std::ptr::NonNull::new_unchecked(cell_addr.to_mut_ptr::<Obj>()),
};
if seen.contains(&(cell.ptr.as_ptr() as usize)) {
panic!();
}
seen.insert(cell.ptr.as_ptr() as usize);
if cell.header().is_marked_non_atomic()
|| cell.vtable as *const _ == &crate::bytecode::CB_VTBL as *const _
{
//let c = crate::runtime::val_str(crate::value::Value::from(cell));
//log!("Keep '{}' at {:p}", c, cell.ptr);
cell.header_mut().unmark_non_atomic();
all_free = false;
} else {
cell.header_mut().unmark_non_atomic();
this.unmark(cell_addr);
let c = crate::runtime::val_str(crate::value::Value::from(cell));
if let Some(destroy_fn) = cell.vtable.destroy_fn {
destroy_fn(cell);
}
std::ptr::write_bytes(cell_addr.to_mut_ptr::<u8>(), 0, this.cell_size);
if free_list.is_null() {
log!("Initialize free list with {:p} ('{}')", cell.raw(), c);
free_list = cell.raw() as *mut _;
(&mut *free_list).next = std::ptr::null_mut();
} else {
let next = free_list;
free_list = cell.raw() as *mut _;
(&mut *free_list).next = next as *mut _;
log!("Sweep {:p} to free list {:p} ('{}')", cell.raw(), next, c);
}
crate::get_vm().heap.allocated -= this.cell_size;
}
} else {
let next = free_list;
free_list = cell_addr.to_mut_ptr();
(&mut *free_list).next = next as *mut _;
//log!("Add {:p} to free list {:p}", cell_addr.to_ptr::<()>(), next);
}
});
self.free_list = free_list;
all_free
}
pub fn allocate(&mut self) -> Address {
let addr = if self.cursor.offset(self.cell_size)
< self
.storage()
.offset(Self::BLOCK_SIZE - std::mem::size_of::<Self>())
{
let c = self.cursor;
self.cursor = self.cursor.offset(self.cell_size);
/*log!(
"Bump allocate {:p}->{:p}",
c.to_ptr::<()>(),
self.cursor.to_ptr::<()>()
);*/
c
} else {
if self.free_list.is_null() {
return Address::null();
} else {
unsafe {
let x = self.free_list;
self.free_list = (&*x).next.cast();
log!(
"Allocate {:p} from free list,next free list cell: {:p} ",
x,
self.free_list
);
Address::from_ptr(x)
}
}
};
if addr.is_non_null() {
self.mark(addr);
}
addr
}
pub fn new(cell_size: usize) -> *mut Self {
let mem = unsafe {
std::alloc::alloc_zeroed(std::alloc::Layout::from_size_align_unchecked(
16 * 1024,
16 * 1024,
))
.cast::<Self>()
};
//log!("Allocate HeapBlock with cell size {} bytes", cell_size);
const FORCE_FREELIST: bool = false;
unsafe {
mem.write(Self {
cell_size,
free_list: std::ptr::null_mut(),
bitset: HashSet::new(),
cursor: Address::null(),
next: Address::null(),
prev: Address::null(),
storage: 0,
});
let mut this = Box::from_raw(mem);
if !FORCE_FREELIST {
this.cursor = Address::from_ptr(&this.storage);
} else {
log!("Force initialize freelist");
this.cursor = this
.storage()
.offset(Self::BLOCK_SIZE - std::mem::size_of::<Self>());
let mut free_list: *mut FreeListEntry = std::ptr::null_mut();
this.for_each_cell(|addr| {
let next = free_list;
{
free_list = addr.to_mut_ptr();
(&mut *free_list).next = next.cast();
}
});
this.free_list = free_list;
}
this.init_bitset();
Box::into_raw(this)
}
}
pub const BLOCK_SIZE: usize = 16 * 1024;
fn init_bitset(&mut self) {
/*let count = self.cell_count();
for _ in 0..(count / 64) {
self.bitset.push(0);
}
self.bitset.bit_init(false);*/
}
pub fn cell_bit(&self, cell_addr: Address) -> usize {
cell_addr.to_usize() % Self::BLOCK_SIZE
// (cell_addr.to_usize() - self as *const Self as usize) / self.cell_size()
}
pub fn mark(&mut self, cell: Address) {
self.bitset.insert(cell);
//self.bitset.bit_set(Self::cell_bit(self, cell));
}
pub fn unmark(&mut self, cell: Address) {
self.bitset.remove(&cell);
//self.bitset.bit_reset(Self::cell_bit(self, cell));
}
pub fn is_marked(&self, cell: Address) -> bool {
self.bitset.contains(&cell)
//self.bitset.bit_test(Self::cell_bit(self, cell))
}
pub fn cell_size(&self) -> usize {
self.cell_size
}
pub fn cell_count(&self) -> usize {
return (Self::BLOCK_SIZE - std::mem::size_of::<Self>() - 1) / self.cell_size;
}
pub fn for_each_cell(&self, mut callback: impl FnMut(Address)) {
for i in 0..self.cell_count() {
callback(self.cell(i));
}
}
pub fn for_each_cell_mut(&mut self, mut callback: impl FnMut(&mut Self, Address)) {
for i in 0..self.cell_count() {
callback(self, self.cell(i));
}
}
pub fn storage(&self) -> Address {
Address::from_ptr(&self.storage)
}
pub fn cell(&self, x: usize) -> Address {
return self.storage().offset(x * self.cell_size());
}
}
pub struct FreeListEntry {
next: *mut u8,
}
|
//! A vector that supports efficient deletion without reordering all subsequent items.
use std::collections::HashMap;
use std::hash::Hash;
use std::iter::FusedIterator;
/// A vector that supports efficient deletion without reordering all subsequent items.
pub struct SparseVec<T> {
items: Vec<Option<T>>,
item_locs: HashMap<T, Vec<usize>>,
}
impl<T> Default for SparseVec<T> {
fn default() -> Self {
SparseVec {
items: Vec::default(),
item_locs: HashMap::default(),
}
}
}
impl<T: Clone + Eq + Hash> SparseVec<T> {
/// Insert item into the vector, see `https://doc.rust-lang.org/std/vec/struct.Vec.html#method.push`
pub fn push(&mut self, item: T) {
self.items.push(Some(item.clone()));
self.item_locs
.entry(item)
.or_insert(Vec::with_capacity(1))
.push(self.items.len() - 1);
}
/// Delete all items of a specific value from this vector. This takes time proportional to the amount of items with that value in the vector, not the total size of the vector.
pub fn delete(&mut self, item: &T) {
if let Some(indices) = self.item_locs.get(item) {
for index in indices {
self.items[*index] = None;
}
}
}
/// Iterate through all items in the vector in order. Deleted items will not appear in the iteration.
pub fn iter(&self) -> impl Iterator<Item = &T> + FusedIterator + DoubleEndedIterator + Clone {
self.items.iter().filter_map(|x| x.as_ref())
}
}
#[cfg(test)]
mod test {
use super::*;
fn collect<T: Eq + Hash + Clone>(sv: &SparseVec<T>) -> Vec<T> {
sv.iter().cloned().collect()
}
#[test]
fn basic() {
let mut x = SparseVec::default();
x.push(0);
x.push(1);
x.push(2);
x.delete(&1);
assert_eq!(collect(&x), vec![0, 2]);
}
#[test]
fn can_implement_default_on_types_that_dont_implement_default() {
struct NoDefault;
let x = SparseVec::<NoDefault>::default();
assert_eq!(x.items.len(), 0);
assert_eq!(x.item_locs.len(), 0);
}
}
|
use crate::ctypes::*;
//use crate::shared::ntdef::CHAR;
use crate::shared::minwindef::{BYTE, DWORD, WORD};
use crate::shared::basetsd::{ULONG_PTR};
pub use crate::shared::ntdef::LARGE_INTEGER;
pub use crate::shared::ntdef::LUID;
pub use crate::shared::ntdef::ULARGE_INTEGER;
pub type PVOID = *mut c_void;
pub type HRESULT = c_long;
pub type LPCSTR = *const CHAR;
pub type LPCWSTR = *const WCHAR;
pub type LPWSTR = *mut WCHAR;
pub type HANDLE = *mut c_void;
pub type VOID = c_void;
pub type CHAR = c_char;
pub type SHORT = c_short;
pub type LONG = c_long;
pub type INT = c_int;
pub type WCHAR = wchar_t;
pub type BOOLEAN = BYTE;
pub type PBOOLEAN = *mut BOOLEAN;
pub const STATUS_WAIT_0: DWORD = 0x00000000;
pub const STATUS_ABANDONED_WAIT_0: DWORD = 0x00000080;
pub const STATUS_USER_APC: DWORD = 0x000000C0;
pub const STATUS_TIMEOUT: DWORD = 0x00000102;
pub const STATUS_PENDING: DWORD = 0x00000103;
STRUCT!{struct RTL_RUN_ONCE {
Ptr: PVOID,
}}
pub type PRTL_RUN_ONCE = *mut RTL_RUN_ONCE;
STRUCT!{struct RTL_BARRIER {
Reserved1: DWORD,
Reserved2: DWORD,
Reserved3: [ULONG_PTR; 2],
Reserved4: DWORD,
Reserved5: DWORD,
}}
pub type PRTL_BARRIER = *mut RTL_BARRIER;
STRUCT!{struct RTL_SRWLOCK {
Ptr: PVOID,
}}
pub type PRTL_SRWLOCK = *mut RTL_SRWLOCK;
pub const RTL_SRWLOCK_INIT: RTL_SRWLOCK = RTL_SRWLOCK { Ptr: 0 as PVOID };
STRUCT!{struct RTL_CONDITION_VARIABLE {
Ptr: PVOID,
}}
pub type PRTL_CONDITION_VARIABLE = *mut RTL_CONDITION_VARIABLE;
pub const RTL_CONDITION_VARIABLE_INIT: RTL_CONDITION_VARIABLE = RTL_CONDITION_VARIABLE {
Ptr: 0 as PVOID,
};
pub const RTL_CONDITION_VARIABLE_LOCKMODE_SHARED: DWORD = 0x1;
STRUCT!{struct LIST_ENTRY {
Flink: *mut LIST_ENTRY,
Blink: *mut LIST_ENTRY,
}}
pub type PLIST_ENTRY = *mut LIST_ENTRY;
STRUCT!{struct RTL_CRITICAL_SECTION_DEBUG {
Type: WORD,
CreatorBackTraceIndex: WORD,
CriticalSection: *mut RTL_CRITICAL_SECTION,
ProcessLocksList: LIST_ENTRY,
EntryCount: DWORD,
ContentionCount: DWORD,
Flags: DWORD,
CreatorBackTraceIndexHigh: WORD,
SpareWORD: WORD,
}}
pub type PRTL_CRITICAL_SECTION_DEBUG = *mut RTL_CRITICAL_SECTION_DEBUG;
STRUCT!{struct RTL_CRITICAL_SECTION {
DebugInfo: PRTL_CRITICAL_SECTION_DEBUG,
LockCount: LONG,
RecursionCount: LONG,
OwningThread: HANDLE,
LockSemaphore: HANDLE,
SpinCount: ULONG_PTR,
}}
pub type PRTL_CRITICAL_SECTION = *mut RTL_CRITICAL_SECTION;
|
#![feature(associated_type_defaults)]
#![feature(min_type_alias_impl_trait)]
#![allow(unused_imports)]
#![allow(clippy::ptr_arg)]
pub mod system {
include!(concat!(env!("OUT_DIR"), "/system.rs"));
}
|
use super::{operator, url};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, Signature, Span, SyntaxShape, Value};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"url path"
}
fn signature(&self) -> Signature {
Signature::build("url path")
.rest(
"rest",
SyntaxShape::CellPath,
"optionally operate by cell path",
)
.category(Category::Network)
}
fn usage(&self) -> &str {
"Get the path of a URL"
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
operator(engine_state, stack, call, input, &url::Url::path)
}
fn examples(&self) -> Vec<Example> {
let span = Span::test_data();
vec![
Example {
description: "Get path of a url",
example: "echo 'http://www.example.com/foo/bar' | url path",
result: Some(Value::String {
val: "/foo/bar".to_string(),
span,
}),
},
Example {
description: "A trailing slash will be reflected in the path",
example: "echo 'http://www.example.com' | url path",
result: Some(Value::String {
val: "/".to_string(),
span,
}),
},
]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}
|
//! Matrix-spec compliant server names.
use crate::error::Error;
/// A Matrix-spec compliant server name.
///
/// It is discouraged to use this type directly – instead use one of the aliases ([`ServerName`](../type.ServerName.html) and
/// [`ServerNameRef`](../type.ServerNameRef.html)) in the crate root.
#[derive(Clone, Copy, Debug)]
pub struct ServerName<T> {
full_id: T,
}
impl<T> ServerName<T>
where
T: AsRef<str>,
{
/// Creates a reference to this `ServerName`.
pub fn as_ref(&self) -> ServerName<&str> {
ServerName { full_id: self.full_id.as_ref() }
}
}
fn try_from<S, T>(server_name: S) -> Result<ServerName<T>, Error>
where
S: AsRef<str> + Into<T>,
{
if !is_valid_server_name(server_name.as_ref()) {
return Err(Error::InvalidServerName);
}
Ok(ServerName { full_id: server_name.into() })
}
common_impls!(ServerName, try_from, "An IP address or hostname");
/// Check whether a given string is a valid server name according to [the specification][].
///
/// Deprecated. Use the `try_from()` method of [`ServerName`](server_name/struct.ServerName.html) to construct
/// a server name instead.
///
/// [the specification]: https://matrix.org/docs/spec/appendices#server-name
#[deprecated]
pub fn is_valid_server_name(name: &str) -> bool {
use std::net::Ipv6Addr;
if name.is_empty() {
return false;
}
let end_of_host = if name.starts_with('[') {
let end_of_ipv6 = match name.find(']') {
Some(idx) => idx,
None => return false,
};
if name[1..end_of_ipv6].parse::<Ipv6Addr>().is_err() {
return false;
}
end_of_ipv6 + 1
} else {
let end_of_host = name.find(':').unwrap_or_else(|| name.len());
if name[..end_of_host]
.bytes()
.any(|byte| !(byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'.'))
{
return false;
}
end_of_host
};
if name.len() == end_of_host {
true
} else if name.as_bytes()[end_of_host] != b':' {
// hostname is followed by something other than ":port"
false
} else {
// are the remaining characters after ':' a valid port?
name[end_of_host + 1..].parse::<u16>().is_ok()
}
}
#[cfg(test)]
mod tests {
use super::is_valid_server_name;
#[test]
fn ipv4_host() {
assert!(is_valid_server_name("127.0.0.1"));
}
#[test]
fn ipv4_host_and_port() {
assert!(is_valid_server_name("1.1.1.1:12000"));
}
#[test]
fn ipv6() {
assert!(is_valid_server_name("[::1]"));
}
#[test]
fn ipv6_with_port() {
assert!(is_valid_server_name("[1234:5678::abcd]:5678"));
}
#[test]
fn dns_name() {
assert!(is_valid_server_name("example.com"));
}
#[test]
fn dns_name_with_port() {
assert!(is_valid_server_name("ruma.io:8080"));
}
#[test]
fn empty_string() {
assert!(!is_valid_server_name(""));
}
#[test]
fn invalid_ipv6() {
assert!(!is_valid_server_name("[test::1]"));
}
#[test]
fn ipv4_with_invalid_port() {
assert!(!is_valid_server_name("127.0.0.1:"));
}
#[test]
fn ipv6_with_invalid_port() {
assert!(!is_valid_server_name("[fe80::1]:100000"));
assert!(!is_valid_server_name("[fe80::1]!"));
}
#[test]
fn dns_name_with_invalid_port() {
assert!(!is_valid_server_name("matrix.org:hello"));
}
}
|
use super::*;
use Result;
use http::HttpClient;
use requests::*;
use types::*;
use serde::{Deserialize, Serialize};
/// A telegram client using an HTTP client to send requests to the telegram
/// bot API.
pub struct HttpTelegramClient<T: HttpClient> {
token: String,
http_client: T,
}
impl<T: HttpClient> HttpTelegramClient<T> {
#[cfg(test)]
fn new(token: String, http_client: T) -> HttpTelegramClient<T> {
HttpTelegramClient {
token: token,
http_client: http_client,
}
}
fn format_url(&self, method: &str) -> String {
format!("https://api.telegram.org/bot{}/{}", self.token, method)
}
fn get<R: Deserialize>(&self, method: &str) -> Result<R> {
let url = self.format_url(method);
let response: Response<R> = try!(self.http_client.get(url));
response.handle()
}
fn post<R: Deserialize, P: Serialize>(&self, method: &str, params: P) -> Result<R> {
let url = self.format_url(method);
let response: Response<R> = try!(self.http_client.post(url, params));
response.handle()
}
}
impl<T: HttpClient> TelegramClient for HttpTelegramClient<T> {
fn new(token: String) -> Result<HttpTelegramClient<T>> {
let http_client = try!(T::new());
Ok(HttpTelegramClient {
token: token,
http_client: http_client,
})
}
fn get_me(&self) -> Result<User> {
self.get("getMe")
}
fn get_updates(&self, params: GetUpdates) -> Result<Vec<Update>> {
self.post("getUpdates", params)
}
fn send_message(&self, params: SendMessage) -> Result<Message> {
self.post("sendMessage", params)
}
}
#[cfg(test)]
mod tests {
use super::*;
use http::MockHttpClient;
#[test]
fn get_me_gets_user_information() {
let token = "123456".to_string();
let mut mock_http_client = MockHttpClient::new().unwrap();
let url = format!("https://api.telegram.org/bot{}/getMe", token);
mock_http_client.mock_get(url,
r#"{
"ok": true,
"result": {
"id": 12345,
"first_name": "Steve",
"last_name": "Smith",
"username": "ssmith01"
}
}"#
.to_string());
let client = HttpTelegramClient::new(token, mock_http_client);
let user = client.get_me().unwrap();
assert_eq!(12345, user.id);
assert_eq!("Steve".to_string(), user.first_name);
assert_eq!(Some("Smith".to_string()), user.last_name);
assert_eq!(Some("ssmith01".to_string()), user.username);
}
#[test]
fn get_updates_fetches_updates() {
let token = "34dfg2sd".to_string();
let mut mock_http_client = MockHttpClient::new().unwrap();
let url = format!("https://api.telegram.org/bot{}/getUpdates", token);
mock_http_client.mock_post(url,
r#"{
"offset": 2,
"limit": 5
}"#
.to_string(),
r#"{
"ok": true,
"result": [
{
"update_id": 1,
"message": {
"message_id": 2,
"date": 3,
"chat": {
"id": 4,
"type": "private"
}
}
}
]
}"#
.to_string());
let client = HttpTelegramClient::new(token, mock_http_client);
let params = GetUpdates {
offset: Some(2),
limit: Some(5),
timeout: None,
allowed_updates: None,
};
let mut updates = client.get_updates(params).unwrap();
assert_eq!(1, updates.len());
let update = updates.drain(..).next().unwrap();
assert_eq!(1, update.update_id);
assert!(update.message.is_some());
let message = update.message.unwrap();
assert_eq!(2, message.message_id);
assert_eq!(3, message.date);
assert_eq!(4, message.chat.id);
assert_eq!("private".to_string(), message.chat.kind);
}
#[test]
fn send_message_sends_message_correctly() {
let token = "90sadlkfs90aj".to_string();
let mut mock_http_client = MockHttpClient::new().unwrap();
let url = format!("https://api.telegram.org/bot{}/sendMessage", token);
mock_http_client.mock_post(url, r#"{
"chat_id": 1235,
"text": "This is a test",
"parse_mode": "Markdown"
}"#.to_string(), r#"{
"ok": true,
"result": {
"message_id": 346456,
"date": 124575,
"chat": {
"id": 983425,
"type": "group"
}
}
}"#.to_string());
let client = HttpTelegramClient::new(token, mock_http_client);
let request = SendMessage{
chat_id: ChatId::Id(1235),
text: "This is a test".to_string(),
parse_mode: Some("Markdown".to_string()),
disable_web_page_preview: None,
disable_notification: None,
reply_to_message_id: None,
reply_markup: None
};
let message = client.send_message(request).unwrap();
assert_eq!(346456, message.message_id);
assert_eq!(124575, message.date);
assert_eq!(983425, message.chat.id);
assert_eq!("group".to_string(), message.chat.kind);
}
}
|
pub mod statemachine;
pub mod linkedlist;
pub mod algorithms; |
use crate::{
import::*,
Broadcast,
node::NodeController,
node::FromNode,
node::NodeConfig,
node::NodeStatus,
proto::Meta,
proto::Net,
proto::Request,
proto::Response,
proto::PingPong,
process::registry::ProcessRegistry,
global::Global,
global::Get,
util::RpcMethod,
util::uuid,
MethodCall,
};
use std::io;
use actix::io::{FramedWrite, WriteHandler};
use tokio::{
net::tcp::OwnedWriteHalf,
net::TcpStream,
};
use actix::Running;
use futures::io::Error;
use crate::process::DispatchError;
pub struct NodeLink {
id: Uuid,
correlation_counter: i64,
stream: FramedWrite<Net, OwnedWriteHalf, NetCodec>,
running: HashMap<i64, Sender<Result<Bytes, DispatchError>>>,
}
#[derive(Debug, Copy, Clone)]
pub struct NetCodec;
impl tokio_util::codec::Encoder<Net> for NetCodec {
type Error = io::Error;
fn encode(&mut self, item: Net, dst: &mut BytesMut) -> Result<(), Self::Error> {
let len = prost::Message::encoded_len(&item);
dst.put_u32(len as _);
prost::Message::encode(&item, dst)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
}
impl tokio_util::codec::Decoder for NetCodec {
type Item = Net;
type Error = io::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if src.len() < 4 {
return Ok(None);
}
let len = u32::from_be_bytes([src[0], src[1], src[2], src[3]]) as usize;
if src.len() < len + 4 {
return Ok(None);
}
let len = src.get_u32() as usize;
let msg = src.split_to(len);
prost::Message::decode(msg)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
.map(Some)
}
}
impl NodeLink {
/// Open connection to a node, exchange IDs, setup local state
pub async fn new(socket: TcpStream) -> (Uuid, SocketAddr, Addr<Self>) {
let codec = NetCodec;
socket.set_nodelay(true).unwrap();
let v = Global::<NodeConfig>::from_registry().send(Get::default()).await.unwrap().unwrap();
let meta = Meta { nodeid: v.id.as_bytes().to_vec() };
let peer_addr = socket.peer_addr().unwrap();
let (rx, tx) = socket.into_split();
let mut tx = tokio_util::codec::FramedWrite::new(tx, codec);
let mut rx = tokio_util::codec::FramedRead::new(rx, codec);
tx.send(Net { meta: Some(meta), ..Default::default() }).await.unwrap();
let other = rx.next().await.unwrap().unwrap().meta.unwrap();
let id: Uuid = uuid(other.nodeid.as_slice());
let tx = tx.into_inner();
let this = Actor::create(|ctx| {
ctx.add_stream(rx);
let tx = FramedWrite::new(tx, NetCodec, ctx);
ctx.run_interval(Duration::from_secs(1), |this: &mut Self, ctx| {
log::trace!("Pinging");
this.stream.write(Net {
ping: Some(PingPong {}),
..Default::default()
});
});
NodeLink {
id: id.clone(),
correlation_counter: 0,
stream: tx,
running: HashMap::new(),
}
});
(id, peer_addr, this)
}
fn handle_return_correlation(&mut self, ctx: &mut Context<Self>, res: Result<Bytes, DispatchError>, corr: i64) {
let (ok, err) = match res {
Ok(v) => (Some(v.to_vec()), None),
Err(e) => (None, Some(e.code())),
};
let res = Response {
correlation: corr,
body: ok,
error: err,
};
let msg = Net {
response: Some(res),
..Default::default()
};
self.stream.write(msg);
}
fn handle_request(&mut self, ctx: &mut Context<Self>, req: Request) {
log::trace!("Received request");
let procid: Option<Uuid> = req.procid.map(uuid).filter(|v| !v.is_nil());
let dispatch = MethodCall {
procid,
method: req.methodid,
body: Bytes::from(req.body),
};
if let Some(procid) = procid {
let procreg = ProcessRegistry::from_registry();
if let Some(corr) = req.correlation {
let work = wrap_future(procreg.send(dispatch).map(|r| r.unwrap()));
let work = work.map(move |res, this: &mut Self, ctx| this.handle_return_correlation(ctx, res, corr));
ctx.spawn(work);
} else {
procreg.do_send(dispatch);
}
} else {
let nodecontrol = NodeController::from_registry();
let dispatch = FromNode {
node_id: self.id,
inner: dispatch,
};
if let Some(corr) = req.correlation {
let work = wrap_future(nodecontrol.send(dispatch).map(|r| r.unwrap()));
let work = work.map(move |res, this: &mut Self, ctx| this.handle_return_correlation(ctx, res, corr));
ctx.spawn(work);
} else {
// Err, here it should be a broadcast
//ctx.spawn(wrap_future(async move { nodecontrol.send(dispatch).await.unwrap().unwrap(); }));
nodecontrol.do_send(dispatch);
// Without process ID, we currently only handle notifications
}
}
}
}
impl Actor for NodeLink {
type Context = Context<Self>;
fn stopped(&mut self, ctx: &mut Self::Context) {
NodeController::from_registry().do_send(NodeStatus::Disconnected(self.id));
}
}
impl WriteHandler<std::io::Error> for NodeLink {
fn error(&mut self, err: Error, ctx: &mut Self::Context) -> Running {
panic!("Invalid data {:?}", err);
// Stop on errors
Running::Stop
}
}
impl StreamHandler<io::Result<Net>> for NodeLink {
fn handle(&mut self, item: io::Result<Net>, ctx: &mut Context<Self>) {
let msg = match item {
Ok(item) => item,
Err(error) => {
log::error!("Error occured, disconnecting");
panic!("Invalid data {:?}", error);
ctx.stop();
return;
}
};
if let Some(ping) = msg.ping {
log::trace!("Got pinged");
self.stream.write(Net {
pong: Some(ping),
..Default::default()
});
}
if let Some(mut req) = msg.request {
self.handle_request(ctx, req);
}
if let Some(res) = msg.response {
if let Some(tx) = self.running.remove(&res.correlation) {
if let Some(err) = res.error {
// TODO: Error from i32
let _ = tx.send(Err(DispatchError::from_code(err)));
} else if let Some(body) = res.body {
let _ = tx.send(Ok(Bytes::from(body)));
} else {
log::error!("Received response without error or body");
let _ = tx.send(Err(DispatchError::Protocol));
}
} else {
log::error!("Missing correlation id: {}", res.correlation)
}
}
}
}
impl Handler<Broadcast> for NodeLink {
type Result = Result<(), DispatchError>;
fn handle(&mut self, msg: Broadcast, ctx: &mut Self::Context) -> Self::Result {
let mut req = Request {
correlation: None,
procid: None,
methodid: msg.method,
body: msg.body.to_vec(),
};
let netreq = Net {
request: Some(req),
..Default::default()
};
self.stream.write(netreq);
Ok(())
}
}
impl Handler<MethodCall> for NodeLink {
type Result = actix::Response<Bytes, DispatchError>;
fn handle(&mut self, msg: MethodCall, ctx: &mut Context<Self>) -> Self::Result {
let mut req = Request {
correlation: None,
procid: msg.procid.map(|id| id.as_bytes().to_vec()),
methodid: msg.method,
body: msg.body.to_vec(),
};
return self.send_request(ctx, req);
}
}
impl NodeLink {
pub(crate) fn send_request(&mut self, ctx: &mut Context<NodeLink>, mut req: Request) -> actix::Response<Bytes, DispatchError> {
self.correlation_counter = self.correlation_counter.wrapping_add(1);
let (tx, rx) = futures::channel::oneshot::channel();
self.running.insert(self.correlation_counter, tx);
req.correlation = Some(self.correlation_counter);
let net = Net {
request: Some(req),
..Default::default()
};
self.stream.write(net);
// Safety timeout
let fut = tokio::time::timeout(Duration::from_secs(60), rx);
actix::Response::fut(fut
.map_err(|_| DispatchError::Timeout)
.map(|v| v.map(|v| v.map_err(|_| DispatchError::MailboxRemote))??)
)
}
}
|
fn check_password(p: i32) -> bool {
let mut m = 10;
let mut repeat_count = 1;
let mut has_twins = false;
let mut non_decreasing = true;
for _ in 1..6 {
let d1 = p % m / (m / 10);
let d2 = p % (m * 10) / m;
m *= 10;
if d1 == d2 {
repeat_count += 1;
} else {
if repeat_count == 2 {
has_twins = true;
}
repeat_count = 1;
}
if d2 > d1 {
non_decreasing = false;
break;
}
}
if repeat_count == 2 {
has_twins = true;
}
return non_decreasing && has_twins;
}
fn main() {
let password_min = 254032;
let password_max = 789860;
println!("{}", (password_min..password_max).filter(|p| check_password(*p)).count());
} |
use crate::commands::wallet::wallet_update;
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use clap::Clap;
use ic_types::Principal;
/// Authorize a wallet custodian.
#[derive(Clap)]
pub struct AuthorizeOpts {
/// Principal of the custodian to authorize.
custodian: String,
}
pub async fn exec(env: &dyn Environment, opts: AuthorizeOpts) -> DfxResult {
let custodian = Principal::from_text(opts.custodian)?;
wallet_update(env, "authorize", custodian.clone()).await?;
println!("Authorized {} as a custodian.", custodian);
Ok(())
}
|
use opencv::prelude::Vector;
//pub mod cam;
pub mod colors;
pub mod contour;
pub mod error;
pub mod gui;
pub mod imageio;
pub mod mat;
pub mod point;
pub mod rect;
pub mod videoio;
pub mod prelude {
pub use crate::gui::{MouseEvent, MouseEvents};
pub use crate::mat::convert_color::ConvertColor;
pub use crate::mat::draw::Draw;
pub use crate::mat::filter::Filter;
pub use crate::mat::FindContours;
pub use crate::mat::InRange;
}
pub use crate::colors::*;
pub use crate::contour::*;
pub use crate::error::*;
pub use crate::gui::mouse_events::*;
pub use crate::gui::GUI;
pub use crate::imageio::imread;
pub use crate::mat::Mat;
pub use crate::point::*;
pub use crate::prelude::*;
pub use crate::rect::*;
pub use crate::videoio::{VideoCapture, VideoWriter};
type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Copy)]
pub enum CVType {
/// 8 bit unsigned, single channel
CV8UC1 = 0,
/// 8 bit signed, single channel
CV8SC1 = 1,
/// 8 bit unsigned, three channels
CV8UC3 = 16,
/// 8 bit signed, three channel
CV8SC3 = 17,
}
impl CVType {
fn unpack(&self) -> i32 {
*self as i32
}
}
|
#[cfg(test)]
mod test {
#![allow(unused_imports)]
//adds itetools methods and tooling to all iterators in scope
use itertools::Itertools;
#[test]
fn test_step_by() {
let v: i32 = (0..10).step_by(3).sum();
assert_eq!(18, v);
}
} |
use ress::prelude::*;
lazy_static! {
pub static ref TOKENS: Vec<Token<&'static str>> =
vec![
Token::Comment(Comment::new_multi_line(
" this file contains all grammatical productions in ECMA-262 edition 5.1 ** * *"
)),
Token::Comment(Comment::new_html(" HTML-style comments ", None)),
Token::Comment(Comment::new_single_line(" whitespace")),
Token::Ident("tab".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Ident("tab".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("verticalTab".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Ident("verticalTab".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("formFeed".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Ident("formFeed".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("space".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Ident("space".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("nbsp".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Ident("nbsp".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("bom".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Ident("bom".into()),
Token::Punct(Punct::SemiColon),
Token::Comment(Comment::new_single_line(" line terminators")),
Token::Ident("lineFeed".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("carriageReturn".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("carriageReturnLineFeed".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("lineSeparator".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("paragraphSeparator".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Comment(Comment::new_single_line(" identifier names")),
Token::Keyword(Keyword::Var("var")),
Token::Ident("$".into()),
Token::Punct(Punct::Comma),
Token::Ident("_".into()),
Token::Punct(Punct::Comma),
Token::Ident(r"\u0078".into()),
Token::Punct(Punct::Comma),
Token::Ident(r"\u{2F9F9}".into()),
Token::Punct(Punct::Comma),
Token::Ident("x$".into()),
Token::Punct(Punct::Comma),
Token::Ident("x_".into()),
Token::Punct(Punct::Comma),
Token::Ident(r"x\u0030".into()),
Token::Punct(Punct::Comma),
Token::Ident(r"x\u{e01d5}".into()),
Token::Punct(Punct::Comma),
Token::Ident("xa".into()),
Token::Punct(Punct::Comma),
Token::Ident("x0".into()),
Token::Punct(Punct::Comma),
Token::Ident("x0a".into()),
Token::Punct(Punct::Comma),
Token::Ident("x0123456789".into()),
Token::Punct(Punct::Comma),
Token::Ident("qwertyuiopasdfghjklzxcvbnm".into()),
Token::Punct(Punct::Comma),
Token::Ident("QWERTYUIOPASDFGHJKLZXCVBNM".into()),
Token::Punct(Punct::SemiColon),
Token::Comment(Comment::new_single_line(
" a representative sample of ID_Start and ID_Continue"
)),
Token::Keyword(Keyword::Var("var")),
Token::Ident("䩶".into()),
Token::Punct(Punct::Comma),
Token::Ident("x󠇕".into()),
Token::Punct(Punct::Comma),
Token::Ident("œ一".into()),
Token::Punct(Punct::Comma),
Token::Ident("ǻ둘".into()),
Token::Punct(Punct::Comma),
Token::Ident("ɤ〩".into()),
Token::Punct(Punct::Comma),
Token::Ident("φ".into()),
Token::Punct(Punct::Comma),
Token::Ident("fiⅷ".into()),
Token::Punct(Punct::Comma),
Token::Ident("ユニコード".into()),
Token::Punct(Punct::Comma),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Var("var")),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Let("Let")),
Token::Ident("letx".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Let("Let")),
Token::Punct(Punct::OpenBracket),
Token::Ident(r"x\u0078".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Const("Const")),
Token::Ident("constx".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Let("Let")),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Let("Let")),
Token::Ident("y".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Const("Const")),
Token::Ident("z".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Null,
Token::Punct(Punct::SemiColon),
Token::Boolean(Boolean::True),
Token::Punct(Punct::SemiColon),
Token::Boolean(Boolean::False),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("00".into()),
Token::Punct(Punct::SemiColon),
Token::Number("1234567890".into()),
Token::Punct(Punct::SemiColon),
Token::Number("01234567".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0.".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0.00".into()),
Token::Punct(Punct::SemiColon),
Token::Number("10.00".into()),
Token::Punct(Punct::SemiColon),
Token::Number(".0".into()),
Token::Punct(Punct::SemiColon),
Token::Number(".00".into()),
Token::Number("0e0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0E0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0.e0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0.00e+0".into()),
Token::Punct(Punct::SemiColon),
Token::Number(".00e-0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0x0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0X0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0x0123456789abcdefABCDEF".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0b0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0B0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0b01".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0b10".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0b10101010".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0o0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0O0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0o01234567".into()),
Token::Punct(Punct::SemiColon),
Token::Number("2e308".into()),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::double("", false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::double("'", false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::double(r#"\'\"\\\b\f\n\r\t\v\0"#, false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::double(r"\1\00\400\000", true)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::double(r"\x01\x23\x45\x67\x89\xAB\xCD\xEF\xab\xcd\xef", false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::double(r"\u0123\u4567\u89AB\uCDEF\u00ab\ucdef", false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::double(
r"\uD834\uDF06\u2603\u03C6 \u{0000001F4a9}\u{1D306}\u{2603}\u{3c6} 𝌆☃φ", false
)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::double(
r"\
", false
)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::single("", false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::single("\"", false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::single(r#"\'\"\\\b\f\n\r\t\v\0"#, false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::single(r"\1\00\400\000", true)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::single(r"\x01\x23\x45\x67\x89\xAB\xCD\xEF\xab\xcd\xef", false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::single(r"\u0123\u4567\u89AB\uCDEF\u00ab\ucdef", false)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::single(
r"\uD834\uDF06\u2603\u03C6 \u{0000001F4a9} \u{1D306}\u{2603}\u{3c6} 𝌆☃φ",
false
)),
Token::Punct(Punct::SemiColon),
Token::String(StringLit::single(
r"\
", false
)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts("x", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts("|", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts("|||", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(r"^$\b\B", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts("(?=(?!(?:(.))))", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(r"a.\f\n\r\t\v\0\[\-\/\\\x00\u0000\uD834\uDF06", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(r"\u{00000001d306}", Some("u"))),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(r"\d\D\s\S\w\W", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(
r"\ca\cb\cc\cd\ce\cf\cg\ch\ci\cj\ck\cl\cm\cn\co\cp\cq\cr\cs\ct\cu\cv\cw\cx\cy\cz",
None
)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(
r"\cA\cB\cC\cD\cE\cF\cG\cH\cI\cJ\cK\cL\cM\cN\cO\cP\cQ\cR\cS\cT\cU\cV\cW\cX\cY\cZ",
None
)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts("[a-z-]", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(r"[^\b\-^]", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(r"[/\]\\]", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".", Some("i"))),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".", Some("g"))),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".", Some("m"))),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".", Some("igm"))),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".*", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".*?", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".+", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".+?", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".?", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".??", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".{0}", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".{0,}", None)),
Token::Punct(Punct::SemiColon),
Token::RegEx(RegEx::from_parts(".{0,0}", None)),
Token::Punct(Punct::SemiColon),
Token::Template(Template::no_sub_template("a", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Template(Template::template_head("", false, false, false)),
Token::Number("0".into()),
Token::Template(Template::template_tail("", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Template(Template::template_head("0", false, false, false)),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("1".into()),
Token::Template(Template::template_tail("2", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Template(Template::template_head("0", false, false, false)),
Token::Template(Template::template_head("1", false, false, false)),
Token::Number("2".into()),
Token::Template(Template::template_tail("3", false, false, false)),
Token::Template(Template::template_tail("4", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Template(Template::no_sub_template(r"\`", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Template(Template::no_sub_template(r"a\${b", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Template(Template::no_sub_template(r"\0\n\x0A\u000A\u{A}", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::This("This")),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::Comma),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::String(StringLit::single("x", false)),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::String(StringLit::double("y", false)),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0.".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0.0".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number(".0".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0e0".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0x0".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("get".into()),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("set".into()),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("get".into()),
Token::String(StringLit::single("y", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("set".into()),
Token::String(StringLit::double("y", false)),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("get".into()),
Token::Number("0".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("set".into()),
Token::Number("0".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("get".into()),
Token::Keyword(Keyword::Var("var")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("set".into()),
Token::Keyword(Keyword::Var("var")),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("get".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("set".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Number("1".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("a".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::String(StringLit::single("b", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::String(StringLit::double("c", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Number("0".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Number(".1".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Number("1.".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Number("1e1".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Keyword(Keyword::Var("var")),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Ident("c".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Ident("d".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBrace),
Token::Ident("f".into()),
Token::Punct(Punct::Comma),
Token::Ident("g".into()),
Token::Punct(Punct::Colon),
Token::Ident("h".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Colon),
Token::Ident("j".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("k".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("set".into()),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBracket),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Ident("c".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Ident("d".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBrace),
Token::Ident("f".into()),
Token::Punct(Punct::Comma),
Token::Ident("g".into()),
Token::Punct(Punct::Colon),
Token::Ident("h".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Colon),
Token::Ident("j".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("k".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Asterisk),
Token::Ident("d".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Asterisk),
Token::String(StringLit::single("e", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Asterisk),
Token::String(StringLit::double("f", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Asterisk),
Token::Number("2".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Asterisk),
Token::Number(".2".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Asterisk),
Token::Number("3.".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Asterisk),
Token::Number("2e2".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Asterisk),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("__proto__".into()),
Token::Punct(Punct::Colon),
Token::Null,
Token::Punct(Punct::Comma),
Token::Ident("get".into()),
Token::Ident("__proto__".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Ident("set".into()),
Token::Ident("__proto__".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::String(StringLit::double("__proto__", false)),
Token::Punct(Punct::Colon),
Token::Null,
Token::Punct(Punct::Comma),
Token::Ident("__proto__".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Number("0.".into()),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Comment(Comment::new_single_line(
" this function makes the NewExpression and CallExpression tests not throw at runtime"
)),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Return("return")),
Token::Ident("f".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Equal),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::Equal),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::New("new")),
Token::Keyword(Keyword::New("new")),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::Comma),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::Period),
Token::Ident("a".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::Ellipsis),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("1".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Keyword(Keyword::Function("function")),
Token::Punct(Punct::Asterisk),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Return("return")),
Token::Keyword(Keyword::Yield("yield")),
Token::Number("2".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Template(Template::no_sub_template("a", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Template(Template::template_head("0", false, false, false)),
Token::Number("1".into()),
Token::Template(Template::template_tail("2", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::DoublePlus),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::DoubleDash),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Delete("Delete")),
Token::Keyword(Keyword::Void("Void")),
Token::Keyword(Keyword::TypeOf("TypeOf")),
Token::Punct(Punct::Plus),
Token::Punct(Punct::Dash),
Token::Punct(Punct::Tilde),
Token::Punct(Punct::Bang),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::DoublePlus),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::DoubleDash),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Asterisk),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::ForwardSlash),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Percent),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Plus),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Dash),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::DoubleLessThan),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::DoubleGreaterThan),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::TripleGreaterThan),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::LessThan),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::GreaterThan),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::LessThanEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::GreaterThanEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Keyword(Keyword::InstanceOf("instanceof")),
Token::Keyword(Keyword::Function("function")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::DoubleEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::BangEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::TripleEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::BangDoubleEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Ampersand),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Caret),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Pipe),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::DoubleAmpersand),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::DoublePipe),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::QuestionMark),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::QuestionMark),
Token::Number("0".into()),
Token::Punct(Punct::QuestionMark),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::DoublePipe),
Token::Number("0".into()),
Token::Punct(Punct::QuestionMark),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::AsteriskEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::ForwardSlashEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::PercentEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::PlusEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::DashEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::DoubleLessThanEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::DoubleGreaterThanEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::TripleGreaterThanEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::AmpersandEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::CaretEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::PipeEqual),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::OpenBrace),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::OpenBrace),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::OpenBrace),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::OpenBrace),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::Comma),
Token::Ident("z".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::If("if")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::If("if")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Else("else")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Do("Do")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::While("While")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Do("Do")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::While("While")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Do("Do")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::While("While")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Number("0".into()),
Token::Keyword(Keyword::While("While")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Var("var")),
Token::Ident("a".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Var("var")),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Var("var")),
Token::Ident("a".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Var("var")),
Token::Ident("a".into()),
Token::Punct(Punct::Equal),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Ident("of".into()),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Var("var")),
Token::Ident("x".into()),
Token::Ident("of".into()),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Continue("continue")),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Continue("continue")),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::For("for")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Break("break")),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Case("case")),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::Break("break")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Return("return")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Return("return")),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::With("With")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Case("case")),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Case("case")),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::Case("case")),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Default("Default")),
Token::Punct(Punct::Colon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Case("case")),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::Default("Default")),
Token::Punct(Punct::Colon),
Token::Keyword(Keyword::Case("case")),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Case("case")),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Case("case")),
Token::Number("0".into()),
Token::Punct(Punct::Colon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Default("Default")),
Token::Punct(Punct::Colon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Switch("switch")),
Token::Punct(Punct::OpenParen),
Token::Number("0".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Default("Default")),
Token::Punct(Punct::Colon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Ident("x".into()),
Token::Punct(Punct::Colon),
Token::Punct(Punct::SemiColon),
Token::Ident("x".into()),
Token::Punct(Punct::Colon),
Token::Ident("y".into()),
Token::Punct(Punct::Colon),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Try("try")),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Throw("throw")),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Catch("catch")),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Try("try")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Catch("catch")),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Try("try")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Finally("finally")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Try("try")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Catch("catch")),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Finally("finally")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Debugger("debugger")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::SemiColon),
Token::Comment(Comment::new_single_line("for (;0;) label: function f(){} 0")),
Token::Comment(Comment::new_single_line("do label: function f(){} while(0)")),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Ident("c".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Ident("d".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBrace),
Token::Ident("f".into()),
Token::Punct(Punct::Comma),
Token::Ident("g".into()),
Token::Punct(Punct::Colon),
Token::Ident("h".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Colon),
Token::Ident("j".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("k".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::String(StringLit::double("use strict", false)),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::String(StringLit::single("use strict", false)),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::String(StringLit::double("other directive", false)),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::String(StringLit::single("other directive", false)),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::OpenParen),
Token::String(StringLit::double("string", false)),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::OpenParen),
Token::String(StringLit::single("string", false)),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::String(StringLit::single("string", false)),
Token::Punct(Punct::Plus),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Function("function")),
Token::Punct(Punct::Asterisk),
Token::Ident("g".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Ident("c".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Ident("d".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBrace),
Token::Ident("f".into()),
Token::Punct(Punct::Comma),
Token::Ident("g".into()),
Token::Punct(Punct::Colon),
Token::Ident("h".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Colon),
Token::Ident("j".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("k".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Return("return")),
Token::Ident("a".into()),
Token::Punct(Punct::Equal),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::Asterisk),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Keyword(Keyword::Yield("yield")),
Token::Ident("c".into()),
Token::Punct(Punct::Equal),
Token::Keyword(Keyword::Yield("yield")),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Punct(Punct::Asterisk),
Token::Ident("g".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Ident("c".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Ident("d".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBrace),
Token::Ident("f".into()),
Token::Punct(Punct::Comma),
Token::Ident("g".into()),
Token::Punct(Punct::Colon),
Token::Ident("h".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Colon),
Token::Ident("j".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("k".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Return("return")),
Token::Ident("a".into()),
Token::Punct(Punct::Equal),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::Asterisk),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Keyword(Keyword::Yield("yield")),
Token::Ident("c".into()),
Token::Punct(Punct::Equal),
Token::Keyword(Keyword::Yield("yield")),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::Plus),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::Asterisk),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::Comma),
Token::Ident("y".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Function("function")),
Token::Ident("f".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Number("0".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Ident("x".into()),
Token::Punct(Punct::EqualGreaterThan),
Token::Ident("x".into()),
Token::Ident("x".into()),
Token::Punct(Punct::EqualGreaterThan),
Token::Ident("x".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Ident("x".into()),
Token::Punct(Punct::EqualGreaterThan),
Token::Ident("y".into()),
Token::Punct(Punct::EqualGreaterThan),
Token::Ident("x".into()),
Token::Ident("x".into()),
Token::Punct(Punct::EqualGreaterThan),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::CloseBrace),
Token::Ident("x".into()),
Token::Punct(Punct::EqualGreaterThan),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Ident("x".into()),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Return("return")),
Token::Ident("x".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Ident("x".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("x".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Ident("c".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Ident("d".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBrace),
Token::Ident("f".into()),
Token::Punct(Punct::Comma),
Token::Ident("g".into()),
Token::Punct(Punct::Colon),
Token::Ident("h".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Colon),
Token::Ident("j".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("k".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenBracket),
Token::Ident("a".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Equal),
Token::Punct(Punct::OpenBracket),
Token::Punct(Punct::Ellipsis),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("a".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Equal),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Try("try")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Catch("catch")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBracket),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Try("try")),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Catch("catch")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::OpenBrace),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Class("class")),
Token::Ident("A".into()),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Class("class")),
Token::Ident("B".into()),
Token::Keyword(Keyword::Extends("extends")),
Token::Keyword(Keyword::New("new")),
Token::Ident("A".into()),
Token::Punct(Punct::OpenBrace),
Token::Ident("constructor".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Ident("c".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Ident("d".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBrace),
Token::Ident("f".into()),
Token::Punct(Punct::Comma),
Token::Ident("g".into()),
Token::Punct(Punct::Colon),
Token::Ident("h".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Colon),
Token::Ident("j".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("k".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Super("super")),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::New("new")),
Token::Punct(Punct::Period),
Token::Ident("target".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Super("super")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Template(Template::no_sub_template("template", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Keyword(Keyword::Super("super")),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::This("This")),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Ident("m".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::Comma),
Token::Ident("b".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBracket),
Token::Ident("c".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Comma),
Token::Ident("d".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("e".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::Comma),
Token::Punct(Punct::OpenBrace),
Token::Ident("f".into()),
Token::Punct(Punct::Comma),
Token::Ident("g".into()),
Token::Punct(Punct::Colon),
Token::Ident("h".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::Comma),
Token::Ident("i".into()),
Token::Punct(Punct::Colon),
Token::Ident("j".into()),
Token::Punct(Punct::Equal),
Token::Number("0".into()),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Comma),
Token::Punct(Punct::Ellipsis),
Token::Ident("k".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Super("super")),
Token::Punct(Punct::Period),
Token::Ident("m".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Super("super")),
Token::Punct(Punct::Period),
Token::Ident("m".into()),
Token::Template(Template::no_sub_template("template", false, false, false)),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::EqualGreaterThan),
Token::Keyword(Keyword::Super("super")),
Token::Punct(Punct::Period),
Token::Ident("m".into()),
Token::Punct(Punct::OpenParen),
Token::Keyword(Keyword::This("This")),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::SemiColon),
Token::Keyword(Keyword::Static("Static")),
Token::Ident("a".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("Static")),
Token::String(StringLit::single("b", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("Static")),
Token::Number("0".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Punct(Punct::Asterisk),
Token::Ident("c".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Punct(Punct::Asterisk),
Token::String(StringLit::double("d", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("Static")),
Token::Punct(Punct::Asterisk),
Token::Number("1".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Punct(Punct::Asterisk),
Token::Punct(Punct::OpenBracket),
Token::Number("1".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Keyword(Keyword::Var("var")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Punct(Punct::Asterisk),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("get".into()),
Token::Ident("e".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("get".into()),
Token::String(StringLit::single("f", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("get".into()),
Token::Number("2".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("get".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("2".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("Static")),
Token::Ident("set".into()),
Token::Ident("g".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("set".into()),
Token::String(StringLit::double("h", false)),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("set".into()),
Token::Number("3".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("set".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("3".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("get".into()),
Token::Keyword(Keyword::If("if")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Static("static")),
Token::Ident("set".into()),
Token::Keyword(Keyword::If("if")),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("a".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::String(StringLit::single("b", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Number("0".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::OpenBracket),
Token::Number("0".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Asterisk),
Token::Ident("c".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Asterisk),
Token::String(StringLit::double("d", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Asterisk),
Token::Number("1".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Asterisk),
Token::Punct(Punct::OpenBracket),
Token::Number("1".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Var("var")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::Asterisk),
Token::Keyword(Keyword::In("in")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Yield("yield")),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Ident("get".into()),
Token::Ident("e".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("get".into()),
Token::String(StringLit::single("f", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("get".into()),
Token::Number("2".into()),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("get".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("2".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("set".into()),
Token::Ident("g".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("set".into()),
Token::String(StringLit::double("h", false)),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("set".into()),
Token::Number("3".into()),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("set".into()),
Token::Punct(Punct::OpenBracket),
Token::Number("3".into()),
Token::Punct(Punct::CloseBracket),
Token::Punct(Punct::OpenParen),
Token::Ident("a".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("get".into()),
Token::Keyword(Keyword::If("if")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Ident("set".into()),
Token::Keyword(Keyword::If("if")),
Token::Punct(Punct::OpenParen),
Token::Ident("f".into()),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseBrace),
Token::Keyword(Keyword::Class("class")),
Token::Ident("C".into()),
Token::Keyword(Keyword::Extends("extends")),
Token::Ident("B".into()),
Token::Punct(Punct::OpenBrace),
Token::String(StringLit::double("constructor", false)),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::OpenBrace),
Token::Keyword(Keyword::Super("super")),
Token::Punct(Punct::OpenParen),
Token::Punct(Punct::CloseParen),
Token::Punct(Punct::SemiColon),
Token::Punct(Punct::CloseBrace),
Token::Punct(Punct::CloseBrace),
];
}
|
use crate::{BoxFuture, Entity, Result};
pub trait Upsert<E: Entity>: Send + Sync {
fn upsert<'a>(&'a self, k: &'a E::Key, v: &'a E) -> BoxFuture<'a, Result<()>>;
}
impl<E, PROVIDER> Upsert<E> for &PROVIDER
where
E: Entity + Sync,
E::Key: Sync,
PROVIDER: Upsert<E> + Send + Sync,
{
fn upsert<'a>(&'a self, k: &'a E::Key, v: &'a E) -> BoxFuture<'a, Result<()>> {
(**self).upsert(k, v)
}
}
/// This trait is implemented when the entity or the key must be changed while insert or update is performed.
/// This case appears when there are triggers on the table, a sequence / identity column.
///
/// [UpsertMut](UpsertMut) trait is not the same as the [Upsert](Upsert) trait since the former need to take
/// a key and entity as mutable parameters.
pub trait UpsertMut<E: Entity>: Send + Sync {
fn upsert_mut<'a>(&'a self, k: &'a mut E::Key, v: &'a mut E) -> BoxFuture<'a, Result<()>>;
}
impl<E, PROVIDER> UpsertMut<E> for &PROVIDER
where
E: Entity + Sync,
E::Key: Sync,
PROVIDER: UpsertMut<E> + Send + Sync,
{
fn upsert_mut<'a>(&'a self, k: &'a mut E::Key, v: &'a mut E) -> BoxFuture<'a, Result<()>> {
(**self).upsert_mut(k, v)
}
}
|
//! Networking library for client/server multiplayer games.
//!
//! Sumi provides a high level API for building networked games. It is built on top of [tokio],
//! and provides an async, futures-based API.
//!
//! [tokio]: https://tokio.rs/
extern crate bincode;
extern crate byteorder;
extern crate crc;
extern crate failure;
extern crate futures;
extern crate rand;
extern crate ring;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate state_machine_future;
extern crate subslice_index;
#[macro_use]
extern crate tokio_core;
use byteorder::{ByteOrder, NetworkEndian, ReadBytesExt, WriteBytesExt};
use crc::crc32::{self, Digest, Hasher32};
use futures::prelude::*;
use rand::Rng;
use rand::os::OsRng;
use ring::aead::{self, Algorithm, CHACHA20_POLY1305, OpeningKey, SealingKey};
use ring::digest::SHA512;
use ring::pbkdf2;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::cmp;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::hash::Hasher;
use std::io::{self, Cursor};
use std::mem;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::str;
use std::time::{Duration, Instant};
use tokio_core::net::UdpSocket;
use tokio_core::reactor::{Handle, Interval, Timeout};
pub use self::send::Send;
pub use self::send_reliable::SendReliable;
pub use self::recv::Receive;
mod recv;
mod send;
mod send_reliable;
// The base password used to generate the encryption keys for the connection listener.
//
// This value ultimately doesn't matter much, since we're we apply a random salt to it each time
// we generate keys.
static SECRET_PASSWORD_DO_NOT_STEAL: &'static [u8] = b"I'm a cool kid how about you?";
// TODO: Attempt to dynamically discover MTU so that we can send larger packets when possible.
// For now, we enforce a maximum packet size to reduce the likelyhood of going over the MTU,
// which would result in packet loss.
const MAX_PACKET_LEN: usize = 1024;
// We want to be able to send the length of the cookie in a packet as a `u8`, so we enforce
// that a cookie be no longer than what a `u8` can represent.
const MAX_COOKIE_LEN: usize = 256;
// TODO: Figure out an appropriate length for the nonce.
const NONCE_LEN: usize = 12;
// Since the nonce is a fixed length, the ciphertext's max size is determined by the remaining
// size of a cookie.
const MAX_CIPHERTEXT_LEN: usize = MAX_COOKIE_LEN - NONCE_LEN;
// The size of the packet header in bytes.
//
// The packet heaer is the 4 byte CRC32 checksum (that includes the implicit protocol ID), the
// 8 byte connection ID, and the 1 byte identifying the packet type.
const HEADER_LEN: usize = 4 + 8 + 1;
// The maximum number of bytes from a message that can be sent in a single packet.
//
// This amount is determined by the maximum size of a single packet, minus the size of the packet
// header, minus the 4 byte sequence number, minus 1 byte specifying the number of packets for
// this message, minus 1 byte for the packet's chunk sequence number, minus 2 bytes for the
// length of the fragment in bytes.
const MAX_FRAGMENT_LEN: usize = MAX_PACKET_LEN - HEADER_LEN - 4 - 1 - 1 - 2;
const MAX_FRAGMENTS_PER_MESSAGE: usize = 256;
// The largest message we allow to be sent.
//
// We cap fragmented messages to 256 fragments, so the largest message we can send is the largest
// size a single fragment can be times 256.
const MAX_MESSAGE_LEN: usize = MAX_FRAGMENT_LEN * MAX_FRAGMENTS_PER_MESSAGE;
// The protocol ID is the first 64 bits of the MD5 hash of "sumi".
const PROTOCOL_ID: u64 = 0x41008F06B7698109;
const CONNECTION_REQUEST: u8 = 1;
const CHALLENGE: u8 = 2;
const CHALLENGE_RESPONSE: u8 = 3;
const CONNECTION_ACCEPTED: u8 = 4;
const MESSAGE: u8 = 5;
const ACK: u8 = 6;
static ALGORITHM: &'static Algorithm = &CHACHA20_POLY1305;
/// A socket server, listenting for connections.
///
/// After creating a `ConnectionListener` by [`bind`]ing it to a socket address, it listens for
/// incoming connections. `ConnectionListener` acts like a stream that yields [`Connection`]
/// objects as new connections are established.
///
/// The socket will be closed when the value is dropped.
///
/// # Examples
///
/// ```no_run
/// # extern crate sumi;
/// # extern crate futures;
/// # extern crate tokio_core;
/// use sumi::ConnectionListener;
/// use futures::Stream;
/// use tokio_core::reactor::Core;
///
/// # fn main() {
/// let mut reactor = Core::new().unwrap();
/// let listener = ConnectionListener::bind("127.0.0.1:80", &reactor.handle())
/// .unwrap()
/// .for_each(|connection| {
/// println!("Made a connection: {:?}", connection);
/// Ok(())
/// });
/// reactor.run(listener).unwrap();
/// # }
/// ```
///
/// [`bind`]: #method.bind
/// [`Connection`]: ./struct.Connection.html
pub struct ConnectionListener {
socket: UdpSocket,
local_address: SocketAddr,
// Map containing all the currently open connections.
open_connections: HashMap<u64, OpenConnection>,
// RNG used for generating nonces for cookie encryption as part of the connection handshake.
rng: OsRng,
// Encryption keys for cookie encryption as part of the connection handshake.
opening_key: OpeningKey,
sealing_key: SealingKey,
// Track the time at which the `ConnectionListener` was created. This is used to send
// timestamps as `Duration`s relative to `start_time`. This is needed since `Instant` can't
// be serialized, but `Duration` can.
start_time: Instant,
// Buffers for reading incoming packets and writing outgoing packets.
read_buffer: Vec<u8>,
write_buffer: Vec<u8>,
handle: Handle,
}
impl ConnectionListener {
/// Creates a new `ConnectionListener` bound to the specified address.
///
/// The returned listener is ready for accepting connections.
///
/// Binding with a port number of 0 will request that the OS assigns a port to this listener.
/// The port allocated can be queried via the [`local_addr`] method.
///
/// The address type can be any implementor of the [`ToSocketAddrs`] trait. See its
/// documentation for concrete examples.
///
/// If `address` yields multiple addresses, `bind` will be attempted with each of the
/// addresses until one succeeds and returns the listener. If none of the addresses succeed
/// in creating a listener, the error returned from the last attempt (the last address) is
/// returned.
///
/// # Examples
///
/// Create a connection listener bound to `127.0.0.1:80`:
///
/// ```no_run
/// # extern crate sumi;
/// # extern crate tokio_core;
/// use sumi::ConnectionListener;
/// use tokio_core::reactor::Core;
///
/// # fn main() {
/// let reactor = Core::new().unwrap();
/// let listener = ConnectionListener::bind("127.0.0.1:80", &reactor.handle()).unwrap();
/// # }
/// ```
///
/// Create a connection listener bound to `127.0.0.1:80`. If that fails, create a
/// listener bound to `127.0.0.1:443`:
///
/// ```no_run
/// # extern crate sumi;
/// # extern crate tokio_core;
/// use std::net::SocketAddr;
/// use sumi::ConnectionListener;
/// use tokio_core::reactor::Core;
///
/// # fn main() {
/// let reactor = Core::new().unwrap();
/// let addrs = [
/// SocketAddr::from(([127, 0, 0, 1], 80)),
/// SocketAddr::from(([127, 0, 0, 1], 443)),
/// ];
/// let listener = ConnectionListener::bind(&addrs[..], &reactor.handle()).unwrap();
/// # }
/// ```
///
/// [`local_addr`]: #method.local_addr
/// [`ToSocketAddrs`]: https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html
pub fn bind<A: ToSocketAddrs>(
addresses: A,
handle: &Handle,
) -> Result<ConnectionListener, io::Error> {
// Iterate over the specified addresses, trying to bind the UDP socket to each one in
// turn. We use the first one that binds successfully, returning an error if none work.
let socket = addresses.to_socket_addrs()?
.fold(None, |result, address| {
match result {
// If we've already bound the socket, don't try the current address.
Some(Ok(socket)) => { Some(Ok(socket)) }
// If we haven't bound a socket yet, try with the current address.
Some(Err(_)) | None => {
Some(UdpSocket::bind(&address, handle))
}
}
})
.unwrap_or(Err(io::ErrorKind::AddrNotAvailable.into()))?;
let local_address = socket.local_addr()?;
// Create the AEAD keys used for encrypting information in a connection challenge.
let mut rng = OsRng::new()?;
let mut salt = [0; 8];
rng.fill_bytes(&mut salt[..]);
let mut key = [0; 32];
// TODO: How many iterations should we use when creating the key?
pbkdf2::derive(
&SHA512,
100,
&salt[..],
&SECRET_PASSWORD_DO_NOT_STEAL[..],
&mut key[..],
);
let opening_key = OpeningKey::new(ALGORITHM, &key[..]).expect("Failed to create opening key");
let sealing_key = SealingKey::new(ALGORITHM, &key[..]).expect("Failed to create sealing key");
Ok(ConnectionListener {
socket,
local_address,
rng,
opening_key,
sealing_key,
start_time: Instant::now(),
open_connections: HashMap::new(),
read_buffer: vec![0; MAX_PACKET_LEN],
write_buffer: Vec::with_capacity(MAX_PACKET_LEN),
handle: handle.clone(),
})
}
/// Returns the local socket address of this listener.
///
/// # Examples
///
/// ```no_run
/// # extern crate sumi;
/// # extern crate tokio_core;
/// use sumi::ConnectionListener;
/// use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr};
/// use tokio_core::reactor::Core;
///
/// # fn main() {
/// let reactor = Core::new().unwrap();
/// let listener = ConnectionListener::bind("127.0.0.1:8080", &reactor.handle()).unwrap();
/// assert_eq!(
/// listener.local_addr().unwrap(),
/// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080))
/// );
/// # }
/// ```
pub fn local_addr(&self) -> Result<SocketAddr, io::Error> {
self.socket.local_addr()
}
}
impl Stream for ConnectionListener {
type Item = Connection;
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
// Poll the socket for incoming packets, forwarding valid packets to the correct endpoint.
loop {
// Read any available messages on the socket. Once we receive a `WouldBlock` error,
// there is no more data to receive.
let (bytes_read, address) = match self.socket.recv_from(&mut self.read_buffer) {
Ok(result) => { result }
Err(error) => {
match error.kind() {
io::ErrorKind::WouldBlock => { break; }
// On Windows, this is returned when a previous send operation resulted
// in an ICMP Port Unreachable message. Unfortunately, we don't get
// enough information on which connection has been broken, so we'll have
// to ignore this and wait for the connection to timeout.
io::ErrorKind::ConnectionReset => { continue; }
// All other error kinds are legit errors, and are returned as such.
_ => {
return Err(error);
}
}
}
};
// Decode the packet, discarding any packets that fail basic verification.
let Packet { connection_id, data, .. } = match decode(&self.read_buffer[.. bytes_read])? {
Some(packet) => { packet }
None => { continue; }
};
match data {
PacketData::ConnectionRequest => {
let cookie = ChallengeCookie {
request_time: self.start_time.elapsed(),
source_addres: address,
connection_id,
};
// Construct the final cookie by combining the nonce and the ciphertext of
// the serialized `ChallengeCookie`.
let cookie_bytes = &mut [0; MAX_COOKIE_LEN][..];
let cookie_len = {
// Split the cookie bytes into two buffers: The front for the nonce, and
// the back for the ciphertext.
let (nonce, ciphertext) = cookie_bytes.split_at_mut(NONCE_LEN);
// Generate the nonce in the front part of the buffer.
self.rng.fill_bytes(nonce);
bincode::serialize_into(
&mut Cursor::new(&mut ciphertext[..]),
&cookie,
bincode::Infinite,
).expect("Failed to serialize challenge cookie");
// Shrink the size of the ciphertext buffer to be exactly the serialized
// size of the cookie + the tag size of the ecryption algorithm.
let serialized_len = bincode::internal::serialized_size(&cookie) as usize;
let ciphertext_len = serialized_len + ALGORITHM.tag_len();
debug_assert!(
ciphertext.len() > ciphertext_len,
"Serialized cookie is too big"
);
let ciphertext = &mut ciphertext[.. ciphertext_len];
// Encrypt the cookie bytes in-place within the ciphertext buffer.
let sealed_len = aead::seal_in_place(
&self.sealing_key,
&nonce[..],
&[],
ciphertext,
ALGORITHM.tag_len(),
).expect("Failed to seal the challenge cookie");
assert_eq!(
sealed_len, ciphertext.len(),
"Sealed length is different than ciphertext length"
);
nonce.len() + ciphertext_len
};
// Write the challenge packet into a buffer.
let cookie = &cookie_bytes[.. cookie_len];
encode(
Packet {
connection_id,
data: PacketData::Challenge(cookie),
},
&mut self.write_buffer,
)?;
// Send that junk to junk town.
match self.socket.send_to(&self.write_buffer[..], &address) {
Ok(..) => {}
Err(error) => {
if error.kind() != io::ErrorKind::WouldBlock {
return Err(error);
}
// TODO: How to do we handle a `WouldBlock` error?
unimplemented!("What do we do if we get a `WouldBlock` error?");
}
}
}
PacketData::ChallengeResponse(cookie) => {
// Split the cookie into the nonce and ciphertext.
let (nonce, ciphertext) = cookie.split_at(NONCE_LEN);
// Copy the ciphertext into another buffer where we can decrypt it in-place.
let cookie_buffer = &mut [0; MAX_CIPHERTEXT_LEN][.. ciphertext.len()];
io::copy(
&mut Cursor::new(ciphertext),
&mut Cursor::new(&mut cookie_buffer[..]),
)?;
// Try to open the cookie.
let open_result = aead::open_in_place(
&self.opening_key,
nonce,
&[],
0,
cookie_buffer,
);
// If we fail to decrypt the cookie, simply discard the packet.
let cookie = match open_result {
Ok(cookie) => cookie,
Err(_) => {
continue;
}
};
// Deserialize the raw bytes of the `ChallengeCookie` back into a struct.
// If it fails to deserialize, just discard the packet.
let cookie = match bincode::deserialize::<ChallengeCookie>(cookie) {
Ok(cookie) => cookie,
Err(_) => {
continue;
}
};
// Discard the packet if it didn't come from the same address that
// the connection request came from.
if cookie.source_addres != address {
continue;
}
// Discard the packet if the connection ID doesn't match the
// connection ID in the cookie.
if cookie.connection_id != connection_id {
continue;
}
// Discard the packet if too much time has passed since the original
// connection request was received.
if (self.start_time + cookie.request_time).elapsed() > Duration::from_secs(1) {
continue;
}
// The cookie has passed validation, which means we can accept the connection!
// Add it to the set of open connections.
let (connection, client) = match self.open_connections.entry(connection_id) {
Entry::Occupied(entry) => { (entry.into_mut(), None) }
Entry::Vacant(entry) => {
// Bind a new UDP socket listening on a local port. We'll forward incoming
// packets for this connection to the socket.
let bind_address = ([127, 0, 0, 1], 0).into();
let socket = UdpSocket::bind(&bind_address, &self.handle)?;
let local_address = socket.local_addr()?;
// Create a client that sends messages to the connection listener.
// TODO: Make disconnect timeout configurable.
let disconnect_timeout =
Timeout::new(Duration::from_secs(1), &self.handle)?;
let client = Connection {
socket,
peer_address: self.local_address,
connection_id,
sequence_number: 0,
send_buffer: Vec::with_capacity(MAX_PACKET_LEN),
recv_buffer: vec![0; 1024],
fragments: HashMap::new(),
handle: self.handle.clone(),
disconnect_timeout,
};
// TODO: Make disconnect timeout configurable.
let disconnect_timeout =
Timeout::new(Duration::from_secs(1), &self.handle)?;
let connection = OpenConnection {
local_address,
remote_address: address,
disconnect_timeout,
};
(entry.insert(connection), Some(client))
}
};
// If the address the packet came from doesn't match the remote address in
// the connection record, discard the packet.
if address != connection.remote_address {
continue;
}
// Encode the connection accepted message.
encode(
Packet { connection_id, data: PacketData::ConnectionAccepted },
&mut self.write_buffer,
)?;
// Send the connection accepted message.
match self.socket.send_to(&self.write_buffer[..], &address) {
Ok(..) => {}
Err(error) => {
if error.kind() != io::ErrorKind::WouldBlock {
return Err(error);
}
// TODO: How to do we handle a `WouldBlock` error?
unimplemented!("What do we do if we get a `WouldBlock` error?");
}
}
// Yield the new connection.
if let Some(client) = client {
return Ok(Async::Ready(Some(client)));
}
}
// For all other packet types, we try to forward it to the correct socket; Either
// the local socket if it came from the client, or the client socket if it came
// from the local socket.
_ => if let Some(connection) = self.open_connections.get_mut(&connection_id) {
let to_address = if address == connection.local_address {
// Forward to the remote address.
connection.remote_address
} else if address == connection.remote_address {
// We've received in incoming packet, so reset the disconnect timeout.
connection.disconnect_timeout
.reset(Instant::now() + Duration::from_secs(1));
// Forward to the local address.
connection.local_address
} else {
// The packet came from an unknown address, simply discard it.
continue;
};
// Send the packet to its real destination.
match self.socket.send_to(&self.read_buffer[.. bytes_read], &to_address) {
Ok(_) => {}
Err(error) => {
if error.kind() == io::ErrorKind::WouldBlock {
panic!("Failed to send a critical message: {:?}", data);
}
return Err(error);
}
}
}
}
}
// Poll each of the open connections for the disconnect timeout, removing any connections
// that have disconnected (or return an error).
self.open_connections.retain(|_, connection| {
match connection.disconnect_timeout.poll() {
Ok(Async::NotReady) => { true }
_ => { false }
}
});
Ok(Async::NotReady)
}
}
/// A connection between a local and remote socket.
///
/// After creating a `Connection` by either [`connect`]ing to a remote host or yielding one
/// from a [`ConnectionListener`], data can be transmitted by... well, by using [`serialized`]
/// to converting it to a type that implements [`Stream`] and [`Sink`].
///
/// The connection will be closed when the value is dropped.
///
/// # Examples
///
/// ```no_run
/// # extern crate sumi;
/// # extern crate tokio_core;
/// # fn main() {
/// use sumi::Connection;
/// use tokio_core::reactor::Core;
///
/// let mut core = Core::new().unwrap();
/// let address = "127.0.0.1:1234".parse().unwrap();
/// let wait_for_connection = Connection::connect(address, &core.handle()).unwrap();
/// let connection = core.run(wait_for_connection).unwrap();
/// # }
/// ```
///
/// [`connect`]: #method.connect
/// [`ConnectionListener`]: ./struct.ConnectionListener.html
/// [`serialized`]: #method.serialized
/// [`Stream`]: https://docs.rs/futures/0.1/futures/stream/trait.Stream.html
/// [`Sink`]: https://docs.rs/futures/0.1/futures/sink/trait.Sink.html
/// ```
#[derive(Debug)]
pub struct Connection {
socket: UdpSocket,
peer_address: SocketAddr,
connection_id: u64,
sequence_number: u32,
// Intermediate buffers used in sending and receiving messages. Unlike a raw UDP socket, we
// need to use intermediate buffers because we have extra packet structure to handle in
// addition to the raw bytes of the message.
send_buffer: Vec<u8>,
recv_buffer: Vec<u8>,
fragments: HashMap<u32, MessageFragments>,
// A handle to the tokio reactor so that we can spawn things like timeouts.
handle: Handle,
// Timeout for determining if we've disconnected from the server. Is reset every time an
// incoming packet is received.
disconnect_timeout: Timeout,
}
impl Connection {
/// Opens a new connection to a remote host at the specified address.
///
/// The function will create a new socket and attempt to connect it to the `address` provided.
/// The returned future will be resolved once the stream has successfully connected. If an
/// error happens during the connection or during the socket creation, that error will be
/// returned to the future instead.
///
/// # Examples
///
/// ```no_run
/// # extern crate sumi;
/// # extern crate tokio_core;
/// # fn main() {
/// use sumi::Connection;
/// use tokio_core::reactor::Core;
///
/// let mut core = Core::new().unwrap();
/// let address = "127.0.0.1:1234".parse().unwrap();
/// let wait_for_connection = Connection::connect(address, &core.handle()).unwrap();
/// let connection = core.run(wait_for_connection).unwrap();
/// # }
pub fn connect(
address: SocketAddr,
handle: &Handle,
) -> Result<ConnectionNew, io::Error> {
let address = address.into();
// What's the right address to bind the local socket to?
let bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0);
let socket = UdpSocket::bind(&bind_address, handle)?;
Ok(ConnectionNew {
socket: Some(socket),
peer_address: address,
start_time: Instant::now(),
connection_id: rand::random(),
state: ConnectionState::AwaitingChallenge,
interval: Interval::new(Duration::from_millis(40), handle)?,
read_buffer: vec![0; MAX_PACKET_LEN],
write_buffer: Vec::with_capacity(MAX_PACKET_LEN),
handle: handle.clone(),
})
}
/// Begins sending a message, returning a futures that resolves when the messages
/// has been fully sent.
pub fn send<T>(mut self, buffer: T) -> Send<T> where T: AsRef<[u8]> {
let num_fragments = {
let buffer = buffer.as_ref();
assert!(
buffer.len() <= MAX_MESSAGE_LEN,
"Message is longer than max len of {} bytes, message len: {}",
MAX_MESSAGE_LEN,
buffer.len()
);
// Increment the sequence number.
self.sequence_number.wrapping_add(1);
// Write the first fragment of the message into the connection's write buffer.
let num_fragments = (buffer.len() as f32 / MAX_FRAGMENT_LEN as f32).ceil() as u8;
let fragment_len = cmp::min(buffer.len(), MAX_FRAGMENT_LEN);
encode(
Packet {
connection_id: self.connection_id,
data: PacketData::Message {
sequence_number: self.sequence_number,
fragment: &buffer[.. fragment_len],
num_fragments,
fragment_number: 0,
},
},
&mut self.send_buffer,
).expect("Error encoding packet");
num_fragments
};
let sequence_number = self.sequence_number;
Send {
state: send::State::start(
self,
buffer,
sequence_number,
num_fragments,
1,
),
}
}
/// Begins sending a message, returning a futures that resolves when the messages
/// has been fully sent.
pub fn send_reliable<T>(mut self, buffer: T) -> SendReliable<T> where T: AsRef<[u8]> {
let num_fragments = {
let buffer = buffer.as_ref();
assert!(
buffer.len() <= MAX_MESSAGE_LEN,
"Message is longer than max len of {} bytes, message len: {}",
MAX_MESSAGE_LEN,
buffer.len()
);
// Increment the sequence number.
self.sequence_number.wrapping_add(1);
// Write the first fragment of the message into the connection's write buffer.
let num_fragments = (buffer.len() as f32 / MAX_FRAGMENT_LEN as f32).ceil() as u8;
let fragment_len = cmp::min(buffer.len(), MAX_FRAGMENT_LEN);
encode(
Packet {
connection_id: self.connection_id,
data: PacketData::Message {
sequence_number: self.sequence_number,
fragment: &buffer[.. fragment_len],
num_fragments,
fragment_number: 0,
},
},
&mut self.send_buffer,
).expect("Error encoding packet");
num_fragments
};
let sequence_number = self.sequence_number;
SendReliable {
state: send_reliable::State::start(
self,
buffer,
sequence_number,
num_fragments,
1,
Duration::from_secs(1),
Duration::from_millis(100),
),
}
}
/// Creates a future that receives a message to be written to the buffer provided.
///
/// The returned future will resolve after a message has been received in full.
pub fn recv<T>(self, buffer: T) -> Receive<T> where T: AsMut<[u8]> {
Receive {
state: recv::State::start(
self,
buffer,
),
}
}
/// Provides a Stream and Sink interface for sending and receiving messages.
///
/// The raw `Connection` only supports sending and receiving messages as byte arrays. In order
/// to simplify higher-level code, this adapter provides automatic serialization and
/// deserialization of messages, making communication easier.
///
/// Serialization is done using [bincode], which provides a reasonable default serialization
/// strategy for most purposes. For more specialized serialization strategies, just... I
/// dunno... do it yourself.
///
/// This function returns a *single* object that is both [`Stream`] and [`Sink`]; grouping
/// this into a single object is often useful for layering things which require both read
/// and write access to the underlying object.
///
/// If you want to work more directly with the stream and sink, consider calling [`split`]
/// on the [`Serialized`] returned by this method, which will break them into separate
/// objects, allowing them to interact more easily.
///
/// [bincode]: https://crates.io/crates/bincode
/// [`Stream`]: https://docs.rs/futures/0.1/futures/stream/trait.Stream.html
/// [`Sink`]: https://docs.rs/futures/0.1/futures/sink/trait.Sink.html
/// [`split`]: https://docs.rs/futures/0.1/futures/stream/trait.Stream.html#method.split
/// [`Serialized`]: ./struct.Serialized.html
pub fn serialized<T, U>(self) -> Serialized<T, U> {
Serialized {
connection: self,
flushed: true,
_send: Default::default(),
_recv: Default::default(),
}
}
}
/// A wrapper around a [`Connection`] that automatically handles serialization.
///
/// This is created by the [`serialized`] method on [`Connection`]. See its documentation for
/// more information.
///
/// [`Connection`]: ./struct.Connection.html
/// [`serialized`]: ./struct.Connection.html#method.serialized
#[derive(Debug)]
pub struct Serialized<T, U> {
connection: Connection,
flushed: bool,
_send: ::std::marker::PhantomData<T>,
_recv: ::std::marker::PhantomData<U>,
}
impl<T, U> Serialized<T, U> {
/// Consumes the `Serialized` returning the underlying [`Connection`].
///
/// [`Connection`]: ./struct.Connection.html
pub fn into_inner(self) -> Connection {
self.connection
}
}
impl<T, U: DeserializeOwned> Stream for Serialized<T, U> {
type Item = U;
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
// Check to see if the connection has timed out waiting for data. If it has, we
if self.connection.disconnect_timeout.poll()? == Async::Ready(()) {
return Ok(Async::Ready(None));
}
loop {
let packet = try_nb!(recv_packet(
&self.connection.socket,
self.connection.peer_address,
&mut self.connection.recv_buffer,
));
// Reset the timeout since we received a packet.
// TODO: Make disconnect timeout configurable.
self.connection.disconnect_timeout.reset(Instant::now() + Duration::from_secs(1));
// Handle the packet according to its type, returning the message's data if we
// received a message packet.
let message_bytes = match packet.data {
PacketData::Message { sequence_number: _, fragment, num_fragments, fragment_number } => {
if num_fragments != 1 || fragment_number != 0 {
unimplemented!("Support receiving multi-fragment messages");
}
fragment
}
// Discard any stray messages that are part of the handshake.
PacketData::ConnectionRequest
| PacketData::Challenge(_)
| PacketData::ChallengeResponse(_)
| PacketData::ConnectionAccepted
| PacketData::Ack(_)
=> { continue; }
};
if let Ok(message) = bincode::deserialize(message_bytes) {
return Ok(Async::Ready(Some(message)));
}
}
}
}
impl<T: Serialize, U> Sink for Serialized<T, U> {
type SinkItem = T;
type SinkError = io::Error;
fn start_send(
&mut self,
item: Self::SinkItem,
) -> StartSend<Self::SinkItem, Self::SinkError> {
if !self.flushed {
match self.poll_complete()? {
Async::Ready(()) => {},
Async::NotReady => return Ok(AsyncSink::NotReady(item)),
}
}
// TODO: Don't allocate each time we serialize a message.
let serialized = bincode::serialize(&item, bincode::Bounded(MAX_FRAGMENT_LEN as u64))
.expect("Serialized size was too big, need to implement message fragmenting");
self.connection.sequence_number += 1;
encode(
Packet {
connection_id: self.connection.connection_id,
data: PacketData::Message {
sequence_number: self.connection.sequence_number,
fragment: &serialized,
num_fragments: 1,
fragment_number: 0,
},
},
&mut self.connection.send_buffer,
)?;
self.flushed = false;
Ok(AsyncSink::Ready)
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
if self.flushed {
return Ok(Async::Ready(()))
}
let n = try_nb!(self.connection.socket.send_to(
&self.connection.send_buffer,
&self.connection.peer_address,
));
let wrote_all = n == self.connection.send_buffer.len();
self.connection.send_buffer.clear();
self.flushed = true;
if wrote_all {
Ok(Async::Ready(()))
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"Failed to write entire datagram to socket",
))
}
}
}
/// Future returned by [`Connection::connect`] which will resolve to a [`Connection`] when the
/// connection is established.
///
/// [`Connection::connect`]: ./struct.Connection.html#method.connect
/// [`Connection`]: ./struct.Connection.html
pub struct ConnectionNew {
// We wrap the socket in an `Option` so that we can move the socket out of the `ConnectionNew`
// future once the connection is accepted.
socket: Option<UdpSocket>,
peer_address: SocketAddr,
start_time: Instant,
connection_id: u64,
state: ConnectionState,
interval: Interval,
read_buffer: Vec<u8>,
write_buffer: Vec<u8>,
handle: Handle,
}
impl Future for ConnectionNew {
type Item = Connection;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// If we've taken too long, return a timeout error.
if self.start_time.elapsed() > Duration::from_secs(1) {
return Err(io::ErrorKind::TimedOut.into());
}
// Read any ready messages on the socket.
loop {
let (bytes_read, address) = {
let socket = self.socket
.as_ref()
.expect("Poll called after connection was established");
if let Async::NotReady = socket.poll_read() {
break;
}
try_nb!(socket.recv_from(&mut self.read_buffer))
};
// Discard the packet if it didn't come from the server we're connecting to.
if address != self.peer_address { continue; }
// Decode that sweet, sweet packet.
let Packet { connection_id, data, .. } = match decode(&self.read_buffer[.. bytes_read])? {
Some(packet) => { packet }
// Discard any packets that fail basic verification.
None => { continue; }
};
// Discard the packet if the connection IDs don't match.
if connection_id != self.connection_id { continue; }
match data {
PacketData::Challenge(cookie) => {
// Update the connection state with the new cookie. If we were already in
// the `ConfirmingChallenge` state, then just update the cookie to the
// new one.
match self.state {
ConnectionState::AwaitingChallenge => {
let mut buffer = Vec::with_capacity(MAX_COOKIE_LEN);
io::copy(
&mut Cursor::new(cookie),
&mut buffer,
)?;
self.state = ConnectionState::ConfirmingChallenge(buffer);
}
ConnectionState::ConfirmingChallenge(ref mut buffer) => {
buffer.clear();
io::copy(
&mut Cursor::new(cookie),
buffer,
)?;
}
}
// Send the challenge response.
encode(
Packet {
connection_id: self.connection_id,
data: PacketData::ChallengeResponse(cookie),
},
&mut self.write_buffer,
)?;
let send_result = self.socket
.as_ref()
.expect("Poll called after connection was established")
.send_to(
&self.write_buffer[..],
&self.peer_address,
);
match send_result {
Ok(..) => {}
// NOTE: We don't do anything when we get a `WouldBlock` error because we'll retry to
// send the message at a regular interval.
Err(error) => {
if error.kind() != io::ErrorKind::WouldBlock {
return Err(error);
}
println!(
"WARNING: Sending the challenge response would block: {:?}",
error,
);
}
}
}
PacketData::ConnectionAccepted => {
let socket = self.socket
.take()
.expect("Poll called after connection was established");
// TODO: Make disconnect timeout configurable.
let disconnect_timeout = Timeout::new(Duration::from_secs(1), &self.handle)?;
return Ok(Async::Ready(Connection {
socket,
peer_address: self.peer_address,
connection_id: self.connection_id,
sequence_number: 0,
send_buffer: mem::replace(&mut self.write_buffer, Vec::new()),
recv_buffer: vec![0; MAX_PACKET_LEN],
fragments: HashMap::new(),
handle: self.handle.clone(),
disconnect_timeout,
}));
}
// Discard all other packet types.
_ => continue,
}
}
// If we haven't received the challenge from the server yet, then see if we should
// resend the connection request (or challenge response).
// ===============================================================================
while let Async::Ready(_) = self.interval.poll()? {
match self.state {
ConnectionState::AwaitingChallenge => {
encode(
Packet {
connection_id: self.connection_id,
data: PacketData::ConnectionRequest,
},
&mut self.write_buffer,
)?;
}
ConnectionState::ConfirmingChallenge(ref cookie) => {
encode(
Packet {
connection_id: self.connection_id,
data: PacketData::ChallengeResponse(&cookie[..]),
},
&mut self.write_buffer,
)?;
}
};
let send_result = self.socket
.as_ref()
.expect("Poll called after connection was established")
.send_to(
&self.write_buffer[..],
&self.peer_address,
);
match send_result {
Ok(..) => {}
// NOTE: We don't do anything when we get a `WouldBlock` error because we'll retry to
// send the message at a regular interval.
Err(error) => {
if error.kind() != io::ErrorKind::WouldBlock {
return Err(error);
}
println!(
"WARNING: Resending request would block: {:?}",
error,
);
}
}
}
Ok(Async::NotReady)
}
}
fn decode<'a>(buffer: &'a [u8]) -> Result<Option<Packet<'a>>, io::Error> {
// Ignore any messages that are too small to at least contain the header, connection
// ID, and message type.
if buffer.len() < HEADER_LEN { return Ok(None); }
// The first 4 bytes of the packet are the CRC32 checksum. We split it off from the rest
// of the packet so that we can verify that the checksum of the data matches the checksum
// in the header.
let (checksum, body) = buffer.split_at(4);
let checksum = NetworkEndian::read_u32(checksum);
// Calculate the checksum of the received data by digesting the implicit protocol header and
// the received packet data.
let mut digest = Digest::new(crc32::IEEE);
digest.write_u64(PROTOCOL_ID);
Hasher32::write(&mut digest, body);
// If the checksum in the packet's header doesn't match the calculated checksum, discard the
// packet.
if checksum != digest.sum32() { return Ok(None); }
let mut cursor = Cursor::new(body);
// Read the connection ID from the packet.
let connection_id = cursor.read_u64::<NetworkEndian>()?;
// Read the message type.
let message_type = cursor.read_u8()?;
let data = match message_type {
CONNECTION_REQUEST => {
// Enforce the connection requests must be the maximum allowed size, in order to
// avoid our protocl being used as part of a DDOS magnification attack.
if buffer.len() != MAX_PACKET_LEN { return Ok(None); }
PacketData::ConnectionRequest
}
CHALLENGE => {
let cookie_len = cursor.read_u8()? as usize;
let cookie_start = cursor.position() as usize;
let cookie_end = cookie_start + cookie_len;
// Ignore the packet if the cookie len is just too long.
if cookie_end > body.len() { return Ok(None); }
PacketData::Challenge(&body[cookie_start .. cookie_end])
}
CHALLENGE_RESPONSE => {
let cookie_len = cursor.read_u8()? as usize;
let cookie_start = cursor.position() as usize;
let cookie_end = cookie_start + cookie_len;
// Ignore the packet if the cookie len is just too long.
if cookie_end > body.len() { return Ok(None); }
PacketData::ChallengeResponse(&body[cookie_start .. cookie_end])
}
CONNECTION_ACCEPTED => { PacketData::ConnectionAccepted }
MESSAGE => {
// Read the sequence number for the message.
let sequence_number = cursor.read_u32::<NetworkEndian>()?;
// Read the number of fragments and the current fragment's number.
let num_fragments = cursor.read_u8()?;
let fragment_number = cursor.read_u8()?;
// If the number of fragments is invalid, discard the packet.
if num_fragments == 0 || fragment_number >= num_fragments { return Ok(None); }
let message_len = cursor.read_u16::<NetworkEndian>()? as usize;
let message_start = cursor.position() as usize;
let message_end = message_start + message_len;
if message_end > body.len() { return Ok(None); }
PacketData::Message {
sequence_number,
fragment: &body[message_start .. message_end],
num_fragments,
fragment_number,
}
}
ACK => {
let sequence_number = cursor.read_u32::<NetworkEndian>()?;
PacketData::Ack(sequence_number)
}
// Ignore any unknown message types.
_ => { return Ok(None); }
};
Ok(Some(Packet { connection_id, data }))
}
fn encode<'a>(packet: Packet<'a>, buffer: &mut Vec<u8>) -> Result<(), io::Error> {
// Reset the output buffer before writing the packet.
buffer.clear();
// Write a placeholder for the checksum. We'll replace this with the real checksum after
// the rest of the packet has been written.
buffer.write_u32::<NetworkEndian>(0)?;
// Write the connection ID.
buffer.write_u64::<NetworkEndian>(packet.connection_id)?;
// Write the packet type.
buffer.write_u8(packet.data.packet_type())?;
// Write some stuff based on the packet data.
match packet.data {
PacketData::ConnectionRequest => {
// Force the packet to be the maximum size.
buffer.resize(MAX_PACKET_LEN, 0);
}
PacketData::Challenge(cookie) | PacketData::ChallengeResponse(cookie) => {
// Write the length of the cookie into the buffer.
debug_assert!(
cookie.len() <= MAX_COOKIE_LEN,
"Cookie is too big for its length to fit in a `u8`"
);
buffer.write_u8(cookie.len() as u8)?;
// Write the cookie into the buffer.
buffer.extend(cookie);
}
PacketData::ConnectionAccepted => {}
PacketData::Message { sequence_number, fragment, num_fragments, fragment_number } => {
// Write the sequence number.
buffer.write_u32::<NetworkEndian>(sequence_number)?;
// Write the number of fragments and the fragment number into the buffer.
debug_assert!(num_fragments >= 1, "Message must have at least 1 fragment");
buffer.write_u8(num_fragments)?;
buffer.write_u8(fragment_number)?;
// Write the length of the fragment into the buffer.
debug_assert!(
fragment.len() <= MAX_FRAGMENT_LEN,
"Message is too big for its length to fit in a `u32`"
);
buffer.write_u16::<NetworkEndian>(fragment.len() as u16)?;
// Write the fragment into the buffer.
buffer.extend(fragment);
}
PacketData::Ack(sequence_number) => {
buffer.write_u32::<NetworkEndian>(sequence_number)?;
}
}
// Split the buffer into the leading checksum and the remaining body of the packet.
let (checksum, body) = buffer.split_at_mut(4);
// Create a CRC32 digest of the implicit protocol ID and the body of the packet.
let mut digest = Digest::new(crc32::IEEE);
digest.write_u64(PROTOCOL_ID);
Hasher32::write(&mut digest, body);
// Write the checksum into the leading 4 bytes of the packet.
NetworkEndian::write_u32(checksum, digest.sum32());
Ok(())
}
/// Returns the next valid packet received from the connected peer.
///
/// `recv_packet` will automatically discard any incoming datagrams that do not come from the
/// connected peer, or that do not pass basic validation. It will repeated polly the
/// underlying socket until it get a valid packet or a `WouldBlock` error.
fn recv_packet<'b>(
socket: &UdpSocket,
peer_address: SocketAddr,
buffer: &'b mut [u8],
) -> Result<Packet<'b>, io::Error> {
let len;
loop {
let (bytes_read, address) = socket.recv_from(buffer)?;
// If the packet didn't come from the other side of the connection, then
// discard it.
if address != peer_address { continue; }
if let Some(_) = decode(&buffer[.. bytes_read])? {
len = bytes_read;
break;
}
}
// HACK: We have to re-decode the packet because borrowck won't let us return a borrowed
// value (i.e. the packet) from the body of a loop. So we return the length of the packet
// from the loop (since it's not a borrowed value) and re-borrow the packet after the
// loop.
Ok(decode(&buffer[.. len])?.unwrap())
}
#[derive(Debug)]
enum ConnectionState {
AwaitingChallenge,
ConfirmingChallenge(Vec<u8>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ChallengeCookie {
request_time: Duration,
source_addres: SocketAddr,
connection_id: u64,
}
/// A collection of fragments for a partially-received message.
///
/// This tracks how many fragments are expected as part of the message, how many fragments have
/// been received so far, and contains the raw data for each of the fragments.
struct MessageFragments {
// The total number of fragments expected for the message.
num_fragments: u8,
// The number of fragments we've received so far.
received: u8,
// The total size in bytes of all the fragments we've received so far. Once the full message
// has been received, this will be the full size of the message in bytes.
bytes_received: usize,
// Placeholders for each of the fragments.
fragments: [bool; MAX_FRAGMENTS_PER_MESSAGE],
}
impl ::std::fmt::Debug for MessageFragments {
fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
write!(formatter, "MessageFragments {{ .. }}")
}
}
#[derive(Debug)]
struct OpenConnection {
local_address: SocketAddr,
remote_address: SocketAddr,
disconnect_timeout: Timeout,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Packet<'a> {
connection_id: u64,
data: PacketData<'a>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PacketData<'a> {
ConnectionRequest,
Challenge(&'a [u8]),
ChallengeResponse(&'a [u8]),
ConnectionAccepted,
Message {
sequence_number: u32,
fragment: &'a [u8],
num_fragments: u8,
fragment_number: u8,
},
Ack(u32),
}
impl<'a> PacketData<'a> {
fn packet_type(&self) -> u8 {
match *self {
PacketData::ConnectionRequest => CONNECTION_REQUEST,
PacketData::Challenge(..) => CHALLENGE,
PacketData::ChallengeResponse(..) => CHALLENGE_RESPONSE,
PacketData::ConnectionAccepted => CONNECTION_ACCEPTED,
PacketData::Message { .. } => MESSAGE,
PacketData::Ack(..) => ACK,
}
}
}
#[cfg(test)]
mod test {
use super::*;
const CONNECTION_ID: u64 = 0x0011223344556677;
static COOKIE: &'static [u8] = b"super good cookie that's totally valid";
#[test]
fn connection_request_roundtrip() {
let mut buffer = Vec::with_capacity(MAX_PACKET_LEN);
let packet = Packet {
connection_id: CONNECTION_ID,
data: PacketData::ConnectionRequest,
};
encode(
packet,
&mut buffer,
).expect("Error encoding packet");
match decode(&buffer[..]).expect("Error decoding packet") {
Some(decoded) => {
assert_eq!(packet, decoded, "Decoded packed doesn't match original");
}
None => { panic!("Packet failed verification"); }
}
}
#[test]
fn challenge_roundtrip() {
let mut buffer = Vec::with_capacity(MAX_PACKET_LEN);
let packet = Packet {
connection_id: CONNECTION_ID,
data: PacketData::Challenge(COOKIE),
};
encode(
packet,
&mut buffer,
).expect("Error encoding packet");
match decode(&buffer[..]).expect("Error decoding packet") {
Some(decoded) => {
assert_eq!(packet, decoded, "Decoded packed doesn't match original");
}
None => { panic!("Packet failed verification"); }
}
}
#[test]
fn challenge_response_roundtrip() {
let mut buffer = Vec::with_capacity(MAX_PACKET_LEN);
let packet = Packet {
connection_id: CONNECTION_ID,
data: PacketData::ChallengeResponse(COOKIE),
};
encode(
packet,
&mut buffer,
).expect("Error encoding packet");
match decode(&buffer[..]).expect("Error decoding packet") {
Some(decoded) => {
assert_eq!(packet, decoded, "Decoded packed doesn't match original");
}
None => { panic!("Packet failed verification"); }
}
}
#[test]
fn connection_accepted_roundtrip() {
let mut buffer = Vec::with_capacity(MAX_PACKET_LEN);
let packet = Packet {
connection_id: CONNECTION_ID,
data: PacketData::ConnectionAccepted,
};
encode(
packet,
&mut buffer,
).expect("Error encoding packet");
match decode(&buffer[..]).expect("Error decoding packet") {
Some(decoded) => {
assert_eq!(packet, decoded, "Decoded packed doesn't match original");
}
None => { panic!("Packet failed verification"); }
}
}
#[test]
fn message_fragment_roundtrip() {
let mut buffer = Vec::with_capacity(MAX_PACKET_LEN);
let packet = Packet {
connection_id: CONNECTION_ID,
data: PacketData::Message {
sequence_number: 4,
fragment: COOKIE,
num_fragments: 123,
fragment_number: 12,
},
};
encode(
packet,
&mut buffer,
).expect("Error encoding packet");
match decode(&buffer[..]).expect("Error decoding packet") {
Some(decoded) => {
assert_eq!(packet, decoded, "Decoded packed doesn't match original");
}
None => { panic!("Packet failed verification"); }
}
}
#[test]
fn ack_roundtrip() {
let mut buffer = Vec::with_capacity(MAX_PACKET_LEN);
let packet = Packet {
connection_id: CONNECTION_ID,
data: PacketData::Ack(7),
};
encode(
packet,
&mut buffer,
).expect("Error encoding packet");
match decode(&buffer[..]).expect("Error decoding packet") {
Some(decoded) => {
assert_eq!(packet, decoded, "Decoded packed doesn't match original");
}
None => { panic!("Packet failed verification"); }
}
}
}
|
use std::process::Command;
use std::env;
const ASM_DIR: &str = "src/arch/x64";
const ASM_INCL_DIR: &str = "src/arch/x64/include";
#[cfg(not(target_arch = "x86_64"))]
fn asm_file(file: &str, out_dir: &str) {}
#[cfg(not(target_arch = "x86_64"))]
fn asm(out_dir: &str) {}
#[cfg(target_arch = "x86_64")]
fn asm_file(file: &str, out_dir: &str)
{
let file = format!("{}/{}", ASM_DIR, file);
let out_name = file.replace("/", "-");
let out_file = format!("lib{}.a", out_name);
println!("cargo:rerun-if-changed={}", file);
let status;
if env::var("DEBUG").unwrap() == "true" {
status = Command::new("nasm")
.arg(file)
.arg("-o")
.arg(format!("{}/{}", out_dir, out_file))
.arg(format!("-I{}", ASM_INCL_DIR))
.arg("-g")
.arg("-f")
.arg("elf64")
.arg("-F")
.arg("Dwarf")
.status()
.expect("couldn't run nasm");
} else {
status = Command::new("nasm")
.arg(file)
.arg("-o")
.arg(format!("{}/{}", out_dir, out_file))
.arg(format!("-I{}", ASM_INCL_DIR))
.arg("-f")
.arg("elf64")
.arg("-F")
.arg("Dwarf")
.status()
.expect("couldn't run nasm");
}
if !status.success() {
panic!("nasm failed with {}", status);
}
println!("cargo:rustc-link-lib=static={}", out_name);
}
#[cfg(target_arch = "x86_64")]
fn asm(out_dir: &str)
{
let incl_files = vec!["asm_def.asm"];
let files = vec![
//"boot/mb2.asm",
"boot/boot.asm",
"boot/long_init.asm",
"boot/ap_boot.asm",
"misc.asm",
"int/int.asm",
"syscall/syscall.asm",
"resources.asm",
];
for f in incl_files.iter() {
println!("cargo:rerun-if-changed={}/{}", ASM_INCL_DIR, f);
}
for f in files.iter() {
asm_file(f, out_dir);
}
}
fn main()
{
let out_dir = env::var("OUT_DIR").unwrap();
println!("cargo:rustc-link-search={}", out_dir);
asm(&out_dir);
}
|
use std::error;
use std::io;
use std::io::BufRead;
use crate::day;
pub type BoxResult<T> = Result<T, Box<dyn error::Error>>;
pub struct Day01 {}
impl day::Day for Day01 {
fn tag(&self) -> &str { "01" }
fn part1(&self, input: &dyn Fn() -> Box<dyn io::Read>) {
println!("{:?}", self.part1_impl(&mut *input()));
}
fn part2(&self, input: &dyn Fn() -> Box<dyn io::Read>) {
println!("{:?}", self.part2_impl(&mut *input()));
}
}
impl Day01 {
fn part1_impl(self: &Self, input: &mut dyn io::Read) -> BoxResult<i32> {
let reader = io::BufReader::new(input);
Ok(reader.lines().map(|s| s.unwrap().parse::<i32>().unwrap() / 3 - 2)
.sum())
}
fn fuel_2(&self, m: i32) -> i32 {
let f = m / 3 - 2;
if f <= 0 {0 } else { f + self.fuel_2(f) }
}
fn part2_impl(self: &Self, input: &mut dyn io::Read) -> BoxResult<i32> {
let reader = io::BufReader::new(input);
Ok(reader.lines().map(|s|
self.fuel_2(s.unwrap().parse::<i32>().unwrap()))
.sum())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test1(s: &str, f: i32) {
assert_eq!(Day01 {}.part1_impl(&mut s.as_bytes()).unwrap(), f);
}
#[test]
fn part1() {
test1("12", 2);
test1("14", 2);
test1("1969", 654);
test1("100756", 33583);
}
fn test2(s: &str, f: i32) {
assert_eq!(Day01 {}.part2_impl(&mut s.as_bytes()).unwrap(), f);
}
#[test]
fn part2() {
test2("1969", 966);
test2("100756", 50346);
}
} |
//! # 61. 旋转链表
//! https://leetcode-cn.com/problems/rotate-list/
//!给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
//! # 解题思路
//!算出链表的长度L,对k求模,获取新的右移位置,循环找到新的头结点,断链,把原始头拼到链表最后
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
#[allow(dead_code)]
fn new_node(val: i32, next: Option<Box<ListNode>>) -> Self {
ListNode { val, next }
}
}
pub struct Solution;
impl Solution {
pub fn rotate_right(head: Option<Box<ListNode>>, k: i32) -> Option<Box<ListNode>> {
if head.is_none() {
return None;
}
let mut dumy_head = Box::new(ListNode::new(0));
dumy_head.next = head;
let mut len = 0;
{
let mut h = &dumy_head;
while h.next.is_some() {
h = h.next.as_ref().unwrap();
len += 1;
}
}
let new_k = k % len;
if new_k == 0 {
return dumy_head.next;
}
let mut end = &mut dumy_head;
for _ in 0..(len - new_k) {
end = end.next.as_mut().unwrap();
}
//新的头节点,从这里断链
let mut new_head = end.next.take();
let mut h = &mut new_head;
//这里有些重复,理论上在计算链表长度的时候就可以获取尾节点
while h.is_some() {
if h.as_ref().unwrap().next.is_none() {
//找到尾部,插入原始的头结点
h.as_mut().unwrap().next = dumy_head.next.take();
break;
}
h = &mut h.as_mut().unwrap().next;
}
dumy_head.next = new_head;
dumy_head.next
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(
super::Solution::rotate_right(
Some(Box::new(super::ListNode::new_node(
1,
Some(Box::new(super::ListNode::new_node(
1,
Some(Box::new(super::ListNode::new_node(3, None))),
))),
))),
1,
),
Some(Box::new(super::ListNode::new_node(
3,
Some(Box::new(super::ListNode::new_node(
1,
Some(Box::new(super::ListNode::new_node(1, None))),
))),
)))
);
}
}
|
//! A lightweight, self-contained s-expression parser and data format.
//! Use `parse` to get an s-expression from its string representation, and the
//! `Display` trait to serialize it, potentially by doing `sexp.to_string()`.
//!
//! **Atoms** is a basic S-expression parser. It parses strings and produces
//! a tree of Cons-cells and atomic values of discrete type. Currently, only
//! the following primitive types are available, and are represented with the
//! `Value` `enum`:
//!
//! * `Nil`
//! * `Cons`
//! * `Symbol`
//! * `String`
//! * `Int`
//! * `Float`
//!
//! The trees are, as expected, formed by `Cons` cells.
//!
//! # Parsing
//!
//! Parsing expressions requires a parser to be attached to the given string.
//!
//! ```rust
//! use atoms::{Parser, StringValue};
//! let text = "(this is a series of symbols)";
//! let parser = Parser::new(&text);
//! let parsed = parser.parse_basic().unwrap();
//! assert_eq!(
//! StringValue::into_list(
//! vec!["this", "is", "a", "series", "of", "symbols"],
//! |s| StringValue::symbol(s).unwrap()
//! ),
//! parsed
//! );
//! ```
//!
//! Custom parsing of symbols can be fairly easily defined allowing for
//! restricted symbol sets with parsing errors. See
//! [`Parser::parse`](struct.Parser.html#method.parse) for more.
//!
//! # Rendering
//!
//! To render out an S-expression, simply use `ToString` or display it
//! directly.
//!
//! ```rust
//! use atoms::StringValue;
//! let value = StringValue::cons(
//! StringValue::symbol("this").unwrap(),
//! StringValue::cons(
//! StringValue::string("is"),
//! StringValue::cons(
//! StringValue::int(4),
//! StringValue::symbol("s-expression").unwrap(),
//! )
//! )
//! );
//! assert_eq!(value.to_string(), "(this \"is\" 4 . s-expression)");
//! ```
//!
#![deny(missing_docs)]
#![deny(unsafe_code)]
extern crate unescape;
#[macro_use]
mod value;
mod parse;
mod error;
pub use value::{Value, StringValue};
pub use parse::Parser;
pub use error::{ParseResult, ParseError};
|
#![macro_use]
#[cfg_attr(spi_v1, path = "v1.rs")]
#[cfg_attr(spi_v2, path = "v2.rs")]
#[cfg_attr(spi_v3, path = "v3.rs")]
mod _version;
use crate::{peripherals, rcc::RccPeripheral};
pub use _version::*;
use crate::gpio::Pin;
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
Framing,
Crc,
ModeFault,
Overrun,
}
// TODO move upwards in the tree
pub enum ByteOrder {
LsbFirst,
MsbFirst,
}
#[derive(Copy, Clone, PartialOrd, PartialEq)]
enum WordSize {
EightBit,
SixteenBit,
}
#[non_exhaustive]
pub struct Config {
pub mode: Mode,
pub byte_order: ByteOrder,
}
impl Default for Config {
fn default() -> Self {
Self {
mode: MODE_0,
byte_order: ByteOrder::MsbFirst,
}
}
}
pub(crate) mod sealed {
use super::*;
pub trait Instance {
fn regs() -> &'static crate::pac::spi::Spi;
}
pub trait SckPin<T: Instance>: Pin {
fn af_num(&self) -> u8;
}
pub trait MosiPin<T: Instance>: Pin {
fn af_num(&self) -> u8;
}
pub trait MisoPin<T: Instance>: Pin {
fn af_num(&self) -> u8;
}
}
pub trait Instance: sealed::Instance + RccPeripheral + 'static {}
pub trait SckPin<T: Instance>: sealed::SckPin<T> + 'static {}
pub trait MosiPin<T: Instance>: sealed::MosiPin<T> + 'static {}
pub trait MisoPin<T: Instance>: sealed::MisoPin<T> + 'static {}
crate::pac::peripherals!(
(spi, $inst:ident) => {
impl sealed::Instance for peripherals::$inst {
fn regs() -> &'static crate::pac::spi::Spi {
&crate::pac::$inst
}
}
impl Instance for peripherals::$inst {}
};
);
macro_rules! impl_pin {
($inst:ident, $pin:ident, $signal:ident, $af:expr) => {
impl $signal<peripherals::$inst> for peripherals::$pin {}
impl sealed::$signal<peripherals::$inst> for peripherals::$pin {
fn af_num(&self) -> u8 {
$af
}
}
};
}
crate::pac::peripheral_pins!(
($inst:ident, spi, SPI, $pin:ident, SCK, $af:expr) => {
impl_pin!($inst, $pin, SckPin, $af);
};
($inst:ident, spi, SPI, $pin:ident, MOSI, $af:expr) => {
impl_pin!($inst, $pin, MosiPin, $af);
};
($inst:ident, spi, SPI, $pin:ident, MISO, $af:expr) => {
impl_pin!($inst, $pin, MisoPin, $af);
};
);
|
use chat_room::*;
use std::collections::HashMap;
pub struct Manager {
rooms: HashMap<ChatRoomId, ChatRoom>
}
impl Manager {
pub fn new() -> Manager {
Manager {
rooms: HashMap::new()
}
}
pub fn create_or_find(&mut self, chat_room_id: ChatRoomId) -> &mut ChatRoom {
if self.rooms.contains_key(&chat_room_id) {
return match self.rooms.get_mut(&chat_room_id) {
Some(meetup) => meetup,
None => unreachable!()
}
}
self.rooms.insert(chat_room_id, ChatRoom::new(chat_room_id));
self.rooms.get_mut(&chat_room_id).unwrap()
}
}
|
#[doc = "Register `RXF1A` reader"]
pub type R = crate::R<RXF1A_SPEC>;
#[doc = "Register `RXF1A` writer"]
pub type W = crate::W<RXF1A_SPEC>;
#[doc = "Field `F1AI` reader - Rx FIFO 1 acknowledge index After the Host has read a message or a sequence of messages from Rx FIFO 1 it has to write the buffer index of the last element read from Rx FIFO 1 to F1AI. This sets the Rx FIFOÂ 1 get index RXF1S\\[F1GI\\]
to F1AI + 1 and update the FIFO 1 Fill Level RXF1S\\[F1FL\\]."]
pub type F1AI_R = crate::FieldReader;
#[doc = "Field `F1AI` writer - Rx FIFO 1 acknowledge index After the Host has read a message or a sequence of messages from Rx FIFO 1 it has to write the buffer index of the last element read from Rx FIFO 1 to F1AI. This sets the Rx FIFOÂ 1 get index RXF1S\\[F1GI\\]
to F1AI + 1 and update the FIFO 1 Fill Level RXF1S\\[F1FL\\]."]
pub type F1AI_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>;
impl R {
#[doc = "Bits 0:2 - Rx FIFO 1 acknowledge index After the Host has read a message or a sequence of messages from Rx FIFO 1 it has to write the buffer index of the last element read from Rx FIFO 1 to F1AI. This sets the Rx FIFOÂ 1 get index RXF1S\\[F1GI\\]
to F1AI + 1 and update the FIFO 1 Fill Level RXF1S\\[F1FL\\]."]
#[inline(always)]
pub fn f1ai(&self) -> F1AI_R {
F1AI_R::new((self.bits & 7) as u8)
}
}
impl W {
#[doc = "Bits 0:2 - Rx FIFO 1 acknowledge index After the Host has read a message or a sequence of messages from Rx FIFO 1 it has to write the buffer index of the last element read from Rx FIFO 1 to F1AI. This sets the Rx FIFOÂ 1 get index RXF1S\\[F1GI\\]
to F1AI + 1 and update the FIFO 1 Fill Level RXF1S\\[F1FL\\]."]
#[inline(always)]
#[must_use]
pub fn f1ai(&mut self) -> F1AI_W<RXF1A_SPEC, 0> {
F1AI_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "FDCAN Rx FIFO 1 acknowledge register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rxf1a::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rxf1a::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RXF1A_SPEC;
impl crate::RegisterSpec for RXF1A_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rxf1a::R`](R) reader structure"]
impl crate::Readable for RXF1A_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rxf1a::W`](W) writer structure"]
impl crate::Writable for RXF1A_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RXF1A to value 0"]
impl crate::Resettable for RXF1A_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
// SPDX-FileCopyrightText: 2017-2022 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// SPDX-License-Identifier: MIT
use axum::{http::StatusCode, response::IntoResponse, routing::get_service, Router};
use std::net::SocketAddr;
use tokio::io;
use tower_http::services::ServeDir;
#[tokio::main]
async fn main() {
let app =
Router::new().fallback(get_service(ServeDir::new("build")).handle_error(handle_error));
let port = 8080;
let addr = SocketAddr::from(([127, 0, 0, 1], port));
println!("Development server listening at port {port}");
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handle_error(_: io::Error) -> impl IntoResponse {
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
}
|
use alloc::arc::{Arc, Weak};
use alloc::boxed::Box;
use collections::String;
use collections::borrow::ToOwned;
use core::cell::Cell;
use core::mem::size_of;
use core::ops::DerefMut;
use core::{ptr, slice};
use arch::context::Context;
use sync::{WaitMap, WaitQueue};
use system::error::{Error, Result, EFAULT, EINVAL, ENODEV, ESPIPE};
use system::scheme::Packet;
use system::syscall::{SYS_CLOSE, SYS_DUP, SYS_FPATH, SYS_FSTAT, SYS_FSYNC, SYS_FTRUNCATE,
SYS_OPEN, SYS_LSEEK, SEEK_SET, SEEK_CUR, SEEK_END, SYS_MKDIR,
SYS_READ, SYS_WRITE, SYS_RMDIR, SYS_UNLINK, Stat};
use super::{Resource, ResourceSeek, KScheme};
struct SchemeInner {
name: String,
context: *mut Context,
next_id: Cell<usize>,
todo: WaitQueue<Packet>,
done: WaitMap<usize, (usize, usize, usize, usize)>,
}
impl SchemeInner {
fn new(name: &str, context: *mut Context) -> SchemeInner {
SchemeInner {
name: name.to_owned(),
context: context,
next_id: Cell::new(1),
todo: WaitQueue::new(),
done: WaitMap::new(),
}
}
fn call(inner: &Weak<SchemeInner>, a: usize, b: usize, c: usize, d: usize) -> Result<usize> {
if let Some(scheme) = inner.upgrade() {
let id = scheme.next_id.get();
//TODO: What should be done about collisions in self.todo or self.done?
let mut next_id = id + 1;
if next_id <= 0 {
next_id = 1;
}
scheme.next_id.set(next_id);
// debugln!("{} {}: {} {} {:X} {:X} {:X}", scheme.name, id, a, ::syscall::name(a), b, c, d);
scheme.todo.send(Packet {
id: id,
a: a,
b: b,
c: c,
d: d
}, "SchemeInner::call todo");
let res = Error::demux(scheme.done.receive(&id, "SchemeInner::call done").0);
// debugln!("{} {}: {} {} {:X} {:X} {:X} = {:?}", scheme.name, id, a, ::syscall::name(a), b, c, d, res);
res
} else {
Err(Error::new(ENODEV))
}
}
fn capture(inner: &Weak<SchemeInner>, mut physical_address: usize, size: usize, writeable: bool) -> Result<usize> {
if let Some(scheme) = inner.upgrade() {
if physical_address >= 0x80000000 {
physical_address -= 0x80000000;
}
unsafe {
let mmap = &mut *(*scheme.context).mmap.get();
return mmap.add_mem(physical_address, size, writeable, false);
}
} else {
return Err(Error::new(ENODEV));
}
}
fn release(inner: &Weak<SchemeInner>, virtual_address: usize) {
if let Some(scheme) = inner.upgrade() {
unsafe {
let mmap = &mut *(*scheme.context).mmap.get();
if let Ok(mut mem) = mmap.get_mem_mut(virtual_address) {
mem.virtual_size = 0;
}
mmap.clean_mem();
}
}
}
}
impl Drop for SchemeInner {
fn drop(&mut self) {
unsafe { &mut *::env().schemes.get() }.retain(|scheme| scheme.scheme() != self.name);
}
}
pub struct SchemeResource {
inner: Weak<SchemeInner>,
file_id: usize,
}
impl SchemeResource {
fn call(&self, a: usize, b: usize, c: usize, d: usize) -> Result<usize> {
SchemeInner::call(&self.inner, a, b, c, d)
}
fn capture(&self, physical_address: usize, size: usize, writeable: bool) -> Result<usize> {
SchemeInner::capture(&self.inner, physical_address, size, writeable)
}
fn release(&self, virtual_address: usize){
SchemeInner::release(&self.inner, virtual_address);
}
}
impl Resource for SchemeResource {
/// Duplicate the resource
fn dup(&self) -> Result<Box<Resource>> {
let file_id = try!(self.call(SYS_DUP, self.file_id, 0, 0));
Ok(Box::new(SchemeResource {
inner: self.inner.clone(),
file_id: file_id
}))
}
/// Return the URL of this resource
fn path(&self, buf: &mut [u8]) -> Result <usize> {
let contexts = unsafe { & *::env().contexts.get() };
let current = try!(contexts.current());
if let Ok(physical_address) = current.translate(buf.as_mut_ptr() as usize, buf.len()) {
let offset = physical_address % 4096;
let virtual_address = try!(self.capture(physical_address - offset, buf.len() + offset, true));
let result = self.call(SYS_FPATH, self.file_id, virtual_address + offset, buf.len());
//debugln!("Read {:X} mapped from {:X} to {:X} offset {} length {} size {} result {:?}", physical_address, buf.as_ptr() as usize, virtual_address + offset, offset, buf.len(), virtual_size, result);
self.release(virtual_address);
result
} else {
debugln!("{}:{} fault {:X} {}", file!(), line!(), buf.as_ptr() as usize, buf.len());
Err(Error::new(EFAULT))
}
}
/// Read data to buffer
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let contexts = unsafe { & *::env().contexts.get() };
let current = try!(contexts.current());
if let Ok(physical_address) = current.translate(buf.as_mut_ptr() as usize, buf.len()) {
let offset = physical_address % 4096;
let virtual_address = try!(self.capture(physical_address - offset, buf.len() + offset, true));
let result = self.call(SYS_READ, self.file_id, virtual_address + offset, buf.len());
//debugln!("Read {:X} mapped from {:X} to {:X} offset {} length {} size {} result {:?}", physical_address, buf.as_ptr() as usize, virtual_address + offset, offset, buf.len(), virtual_size, result);
self.release(virtual_address);
result
} else {
debugln!("{}:{} fault {:X} {}", file!(), line!(), buf.as_ptr() as usize, buf.len());
Err(Error::new(EFAULT))
}
}
/// Write to resource
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let contexts = unsafe { & *::env().contexts.get() };
let current = try!(contexts.current());
if let Ok(physical_address) = current.translate(buf.as_ptr() as usize, buf.len()) {
let offset = physical_address % 4096;
let virtual_address = try!(self.capture(physical_address - offset, buf.len() + offset, false));
let result = self.call(SYS_WRITE, self.file_id, virtual_address + offset, buf.len());
// debugln!("Write {:X} mapped from {:X} to {:X} offset {} length {} result {:?}", physical_address, buf.as_ptr() as usize, virtual_address + offset, offset, buf.len(), result);
self.release(virtual_address);
result
} else {
debugln!("{}:{} fault {:X} {}", file!(), line!(), buf.as_ptr() as usize, buf.len());
Err(Error::new(EFAULT))
}
}
/// Seek
fn seek(&mut self, pos: ResourceSeek) -> Result<usize> {
let (whence, offset) = match pos {
ResourceSeek::Start(offset) => (SEEK_SET, offset as usize),
ResourceSeek::Current(offset) => (SEEK_CUR, offset as usize),
ResourceSeek::End(offset) => (SEEK_END, offset as usize)
};
self.call(SYS_LSEEK, self.file_id, offset, whence)
}
/// Stat the resource
fn stat(&self, stat: &mut Stat) -> Result<()> {
let buf = unsafe { slice::from_raw_parts_mut(stat as *mut Stat as *mut u8, size_of::<Stat>()) };
let contexts = unsafe { & *::env().contexts.get() };
let current = try!(contexts.current());
if let Ok(physical_address) = current.translate(buf.as_mut_ptr() as usize, buf.len()) {
let offset = physical_address % 4096;
let virtual_address = try!(self.capture(physical_address - offset, buf.len() + offset, true));
let result = self.call(SYS_FSTAT, self.file_id, virtual_address + offset, 0);
self.release(virtual_address);
result.and(Ok(()))
} else {
debugln!("{}:{} fault {:X} {}", file!(), line!(), buf.as_ptr() as usize, buf.len());
Err(Error::new(EFAULT))
}
}
/// Sync the resource
fn sync(&mut self) -> Result<()> {
self.call(SYS_FSYNC, self.file_id, 0, 0).and(Ok(()))
}
/// Truncate the resource
fn truncate(&mut self, len: usize) -> Result<()> {
self.call(SYS_FTRUNCATE, self.file_id, len, 0).and(Ok(()))
}
}
impl Drop for SchemeResource {
fn drop(&mut self) {
let _ = self.call(SYS_CLOSE, self.file_id, 0, 0);
}
}
pub struct SchemeServerResource {
inner: Arc<SchemeInner>,
}
impl Resource for SchemeServerResource {
/// Duplicate the resource
fn dup(&self) -> Result<Box<Resource>> {
Ok(box SchemeServerResource {
inner: self.inner.clone()
})
}
/// Return the URL of this resource
fn path(&self, buf: &mut [u8]) -> Result<usize> {
let mut i = 0;
let path_a = b":";
while i < buf.len() && i < path_a.len() {
buf[i] = path_a[i];
i += 1;
}
let path_b = self.inner.name.as_bytes();
while i < buf.len() && i - path_a.len() < path_b.len() {
buf[i] = path_b[i - path_a.len()];
i += 1;
}
Ok(i)
}
/// Read data to buffer
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
if buf.len() >= size_of::<Packet>() {
let mut i = 0;
let packet = self.inner.todo.receive("SchemeServerResource::read todo");
unsafe { ptr::write(buf.as_mut_ptr().offset(i as isize) as *mut Packet, packet); }
i += size_of::<Packet>();
while i + size_of::<Packet>() <= buf.len() {
if let Some(packet) = unsafe { self.inner.todo.inner() }.pop_front() {
unsafe { ptr::write(buf.as_mut_ptr().offset(i as isize) as *mut Packet, packet); }
i += size_of::<Packet>();
} else {
break;
}
}
Ok(i)
} else {
Err(Error::new(EINVAL))
}
}
/// Write to resource
fn write(&mut self, buf: &[u8]) -> Result<usize> {
if buf.len() >= size_of::<Packet>() {
let mut i = 0;
while i <= buf.len() - size_of::<Packet>() {
let packet = unsafe { & *(buf.as_ptr().offset(i as isize) as *const Packet) };
self.inner.done.send(packet.id, (packet.a, packet.b, packet.c, packet.d), "SchemeServerResource::write done");
i += size_of::<Packet>();
}
Ok(i)
} else {
Err(Error::new(EINVAL))
}
}
/// Seek
fn seek(&mut self, _pos: ResourceSeek) -> Result<usize> {
Err(Error::new(ESPIPE))
}
/// Sync the resource
fn sync(&mut self) -> Result<()> {
Err(Error::new(EINVAL))
}
fn truncate(&mut self, _len: usize) -> Result<()> {
Err(Error::new(EINVAL))
}
}
/// Scheme has to be wrapped
pub struct Scheme {
name: String,
inner: Weak<SchemeInner>
}
impl Scheme {
pub fn new(name: &str) -> Result<(Box<Scheme>, Box<Resource>)> {
let contexts = unsafe { &mut *::env().contexts.get() };
let mut current = try!(contexts.current_mut());
let server = box SchemeServerResource {
inner: Arc::new(SchemeInner::new(name, current.deref_mut()))
};
let scheme = box Scheme {
name: name.to_owned(),
inner: Arc::downgrade(&server.inner)
};
Ok((scheme, server))
}
fn call(&self, a: usize, b: usize, c: usize, d: usize) -> Result<usize> {
SchemeInner::call(&self.inner, a, b, c, d)
}
fn capture(&self, physical_address: usize, size: usize, writeable: bool) -> Result<usize> {
SchemeInner::capture(&self.inner, physical_address, size, writeable)
}
fn release(&self, virtual_address: usize){
SchemeInner::release(&self.inner, virtual_address);
}
}
impl KScheme for Scheme {
fn on_irq(&mut self, _irq: u8) {
}
fn scheme(&self) -> &str {
&self.name
}
fn open(&mut self, path: &str, flags: usize) -> Result<Box<Resource>> {
let virtual_address = try!(self.capture(path.as_ptr() as usize, path.len(), false));
let result = self.call(SYS_OPEN, virtual_address, path.len(), flags);
self.release(virtual_address);
match result {
Ok(file_id) => Ok(box SchemeResource {
inner: self.inner.clone(),
file_id: file_id,
}),
Err(err) => Err(err)
}
}
fn mkdir(&mut self, path: &str, flags: usize) -> Result<()> {
let virtual_address = try!(self.capture(path.as_ptr() as usize, path.len(), false));
let result = self.call(SYS_MKDIR, virtual_address, path.len(), flags);
self.release(virtual_address);
result.and(Ok(()))
}
fn rmdir(&mut self, path: &str) -> Result<()> {
let virtual_address = try!(self.capture(path.as_ptr() as usize, path.len(), false));
let result = self.call(SYS_RMDIR, virtual_address, path.len(), 0);
self.release(virtual_address);
result.and(Ok(()))
}
fn unlink(&mut self, path: &str) -> Result<()> {
let virtual_address = try!(self.capture(path.as_ptr() as usize, path.len(), false));
let result = self.call(SYS_UNLINK, virtual_address, path.len(), 0);
self.release(virtual_address);
result.and(Ok(()))
}
}
|
// 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
// 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
// 注意:给定 n 是一个正整数。
// 示例 1:
// 输入: 2
// 输出: 2
// 解释: 有两种方法可以爬到楼顶。
// 1. 1 阶 + 1 阶
// 2. 2 阶
// 示例 2:
// 输入: 3
// 输出: 3
// 解释: 有三种方法可以爬到楼顶。
// 1. 1 阶 + 1 阶 + 1 阶
// 2. 1 阶 + 2 阶
// 3. 2 阶 + 1 阶
struct Solution{}
impl Solution {
pub fn climb_stairs(n: i32) -> i32 {
let result: i32 = n - 3;
if result > 0 {
((1f64 / 5f64.sqrt()) * (((1f64 + 5f64.sqrt()) / 2f64).powi(n + 1) - ((1f64 - 5f64.sqrt()) / 2f64).powi(n + 1))).round() as i32
} else {
n
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_climb_stairs() {
assert_eq!(Solution::climb_stairs(1), 1);
assert_eq!(Solution::climb_stairs(2), 2);
assert_eq!(Solution::climb_stairs(3), 3);
assert_eq!(Solution::climb_stairs(4), 5);
assert_eq!(Solution::climb_stairs(5), 8);
assert_eq!(Solution::climb_stairs(6), 13);
assert_eq!(Solution::climb_stairs(35), 14930352);
}
} |
use std::collections::HashSet;
use std::error::Error;
use std::io::{self, Read, Write};
use std::result;
type Result<T> = result::Result<T, Box<Error>>;
fn main() -> Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let final_freq = one(&input)?;
writeln!(io::stdout(), "Final Freq: {}", final_freq)?;
let first_recurrent_freq = two(&input)?;
writeln!(io::stdout(), "1st Recurrent Freq: {}", first_recurrent_freq)?;
Ok(())
}
fn one(input: &str) -> Result<i32> {
let final_freq: i32 = input
.lines()
.map(|line| line.parse::<i32>())
.filter_map(|r| r.ok())
.sum();
Ok(final_freq)
}
fn two(input: &str) -> Result<i32> {
let mut freqs = input
.lines()
.map(|line| line.parse::<i32>())
.filter_map(|r| r.ok())
.cycle();
let mut history = HashSet::new();
let mut freq: i32 = 0;
while history.insert(freq) {
if let Some(f) = freqs.next() {
freq += f;
}
}
Ok(freq)
}
#[test]
fn one_should_return_final_freqency() {
assert_eq!(360, one("100\n200\n60\n400\n-400").unwrap());
}
#[test]
fn one_should_ignore_non_int_input() {
assert_eq!(360, one("100\n200\nlolololol\n60\n").unwrap());
}
#[test]
fn two_should_return_first_recurrent_freqency() {
assert_eq!(300, two("100\n200\n60\n-60").unwrap());
}
|
extern crate sync;
use sync::{Arc, Mutex};
fn main() {
let x1 = Arc::new(Mutex::new(0));
let y1 = Arc::new(Mutex::new(0));
let x2 = x1.clone();
let y2 = y1.clone();
spawn(proc() {
for _ in range(0u, 100) {
let i = x2.lock();
let j = y2.lock();
let _ = *i + *j;
}
});
for _ in range(0u, 100) {
let j = y1.lock();
let i = x1.lock();
let _ = *i + *j;
}
} |
use std::error::Error;
#[derive(Debug)]
pub struct World {
blocks: Vec<Vec<bool>>, // access as blocks[y][x]
width: usize,
height: usize,
user_x: f64,
user_y: f64,
user_angle: f64,
}
impl World {
pub fn new(width: usize, height: usize) -> Self {
Self {
blocks: vec![vec![false; width]; height],
width,
height,
user_x: 4.0,
user_y: 4.0,
user_angle: 0.0,
}
}
// angle is given in radians
pub fn cast(&self, start_x: f64, start_y: f64, angle: f64) -> f64 {
// first, check collisions with vertical part of blocks
let mut shortest_distance: f64 = f64::MAX;
let mut x = if angle.cos() > 0.0 {
start_x.ceil()
} else {
start_x.floor()
};
let dx = angle.cos().signum();
let slope = angle.tan();
let dy = slope * dx;
let mut y = start_y + slope * (x - start_x);
while x >= 0.0 && x < (self.width as f64) && y >= 0.0 && y < (self.height as f64) {
let lookup_x = (x + if dx < 0.0 { -1.0 } else { 0.0 }) as usize;
let lookup_y = y as usize;
if self.blocks[lookup_y][lookup_x] {
break;
}
x += dx;
y += dy;
}
shortest_distance = f64::min(
shortest_distance,
((start_x - x).powi(2) + (start_y - y).powi(2)).sqrt(),
);
// now, check collisions with horizontal part of blocks
let mut y = if angle.sin() > 0.0 {
start_y.ceil()
} else {
start_y.floor()
};
let dy = angle.sin().signum();
let slope = angle.tan();
let dx = dy / slope;
let mut x = start_x + (y - start_y) / slope;
while x >= 0.0 && x < (self.width as f64) && y >= 0.0 && y < (self.height as f64) {
let lookup_x = x as usize;
let lookup_y = (y + if dy < 0.0 { -1.0 } else { 0.0 }) as usize;
if self.blocks[lookup_y][lookup_x] {
break;
}
x += dx;
y += dy;
}
shortest_distance = f64::min(
shortest_distance,
((start_x - x).powi(2) + (start_y - y).powi(2)).sqrt(),
);
shortest_distance
}
pub fn block_at(&self, x: usize, y: usize) -> Result<bool, Box<dyn Error>> {
if x >= self.width || y >= self.height {
Err(format!(
"({}, {}) is out of bounds for world with width {} and height {}",
x, y, self.width, self.height
)
.into())
} else {
Ok(self.blocks[y][x])
}
}
pub fn set_block(&mut self, x: usize, y: usize, block: bool) -> Result<(), Box<dyn Error>> {
if x >= self.width || y >= self.height {
Err(format!(
"({}, {}) is out of bounds for world with width {} and height {}",
x, y, self.width, self.height
)
.into())
} else {
self.blocks[y][x] = block;
Ok(())
}
}
// angle is given in radians
pub fn rotate_user(&mut self, delta_angle: f64) {
self.user_angle += delta_angle;
}
pub fn move_user(&mut self, amount: f64) {
self.user_x += amount * self.user_angle.cos();
self.user_y += amount * self.user_angle.sin();
}
pub fn get_user_x(&self) -> f64 {
self.user_x
}
pub fn get_user_y(&self) -> f64 {
self.user_y
}
pub fn get_user_angle(&self) -> f64 {
self.user_angle
}
}
|
#![allow(non_snake_case)]
#[macro_use]
extern crate lazy_static;
extern crate serde_json;
extern crate vmtests;
use serde_json::Value;
use std::collections::HashMap;
use vmtests::{load_tests, run_test};
lazy_static! {
static ref TESTS: HashMap<String, Value> = load_tests("tests/vmPushDupSwapTest/");
}
#[test]
fn test_dup1() {
assert!(run_test(&TESTS["dup1"]));
}
#[test]
fn test_dup10() {
assert!(run_test(&TESTS["dup10"]));
}
#[test]
fn test_dup11() {
assert!(run_test(&TESTS["dup11"]));
}
#[test]
fn test_dup12() {
assert!(run_test(&TESTS["dup12"]));
}
#[test]
fn test_dup13() {
assert!(run_test(&TESTS["dup13"]));
}
#[test]
fn test_dup14() {
assert!(run_test(&TESTS["dup14"]));
}
#[test]
fn test_dup15() {
assert!(run_test(&TESTS["dup15"]));
}
#[test]
fn test_dup16() {
assert!(run_test(&TESTS["dup16"]));
}
#[test]
fn test_dup2() {
assert!(run_test(&TESTS["dup2"]));
}
#[test]
fn test_dup2error() {
assert!(run_test(&TESTS["dup2error"]));
}
#[test]
fn test_dup3() {
assert!(run_test(&TESTS["dup3"]));
}
#[test]
fn test_dup4() {
assert!(run_test(&TESTS["dup4"]));
}
#[test]
fn test_dup5() {
assert!(run_test(&TESTS["dup5"]));
}
#[test]
fn test_dup6() {
assert!(run_test(&TESTS["dup6"]));
}
#[test]
fn test_dup7() {
assert!(run_test(&TESTS["dup7"]));
}
#[test]
fn test_dup8() {
assert!(run_test(&TESTS["dup8"]));
}
#[test]
fn test_dup9() {
assert!(run_test(&TESTS["dup9"]));
}
#[test]
fn test_push1() {
assert!(run_test(&TESTS["push1"]));
}
#[test]
fn test_push10() {
assert!(run_test(&TESTS["push10"]));
}
#[test]
fn test_push11() {
assert!(run_test(&TESTS["push11"]));
}
#[test]
fn test_push12() {
assert!(run_test(&TESTS["push12"]));
}
#[test]
fn test_push13() {
assert!(run_test(&TESTS["push13"]));
}
#[test]
fn test_push14() {
assert!(run_test(&TESTS["push14"]));
}
#[test]
fn test_push15() {
assert!(run_test(&TESTS["push15"]));
}
#[test]
fn test_push16() {
assert!(run_test(&TESTS["push16"]));
}
#[test]
fn test_push17() {
assert!(run_test(&TESTS["push17"]));
}
#[test]
fn test_push18() {
assert!(run_test(&TESTS["push18"]));
}
#[test]
fn test_push19() {
assert!(run_test(&TESTS["push19"]));
}
#[test]
fn test_push1_missingStack() {
assert!(run_test(&TESTS["push1_missingStack"]));
}
#[test]
fn test_push2() {
assert!(run_test(&TESTS["push2"]));
}
#[test]
fn test_push20() {
assert!(run_test(&TESTS["push20"]));
}
#[test]
fn test_push21() {
assert!(run_test(&TESTS["push21"]));
}
#[test]
fn test_push22() {
assert!(run_test(&TESTS["push22"]));
}
#[test]
fn test_push23() {
assert!(run_test(&TESTS["push23"]));
}
#[test]
fn test_push24() {
assert!(run_test(&TESTS["push24"]));
}
#[test]
fn test_push25() {
assert!(run_test(&TESTS["push25"]));
}
#[test]
fn test_push26() {
assert!(run_test(&TESTS["push26"]));
}
#[test]
fn test_push27() {
assert!(run_test(&TESTS["push27"]));
}
#[test]
fn test_push28() {
assert!(run_test(&TESTS["push28"]));
}
#[test]
fn test_push29() {
assert!(run_test(&TESTS["push29"]));
}
#[test]
fn test_push3() {
assert!(run_test(&TESTS["push3"]));
}
#[test]
fn test_push30() {
assert!(run_test(&TESTS["push30"]));
}
#[test]
fn test_push31() {
assert!(run_test(&TESTS["push31"]));
}
#[test]
fn test_push32() {
assert!(run_test(&TESTS["push32"]));
}
// #[test]
// fn test_push32AndSuicide() {
// assert!(run_test(&TESTS["push32AndSuicide"]));
// }
#[test]
fn test_push32FillUpInputWithZerosAtTheEnd() {
assert!(run_test(&TESTS["push32FillUpInputWithZerosAtTheEnd"]));
}
#[test]
fn test_push32Undefined() {
assert!(run_test(&TESTS["push32Undefined"]));
}
#[test]
fn test_push32Undefined2() {
assert!(run_test(&TESTS["push32Undefined2"]));
}
#[test]
fn test_push32Undefined3() {
assert!(run_test(&TESTS["push32Undefined3"]));
}
#[test]
fn test_push33() {
assert!(run_test(&TESTS["push33"]));
}
#[test]
fn test_push4() {
assert!(run_test(&TESTS["push4"]));
}
#[test]
fn test_push5() {
assert!(run_test(&TESTS["push5"]));
}
#[test]
fn test_push6() {
assert!(run_test(&TESTS["push6"]));
}
#[test]
fn test_push7() {
assert!(run_test(&TESTS["push7"]));
}
#[test]
fn test_push8() {
assert!(run_test(&TESTS["push8"]));
}
#[test]
fn test_push9() {
assert!(run_test(&TESTS["push9"]));
}
#[test]
fn test_swap1() {
assert!(run_test(&TESTS["swap1"]));
}
#[test]
fn test_swap10() {
assert!(run_test(&TESTS["swap10"]));
}
#[test]
fn test_swap11() {
assert!(run_test(&TESTS["swap11"]));
}
#[test]
fn test_swap12() {
assert!(run_test(&TESTS["swap12"]));
}
#[test]
fn test_swap13() {
assert!(run_test(&TESTS["swap13"]));
}
#[test]
fn test_swap14() {
assert!(run_test(&TESTS["swap14"]));
}
#[test]
fn test_swap15() {
assert!(run_test(&TESTS["swap15"]));
}
#[test]
fn test_swap16() {
assert!(run_test(&TESTS["swap16"]));
}
#[test]
fn test_swap2() {
assert!(run_test(&TESTS["swap2"]));
}
#[test]
fn test_swap2error() {
assert!(run_test(&TESTS["swap2error"]));
}
#[test]
fn test_swap3() {
assert!(run_test(&TESTS["swap3"]));
}
#[test]
fn test_swap4() {
assert!(run_test(&TESTS["swap4"]));
}
#[test]
fn test_swap5() {
assert!(run_test(&TESTS["swap5"]));
}
#[test]
fn test_swap6() {
assert!(run_test(&TESTS["swap6"]));
}
#[test]
fn test_swap7() {
assert!(run_test(&TESTS["swap7"]));
}
#[test]
fn test_swap8() {
assert!(run_test(&TESTS["swap8"]));
}
#[test]
fn test_swap9() {
assert!(run_test(&TESTS["swap9"]));
}
#[test]
fn test_swapjump1() {
assert!(run_test(&TESTS["swapjump1"]));
}
|
//! An `Instruction` holds an `Operation`.
//!
//! An `instruction` gives location to an `Operation`.
//!
//! An `Instruction` is created automatically when calling various `Operation`-type functions
//! over a `Block`, such as `Block::assign`.
use il::*;
use std::fmt;
/// An `Instruction` represents location, and non-semantical information about
/// an `Operation`.
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct Instruction {
operation: Operation,
index: u64,
comment: Option<String>,
address: Option<u64>
}
impl Instruction {
pub(crate) fn new(index: u64, operation: Operation) -> Instruction {
Instruction {
operation: operation,
index: index,
comment: None,
address: None
}
}
pub(crate) fn assign(index: u64, dst: Scalar, src: Expression) -> Instruction {
Instruction::new(index, Operation::assign(dst, src))
}
pub(crate) fn store(
instruction_index: u64,
dst: Array,
dst_index: Expression,
src: Expression
) -> Instruction {
Instruction::new(instruction_index, Operation::store(dst, dst_index, src))
}
pub(crate) fn load(
instruction_index: u64,
dst: Scalar,
src_index: Expression,
src: Array
) -> Instruction {
Instruction::new(instruction_index, Operation::load(dst, src_index, src))
}
pub(crate) fn brc(index: u64, target: Expression, condition: Expression)
-> Instruction {
Instruction::new(index, Operation::brc(target, condition))
}
pub(crate) fn phi(index: u64, dst: MultiVar, src: Vec<MultiVar>)
-> Instruction {
Instruction::new(index, Operation::phi(dst, src))
}
pub(crate) fn raise(index: u64, expr: Expression) -> Instruction {
Instruction::new(index, Operation::Raise { expr: expr })
}
/// Returns `true` if the `Operation` for this `Instruction` is `Operation::Assign`
pub fn is_assign(&self) -> bool {
if let Operation::Assign{..} = self.operation {
true
}
else {
false
}
}
/// Returns `true` if the `Operation` for this `Instruction` is `Operation::Store`
pub fn is_store(&self) -> bool {
if let Operation::Store{..} = self.operation {
true
}
else {
false
}
}
/// Returns `true` if the `Operation` for this `Instruction` is `Operation::Load`
pub fn is_load(&self) -> bool {
if let Operation::Load{..} = self.operation {
true
}
else {
false
}
}
/// Returns `true` if the `Operation` for this `Instruction` is `Operation::Brc`
pub fn is_brc(&self) -> bool {
if let Operation::Brc{..} = self.operation {
true
}
else {
false
}
}
/// Returns `true` if the `Operation` for this `Instruction` is `Operation::Phi`
pub fn is_phi(&self) -> bool {
if let Operation::Phi{..} = self.operation {
true
}
else {
false
}
}
/// Returns `true` if the `Operation` for this `Instruction` is `Operation::Raise`
pub fn is_raise(&self) -> bool {
if let Operation::Raise{..} = self.operation {
true
}
else {
false
}
}
/// Get the `Operation` for this `Instruction`
pub fn operation(&self) -> &Operation {
&self.operation
}
/// Get a mutable reference to the `Operation` for this `Instruction`
pub fn operation_mut(&mut self) -> &mut Operation {
&mut self.operation
}
/// Get the index for this `Instruction`.
///
/// An `Instruction` index is assigned by its parent `Block` and uniquely identifies the
/// `Instruction` within the `Block`. `Instruction` indices need not be continuous, nor
/// in order.
pub fn index(&self) -> u64 {
self.index
}
/// Get the optional comment for this `Instruction`
pub fn comment(&self) -> &Option<String> {
&self.comment
}
/// Set the optional comment for this `Instruction`
pub fn set_comment(&mut self, comment: Option<String>) {
self.comment = comment;
}
/// Get the optional address for this `Instruction`
///
/// An `Instruction` will typically have an address if one was given by a translator. It is
/// not uncommon for there to be a mixture of `Instruction`s with and without comments. For
/// example, applying SSA to a `Function` will cause `Phi` instructions to be inserted, and
/// these instructions will not have addresses.
pub fn address(&self) -> Option<u64> {
self.address.clone()
}
/// Set the optional address for this `Instruction`
pub fn set_address(&mut self, address: Option<u64>) {
self.address = address;
}
/// Clone this instruction with a new index.
pub(crate) fn clone_new_index(&self, index: u64) -> Instruction {
Instruction {
operation: self.operation.clone(),
index: index,
comment: self.comment.clone(),
address: self.address
}
}
/// Get the `Variable` which will be written by this `Instruction`.
///
/// This is a convenience function around `Operation::variable_written`.
pub fn variable_written(&self) -> Option<&Variable> {
self.operation.variable_written()
}
/// Get a mutable reference to the `Variable` which will be written by this `Instruction`.
///
/// This is a convenience function around `Operation::variable_written_mut`.
pub fn variable_written_mut(&mut self) -> Option<&mut Variable> {
self.operation.variable_written_mut()
}
/// Get a Vec of each `Variable` read by this `Instruction`.
///
/// This is a convenience function around `Operation::variables_read`.
pub fn variables_read(&self) -> Vec<&Variable> {
self.operation.variables_read()
}
/// Get a Vec of mutable references for each `Variable` read by this `Instruction`.
///
/// This is a convenience function around `Operation::variables_read_mut`.
pub fn variables_read_mut(&mut self) -> Vec<&mut Variable> {
self.operation.variables_read_mut()
}
}
impl fmt::Display for Instruction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let prefix = match self.address {
Some(address) =>
format!("{:X} {:02X} {}", address, self.index, self.operation),
None =>
format!("{:02X} {}", self.index, self.operation)
};
if let Some(ref comment) = self.comment {
write!(f, "{} // {}", prefix, comment)
}
else {
write!(f, "{}", prefix)
}
}
} |
use std::io::{Read, Write};
const PROJECT_NAME: &str = "ynab";
// XXX is this fixed? or is it specific to my account?
const SPLIT_CATEGORY_ID: &str = "4f42d139-ded2-4782-b16e-e944868fbf62";
const SCHEMA: &str = include_str!("../data/schema.sql");
pub fn api_key() -> std::path::PathBuf {
directories::ProjectDirs::from("", "", PROJECT_NAME)
.unwrap()
.config_dir()
.join("api-key")
}
pub fn read_api_key() -> String {
let mut key = String::new();
let key_file = api_key();
std::fs::File::open(key_file.clone())
.unwrap()
.read_to_string(&mut key)
.unwrap();
let key = key.trim();
key.to_string()
}
#[allow(clippy::cognitive_complexity)]
fn main() {
if std::env::args().nth(1).as_ref().map(|s| s.as_str()) == Some("schema")
{
print!("{}", SCHEMA);
std::process::exit(0);
}
let key = read_api_key();
let mut ynab_config = ynab_api::apis::configuration::Configuration::new();
ynab_config.api_key = Some(ynab_api::apis::configuration::ApiKey {
prefix: Some("Bearer".to_string()),
key: key.to_string(),
});
let api = ynab_api::apis::client::APIClient::new(ynab_config);
let budget_id = api
.budgets_api()
.get_budgets()
.unwrap()
.data
.budgets
.iter()
.next()
.unwrap()
.id
.clone();
let budget = api
.budgets_api()
.get_budget_by_id(&budget_id, None)
.unwrap()
.data
.budget;
let mut file = std::fs::File::create("accounts.tsv").unwrap();
for account in budget.accounts.unwrap() {
if account.deleted {
continue;
}
file.write_all(
[
account.id.as_ref(),
account.name.as_ref(),
if account.on_budget { "1" } else { "0" },
if account.closed { "1" } else { "0" },
&format!("{}", account.balance),
&format!("{}", account.cleared_balance),
&format!("{}", account.uncleared_balance),
]
.join("\t")
.as_bytes(),
)
.unwrap();
file.write_all(b"\n").unwrap();
}
file.sync_all().unwrap();
let mut file = std::fs::File::create("category_groups.tsv").unwrap();
for category_group in budget.category_groups.unwrap() {
if category_group.deleted {
continue;
}
file.write_all(
[
category_group.id.as_ref(),
category_group.name.as_ref(),
if category_group.hidden { "1" } else { "0" },
]
.join("\t")
.as_bytes(),
)
.unwrap();
file.write_all(b"\n").unwrap();
}
file.sync_all().unwrap();
let mut file = std::fs::File::create("categories.tsv").unwrap();
for category in budget.categories.unwrap() {
if category.deleted {
continue;
}
file.write_all(
[
category.id.as_ref(),
category.category_group_id.as_ref(),
category.name.as_ref(),
if category.hidden { "1" } else { "0" },
&format!("{}", category.budgeted),
&format!("{}", category.activity),
&format!("{}", category.balance),
]
.join("\t")
.as_bytes(),
)
.unwrap();
file.write_all(b"\n").unwrap();
}
file.sync_all().unwrap();
let mut file = std::fs::File::create("payees.tsv").unwrap();
for payee in budget.payees.unwrap() {
if payee.deleted {
continue;
}
let name: &str = payee.name.as_ref();
file.write_all(
[
payee.id.as_ref(),
name.trim(),
payee
.transfer_account_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
]
.join("\t")
.as_bytes(),
)
.unwrap();
file.write_all(b"\n").unwrap();
}
file.sync_all().unwrap();
let mut file = std::fs::File::create("transactions.tsv").unwrap();
for transaction in budget.transactions.unwrap() {
if transaction.deleted {
continue;
}
let parts: &[&str] = &[
transaction.id.as_ref(),
transaction.date.as_ref(),
&format!("{}", transaction.amount),
transaction
.memo
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
cleared_to_str(transaction.cleared),
if transaction.approved { "1" } else { "0" },
transaction
.flag_color
.map(t_flag_color_to_str)
.unwrap_or("\\N"),
transaction.account_id.as_ref(),
transaction
.payee_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
transaction
.category_id
.as_ref()
.map(|s| s.as_str())
.and_then(|id| {
// the split category doesn't appear to be in the
// categories data, so we have to exclude it or else
// the NOT NULL constraint will fail
if id == SPLIT_CATEGORY_ID {
None
} else {
Some(id)
}
})
.unwrap_or("\\N"),
transaction
.transfer_account_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
];
file.write_all(parts.join("\t").as_bytes()).unwrap();
file.write_all(b"\n").unwrap();
}
file.sync_all().unwrap();
let mut file = std::fs::File::create("subtransactions.tsv").unwrap();
for subtransaction in budget.subtransactions.unwrap() {
if subtransaction.deleted {
continue;
}
file.write_all(
[
subtransaction.id.as_ref(),
subtransaction.transaction_id.as_ref(),
format!("{}", subtransaction.amount).as_ref(),
subtransaction
.memo
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
subtransaction
.payee_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
subtransaction
.category_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
subtransaction
.transfer_account_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
]
.join("\t")
.as_bytes(),
)
.unwrap();
file.write_all(b"\n").unwrap();
}
file.sync_all().unwrap();
let mut file = std::fs::File::create("months.tsv").unwrap();
let mut file2 = std::fs::File::create("categories_by_month.tsv").unwrap();
for month in budget.months.unwrap() {
if month.deleted {
continue;
}
file.write_all([month.month.as_ref()].join("\t").as_bytes())
.unwrap();
file.write_all(b"\n").unwrap();
for category in month.categories {
if category.deleted {
continue;
}
file2
.write_all(
[
month.month.as_ref(),
category.id.as_ref(),
category.category_group_id.as_ref(),
category.name.as_ref(),
if category.hidden { "1" } else { "0" },
&format!("{}", category.budgeted),
&format!("{}", category.activity),
&format!("{}", category.balance),
]
.join("\t")
.as_bytes(),
)
.unwrap();
file2.write_all(b"\n").unwrap();
}
}
file.sync_all().unwrap();
file2.sync_all().unwrap();
let mut file =
std::fs::File::create("scheduled_transactions.tsv").unwrap();
for scheduled_transaction in budget.scheduled_transactions.unwrap() {
if scheduled_transaction.deleted {
continue;
}
let parts: &[&str] = &[
scheduled_transaction.id.as_ref(),
scheduled_transaction.date_next.as_ref(),
frequency_to_str(scheduled_transaction.frequency),
&format!("{}", scheduled_transaction.amount),
scheduled_transaction
.memo
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
scheduled_transaction
.flag_color
.map(st_flag_color_to_str)
.unwrap_or("\\N"),
scheduled_transaction.account_id.as_ref(),
scheduled_transaction
.payee_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
// the split category doesn't appear to be in the categories
// data, so we have to exclude it or else the NOT NULL
// constraint will fail
if scheduled_transaction
.category_id
.as_ref()
.map(|s| s.as_str())
== Some(SPLIT_CATEGORY_ID)
{
"\\N"
} else {
scheduled_transaction
.category_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N")
},
scheduled_transaction
.transfer_account_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
];
file.write_all(parts.join("\t").as_bytes()).unwrap();
file.write_all(b"\n").unwrap();
}
file.sync_all().unwrap();
let mut file =
std::fs::File::create("scheduled_subtransactions.tsv").unwrap();
for scheduled_subtransaction in budget.scheduled_subtransactions.unwrap()
{
if scheduled_subtransaction.deleted {
continue;
}
file.write_all(
[
scheduled_subtransaction.id.as_ref(),
scheduled_subtransaction.scheduled_transaction_id.as_ref(),
format!("{}", scheduled_subtransaction.amount).as_ref(),
scheduled_subtransaction
.memo
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
scheduled_subtransaction
.payee_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
scheduled_subtransaction
.category_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
scheduled_subtransaction
.transfer_account_id
.as_ref()
.map(|s| s.as_str())
.unwrap_or("\\N"),
]
.join("\t")
.as_bytes(),
)
.unwrap();
file.write_all(b"\n").unwrap();
}
file.sync_all().unwrap();
}
fn cleared_to_str(
cleared: ynab_api::models::transaction_summary::Cleared,
) -> &'static str {
use ynab_api::models::transaction_summary::Cleared::*;
match cleared {
Cleared => "cleared",
Uncleared => "uncleared",
Reconciled => "reconciled",
}
}
fn t_flag_color_to_str(
flag_color: ynab_api::models::transaction_summary::FlagColor,
) -> &'static str {
use ynab_api::models::transaction_summary::FlagColor::*;
match flag_color {
Red => "red",
Orange => "orange",
Yellow => "yellow",
Green => "green",
Blue => "blue",
Purple => "purple",
}
}
fn st_flag_color_to_str(
flag_color: ynab_api::models::scheduled_transaction_summary::FlagColor,
) -> &'static str {
use ynab_api::models::scheduled_transaction_summary::FlagColor::*;
match flag_color {
Red => "red",
Orange => "orange",
Yellow => "yellow",
Green => "green",
Blue => "blue",
Purple => "purple",
}
}
fn frequency_to_str(
frequency: ynab_api::models::scheduled_transaction_summary::Frequency,
) -> &'static str {
use ynab_api::models::scheduled_transaction_summary::Frequency::*;
match frequency {
Never => "never",
Daily => "daily",
Weekly => "weekly",
EveryOtherWeek => "everyOtherWeek",
TwiceAMonth => "twiceAMonth",
Every4Weeks => "every4Weeks",
Monthly => "monthly",
EveryOtherMonth => "everyOtherMonth",
Every3Months => "every3Months",
Every4Months => "every4Months",
TwiceAYear => "twiceAYear",
Yearly => "yearly",
EveryOtherYear => "everyOtherYear",
}
}
|
// A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
//
// Find the largest palindrome made from the product of two 3-digit numbers.
fn main() {
let mut max = 0;
for i in 100..1000 {
for j in 100..1000 {
let curr_val = i * j;
if is_palindrome(curr_val.to_string()) {
if curr_val > max {
max = curr_val;
}
}
}
}
println!("Max: {}", max);
}
fn is_palindrome(val: String) -> (bool) {
let chars: Vec<char> = val.chars().collect();
let rev_chars: Vec<char> = val.chars().rev().collect();
return chars.eq(&rev_chars);
}
|
use std::io;
use dns_resolver::Resolver;
use slings::runtime::Runtime;
#[cfg(feature = "slings-runtime")]
fn main() -> io::Result<()> {
let runtime = Runtime::new()?;
let resolver = Resolver::new();
runtime.block_on(async {
let ips = resolver.lookup_host("baidu.com").await?;
println!("ips: {:?}", ips);
Ok(())
})
}
#[cfg(not(feature = "slings-runtime"))]
fn main() {
println!("slings-runtime feature must be enabled")
}
|
use crate::dns::answer::Answer;
use crate::dns::header::Header;
use crate::dns::question::Question;
pub struct Message {
pub header: Header,
pub questions: Vec<Question>,
pub answers: Vec<Answer>,
}
impl Message {
pub fn unpack(buffer: &[u8]) -> Message {
let offset: usize = 0;
let (header, mut offset) = Header::unpack(buffer, offset);
let mut questions = Vec::with_capacity(header.question_count as usize);
for _ in 0..header.question_count {
match Question::unpack(buffer, offset) {
(question, updated_offset) => {
questions.push(question);
offset = updated_offset;
}
}
}
Message {
header,
questions,
answers: Vec::new(), // TODO parse answers
}
}
pub fn pack(&self, buffer: &mut [u8]) -> usize {
let mut offset: usize = 0;
offset = self.header.pack(buffer, offset);
for question in self.questions.iter() {
offset = question.pack(buffer, offset);
}
for answer in self.answers.iter() {
offset = answer.pack(buffer, offset);
}
offset
}
}
|
// Copyright (c) 2020 kprotty
//
// 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 core::{
slice::from_raw_parts,
str::from_utf8_unchecked,
sync::atomic::{AtomicUsize, Ordering},
};
#[inline]
pub fn spin_loop_hint() {
core::sync::atomic::spin_loop_hint()
}
#[inline]
pub fn is_intel() -> bool {
IsIntel::get()
}
const IS_UNINIT: usize = 0;
const IS_INTEL: usize = 1;
const IS_NOT_INTEL: usize = 2;
static STATE: AtomicUsize = AtomicUsize::new(IS_UNINIT);
struct IsIntel {}
impl IsIntel {
#[inline]
fn get() -> bool {
let state = match STATE.load(Ordering::Relaxed) {
IS_UNINIT => Self::get_slow(),
state => state,
};
state == IS_INTEL
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
#[cold]
fn get_slow() -> usize {
let state = IS_NOT_INTEL;
STATE.store(state, Ordering::Relaxed);
state
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[cold]
fn get_slow() -> usize {
#[cfg(target_arch = "x86")]
use core::arch::x86::{CpuidResult, __cpuid};
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::{CpuidResult, __cpuid};
let state = match unsafe {
let CpuidResult { ebx, ecx, edx, .. } = __cpuid(0);
let vendor = &[ebx, edx, ecx] as *const _ as *const u8;
let vendor = from_utf8_unchecked(from_raw_parts(vendor, 3 * 4));
vendor == "GenuineIntel"
} {
true => IS_INTEL,
_ => IS_NOT_INTEL,
};
STATE.store(state, Ordering::Relaxed);
state
}
}
|
use std::fs::read_to_string;
fn main() {
let input = read_to_string("d10-input").expect("something went wrong reading file");
let mut data: Vec<i32> = input.lines().map(|n| n.parse().unwrap()).collect();
data.sort_unstable();
let (ones, twos, threes) = data
.windows(2)
.fold((1, 0, 1), |(ones, twos, threes), n| match n[1] - n[0] {
1 => (ones + 1, twos, threes),
2 => (ones, twos + 1, threes),
3 => (ones, twos, threes + 1),
_ => unreachable!(),
});
println!("Number of 1s {}, 2s {}, 3s {}", ones, twos, threes);
println!("Answer to part 1: {} x {} = {}", ones, threes, ones * threes);
} |
/// An enum to represent all characters in the Kanbun block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Kanbun {
/// \u{3190}: '㆐'
IdeographicAnnotationLinkingMark,
/// \u{3191}: '㆑'
IdeographicAnnotationReverseMark,
/// \u{3192}: '㆒'
IdeographicAnnotationOneMark,
/// \u{3193}: '㆓'
IdeographicAnnotationTwoMark,
/// \u{3194}: '㆔'
IdeographicAnnotationThreeMark,
/// \u{3195}: '㆕'
IdeographicAnnotationFourMark,
/// \u{3196}: '㆖'
IdeographicAnnotationTopMark,
/// \u{3197}: '㆗'
IdeographicAnnotationMiddleMark,
/// \u{3198}: '㆘'
IdeographicAnnotationBottomMark,
/// \u{3199}: '㆙'
IdeographicAnnotationFirstMark,
/// \u{319a}: '㆚'
IdeographicAnnotationSecondMark,
/// \u{319b}: '㆛'
IdeographicAnnotationThirdMark,
/// \u{319c}: '㆜'
IdeographicAnnotationFourthMark,
/// \u{319d}: '㆝'
IdeographicAnnotationHeavenMark,
/// \u{319e}: '㆞'
IdeographicAnnotationEarthMark,
}
impl Into<char> for Kanbun {
fn into(self) -> char {
match self {
Kanbun::IdeographicAnnotationLinkingMark => '㆐',
Kanbun::IdeographicAnnotationReverseMark => '㆑',
Kanbun::IdeographicAnnotationOneMark => '㆒',
Kanbun::IdeographicAnnotationTwoMark => '㆓',
Kanbun::IdeographicAnnotationThreeMark => '㆔',
Kanbun::IdeographicAnnotationFourMark => '㆕',
Kanbun::IdeographicAnnotationTopMark => '㆖',
Kanbun::IdeographicAnnotationMiddleMark => '㆗',
Kanbun::IdeographicAnnotationBottomMark => '㆘',
Kanbun::IdeographicAnnotationFirstMark => '㆙',
Kanbun::IdeographicAnnotationSecondMark => '㆚',
Kanbun::IdeographicAnnotationThirdMark => '㆛',
Kanbun::IdeographicAnnotationFourthMark => '㆜',
Kanbun::IdeographicAnnotationHeavenMark => '㆝',
Kanbun::IdeographicAnnotationEarthMark => '㆞',
}
}
}
impl std::convert::TryFrom<char> for Kanbun {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'㆐' => Ok(Kanbun::IdeographicAnnotationLinkingMark),
'㆑' => Ok(Kanbun::IdeographicAnnotationReverseMark),
'㆒' => Ok(Kanbun::IdeographicAnnotationOneMark),
'㆓' => Ok(Kanbun::IdeographicAnnotationTwoMark),
'㆔' => Ok(Kanbun::IdeographicAnnotationThreeMark),
'㆕' => Ok(Kanbun::IdeographicAnnotationFourMark),
'㆖' => Ok(Kanbun::IdeographicAnnotationTopMark),
'㆗' => Ok(Kanbun::IdeographicAnnotationMiddleMark),
'㆘' => Ok(Kanbun::IdeographicAnnotationBottomMark),
'㆙' => Ok(Kanbun::IdeographicAnnotationFirstMark),
'㆚' => Ok(Kanbun::IdeographicAnnotationSecondMark),
'㆛' => Ok(Kanbun::IdeographicAnnotationThirdMark),
'㆜' => Ok(Kanbun::IdeographicAnnotationFourthMark),
'㆝' => Ok(Kanbun::IdeographicAnnotationHeavenMark),
'㆞' => Ok(Kanbun::IdeographicAnnotationEarthMark),
_ => Err(()),
}
}
}
impl Into<u32> for Kanbun {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for Kanbun {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for Kanbun {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl Kanbun {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
Kanbun::IdeographicAnnotationLinkingMark
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("Kanbun{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use universe::Universe;
pub fn check_area(ch_area: (i32, i32), universe: &mut Universe){
let (area_old, area) = match universe.player{
Some(ref mut x) => {
let old = x.area;
x.area.0 += ch_area.0;
x.area.1 += ch_area.1;
let new = x.area;
(old, new)
}
None => {
((0, 0), (0, 0))
}
};
for obj in universe.get_go_by_area(area_old){
match obj.render_object{
Some(ref mut x) => {
if obj.tags.contains(&"Planet".to_string()) || obj.tags.contains(&"Rings".to_string()){
x.enabled = false;
}
}
None => {}
}
}
println!("{:?}", area);
for obj in universe.get_go_by_area(area){
match obj.render_object{
Some(ref mut x) => {
if obj.tags.contains(&"Planet".to_string()) || obj.tags.contains(&"Rings".to_string()){
x.enabled = true;
}
}
None => {}
}
}
}
|
#[macro_export]
macro_rules! image_assets {
($($texcoords_name:ident $name:ident: $sprite_type:ident [$texcoords:expr][$w:expr;$h:expr] $path:expr),+) => {
pub struct Images {
$(
pub $name: ImageAsset,
pub $texcoords_name: [Texcoords; $texcoords]
// concat_idents!($name, _texcoords): [Texcoords, $num_texcoords]
),*
}
impl Images {
pub fn init(&mut self, gl_data: *const GLData) {
$(
self.$name = ImageAsset {
gl_data: gl_data,
filename: $path,
vbo: 0,
set_attributes: $sprite_type::set,
shader: $sprite_type::shader,
attributes_size: size_of::<$sprite_type>(),
texture: unsafe { zeroed() },
frame_width: $w,
frame_height: $h,
texcoord_count: $texcoords
};
)*
}
}
}
}
macro_rules! vertex_attrib_pointer {
(float, $loc:expr, $size:expr, $offset:expr) => {
gl::VertexAttribPointer(
$loc, 1, gl::FLOAT, gl::FALSE as GLboolean,
$size, transmute($offset)
);
};
(vec2, $loc:expr, $size:expr, $offset:expr) => {
gl::VertexAttribPointer(
$loc, 2, gl::FLOAT, gl::FALSE as GLboolean,
$size, transmute($offset)
);
};
(ivec2, $loc:expr, $size:expr, $offset:expr) => {
gl::VertexAttribIPointer(
$loc, 2, gl::INT,
$size, transmute($offset)
);
};
($int_type:ident, $loc:expr, $size:expr, $offset:expr) => {
gl::VertexAttribIPointer(
$loc, 1, gl::INT,
$size, transmute($offset)
);
};
}
#[macro_export]
macro_rules! shader_assets {
(
$(
$sprite_type:ident:
[vertex]
$(layout (location = $loc:expr) in $glsltype:ident($attrtype:ty) $name:ident;)*
($vertmain:expr)
[fragment]
($fragmain:expr)
)+
) => {
pub struct Shader {
pub program: GLuint,
pub cam_pos_uniform: GLint,
pub scale_uniform: GLint,
pub sprite_size_uniform: GLint,
pub screen_size_uniform: GLint,
pub tex_uniform: GLint,
pub frames_uniform: GLint,
}
#[allow(non_snake_case)]
pub struct Shaders {
$( pub $sprite_type: Shader ),*
}
impl Shaders {
pub fn count() -> usize {
let mut c = 0;
$(
$fragmain; // compiler complains if we don't reference stuff in loop.
c += 1;
)*
c
}
pub fn compile(gl_data: &mut GLData, window: &glfw::Window) -> Vec<&'static str> {
let mut failed = Vec::<&'static str>::with_capacity(Shaders::count());
let cam_pos_str = CString::new("cam_pos".to_string()).unwrap();
let scale_str = CString::new("scale".to_string()).unwrap();
let sprite_size_str = CString::new("sprite_size".to_string()).unwrap();
let screen_size_str = CString::new("screen_size".to_string()).unwrap();
let tex_str = CString::new("tex".to_string()).unwrap();
let frames_str = CString::new("frames".to_string()).unwrap();
$(unsafe {
println!("About to compile {}", stringify!($sprite_type));
let ref mut shader = gl_data.shaders.$sprite_type;
let existing_program =
if gl::IsProgram(shader.program) == gl::TRUE {
Some(shader.program)
} else { None };
shader.program = match render::create_program($sprite_type::vertex_shader(), $sprite_type::fragment_shader()) {
Some(program) => {
gl::UseProgram(program);
shader.cam_pos_uniform = gl::GetUniformLocation(program, cam_pos_str.as_ptr());
shader.scale_uniform = gl::GetUniformLocation(program, scale_str.as_ptr());
shader.sprite_size_uniform = gl::GetUniformLocation(program, sprite_size_str.as_ptr());
shader.screen_size_uniform = gl::GetUniformLocation(program, screen_size_str.as_ptr());
shader.tex_uniform = gl::GetUniformLocation(program, tex_str.as_ptr());
shader.frames_uniform = gl::GetUniformLocation(program, frames_str.as_ptr());
// TODO this should maybe be handled elsewhere
gl::Uniform1f(shader.scale_uniform, 2.0);
match window.get_size() {
(width, height) => gl::Uniform2f(shader.screen_size_uniform, width as f32, height as f32)
}
match existing_program {
Some(existing) => gl::DeleteProgram(existing),
_ => {}
}
program
}
None => {
failed.push(stringify!($sprite_type));
shader.program
}
}
})*
failed
}
pub fn each_shader<F>(&mut self, mut f: F) where F: FnMut(&mut Shader, &'static str) {
$( f(&mut self.$sprite_type, stringify!($sprite_type)); )*
}
}
$(
#[derive(Clone)]
pub struct $sprite_type {
$( pub $name: $attrtype ),*
}
impl Copy for $sprite_type { }
impl $sprite_type {
#[allow(unused_assignments)] // Compiler is wrong about offset not being used...
pub fn set(vbo: GLuint) { unsafe {
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
let size_of_sprite = size_of::<$sprite_type>() as GLint;
let mut offset: i64 = 0;
$(
gl::EnableVertexAttribArray($loc);
vertex_attrib_pointer!(
$glsltype, $loc,
size_of_sprite, offset
);
gl::VertexAttribDivisor($loc, 1);
offset += size_of::<$attrtype>() as i64;
)*
gl::BindBuffer(gl::ARRAY_BUFFER, 0);
}}
pub fn shader<'a>(gl_data: &'a GLData) -> &'a Shader {
&gl_data.shaders.$sprite_type
}
pub fn vertex_shader() -> String {
let mut vertex = String::with_capacity(4092);
vertex.push_str("
#version 300 es
precision mediump float;
// Per vertex, normalized:
layout (location = 0) in vec2 vertex_pos;
// Per instance:
");
$({
if $loc == 0 {
panic!("Shader location 0 is reserved for vertex position")
}
vertex.push_str(&format!("layout (location = {}) in {} {};\n",
$loc, stringify!($glsltype), stringify!($name)
));
});*
vertex.push_str("
// NOTE up this if you run into problems
uniform vec2[256] frames;
uniform vec2 screen_size;
uniform vec2 cam_pos; // in pixels
uniform vec2 sprite_size; // in pixels
uniform float scale;
out vec2 texcoord;
const vec2 TEXCOORD_FROM_ID[4] = vec2[4](
vec2(1.0, 1.0), vec2(1.0, 0.0),
vec2(0.0, 0.0), vec2(0.0, 1.0)
);
vec2 from_pixel(vec2 pos)
{
return pos / screen_size;
}
ivec2 from_pixel(ivec2 pos)
{
return pos / ivec2(screen_size);
}
int flipped_vertex_id()
{
return 3 - gl_VertexID;
}
// These are I suppose an optimization for squares
// rotating about their centers.
const float VERT_DIST = 1.41421356237;
const float ANGLE_OFFSETS[4] = float[4](
// pi/4
0.78539816339,
// 7pi/4
5.49778714378,
// 5pi/4
3.92699081699,
// 3pi/4
2.35619449019
);
vec4 color_from(int color)
{
// Totally assumes little endian...
int red = int((uint(color) & 0xFF000000u) >> 24u);
return vec4(
float(red) / 256.0,
float((color & 0x00FF0000) >> 16) / 256.0,
float((color & 0x0000FF00) >> 8) / 256.0,
float( color & 0x000000FF) / 256.0
);
}
");
vertex.push_str($vertmain);
// println!("VERTEX:\n{}", vertex);
vertex
}
pub fn fragment_shader() -> String {
let mut fragment = String::with_capacity(1028);
fragment.push_str("
#version 300 es
precision mediump float;
in vec2 texcoord;
out vec4 color;
uniform sampler2D tex;
bool approx(vec4 a, vec4 b, float alpha)
{
vec4 diff = abs(a - b);
return diff.x <= alpha &&
diff.y <= alpha &&
diff.z <= alpha &&
diff.w <= alpha;
}
");
fragment.push_str($fragmain);
// println!("FRAGMENT:\n{}", fragment);
fragment
}
}
)*
}
}
|
use crate::translations::translations::{
bytes_report_translation, packets_report_translation, recent_report_translation,
};
use crate::Language;
/// Enum representing the possible kinds of displayed relevant connections.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(clippy::enum_variant_names)]
pub enum ReportSortType {
MostRecent,
MostBytes,
MostPackets,
}
impl ReportSortType {
pub fn all_strings(language: Language) -> Vec<&'static str> {
vec![
recent_report_translation(language),
bytes_report_translation(language),
packets_report_translation(language),
]
}
pub fn get_picklist_label(self, language: Language) -> &'static str {
match self {
ReportSortType::MostRecent => recent_report_translation(language),
ReportSortType::MostBytes => bytes_report_translation(language),
ReportSortType::MostPackets => packets_report_translation(language),
}
}
}
|
//! Type definitions for `<metal_geometric>`.
//!
//! All methods are already declared in `vek` for any `Vec`:
//! - `cross`
//! - `distance`
//! - `distance_squared`
//! - `dot`
//! - `face_forward` (`faceforward`)
//! - `magnitude` (`length`)
//! - `magnitude_squared` (`length_squared`)
//! - `normalize`
//! - `reflect`
//! - `refract`
|
use std::ops::Deref;
use std::ptr;
use winapi::um::{d3d11, d3dcommon};
use wio::com::ComPtr;
pub type DeviceRaw = ComPtr<d3d11::ID3D11Device>;
pub struct Device(DeviceRaw);
pub type DeviceContextRaw = ComPtr<d3d11::ID3D11DeviceContext>;
pub struct DeviceContext(DeviceContextRaw);
impl Device {
pub fn new() -> (Device, DeviceContext) {
let mut feature_level = d3dcommon::D3D_FEATURE_LEVEL_11_0;
unsafe {
let mut device = ptr::null_mut();
let mut device_context = ptr::null_mut();
let _hr = d3d11::D3D11CreateDevice(
ptr::null_mut(), // default adapter
d3dcommon::D3D_DRIVER_TYPE_HARDWARE,
ptr::null_mut(),
d3d11::D3D11_CREATE_DEVICE_BGRA_SUPPORT, // required
ptr::null(),
0,
d3d11::D3D11_SDK_VERSION,
&mut device as *mut _,
&mut feature_level,
&mut device_context as *mut _,
);
(
Device(DeviceRaw::from_raw(device)),
DeviceContext(DeviceContextRaw::from_raw(device_context)),
)
}
}
}
impl Deref for Device {
type Target = DeviceRaw;
fn deref(&self) -> &Self::Target {
&self.0
}
}
|
use std::io::Cursor;
use crate::{Field, ParseError, ReadExt, WriteExt};
pub fn encode_inputdata(data: &[u8], w: &mut Vec<u8>) {
let length = data.len();
assert!(length <= std::u8::MAX as usize);
w.write_byte(length as u8);
w.write_bytes(data);
}
pub fn decode_inputdata<'a>(cursor: &mut Cursor<&[u8]>) -> Result<Vec<u8>, ParseError> {
match cursor.read_byte() {
Err(..) => Err(ParseError::NotEnoughBytes(Field::InputDataLength)),
Ok(byte) => {
let length = byte as usize;
cursor
.read_bytes(length)
.map_err(|_| ParseError::NotEnoughBytes(Field::InputData))
}
}
}
|
use client::*;
use result::BestbuyResult;
mod types;
pub use self::types::*;
#[derive(Serialize)]
pub enum OfferSort {
#[serde(rename = "totalPrice")]
TotalPrice,
#[serde(rename = "price")]
Price,
#[serde(rename = "productTitle")]
ProductTitle,
}
use types::{Pagination, Sort};
pub type ListOffersSort = Sort<OfferSort>;
#[derive(Default, Serialize, Clone)]
pub struct ListOffersParams {
pub offer_state_codes: Option<Vec<String>>,
pub sku: Option<String>,
pub product_id: Option<String>,
pub favorite: bool,
}
#[derive(Serialize, Deserialize)]
pub struct ListOffersResponse {
pub offers: Vec<Offer>,
pub total_count: i32,
}
pub trait OfferApi {
fn list_offers(
&self,
params: &ListOffersParams,
sort: Option<ListOffersSort>,
page: Option<Pagination>,
) -> BestbuyResult<ListOffersResponse>;
}
impl OfferApi for BestbuyClient {
fn list_offers(
&self,
params: &ListOffersParams,
sort: Option<ListOffersSort>,
page: Option<Pagination>,
) -> BestbuyResult<ListOffersResponse> {
let mut req = self.request(Method::Get, "/api/offers");
req.query(¶ms);
if let Some(sort) = sort {
req.query(&sort);
}
if let Some(page) = page {
req.query(&page);
}
req.send()?.get_response()
}
}
|
use super::cgmath;
use super::cgmath::perspective;
use super::cgmath::SquareMatrix;
use super::cgmath::Matrix4;
pub struct Camera {
pub view_from_world: cgmath::Matrix4<f32>,
pub proj_from_view: cgmath::Matrix4<f32>,
pub position: cgmath::Point3<f32>,
pub angle_yaw: f32,
pub angle_pitch: f32
}
impl Camera {
pub fn new() -> Camera {
let mut cam = Camera {
view_from_world: Matrix4::<f32>::identity(),
proj_from_view: Matrix4::<f32>::identity(),
position: cgmath::Point3::<f32>::new(0.0, 300.0, -1500.0),
angle_yaw: 0.0,
angle_pitch: 0.0
};
cam.update_matrices();
cam
}
pub fn update_matrices(&mut self) {
self.view_from_world = super::cgmath::Matrix4::look_at(self.position,
cgmath::Point3::<f32>::new(0.0, 0.0, 0.0),
cgmath::Vector3::<f32>::new(0.0, 1.0, 0.0));
let rot = super::cgmath::Matrix4::from_angle_x(super::cgmath::Deg::<f32>(self.angle_pitch));
self.view_from_world = self.view_from_world * rot;
let rot = super::cgmath::Matrix4::from_angle_y(super::cgmath::Deg::<f32>(self.angle_yaw));
self.view_from_world = self.view_from_world * rot;
self.proj_from_view = perspective(cgmath::Rad(0.785398), 4.0 / 3.0, 0.5, 10000.0);
}
} |
use std::time::SystemTime;
fn main() {
let time_now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
println!("Finally the time stamp::{:?} ",time_now);
} |
//! All the traits exposed to be used in other custom pallets
use crate::utils::keys::{Commitment, ScalarData};
use bulletproofs::PedersenGens;
pub use frame_support::dispatch;
use sp_std::vec::Vec;
/// Tree trait definition to be used in other pallets
pub trait Tree<AccountId, BlockNumber, TreeId> {
/// Check if nullifier is already used, in which case return an error
fn has_used_nullifier(id: TreeId, nullifier: ScalarData) -> Result<(), dispatch::DispatchError>;
/// Sets stopped flag in storage. This flag doesn't do much by itself, it is
/// up to higher-level pallet to find the use for it
/// Can only be called by the manager, regardless if the manager is required
fn set_stopped(sender: AccountId, tree_id: TreeId, stopped: bool) -> Result<(), dispatch::DispatchError>;
/// Sets whether the manager is required for guarded calls.
/// Can only be called by the current manager
fn set_manager_required(
sender: AccountId,
id: TreeId,
is_manager_required: bool,
) -> Result<(), dispatch::DispatchError>;
/// Sets manager account id
/// Can only be called by the current manager
fn set_manager(sender: AccountId, id: TreeId, new_manager: AccountId) -> Result<(), dispatch::DispatchError>;
/// Creates a new Tree tree, including a manager for that tree
fn create_tree(sender: AccountId, is_manager_required: bool, depth: u8) -> Result<TreeId, dispatch::DispatchError>;
/// Adds members/leaves to the tree
fn add_members(sender: AccountId, id: TreeId, members: Vec<ScalarData>) -> Result<(), dispatch::DispatchError>;
/// Adds a nullifier to the storage
/// Can only be called by the manager if the manager is required
fn add_nullifier(sender: AccountId, id: TreeId, nullifier: ScalarData) -> Result<(), dispatch::DispatchError>;
/// Verify membership proof
fn verify(id: TreeId, leaf: ScalarData, path: Vec<(bool, ScalarData)>) -> Result<(), dispatch::DispatchError>;
/// Verify zero-knowladge membership proof
fn verify_zk_membership_proof(
tree_id: TreeId,
cached_block: BlockNumber,
cached_root: ScalarData,
comms: Vec<Commitment>,
nullifier_hash: ScalarData,
proof_bytes: Vec<u8>,
leaf_index_commitments: Vec<Commitment>,
proof_commitments: Vec<Commitment>,
recipient: ScalarData,
relayer: ScalarData,
) -> Result<(), dispatch::DispatchError>;
fn verify_zk(
pc_gens: PedersenGens,
m_root: ScalarData,
depth: u8,
comms: Vec<Commitment>,
nullifier_hash: ScalarData,
proof_bytes: Vec<u8>,
leaf_index_commitments: Vec<Commitment>,
proof_commitments: Vec<Commitment>,
recipient: ScalarData,
relayer: ScalarData,
) -> Result<(), dispatch::DispatchError>;
}
|
pub mod font;
mod inline;
pub mod text;
use crate::cssom::{Unit, Value};
use crate::dom::NodeType;
use crate::style::*;
use font::{with_thread_local_font_context, FontContext};
use inline::InlineBox;
use std::cell::RefCell;
use std::mem;
use std::rc::Rc;
use text::{LineBreakLeafIter, TextNode, TextRun};
// CSS box model. All sizes are in px.
#[derive(Default, Debug, Clone)]
pub struct Dimensions {
pub content: Rect,
pub padding: EdgeSizes,
pub border: EdgeSizes,
pub margin: EdgeSizes,
}
impl Dimensions {
pub fn padding_box(&self) -> Rect {
self.content.expanded_by(&self.padding)
}
pub fn border_box(&self) -> Rect {
self.padding_box().expanded_by(&self.border)
}
pub fn margin_box(&self) -> Rect {
self.border_box().expanded_by(&self.margin)
}
pub fn padding_horizontal_box(&self) -> Rect {
self.content.expanded_horizontal_by(&self.padding)
}
pub fn border_horizontal_box(&self) -> Rect {
self.padding_horizontal_box()
.expanded_horizontal_by(&self.border)
}
pub fn margin_horizontal_box(&self) -> Rect {
self.border_horizontal_box()
.expanded_horizontal_by(&self.margin)
}
pub fn padding_top_offset(&self) -> f32 {
self.padding.top
}
pub fn border_top_offset(&self) -> f32 {
self.padding_top_offset() + self.border.top
}
pub fn padding_left_offset(&self) -> f32 {
self.padding.left
}
pub fn border_left_offset(&self) -> f32 {
self.padding_left_offset() + self.border.left
}
pub fn margin_left_offset(&self) -> f32 {
self.border_left_offset() + self.margin.left
}
pub fn padding_right_offset(&self) -> f32 {
self.padding.right
}
pub fn border_right_offset(&self) -> f32 {
self.padding_right_offset() + self.border.right
}
pub fn margin_right_offset(&self) -> f32 {
self.border_right_offset() + self.margin.right
}
pub fn reset_edge_top(&mut self) {
self.padding.top = 0.;
self.border.top = 0.;
self.margin.top = 0.;
}
pub fn reset_edge_bottom(&mut self) {
self.padding.bottom = 0.;
self.border.bottom = 0.;
self.margin.bottom = 0.;
}
pub fn reset_edge_left(&mut self) {
self.padding.left = 0.;
self.border.left = 0.;
self.margin.left = 0.;
}
pub fn reset_edge_right(&mut self) {
self.padding.right = 0.;
self.border.right = 0.;
self.margin.right = 0.;
}
}
#[derive(Default, Debug, Clone)]
pub struct Rect {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
impl Rect {
fn expanded_by(&self, edge: &EdgeSizes) -> Rect {
Rect {
x: self.x - edge.left,
y: self.y - edge.top,
width: self.width + edge.left + edge.right,
height: self.height + edge.top + edge.bottom,
}
}
fn expanded_horizontal_by(&self, edge: &EdgeSizes) -> Rect {
Rect {
x: self.x - edge.left,
y: self.y,
width: self.width + edge.left + edge.right,
height: self.height,
}
}
}
#[derive(Default, Debug, Clone)]
pub struct EdgeSizes {
pub left: f32,
pub right: f32,
pub top: f32,
pub bottom: f32,
}
#[derive(Debug)]
pub struct LayoutBox<'a> {
pub dimensions: Rc<RefCell<Dimensions>>,
pub box_type: BoxType<'a>,
pub children: Vec<LayoutBox<'a>>,
/// used for line breaking
pub is_splitted: bool,
pub is_hidden: bool,
}
impl<'a> Clone for LayoutBox<'a> {
fn clone(&self) -> LayoutBox<'a> {
let mut layout_box = LayoutBox::new(self.box_type.clone());
let d = self.dimensions.borrow();
layout_box.dimensions = Rc::new(RefCell::new(d.clone()));
layout_box.children = self.children.clone();
layout_box
}
}
impl<'a> LayoutBox<'a> {
pub fn new(box_type: BoxType<'a>) -> LayoutBox<'a> {
LayoutBox {
box_type,
dimensions: Rc::new(RefCell::new(Default::default())),
children: vec![],
is_splitted: false,
is_hidden: false,
}
}
fn get_style_node(&self) -> &'a StyledNode<'a> {
match &self.box_type {
BoxType::BlockNode(node) | BoxType::InlineNode(node) => node,
BoxType::TextNode(node) => node.styled_node,
BoxType::AnonymousBlock => panic!("Anonymous block box has no style node"),
}
}
pub fn layout(&mut self, containing_block: Rc<RefCell<Dimensions>>) {
match self.box_type {
BoxType::BlockNode(_) => self.layout_block(containing_block),
BoxType::AnonymousBlock => {
let containing_block = containing_block.borrow();
{
let mut d = self.dimensions.borrow_mut();
d.content.x = containing_block.content.x;
d.content.y = containing_block.content.y;
}
// Anonymous block is including only inline box in children
let mut inline_box = InlineBox::new(
containing_block.clone(),
mem::replace(&mut self.children, Vec::new()),
);
inline_box.process();
let mut d = self.dimensions.borrow_mut();
d.content.width = inline_box.width;
d.content.height = inline_box.height;
self.children = inline_box.boxes;
}
// All inline node and text node are contained in anonymous box.
BoxType::InlineNode(_) | BoxType::TextNode(_) => unreachable!(),
}
}
fn layout_block(&mut self, containing_block: Rc<RefCell<Dimensions>>) {
// Child width depends on parent width,
// so parent width need to be calculated before child width.
self.calculate_block_width(containing_block.clone());
self.calculate_block_position(containing_block);
self.layout_block_children();
// Parent height is affected by child layout,
// so parent height need to be calculated after children are laid out.
self.calculate_block_height();
}
fn calculate_block_width(&mut self, containing_block: Rc<RefCell<Dimensions>>) {
let style = self.get_style_node();
// `width` has initial value `auto`.
let auto = Value::Keyword("auto".into());
let mut width = style.value("width").unwrap_or_else(|| auto.clone());
// `margin`, `border`, `padding` has initial value `0`.
let zero = Value::Length(0.0, Unit::Px);
let mut margin_left = style.lookup("margin-left", "margin", &zero);
let mut margin_right = style.lookup("margin-right", "margin", &zero);
let border_left = style.lookup("border-left-width", "border", &zero);
let border_right = style.lookup("border-right-width", "border", &zero);
let padding_left = style.lookup("padding-left", "padding", &zero);
let padding_right = style.lookup("padding-right", "padding", &zero);
let total: f32 = [
margin_left.to_px(),
margin_right.to_px(),
border_left.to_px(),
border_right.to_px(),
padding_left.to_px(),
padding_right.to_px(),
width.to_px(),
]
.iter()
.sum();
let containing_block = containing_block.borrow();
if width != auto && total > containing_block.content.width {
if margin_left == auto {
margin_left = Value::Length(0.0, Unit::Px);
}
if margin_right == auto {
margin_right = Value::Length(0.0, Unit::Px);
}
}
let underflow = containing_block.content.width - total;
match (width == auto, margin_left == auto, margin_right == auto) {
(false, false, false) => {
margin_right = Value::Length(margin_right.to_px() + underflow, Unit::Px);
}
(false, false, true) => {
margin_right = Value::Length(underflow, Unit::Px);
}
(false, true, false) => {
margin_left = Value::Length(underflow, Unit::Px);
}
(true, _, _) => {
if margin_left == auto {
margin_left = Value::Length(0.0, Unit::Px)
}
if margin_right == auto {
margin_right = Value::Length(0.0, Unit::Px)
}
if underflow > 0.0 {
width = Value::Length(underflow, Unit::Px);
} else {
width = Value::Length(0.0, Unit::Px);
margin_right = Value::Length(margin_right.to_px() + underflow, Unit::Px);
}
}
(false, true, true) => {
margin_left = Value::Length(underflow / 2.0, Unit::Px);
margin_right = Value::Length(underflow / 2.0, Unit::Px);
}
}
let mut d = self.dimensions.borrow_mut();
d.content.width = width.to_px();
d.margin.left = margin_left.to_px();
d.margin.right = margin_right.to_px();
d.padding.left = padding_left.to_px();
d.padding.right = padding_right.to_px();
d.border.left = border_left.to_px();
d.border.right = border_right.to_px();
}
fn calculate_block_position(&mut self, containing_block: Rc<RefCell<Dimensions>>) {
let containing_block = containing_block.borrow();
self.assign_vertical_margin_box();
let mut d = self.dimensions.borrow_mut();
d.content.x = containing_block.content.x + d.margin.left + d.border.left + d.padding.left;
d.content.y = containing_block.content.height
+ containing_block.content.y
+ d.margin.top
+ d.border.top
+ d.padding.top;
}
fn layout_block_children(&mut self) {
let parent_dimensions = &self.dimensions;
for child in &mut self.children {
child.layout(parent_dimensions.clone());
let mut d = parent_dimensions.borrow_mut();
let child_d = child.dimensions.borrow();
d.content.height += child_d.margin_box().height;
}
}
fn calculate_block_height(&mut self) {
if let Some(Value::Length(height, Unit::Px)) = self.get_style_node().value("height") {
self.dimensions.borrow_mut().content.height = height;
}
}
/// When a anonymous box has some node, this node will be placed horizontally.
fn get_inline_container(&mut self) -> &mut LayoutBox<'a> {
match self.box_type {
BoxType::TextNode(_) | BoxType::InlineNode(_) | BoxType::AnonymousBlock => self,
BoxType::BlockNode(_) => {
match self.children.last() {
Some(&LayoutBox {
box_type: BoxType::AnonymousBlock,
..
}) => {}
_ => self.children.push(LayoutBox::new(BoxType::AnonymousBlock)),
};
self.children.last_mut().unwrap()
}
}
}
fn assign_vertical_margin_box(&self) {
let node = self.get_style_node();
let mut d = self.dimensions.borrow_mut();
let zero = Value::Length(0.0, Unit::Px);
d.margin.top = node.lookup("margin-top", "margin", &zero).to_px();
d.margin.bottom = node.lookup("margin-bottom", "margin", &zero).to_px();
d.border.top = node.lookup("border-top-width", "border", &zero).to_px();
d.border.bottom = node.lookup("border-bottom-width", "border", &zero).to_px();
d.padding.top = node.lookup("padding-top", "padding", &zero).to_px();
d.padding.bottom = node.lookup("padding-bottom", "padding", &zero).to_px();
}
fn assign_horizontal_margin_box(&self) {
let node = self.get_style_node();
let mut d = self.dimensions.borrow_mut();
let zero = Value::Length(0.0, Unit::Px);
d.margin.left = node.lookup("margin-left", "margin", &zero).to_px();
d.margin.right = node.lookup("margin-right", "margin", &zero).to_px();
d.border.left = node.lookup("border-left-width", "border", &zero).to_px();
d.border.right = node.lookup("border-right-width", "border", &zero).to_px();
d.padding.left = node.lookup("padding-left", "padding", &zero).to_px();
d.padding.right = node.lookup("padding-right", "padding", &zero).to_px();
}
fn reset_all_edge_left(&mut self) -> f32 {
if self.is_splitted {
return 0.;
}
self.is_splitted = true;
let mut d = self.dimensions.borrow_mut();
let left = d.margin_left_offset();
d.content.width -= d.padding.left;
d.reset_edge_left();
let len = self.children.len();
if len != 0 {
let left = self.children[0].reset_all_edge_left();
d.content.width -= left;
}
left
}
fn reset_all_edge_right(&mut self) -> f32 {
let mut d = self.dimensions.borrow_mut();
let right = d.margin_right_offset();
d.content.width -= d.padding.right;
d.reset_edge_right();
let len = self.children.len();
if len != 0 {
let right = self.children[len - 1].reset_all_edge_right();
d.content.width -= right;
}
right
}
}
#[derive(Debug, Clone)]
pub enum BoxType<'a> {
BlockNode(&'a StyledNode<'a>),
InlineNode(&'a StyledNode<'a>),
TextNode(TextNode<'a>),
AnonymousBlock,
}
pub fn layout_tree<'a>(
node: &'a StyledNode<'a>,
containing_block: Rc<RefCell<Dimensions>>,
) -> LayoutBox<'a> {
// The layout algorithm expects the container height to start at 0.
// TODO: Save the initial containing block height, for calculating percent heights.
containing_block.borrow_mut().content.height = 0.0;
let mut root_box = with_thread_local_font_context(|font_context| {
let mut last_whitespace = false;
build_layout_tree(node, None, font_context, &mut last_whitespace, &mut None).unwrap()
});
root_box.layout(containing_block);
root_box
}
pub fn build_layout_tree<'a>(
style_node: &'a StyledNode<'a>,
container: Option<&mut LayoutBox<'a>>,
font_context: &mut FontContext,
last_whitespace: &mut bool,
breaker: &mut Option<LineBreakLeafIter>,
) -> Option<LayoutBox<'a>> {
let mut root = {
let box_type = match style_node.display() {
Display::Block => {
*last_whitespace = false;
// Reset breaker because BlockNode make new line
*breaker = None;
BoxType::BlockNode(style_node)
}
Display::Inline => match &style_node.node.node_type {
NodeType::Element(_) => BoxType::InlineNode(style_node),
NodeType::Text(_) => {
let layout_box = match container {
Some(layout_box) => layout_box,
None => unreachable!(),
};
TextRun::scan_for_runs(
layout_box,
style_node,
font_context,
last_whitespace,
breaker,
);
return None;
}
},
Display::None => panic!("Root node must has `display: none;`."),
};
LayoutBox::new(box_type)
};
{
for child in &style_node.children {
match child.display() {
Display::Block => {
if let Some(layout_box) = build_layout_tree(
child,
Some(&mut root),
font_context,
last_whitespace,
breaker,
) {
root.children.push(layout_box);
}
}
Display::Inline => {
if let Some(layout_box) = build_layout_tree(
child,
Some(&mut root),
font_context,
last_whitespace,
breaker,
) {
root.get_inline_container().children.push(layout_box);
}
}
Display::None => {}
}
}
}
Some(root)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cssom::*;
use crate::parser::css::*;
use crate::parser::html::*;
#[test]
fn test_block() {
let html = "
<body class='bar'>
<div id='foo' class='bar'></div>
<div>test</div>
<div>test</div>
</body>
";
let ua_css = "body, div { display: block; }";
let css = "
.bar {
height: auto;
width: 1000px;
}
div {
width: 100px;
height: 200px;
margin: auto;
}
div#foo.bar {
height: auto;
}
div#foo {
color: red;
}
";
let mut html_parser = HTMLParser::new(html.into());
let mut ua_css_parser = CSSParser::new(ua_css.into());
let mut css_parser = CSSParser::new(css.into());
let dom = html_parser.run();
let ua_rules = ua_css_parser.parse_rules(Origin::UA);
let mut rules = css_parser.parse_rules(Origin::Author);
rules.extend(ua_rules);
let cssom = Stylesheet::new(rules);
let styled_node = create_style_tree(&dom, &cssom, None);
let mut viewport: Dimensions = Default::default();
viewport.content.width = 800.0;
viewport.content.height = 600.0;
layout_tree(&styled_node, Rc::new(RefCell::new(viewport)));
}
}
|
//! The `server` module hosts all the server microservices.
use bank::Bank;
use crdt::{Crdt, ReplicatedData};
use ncp::Ncp;
use packet;
use rpu::Rpu;
use std::io::Write;
use std::net::UdpSocket;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, RwLock};
use std::thread::JoinHandle;
use std::time::Duration;
use streamer;
use tpu::Tpu;
use tvu::Tvu;
pub struct Server {
pub thread_hdls: Vec<JoinHandle<()>>,
}
impl Server {
/// Create a server instance acting as a leader.
///
/// ```text
/// .---------------------.
/// | Leader |
/// | |
/// .--------. | .-----. |
/// | |---->| | |
/// | Client | | | RPU | |
/// | |<----| | |
/// `----+---` | `-----` |
/// | | ^ |
/// | | | |
/// | | .--+---. |
/// | | | Bank | |
/// | | `------` |
/// | | ^ |
/// | | | | .------------.
/// | | .--+--. .-----. | | |
/// `-------->| TPU +-->| NCP +------>| Validators |
/// | `-----` `-----` | | |
/// | | `------------`
/// `---------------------`
/// ```
pub fn new_leader<W: Write + Send + 'static>(
bank: Bank,
tick_duration: Option<Duration>,
me: ReplicatedData,
requests_socket: UdpSocket,
transactions_socket: UdpSocket,
broadcast_socket: UdpSocket,
respond_socket: UdpSocket,
gossip_socket: UdpSocket,
exit: Arc<AtomicBool>,
writer: W,
) -> Self {
let bank = Arc::new(bank);
let mut thread_hdls = vec![];
let rpu = Rpu::new(bank.clone(), requests_socket, respond_socket, exit.clone());
thread_hdls.extend(rpu.thread_hdls);
let blob_recycler = packet::BlobRecycler::default();
let tpu = Tpu::new(
bank.clone(),
tick_duration,
transactions_socket,
blob_recycler.clone(),
exit.clone(),
writer,
);
thread_hdls.extend(tpu.thread_hdls);
let crdt = Arc::new(RwLock::new(Crdt::new(me)));
let window = streamer::default_window();
let gossip_send_socket = UdpSocket::bind("0.0.0.0:0").expect("bind 0");
let ncp = Ncp::new(
crdt.clone(),
window.clone(),
gossip_socket,
gossip_send_socket,
exit.clone(),
).expect("Ncp::new");
thread_hdls.extend(ncp.thread_hdls);
let t_broadcast = streamer::broadcaster(
broadcast_socket,
exit.clone(),
crdt,
window,
blob_recycler.clone(),
tpu.blob_receiver,
);
thread_hdls.extend(vec![t_broadcast]);
Server { thread_hdls }
}
/// Create a server instance acting as a validator.
///
/// ```text
/// .-------------------------------.
/// | Validator |
/// | |
/// .--------. | .-----. |
/// | |-------------->| | |
/// | Client | | | RPU | |
/// | |<--------------| | |
/// `--------` | `-----` |
/// | ^ |
/// | | |
/// | .--+---. |
/// | | Bank | |
/// | `------` |
/// | ^ |
/// .--------. | | | .------------.
/// | | | .-----. .--+--. .-----. | | |
/// | Leader |--->| NCP +-->| TVU +-->| NCP +------>| Validators |
/// | | | `-----` `-----` `-----` | | |
/// `--------` | | `------------`
/// `-------------------------------`
/// ```
pub fn new_validator(
bank: Bank,
me: ReplicatedData,
requests_socket: UdpSocket,
respond_socket: UdpSocket,
replicate_socket: UdpSocket,
gossip_socket: UdpSocket,
repair_socket: UdpSocket,
leader_repl_data: ReplicatedData,
exit: Arc<AtomicBool>,
) -> Self {
let bank = Arc::new(bank);
let mut thread_hdls = vec![];
let rpu = Rpu::new(bank.clone(), requests_socket, respond_socket, exit.clone());
thread_hdls.extend(rpu.thread_hdls);
let tvu = Tvu::new(
bank.clone(),
me,
gossip_socket,
replicate_socket,
repair_socket,
leader_repl_data,
exit.clone(),
);
thread_hdls.extend(tvu.thread_hdls);
Server { thread_hdls }
}
}
#[cfg(test)]
mod tests {
use bank::Bank;
use crdt::TestNode;
use mint::Mint;
use server::Server;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[test]
fn validator_exit() {
let tn = TestNode::new();
let alice = Mint::new(10_000);
let bank = Bank::new(&alice);
let exit = Arc::new(AtomicBool::new(false));
let v = Server::new_validator(
bank,
tn.data.clone(),
tn.sockets.requests,
tn.sockets.respond,
tn.sockets.replicate,
tn.sockets.gossip,
tn.sockets.repair,
tn.data,
exit.clone(),
);
exit.store(true, Ordering::Relaxed);
for t in v.thread_hdls {
t.join().unwrap();
}
}
}
|
#![feature(associated_type_defaults)]
pub mod error;
pub mod value;
pub mod domain;
pub mod condition;
pub mod expression;
mod testproperty;
|
#[doc = "Register `GTZC1_TZSC_PRIVCFGR1` reader"]
pub type R = crate::R<GTZC1_TZSC_PRIVCFGR1_SPEC>;
#[doc = "Register `GTZC1_TZSC_PRIVCFGR1` writer"]
pub type W = crate::W<GTZC1_TZSC_PRIVCFGR1_SPEC>;
#[doc = "Field `TIM2PRIV` reader - privileged access mode for TIM2"]
pub type TIM2PRIV_R = crate::BitReader;
#[doc = "Field `TIM2PRIV` writer - privileged access mode for TIM2"]
pub type TIM2PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM3PRIV` reader - privileged access mode for TIM3"]
pub type TIM3PRIV_R = crate::BitReader;
#[doc = "Field `TIM3PRIV` writer - privileged access mode for TIM3"]
pub type TIM3PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM6PRIV` reader - privileged access mode for TIM6"]
pub type TIM6PRIV_R = crate::BitReader;
#[doc = "Field `TIM6PRIV` writer - privileged access mode for TIM6"]
pub type TIM6PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM7PRIV` reader - privileged access mode for TIM7"]
pub type TIM7PRIV_R = crate::BitReader;
#[doc = "Field `TIM7PRIV` writer - privileged access mode for TIM7"]
pub type TIM7PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WWDGPRIV` reader - privileged access mode for WWDG"]
pub type WWDGPRIV_R = crate::BitReader;
#[doc = "Field `WWDGPRIV` writer - privileged access mode for WWDG"]
pub type WWDGPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `IWDGPRIV` reader - privileged access mode for IWDG"]
pub type IWDGPRIV_R = crate::BitReader;
#[doc = "Field `IWDGPRIV` writer - privileged access mode for IWDG"]
pub type IWDGPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI2PRIV` reader - privileged access mode for SPI2"]
pub type SPI2PRIV_R = crate::BitReader;
#[doc = "Field `SPI2PRIV` writer - privileged access mode for SPI2"]
pub type SPI2PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI3PRIV` reader - privileged access mode for SPI3"]
pub type SPI3PRIV_R = crate::BitReader;
#[doc = "Field `SPI3PRIV` writer - privileged access mode for SPI3"]
pub type SPI3PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART2PRIV` reader - privileged access mode for USART2"]
pub type USART2PRIV_R = crate::BitReader;
#[doc = "Field `USART2PRIV` writer - privileged access mode for USART2"]
pub type USART2PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART3PRIV` reader - privileged access mode for USART3"]
pub type USART3PRIV_R = crate::BitReader;
#[doc = "Field `USART3PRIV` writer - privileged access mode for USART3"]
pub type USART3PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C1PRIV` reader - privileged access mode for I2C1"]
pub type I2C1PRIV_R = crate::BitReader;
#[doc = "Field `I2C1PRIV` writer - privileged access mode for I2C1"]
pub type I2C1PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I2C2PRIV` reader - privileged access mode for I2C2"]
pub type I2C2PRIV_R = crate::BitReader;
#[doc = "Field `I2C2PRIV` writer - privileged access mode for I2C2"]
pub type I2C2PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `I3C1PRIV` reader - privileged access mode for I3C1"]
pub type I3C1PRIV_R = crate::BitReader;
#[doc = "Field `I3C1PRIV` writer - privileged access mode for I3C1"]
pub type I3C1PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `CRSPRIV` reader - privileged access mode for CRS"]
pub type CRSPRIV_R = crate::BitReader;
#[doc = "Field `CRSPRIV` writer - privileged access mode for CRS"]
pub type CRSPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DAC1PRIV` reader - privileged access mode for DAC1"]
pub type DAC1PRIV_R = crate::BitReader;
#[doc = "Field `DAC1PRIV` writer - privileged access mode for DAC1"]
pub type DAC1PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DTSPRIV` reader - privileged access mode for DTS"]
pub type DTSPRIV_R = crate::BitReader;
#[doc = "Field `DTSPRIV` writer - privileged access mode for DTS"]
pub type DTSPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `LPTIM2PRIV` reader - privileged access mode for LPTIM2"]
pub type LPTIM2PRIV_R = crate::BitReader;
#[doc = "Field `LPTIM2PRIV` writer - privileged access mode for LPTIM2"]
pub type LPTIM2PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - privileged access mode for TIM2"]
#[inline(always)]
pub fn tim2priv(&self) -> TIM2PRIV_R {
TIM2PRIV_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - privileged access mode for TIM3"]
#[inline(always)]
pub fn tim3priv(&self) -> TIM3PRIV_R {
TIM3PRIV_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 4 - privileged access mode for TIM6"]
#[inline(always)]
pub fn tim6priv(&self) -> TIM6PRIV_R {
TIM6PRIV_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - privileged access mode for TIM7"]
#[inline(always)]
pub fn tim7priv(&self) -> TIM7PRIV_R {
TIM7PRIV_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 9 - privileged access mode for WWDG"]
#[inline(always)]
pub fn wwdgpriv(&self) -> WWDGPRIV_R {
WWDGPRIV_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - privileged access mode for IWDG"]
#[inline(always)]
pub fn iwdgpriv(&self) -> IWDGPRIV_R {
IWDGPRIV_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - privileged access mode for SPI2"]
#[inline(always)]
pub fn spi2priv(&self) -> SPI2PRIV_R {
SPI2PRIV_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - privileged access mode for SPI3"]
#[inline(always)]
pub fn spi3priv(&self) -> SPI3PRIV_R {
SPI3PRIV_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - privileged access mode for USART2"]
#[inline(always)]
pub fn usart2priv(&self) -> USART2PRIV_R {
USART2PRIV_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - privileged access mode for USART3"]
#[inline(always)]
pub fn usart3priv(&self) -> USART3PRIV_R {
USART3PRIV_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 17 - privileged access mode for I2C1"]
#[inline(always)]
pub fn i2c1priv(&self) -> I2C1PRIV_R {
I2C1PRIV_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - privileged access mode for I2C2"]
#[inline(always)]
pub fn i2c2priv(&self) -> I2C2PRIV_R {
I2C2PRIV_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 19 - privileged access mode for I3C1"]
#[inline(always)]
pub fn i3c1priv(&self) -> I3C1PRIV_R {
I3C1PRIV_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bit 20 - privileged access mode for CRS"]
#[inline(always)]
pub fn crspriv(&self) -> CRSPRIV_R {
CRSPRIV_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 25 - privileged access mode for DAC1"]
#[inline(always)]
pub fn dac1priv(&self) -> DAC1PRIV_R {
DAC1PRIV_R::new(((self.bits >> 25) & 1) != 0)
}
#[doc = "Bit 30 - privileged access mode for DTS"]
#[inline(always)]
pub fn dtspriv(&self) -> DTSPRIV_R {
DTSPRIV_R::new(((self.bits >> 30) & 1) != 0)
}
#[doc = "Bit 31 - privileged access mode for LPTIM2"]
#[inline(always)]
pub fn lptim2priv(&self) -> LPTIM2PRIV_R {
LPTIM2PRIV_R::new(((self.bits >> 31) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - privileged access mode for TIM2"]
#[inline(always)]
#[must_use]
pub fn tim2priv(&mut self) -> TIM2PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 0> {
TIM2PRIV_W::new(self)
}
#[doc = "Bit 1 - privileged access mode for TIM3"]
#[inline(always)]
#[must_use]
pub fn tim3priv(&mut self) -> TIM3PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 1> {
TIM3PRIV_W::new(self)
}
#[doc = "Bit 4 - privileged access mode for TIM6"]
#[inline(always)]
#[must_use]
pub fn tim6priv(&mut self) -> TIM6PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 4> {
TIM6PRIV_W::new(self)
}
#[doc = "Bit 5 - privileged access mode for TIM7"]
#[inline(always)]
#[must_use]
pub fn tim7priv(&mut self) -> TIM7PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 5> {
TIM7PRIV_W::new(self)
}
#[doc = "Bit 9 - privileged access mode for WWDG"]
#[inline(always)]
#[must_use]
pub fn wwdgpriv(&mut self) -> WWDGPRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 9> {
WWDGPRIV_W::new(self)
}
#[doc = "Bit 10 - privileged access mode for IWDG"]
#[inline(always)]
#[must_use]
pub fn iwdgpriv(&mut self) -> IWDGPRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 10> {
IWDGPRIV_W::new(self)
}
#[doc = "Bit 11 - privileged access mode for SPI2"]
#[inline(always)]
#[must_use]
pub fn spi2priv(&mut self) -> SPI2PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 11> {
SPI2PRIV_W::new(self)
}
#[doc = "Bit 12 - privileged access mode for SPI3"]
#[inline(always)]
#[must_use]
pub fn spi3priv(&mut self) -> SPI3PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 12> {
SPI3PRIV_W::new(self)
}
#[doc = "Bit 13 - privileged access mode for USART2"]
#[inline(always)]
#[must_use]
pub fn usart2priv(&mut self) -> USART2PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 13> {
USART2PRIV_W::new(self)
}
#[doc = "Bit 14 - privileged access mode for USART3"]
#[inline(always)]
#[must_use]
pub fn usart3priv(&mut self) -> USART3PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 14> {
USART3PRIV_W::new(self)
}
#[doc = "Bit 17 - privileged access mode for I2C1"]
#[inline(always)]
#[must_use]
pub fn i2c1priv(&mut self) -> I2C1PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 17> {
I2C1PRIV_W::new(self)
}
#[doc = "Bit 18 - privileged access mode for I2C2"]
#[inline(always)]
#[must_use]
pub fn i2c2priv(&mut self) -> I2C2PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 18> {
I2C2PRIV_W::new(self)
}
#[doc = "Bit 19 - privileged access mode for I3C1"]
#[inline(always)]
#[must_use]
pub fn i3c1priv(&mut self) -> I3C1PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 19> {
I3C1PRIV_W::new(self)
}
#[doc = "Bit 20 - privileged access mode for CRS"]
#[inline(always)]
#[must_use]
pub fn crspriv(&mut self) -> CRSPRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 20> {
CRSPRIV_W::new(self)
}
#[doc = "Bit 25 - privileged access mode for DAC1"]
#[inline(always)]
#[must_use]
pub fn dac1priv(&mut self) -> DAC1PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 25> {
DAC1PRIV_W::new(self)
}
#[doc = "Bit 30 - privileged access mode for DTS"]
#[inline(always)]
#[must_use]
pub fn dtspriv(&mut self) -> DTSPRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 30> {
DTSPRIV_W::new(self)
}
#[doc = "Bit 31 - privileged access mode for LPTIM2"]
#[inline(always)]
#[must_use]
pub fn lptim2priv(&mut self) -> LPTIM2PRIV_W<GTZC1_TZSC_PRIVCFGR1_SPEC, 31> {
LPTIM2PRIV_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "GTZC1 TZSC privilege configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gtzc1_tzsc_privcfgr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gtzc1_tzsc_privcfgr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct GTZC1_TZSC_PRIVCFGR1_SPEC;
impl crate::RegisterSpec for GTZC1_TZSC_PRIVCFGR1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`gtzc1_tzsc_privcfgr1::R`](R) reader structure"]
impl crate::Readable for GTZC1_TZSC_PRIVCFGR1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`gtzc1_tzsc_privcfgr1::W`](W) writer structure"]
impl crate::Writable for GTZC1_TZSC_PRIVCFGR1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets GTZC1_TZSC_PRIVCFGR1 to value 0"]
impl crate::Resettable for GTZC1_TZSC_PRIVCFGR1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use super::u512;
// Constructors from standard integer types
impl From<u128> for u512 {
fn from(value: u128) -> u512 {
return u512 { data: [value as u64, (value >> 64) as u64, 0, 0, 0, 0, 0, 0] };
}
}
impl From<u8> for u512 { fn from(value: u8) -> u512 { u512::from(value as u128) } }
impl From<&u8> for u512 { fn from(value: &u8) -> u512 { u512::from(*value as u128) } }
impl From<u16> for u512 { fn from(value: u16) -> u512 { u512::from(value as u128) } }
impl From<&u16> for u512 { fn from(value: &u16) -> u512 { u512::from(*value as u128) } }
impl From<u32> for u512 { fn from(value: u32) -> u512 { u512::from(value as u128) } }
impl From<&u32> for u512 { fn from(value: &u32) -> u512 { u512::from(*value as u128) } }
impl From<u64> for u512 { fn from(value: u64) -> u512 { u512::from(value as u128) } }
impl From<&u64> for u512 { fn from(value: &u64) -> u512 { u512::from(*value as u128) } }
impl From<&u128> for u512 { fn from(value: &u128) -> u512 { u512::from(*value) } }
impl From<i128> for u512 {
fn from(value: i128) -> u512 {
if value < 0 {
panic!("Tried to create u512 from negative value!");
}
return u512::from(value as u128);
}
}
impl From<i8> for u512 { fn from(value: i8) -> u512 { u512::from(value as i128) } }
impl From<&i8> for u512 { fn from(value: &i8) -> u512 { u512::from(*value as i128) } }
impl From<i16> for u512 { fn from(value: i16) -> u512 { u512::from(value as i128) } }
impl From<&i16> for u512 { fn from(value: &i16) -> u512 { u512::from(*value as i128) } }
impl From<i32> for u512 { fn from(value: i32) -> u512 { u512::from(value as i128) } }
impl From<&i32> for u512 { fn from(value: &i32) -> u512 { u512::from(*value as i128) } }
impl From<i64> for u512 { fn from(value: i64) -> u512 { u512::from(value as i128) } }
impl From<&i64> for u512 { fn from(value: &i64) -> u512 { u512::from(*value as i128) } }
impl From<&i128> for u512 { fn from(value: &i128) -> u512 { u512::from(*value) } }
|
use bindings::{
Windows::Data::Xml::Dom::XmlDocument,
Windows::Foundation::TypedEventHandler,
Windows::Win32::Foundation::{CloseHandle, HANDLE, HINSTANCE, MAX_PATH, PWSTR},
Windows::Win32::Security::{
GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY, TOKEN_ADJUST_PRIVILEGES,
LookupPrivilegeValueW, AdjustTokenPrivileges, TOKEN_PRIVILEGES, LUID_AND_ATTRIBUTES,
SE_PRIVILEGE_ENABLED,
},
Windows::Win32::Storage::StructuredStorage::{
PROPVARIANT_0_0_0_abi, PROPVARIANT_0_0_abi, PROPVARIANT, PROPVARIANT_0,
},
Windows::Win32::System::Com::{CoCreateInstance, IPersistFile, CLSCTX_INPROC_SERVER},
Windows::Win32::System::Diagnostics::Debug::{GetLastError, FACILITY_WIN32, WIN32_ERROR},
Windows::Win32::System::Diagnostics::ToolHelp::{
PROCESSENTRY32W, CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS,
},
Windows::Win32::System::LibraryLoader::GetModuleFileNameW,
Windows::Win32::System::OleAutomation::VT_LPWSTR,
Windows::Win32::System::PropertiesSystem::{IPropertyStore, PROPERTYKEY},
Windows::Win32::System::Threading::{
GetCurrentProcess, OpenProcessToken, OpenProcess, TerminateProcess,
PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE,
},
Windows::Win32::System::SystemServices::LUID,
Windows::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
Windows::Win32::System::WinRT::{RoInitialize, RO_INIT_MULTITHREADED},
Windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID,
Windows::Win32::UI::Shell::{IShellLinkW, ShellLink},
Windows::UI::Notifications::{
ToastNotification, ToastNotificationManager, NotificationData, ToastDismissedEventArgs,
ToastDismissalReason,
},
};
use std::os::windows::prelude::*;
use std::path::Path;
use std::thread::sleep;
use std::time::Duration;
use std::{alloc, mem, slice, ptr};
use std::{
ffi::{OsStr, OsString},
mem::MaybeUninit,
sync::{Arc, Mutex},
};
use std::ptr::addr_of_mut;
use windows::{Guid, Interface, HRESULT};
macro_rules! enclose {
( ($( $x:ident ),*) $y:expr ) => {
{
$(let $x = $x.clone();)*
$y
}
};
}
const PKEY_AppUserModel_ID: PROPERTYKEY = PROPERTYKEY {
fmtid: Guid::from_values(
0x9F4C2855,
0x9F79,
0x4B39,
[0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3],
),
pid: 5,
};
const fn hresult_from_win32_error(e: WIN32_ERROR) -> HRESULT {
let e = e.0;
let e = if e as i32 <= 0 {
e
} else {
(e & 0x0000FFFF) | (FACILITY_WIN32.0 << 16) | 0x80000000
};
HRESULT(e)
}
fn hresult_from_last_error() -> HRESULT {
hresult_from_win32_error(unsafe { GetLastError() })
}
fn osstr_to_vec_u16_with_zero(s: &OsStr) -> Vec<u16> {
s.encode_wide().chain(Some(0)).collect()
}
fn osstr_from_slice_with_zero(s: &[u16]) -> OsString {
let len = s.iter().position(|i| *i == 0).unwrap_or(s.len());
OsString::from_wide(&s[..len])
}
unsafe fn osstr_from_ptr(ptr: *const u16, maxlen: usize) -> OsString {
let len = (0..maxlen).position(|i| *ptr.add(i) == 0).unwrap_or(maxlen);
OsString::from_wide(slice::from_raw_parts(ptr, len))
}
// Panic: The function will panic when allocation fails or size_fn returns 0
fn call_system_api_with_osstr<FS, FB, E>(size_hint_fn: FS, body_fn: FB) -> Result<OsString, E>
where
FS: FnOnce() -> usize, // usize: Buffer size (including '\0')
FB: FnOnce(*mut u16, usize) -> Result<usize, E>, // usize: Acutal size (not including '\0')
{
unsafe {
let buf_len = size_hint_fn();
assert!(buf_len > 0);
let mem_size = mem::size_of::<u16>().checked_mul(buf_len).unwrap();
let mem_layout = alloc::Layout::from_size_align(mem_size, mem::align_of::<u16>()).unwrap();
let str_buf = alloc::alloc(mem_layout) as *mut u16;
if str_buf.is_null() {
let noun_postfix = if mem_size == 1 { "" } else { "s" };
panic!(
"Memory allocation of {} byte{} failed",
mem_size, noun_postfix
);
}
// Assuming body_fn fills in a 0-terminated string
let ret_val = body_fn(str_buf, buf_len).map(|actual_len| {
let slice = slice::from_raw_parts(str_buf, actual_len);
OsString::from_wide(slice)
});
alloc::dealloc(str_buf as _, mem_layout);
ret_val
}
}
fn create_shortcut(path: &str) -> windows::Result<()> {
unsafe {
let exe_path = call_system_api_with_osstr(
|| MAX_PATH as _,
|ptr, size| -> windows::Result<usize> {
match GetModuleFileNameW(HINSTANCE::NULL, PWSTR(ptr), size as _) {
0 => Err(hresult_from_last_error().into()),
len => Ok(len as _),
}
},
)?;
dbg!(&exe_path);
let shell_link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?;
shell_link.SetPath(PWSTR(osstr_to_vec_u16_with_zero(&exe_path).as_mut_ptr()))?;
shell_link.SetArguments("")?;
let property_store: IPropertyStore = shell_link.cast()?;
// !!! Workaround for InitPropVariantFromString
let mut property_var_str: Vec<u16> = APP_AUMID.encode_utf16().collect();
let property_var = PROPVARIANT {
Anonymous: PROPVARIANT_0 {
Anonymous: PROPVARIANT_0_0_abi {
vt: VT_LPWSTR.0 as u16,
wReserved1: 0,
wReserved2: 0,
wReserved3: 0,
Anonymous: PROPVARIANT_0_0_0_abi {
pwszVal: PWSTR(property_var_str.as_mut_ptr()),
},
},
},
};
// !!! Workaround end
property_store.SetValue(&PKEY_AppUserModel_ID, &property_var)?;
property_store.Commit()?;
let persist_file: IPersistFile = shell_link.cast()?;
persist_file.Save(path, true)?;
Ok(())
}
}
fn is_elevated() -> bool {
unsafe {
let mut handle = MaybeUninit::<HANDLE>::uninit();
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, handle.as_mut_ptr()) == false {
return false;
}
let handle = handle.assume_init();
let mut elevation = MaybeUninit::<TOKEN_ELEVATION>::uninit();
let mut ret_size = MaybeUninit::uninit();
if GetTokenInformation(
handle,
TokenElevation,
elevation.as_mut_ptr() as _,
std::mem::size_of::<TOKEN_ELEVATION>() as _,
ret_size.as_mut_ptr(),
) == false
{
CloseHandle(handle);
return false;
}
CloseHandle(handle);
let elevation = elevation.assume_init();
elevation.TokenIsElevated != 0
}
}
fn get_process_id_from_name(name: &str) -> windows::Result<Option<u32>> {
unsafe {
let mut entry = MaybeUninit::<PROCESSENTRY32W>::uninit();
addr_of_mut!((*entry.as_mut_ptr()).dwSize).write(mem::size_of::<PROCESSENTRY32W>() as _);
let handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if handle.is_invalid() {
return Err(hresult_from_last_error().into());
}
if Process32FirstW(handle, entry.as_mut_ptr()) == false {
return Err(hresult_from_last_error().into());
}
let mut entry = entry.assume_init();
if osstr_from_slice_with_zero(&entry.szExeFile) == name {
CloseHandle(handle);
return Ok(Some(entry.th32ProcessID));
}
while Process32NextW(handle, addr_of_mut!(entry)) != false {
if osstr_from_slice_with_zero(&entry.szExeFile) == name {
CloseHandle(handle);
return Ok(Some(entry.th32ProcessID));
}
}
CloseHandle(handle);
Ok(None)
}
}
fn enable_debug_privilege() -> windows::Result<()> {
unsafe {
let mut handle = MaybeUninit::<HANDLE>::uninit();
if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, handle.as_mut_ptr()) == false {
return Err(hresult_from_last_error().into());
}
let handle = handle.assume_init();
let mut luid = MaybeUninit::<LUID>::uninit();
if LookupPrivilegeValueW(None, "SeDebugPrivilege", luid.as_mut_ptr()) == false {
CloseHandle(handle);
return Err(hresult_from_last_error().into());
}
let luid = luid.assume_init();
let mut tkp = TOKEN_PRIVILEGES {
PrivilegeCount: 1,
Privileges: [LUID_AND_ATTRIBUTES { Luid: luid, Attributes: SE_PRIVILEGE_ENABLED }],
};
if AdjustTokenPrivileges(handle, false, addr_of_mut!(tkp), 0, ptr::null_mut(), ptr::null_mut()) == false {
CloseHandle(handle);
return Err(hresult_from_last_error().into());
}
CloseHandle(handle);
Ok(())
}
}
const APP_AUMID: &'static str = "ApkipaLimitedCompany.DwmKillerCUI.Main.v0_1_0";
// usize: MB
fn get_dwm_mem_usage() -> windows::Result<usize> {
unsafe {
let process_id = get_process_id_from_name("dwm.exe")?.unwrap_or(0);
let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, process_id);
if handle.is_null() {
return Err(hresult_from_last_error().into());
}
let mut counters = MaybeUninit::<PROCESS_MEMORY_COUNTERS>::uninit();
if K32GetProcessMemoryInfo(handle, counters.as_mut_ptr(), mem::size_of::<PROCESS_MEMORY_COUNTERS>() as _) == false {
CloseHandle(handle);
return Err(hresult_from_last_error().into());
}
CloseHandle(handle);
let counters = counters.assume_init();
Ok(counters.PagefileUsage / 1024 / 1024)
}
}
fn kill_dwm() -> windows::Result<()> {
unsafe {
let process_id = get_process_id_from_name("dwm.exe")?.unwrap_or(0);
let handle = OpenProcess(PROCESS_TERMINATE, false, process_id);
if handle.is_null() {
return Err(hresult_from_last_error().into());
}
if TerminateProcess(handle, 1) == false {
CloseHandle(handle);
return Err(hresult_from_last_error().into());
}
CloseHandle(handle);
Ok(())
}
}
fn gen_toast_details_string(mem_limit: usize, cur_mem: usize) -> String {
format!("dwm.exe 内存占用已达 {} MB,超过了设定的 {} MB。点击以进行重启。", cur_mem, mem_limit)
}
fn gen_toast_notification(mem_limit: usize, cur_mem: usize) -> windows::Result<ToastNotification> {
// <toast><visual><binding template="ToastText02"><text id="1">title</text><text id="2">text</text></binding></visual></toast>
let mut xml_str = String::new();
xml_str += r#"<toast><visual><binding template="ToastText02"><text id="1">"#;
xml_str += r#"dwm.exe 内存溢出"#;
xml_str += r#"</text><text id="2">"#;
// xml_str += &gen_toast_details_string(mem_mb_num);
xml_str += r#"{details}"#;
xml_str += r#"</text></binding></visual></toast>"#;
let toast_xml = XmlDocument::new()?;
toast_xml.LoadXml(xml_str)?;
let toast = ToastNotification::CreateToastNotification(toast_xml)?;
let data = NotificationData::new()?;
data.Values()?.Insert("details", gen_toast_details_string(mem_limit, cur_mem))?;
toast.SetData(data)?;
Ok(toast)
}
fn update_toast_notification(toast: &ToastNotification, mem_limit: usize, cur_mem: usize) -> windows::Result<()> {
toast.Data()?.Values()?.Insert("details", gen_toast_details_string(mem_limit, cur_mem))?;
Ok(())
}
struct ToastData {
toast: ToastNotification,
mem_limit: usize,
last_mem: usize,
}
fn main() -> windows::Result<()> {
// unsafe {
// RoInitialize(RO_INIT_MULTITHREADED)?;
// SetCurrentProcessExplicitAppUserModelID(APP_AUMID)?;
// }
// let shortcut_path = "App.lnk";
// if !Path::new(shortcut_path).exists() {
// create_shortcut(shortcut_path)?;
// }
enable_debug_privilege()?;
println!("DwmKiller v{}\n", env!("CARGO_PKG_VERSION"));
const DWM_INITIAL_MEM_LIMIT: usize = 500;
const MEM_LIMIT_STEP: usize = 100;
if !is_elevated() {
eprintln!("错误:权限不足。请以管理员权限运行此应用。");
sleep(Duration::from_secs(3));
return Ok(());
}
let manager = ToastNotificationManager::CreateToastNotifierWithId(APP_AUMID)?;
let toast_mutex = Arc::new(Mutex::new(ToastData {
toast: gen_toast_notification(DWM_INITIAL_MEM_LIMIT, 0)?,
mem_limit: DWM_INITIAL_MEM_LIMIT,
last_mem: 0,
}));
let activated_handler = TypedEventHandler::new(
enclose! { (manager, toast_mutex) move |_, _| {
let mut unlocked = toast_mutex.lock().unwrap();
println!("信息:通知已被激活。");
let _ = manager.Hide(&unlocked.toast);
if kill_dwm().is_err() {
eprintln!("错误:无法终止 dwm.exe。请手动杀死进程。");
return Ok(());
}
unlocked.last_mem = 0;
unlocked.mem_limit = DWM_INITIAL_MEM_LIMIT;
Ok(())
}},
);
let dismissed_handler = TypedEventHandler::new(
enclose! { (manager, toast_mutex) move |_, e: &Option<ToastDismissedEventArgs>| {
let e = e.as_ref().unwrap();
let mut unlocked = toast_mutex.lock().unwrap();
match e.Reason().unwrap() {
ToastDismissalReason::UserCanceled => {
println!("信息:通知已被忽略。");
let _ = manager.Hide(&unlocked.toast);
while unlocked.last_mem >= unlocked.mem_limit {
unlocked.mem_limit += MEM_LIMIT_STEP;
}
unlocked.last_mem = 0;
}
ToastDismissalReason::ApplicationHidden | ToastDismissalReason::TimedOut | _ => (),
}
Ok(())
}},
);
let try_update_toast_closure = enclose! { (manager, toast_mutex, activated_handler, dismissed_handler) move || {
let mut unlocked = toast_mutex.lock().unwrap();
let cur_mem = get_dwm_mem_usage().unwrap_or_else(|e| {
eprintln!("错误:无法获取 dwm.exe 内存占用 ({:?})。", e);
0
});
println!("当前内存用量:{} / {} MB", cur_mem, unlocked.mem_limit);
if unlocked.last_mem >= unlocked.mem_limit {
// Already approached the limit, ignore for now
return false;
}
unlocked.last_mem = cur_mem;
if cur_mem >= unlocked.mem_limit {
let _ = manager.Hide(&unlocked.toast);
unlocked.toast = gen_toast_notification(unlocked.mem_limit, cur_mem).unwrap();
// update_toast_notification(&unlocked.toast, unlocked.mem_limit, cur_mem).unwrap();
unlocked.toast.Activated(&activated_handler).unwrap();
unlocked.toast.Dismissed(&dismissed_handler).unwrap();
return true;
}
false
}};
loop {
if try_update_toast_closure() {
let unlocked = toast_mutex.lock().unwrap();
manager.Show(&unlocked.toast)?;
}
sleep(Duration::from_secs(60));
}
}
|
pub mod test {
pub struct xte {
}
} |
use actix_web::{HttpRequest, HttpResponse};
use super::super::app::AppEnvironment;
pub async fn dispatch_default_index(app: AppEnvironment, _: HttpRequest) -> HttpResponse {
let output = format!(
"<!DOCTYPE html>
<html><head>
<meta charset=\"utf-8\" />
<style type=\"text/css\">
table {{ border-collapse: collapse; border: .05rem solid #d3d3d3; }}
table th, table td {{ border: 1px solid black; padding: 0.5rem; }}
</style>
<title>{}</title></head>
<body>{}</body></html>",
app.appname,
app.html_info()
);
HttpResponse::Forbidden()
.content_type("text/html")
.body(output)
}
|
//! [Worldedit](https://github.com/EngineHub/WorldEdit) and [RedstoneTools](https://github.com/paulikauro/RedstoneTools) implementation
mod schematic;
use super::{Plot, PlotWorld};
use crate::blocks::{
Block, BlockEntity, BlockFace, BlockFacing, BlockPos, FlipDirection, RotateAmt,
};
use crate::chat::{ChatComponentBuilder, ColorCode};
use crate::player::{Player, PlayerPos};
use crate::world::storage::PalettedBitBuffer;
use crate::world::World;
use log::error;
use rand::Rng;
use regex::Regex;
use schematic::{load_schematic, save_schematic};
use std::collections::HashMap;
use std::fmt;
use std::lazy::SyncLazy;
use std::ops::RangeInclusive;
use std::time::Instant;
// Attempts to execute a worldedit command. Returns true of the command was handled.
// The command is not handled if it is not found in the worldedit commands and alias lists.
pub fn execute_command(
plot: &mut Plot,
player_idx: usize,
command: &str,
args: &mut Vec<&str>,
) -> bool {
let player = &mut plot.players[player_idx];
let command = if let Some(command) = COMMANDS.get(command) {
command
} else if let Some(command) = ALIASES.get(command) {
let mut alias: Vec<&str> = command.split(' ').collect();
let command = alias.remove(0);
if alias.len() > 1 {
args.append(&mut alias);
}
&COMMANDS[command]
} else {
return false;
};
let mut ctx = CommandExecuteContext {
plot: &mut plot.world,
player,
arguments: Vec::new(),
flags: Vec::new(),
};
let wea = ctx.player.has_permission("plots.worldedit.bypass");
if !wea {
if let Some(owner) = plot.owner {
if owner != ctx.player.uuid {
// tried to worldedit on plot that wasn't theirs
ctx.player.send_no_permission_message();
return true;
}
} else {
// tried to worldedit on unclaimed plot
ctx.player.send_no_permission_message();
return true;
}
}
if !command.permission_node.is_empty() && !ctx.player.has_permission(command.permission_node) {
ctx.player.send_no_permission_message();
return true;
}
if command.requires_positions {
let plot_x = ctx.plot.x;
let plot_z = ctx.plot.z;
let player = &mut ctx.player;
if player.first_position.is_none() || player.second_position.is_none() {
player.send_error_message("Make a region selection first.");
return true;
}
let first_pos = player.first_position.unwrap();
let second_pos = player.second_position.unwrap();
if !Plot::in_plot_bounds(plot_x, plot_z, first_pos.x, first_pos.z) {
player.send_system_message("First position is outside plot bounds!");
return true;
}
if !Plot::in_plot_bounds(plot_x, plot_z, second_pos.x, second_pos.z) {
player.send_system_message("Second position is outside plot bounds!");
return true;
}
}
if command.requires_clipboard {
let player = &mut ctx.player;
if player.worldedit_clipboard.is_none() {
player.send_error_message("Your clipboard is empty. Use //copy first.");
return true;
}
}
let flag_descs = command.flags;
let mut arg_removal_idxs = Vec::new();
for (i, arg) in args.iter().enumerate() {
if arg.starts_with('-') {
let mut with_argument = false;
let flags = arg.chars();
for flag in flags.skip(1) {
if with_argument {
ctx.player
.send_error_message("Flag with argument must be last in grouping");
return true;
}
let flag_desc = if let Some(desc) = flag_descs.iter().find(|d| d.letter == flag) {
desc
} else {
ctx.player
.send_error_message(&format!("Unknown flag: {}", flag));
return true;
};
arg_removal_idxs.push(i);
if flag_desc.argument_type.is_some() {
arg_removal_idxs.push(i + 1);
with_argument = true;
}
ctx.flags.push(flag);
}
}
}
for idx in arg_removal_idxs.iter().rev() {
args.remove(*idx);
}
let arg_descs = command.arguments;
if args.len() > arg_descs.len() {
ctx.player.send_error_message("Too many arguments.");
return true;
}
for (i, arg_desc) in arg_descs.iter().enumerate() {
let arg = args.get(i).copied();
match Argument::parse(&ctx, arg_desc, arg) {
Ok(default_arg) => ctx.arguments.push(default_arg),
Err(err) => {
ctx.player.send_error_message(&err.to_string());
return true;
}
}
}
plot.redpiler.reset(ctx.plot);
(command.execute_fn)(ctx);
true
}
#[derive(Debug)]
struct ArgumentParseError {
arg_type: ArgumentType,
reason: String,
}
impl ArgumentParseError {
fn new(arg_type: ArgumentType, reason: &str) -> ArgumentParseError {
ArgumentParseError {
arg_type,
reason: String::from(reason),
}
}
}
impl fmt::Display for ArgumentParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Error parsing argument of type {:?}: {}",
self.arg_type, self.reason
)
}
}
impl std::error::Error for ArgumentParseError {}
type ArgumentParseResult = Result<Argument, ArgumentParseError>;
#[derive(Copy, Clone, Debug)]
enum ArgumentType {
UnsignedInteger,
Direction,
/// Used for diag directions in redstonetools commands
DirectionVector,
Mask,
Pattern,
String,
}
#[derive(Debug, Clone)]
enum Argument {
UnsignedInteger(u32),
Direction(BlockFacing),
DirectionVector(BlockPos),
Pattern(WorldEditPattern),
Mask(WorldEditPattern),
String(String),
}
impl Argument {
fn unwrap_uint(&self) -> u32 {
match self {
Argument::UnsignedInteger(val) => *val,
_ => panic!("Argument was not an UnsignedInteger"),
}
}
fn unwrap_direction(&self) -> BlockFacing {
match self {
Argument::Direction(val) => *val,
_ => panic!("Argument was not an Direction"),
}
}
fn unwrap_direction_vec(&self) -> BlockPos {
match self {
Argument::DirectionVector(val) => *val,
_ => panic!("Argument was not an DirectionVector"),
}
}
fn unwrap_pattern(&self) -> &WorldEditPattern {
match self {
Argument::Pattern(val) => val,
_ => panic!("Argument was not a Pattern"),
}
}
fn unwrap_mask(&self) -> &WorldEditPattern {
match self {
Argument::Mask(val) => val,
_ => panic!("Argument was not a Mask"),
}
}
fn unwrap_string(&self) -> &String {
match self {
Argument::String(val) => val,
_ => panic!("Argument was not a String"),
}
}
fn get_default(
ctx: &CommandExecuteContext<'_>,
desc: &ArgumentDescription,
) -> ArgumentParseResult {
if let Some(default) = &desc.default {
return Ok(default.clone());
}
let arg_type = desc.argument_type;
match arg_type {
ArgumentType::Direction | ArgumentType::DirectionVector => {
Argument::parse(ctx, desc, Some("me"))
}
ArgumentType::UnsignedInteger => Ok(Argument::UnsignedInteger(1)),
_ => Err(ArgumentParseError::new(
arg_type,
"argument can't be inferred",
)),
}
}
fn parse(
ctx: &CommandExecuteContext<'_>,
desc: &ArgumentDescription,
arg: Option<&str>,
) -> ArgumentParseResult {
if arg.is_none() {
return Argument::get_default(ctx, desc);
}
let arg = arg.unwrap();
let arg_type = desc.argument_type;
match arg_type {
ArgumentType::Direction => {
let player_facing = ctx.player.get_facing();
Ok(Argument::Direction(match arg {
"me" => player_facing,
"u" | "up" => BlockFacing::Up,
"d" | "down" => BlockFacing::Down,
"l" | "left" => player_facing.rotate_ccw(),
"r" | "right" => player_facing.rotate(),
_ => return Err(ArgumentParseError::new(arg_type, "unknown direction")),
}))
}
ArgumentType::UnsignedInteger => match arg.parse::<u32>() {
Ok(num) => Ok(Argument::UnsignedInteger(num)),
Err(_) => Err(ArgumentParseError::new(arg_type, "error parsing uint")),
},
ArgumentType::Pattern => match WorldEditPattern::from_str(arg) {
Ok(pattern) => Ok(Argument::Pattern(pattern)),
Err(err) => Err(ArgumentParseError::new(arg_type, &err.to_string())),
},
// Masks are net yet implemented, so in the meantime they can be treated as patterns
ArgumentType::Mask => match WorldEditPattern::from_str(arg) {
Ok(pattern) => Ok(Argument::Mask(pattern)),
Err(err) => Err(ArgumentParseError::new(arg_type, &err.to_string())),
},
ArgumentType::String => Ok(Argument::String(arg.to_owned())),
ArgumentType::DirectionVector => {
let mut vec = BlockPos::new(0, 0, 0);
let player_facing = ctx.player.get_facing();
if arg == "me" {
vec = player_facing.offset_pos(vec, 1);
if !matches!(player_facing, BlockFacing::Down | BlockFacing::Up) {
let pitch = ctx.player.pitch;
if pitch > 22.5 {
vec.y -= 1;
} else if pitch < -22.5 {
vec.y += 1;
}
}
return Ok(Argument::DirectionVector(vec));
}
let mut base_dir = arg;
if arg.len() > 1 && matches!(arg.chars().last(), Some('u' | 'd')) {
match arg.chars().last().unwrap() {
'u' => vec.y += 1,
'd' => vec.y -= 1,
_ => unreachable!(),
}
base_dir = &arg[..1];
}
let facing = match base_dir {
"u" | "up" => BlockFacing::Up,
"d" | "down" => BlockFacing::Down,
"l" | "left" => player_facing.rotate_ccw(),
"r" | "right" => player_facing.rotate(),
_ => return Err(ArgumentParseError::new(arg_type, "unknown direction")),
};
let vec = facing.offset_pos(vec, 1);
Ok(Argument::DirectionVector(vec))
}
}
}
}
struct ArgumentDescription {
name: &'static str,
argument_type: ArgumentType,
description: &'static str,
default: Option<Argument>,
}
macro_rules! argument {
($name:literal, $type:ident, $desc:literal) => {
ArgumentDescription {
name: $name,
argument_type: ArgumentType::$type,
description: $desc,
default: None,
}
};
($name:literal, $type:ident, $desc:literal, $default:literal) => {
ArgumentDescription {
name: $name,
argument_type: ArgumentType::$type,
description: $desc,
default: Some(Argument::$type($default)),
}
};
}
struct FlagDescription {
letter: char,
argument_type: Option<ArgumentType>,
description: &'static str,
}
macro_rules! flag {
($name:literal, $type:ident, $desc:literal) => {
FlagDescription {
letter: $name,
argument_type: $type,
description: $desc,
}
};
}
struct CommandExecuteContext<'a> {
plot: &'a mut PlotWorld,
player: &'a mut Player,
arguments: Vec<Argument>,
flags: Vec<char>,
}
impl<'a> CommandExecuteContext<'a> {
fn has_flag(&self, c: char) -> bool {
self.flags.contains(&c)
}
}
struct WorldeditCommand {
arguments: &'static [ArgumentDescription],
flags: &'static [FlagDescription],
requires_positions: bool,
requires_clipboard: bool,
execute_fn: fn(CommandExecuteContext<'_>),
description: &'static str,
permission_node: &'static str,
}
impl Default for WorldeditCommand {
fn default() -> Self {
Self {
arguments: &[],
flags: &[],
execute_fn: execute_unimplemented,
description: "",
requires_clipboard: false,
requires_positions: false,
permission_node: "",
}
}
}
static COMMANDS: SyncLazy<HashMap<&'static str, WorldeditCommand>> = SyncLazy::new(|| {
map! {
"up" => WorldeditCommand {
execute_fn: execute_up,
description: "Go upwards some distance",
arguments: &[
argument!("distance", UnsignedInteger, "Distance to go upwards")
],
permission_node: "worldedit.navigation.up",
..Default::default()
},
"/pos1" => WorldeditCommand {
execute_fn: execute_pos1,
description: "Set position 1",
permission_node: "worldedit.selection.pos",
..Default::default()
},
"/pos2" => WorldeditCommand {
execute_fn: execute_pos2,
description: "Set position 2",
permission_node: "worldedit.selection.pos",
..Default::default()
},
"/hpos1" => WorldeditCommand {
execute_fn: execute_hpos1,
description: "Set position 1 to targeted block",
permission_node: "worldedit.selection.hpos",
..Default::default()
},
"/hpos2" => WorldeditCommand {
execute_fn: execute_hpos2,
description: "Set position 2 to targeted block",
permission_node: "worldedit.selection.hpos",
..Default::default()
},
"/sel" => WorldeditCommand {
execute_fn: execute_sel,
description: "Choose a region selector",
..Default::default()
},
"/set" => WorldeditCommand {
arguments: &[
argument!("pattern", Pattern, "The pattern of blocks to set")
],
requires_positions: true,
execute_fn: execute_set,
description: "Sets all the blocks in the region",
permission_node: "worldedit.region.stack",
..Default::default()
},
"/replace" => WorldeditCommand {
arguments: &[
argument!("from", Mask, "The mask representng blocks to replace"),
argument!("to", Pattern, "The pattern of blocks to replace with")
],
requires_positions: true,
execute_fn: execute_replace,
description: "Replace all blocks in a selection with another",
permission_node: "worldedit.region.replace",
..Default::default()
},
"/copy" => WorldeditCommand {
requires_positions: true,
execute_fn: execute_copy,
description: "Copy the selection to the clipboard",
permission_node: "worldedit.clipboard.copy",
..Default::default()
},
"/cut" => WorldeditCommand {
requires_positions: true,
execute_fn: execute_cut,
description: "Cut the selection to the clipboard",
permission_node: "worldedit.clipboard.cut",
..Default::default()
},
"/paste" => WorldeditCommand {
requires_clipboard: true,
execute_fn: execute_paste,
description: "Paste the clipboard's contents",
flags: &[
flag!('a', None, "Skip air blocks")
],
permission_node: "worldedit.clipboard.paste",
..Default::default()
},
"/undo" => WorldeditCommand {
execute_fn: execute_undo,
description: "Undoes the last action (from history)",
permission_node: "worldedit.history.undo",
..Default::default()
},
"/redo" => WorldeditCommand {
execute_fn: execute_redo,
description: "Redoes the last action (from history)",
permission_node: "worldedit.history.redo",
..Default::default()
},
"/stack" => WorldeditCommand {
arguments: &[
argument!("count", UnsignedInteger, "# of copies to stack"),
argument!("direction", Direction, "The direction to stack")
],
requires_positions: true,
execute_fn: execute_stack,
description: "Repeat the contents of the selection",
flags: &[
flag!('a', None, "Ignore air blocks")
],
permission_node: "worldedit.region.stack",
..Default::default()
},
"/move" => WorldeditCommand {
arguments: &[
argument!("count", UnsignedInteger, "The distance to move"),
argument!("direction", Direction, "The direction to move")
],
requires_positions: true,
execute_fn: execute_move,
description: "Move the contents of the selection",
flags: &[
flag!('a', None, "Ignore air blocks"),
flag!('s', None, "Shift the selection to the target location")
],
permission_node: "worldedit.region.move",
..Default::default()
},
"/count" => WorldeditCommand {
arguments: &[
argument!("mask", Mask, "The mask of blocks to match")
],
requires_positions: true,
execute_fn: execute_count,
description: "Counts the number of blocks matching a mask",
permission_node: "worldedit.analysis.count",
..Default::default()
},
"/load" => WorldeditCommand {
arguments: &[
argument!("name", String, "The file name of the schematic to load")
],
execute_fn: execute_load,
description: "Loads a schematic file into the clipboard",
permission_node: "worldedit.clipboard.load",
..Default::default()
},
"/save" => WorldeditCommand {
arguments: &[
argument!("name", String, "The file name of the schematic to save")
],
requires_clipboard: true,
execute_fn: execute_save,
description: "Save a schematic file from the clipboard",
permission_node: "worldedit.clipboard.save",
..Default::default()
},
"/expand" => WorldeditCommand {
arguments: &[
argument!("amount", UnsignedInteger, "Amount to expand the selection by"),
argument!("direction", Direction, "Direction to expand")
],
requires_positions: true,
execute_fn: execute_expand,
description: "Expand the selection area",
permission_node: "worldedit.selection.expand",
..Default::default()
},
"/contract" => WorldeditCommand {
arguments: &[
argument!("amount", UnsignedInteger, "Amount to contract the selection by"),
argument!("direction", Direction, "Direction to contract")
],
requires_positions: true,
execute_fn: execute_contract,
description: "Contract the selection area",
permission_node: "worldedit.selection.contract",
..Default::default()
},
"/shift" => WorldeditCommand {
arguments: &[
argument!("amount", UnsignedInteger, "Amount to shift the selection by"),
argument!("direction", Direction, "Direction to shift")
],
requires_positions: true,
execute_fn: execute_shift,
description: "Shift the selection area",
permission_node: "worldedit.selection.shift",
..Default::default()
},
"/flip" => WorldeditCommand {
arguments: &[
argument!("direction", Direction, "The direction to flip, defaults to look direction"),
],
requires_clipboard: true,
execute_fn: execute_flip,
description: "Flip the contents of the clipboard across the origin",
..Default::default()
},
"/rotate" => WorldeditCommand {
arguments: &[
argument!("rotateY", UnsignedInteger, "Amount to rotate on the x-axis", 0),
],
requires_clipboard: true,
execute_fn: execute_rotate,
description: "Rotate the contents of the clipboard",
..Default::default()
},
"/rstack" => WorldeditCommand {
arguments: &[
argument!("count", UnsignedInteger, "# of copies to stack"),
argument!("spacing", UnsignedInteger, "The spacing between each selection", 2),
argument!("direction", DirectionVector, "The direction to stack")
],
flags: &[
flag!('a', None, "Include air blocks"),
flag!('e', None, "Expand selection")
],
execute_fn: execute_rstack,
description: "Like //stack but allows the stacked copies to overlap, supports more directions, and more flags",
permission_node: "redstonetools.rstack",
..Default::default()
},
"/help" => WorldeditCommand {
arguments: &[
argument!("command", String, "Command to retrieve help for"),
],
execute_fn: execute_help,
description: "Displays help for WorldEdit commands",
permission_node: "worldedit.help",
..Default::default()
}
}
});
static ALIASES: SyncLazy<HashMap<&'static str, &'static str>> = SyncLazy::new(|| {
map! {
"u" => "up",
"/1" => "/pos1",
"/2" => "/pos2",
"/c" => "/copy",
"/x" => "/cut",
"/v" => "/paste",
"/va" => "/paste -a",
"/s" => "/stack",
"/sa" => "/stack -a",
"/e" => "/expand",
"/r" => "/rotate",
"/f" => "/flip",
"/h1" => "/hpos1",
"/h2" => "/hpos2",
"/rs" => "/rstack"
}
});
#[derive(Debug, Clone)]
pub struct WorldEditPatternPart {
pub weight: f32,
pub block_id: u32,
}
#[derive(Clone, Debug)]
pub struct WorldEditClipboard {
pub offset_x: i32,
pub offset_y: i32,
pub offset_z: i32,
pub size_x: u32,
pub size_y: u32,
pub size_z: u32,
pub data: PalettedBitBuffer,
pub block_entities: HashMap<BlockPos, BlockEntity>,
}
#[derive(Clone, Debug)]
pub struct WorldEditUndo {
clipboards: Vec<WorldEditClipboard>,
pos: BlockPos,
plot_x: i32,
plot_z: i32,
}
pub enum PatternParseError {
UnknownBlock(String),
InvalidPattern(String),
}
impl fmt::Display for PatternParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PatternParseError::UnknownBlock(block) => write!(f, "unknown block: {}", block),
PatternParseError::InvalidPattern(pattern) => write!(f, "invalid pattern: {}", pattern),
}
}
}
pub type PatternParseResult<T> = std::result::Result<T, PatternParseError>;
#[derive(Debug, Clone)]
pub struct WorldEditPattern {
pub parts: Vec<WorldEditPatternPart>,
}
impl WorldEditPattern {
pub fn from_str(pattern_str: &str) -> PatternParseResult<WorldEditPattern> {
let mut pattern = WorldEditPattern { parts: Vec::new() };
for part in pattern_str.split(',') {
static RE: SyncLazy<Regex> = SyncLazy::new(|| {
Regex::new(r"^(([0-9]+(\.[0-9]+)?)%)?(=)?([0-9]+|(minecraft:)?[a-zA-Z_]+)(:([0-9]+)|\[(([a-zA-Z_]+=[a-zA-Z0-9]+,?)+?)\])?((\|([^|]*?)){1,4})?$").unwrap()
});
let pattern_match = RE
.captures(part)
.ok_or_else(|| PatternParseError::InvalidPattern(part.to_owned()))?;
let block = if pattern_match.get(4).is_some() {
Block::from_id(
pattern_match
.get(5)
.map_or("0", |m| m.as_str())
.parse::<u32>()
.unwrap(),
)
} else {
let block_name = pattern_match
.get(5)
.unwrap()
.as_str()
.trim_start_matches("minecraft:");
Block::from_name(block_name)
.ok_or_else(|| PatternParseError::UnknownBlock(part.to_owned()))?
};
let weight = pattern_match
.get(2)
.map_or("100", |m| m.as_str())
.parse::<f32>()
.unwrap()
/ 100.0;
pattern.parts.push(WorldEditPatternPart {
weight,
block_id: block.get_id(),
});
}
Ok(pattern)
}
pub fn matches(&self, block: Block) -> bool {
let block_id = block.get_id();
self.parts.iter().any(|part| part.block_id == block_id)
}
pub fn pick(&self) -> Block {
let mut weight_sum = 0.0;
for part in &self.parts {
weight_sum += part.weight;
}
let mut rng = rand::thread_rng();
let mut random = rng.gen_range(0.0..weight_sum);
let mut selected = &WorldEditPatternPart {
block_id: 0,
weight: 0.0,
};
for part in &self.parts {
random -= part.weight;
if random <= 0.0 {
selected = part;
break;
}
}
Block::from_id(selected.block_id)
}
}
struct ChunkChangedRecord {
chunk_x: i32,
chunk_z: i32,
block_count: usize,
}
struct WorldEditOperation {
pub records: Vec<ChunkChangedRecord>,
x_range: RangeInclusive<i32>,
y_range: RangeInclusive<i32>,
z_range: RangeInclusive<i32>,
}
impl WorldEditOperation {
fn new(first_pos: BlockPos, second_pos: BlockPos) -> WorldEditOperation {
let start_pos = first_pos.min(second_pos);
let end_pos = first_pos.max(second_pos);
let mut records: Vec<ChunkChangedRecord> = Vec::new();
for chunk_x in (start_pos.x >> 4)..=(end_pos.x >> 4) {
for chunk_z in (start_pos.z >> 4)..=(end_pos.z >> 4) {
records.push(ChunkChangedRecord {
chunk_x,
chunk_z,
block_count: 0,
});
}
}
let x_range = start_pos.x..=end_pos.x;
let y_range = start_pos.y..=end_pos.y;
let z_range = start_pos.z..=end_pos.z;
WorldEditOperation {
records,
x_range,
y_range,
z_range,
}
}
fn update_block(&mut self, block_pos: BlockPos) {
let chunk_x = block_pos.x >> 4;
let chunk_z = block_pos.z >> 4;
if let Some(packet) = self
.records
.iter_mut()
.find(|c| c.chunk_x == chunk_x && c.chunk_z == chunk_z)
{
packet.block_count += 1;
}
}
fn blocks_updated(&self) -> usize {
let mut blocks_updated = 0;
for record in &self.records {
blocks_updated += record.block_count;
}
blocks_updated
}
fn x_range(&self) -> RangeInclusive<i32> {
self.x_range.clone()
}
fn y_range(&self) -> RangeInclusive<i32> {
self.y_range.clone()
}
fn z_range(&self) -> RangeInclusive<i32> {
self.z_range.clone()
}
}
fn ray_trace_block(
world: &impl World,
mut pos: PlayerPos,
start_pitch: f64,
start_yaw: f64,
max_distance: f64,
) -> Option<BlockPos> {
let check_distance = 0.2;
// Player view height
pos.y += 1.65;
let rot_x = (start_yaw + 90.0) % 360.0;
let rot_y = start_pitch * -1.0;
let h = check_distance * rot_y.to_radians().cos();
let offset_x = h * rot_x.to_radians().cos();
let offset_y = check_distance * rot_y.to_radians().sin();
let offset_z = h * rot_x.to_radians().sin();
let mut current_distance = 0.0;
while current_distance < max_distance {
let block_pos = pos.block_pos();
let block = world.get_block(block_pos);
if !matches!(block, Block::Air {}) {
return Some(block_pos);
}
pos.x += offset_x;
pos.y += offset_y;
pos.z += offset_z;
current_distance += check_distance;
}
None
}
fn worldedit_send_operation(plot: &mut PlotWorld, operation: WorldEditOperation) {
for packet in operation.records {
let chunk = match plot.get_chunk(packet.chunk_x, packet.chunk_z) {
Some(chunk) => chunk,
None => continue,
};
let chunk_data = chunk.encode_packet();
for player in &mut plot.packet_senders {
player.send_packet(&chunk_data);
}
}
}
fn worldedit_start_operation(player: &mut Player) -> WorldEditOperation {
let first_pos = player.first_position.unwrap();
let second_pos = player.second_position.unwrap();
WorldEditOperation::new(first_pos, second_pos)
}
fn execute_set(ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let pattern = ctx.arguments[0].unwrap_pattern();
let mut operation = worldedit_start_operation(ctx.player);
capture_undo(
ctx.plot,
ctx.player,
ctx.player.first_position.unwrap(),
ctx.player.second_position.unwrap(),
);
for x in operation.x_range() {
for y in operation.y_range() {
for z in operation.z_range() {
let block_pos = BlockPos::new(x, y, z);
let block_id = pattern.pick().get_id();
if ctx.plot.set_block_raw(block_pos, block_id) {
operation.update_block(block_pos);
}
}
}
}
let blocks_updated = operation.blocks_updated();
worldedit_send_operation(ctx.plot, operation);
ctx.player.send_worldedit_message(&format!(
"Operation completed: {} block(s) affected ({:?})",
blocks_updated,
start_time.elapsed()
));
}
fn execute_replace(ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let filter = ctx.arguments[0].unwrap_mask();
let pattern = ctx.arguments[1].unwrap_pattern();
let mut operation = worldedit_start_operation(ctx.player);
capture_undo(
ctx.plot,
ctx.player,
ctx.player.first_position.unwrap(),
ctx.player.second_position.unwrap(),
);
for x in operation.x_range() {
for y in operation.y_range() {
for z in operation.z_range() {
let block_pos = BlockPos::new(x, y, z);
if filter.matches(ctx.plot.get_block(block_pos)) {
let block_id = pattern.pick().get_id();
if ctx.plot.set_block_raw(block_pos, block_id) {
operation.update_block(block_pos);
}
}
}
}
}
let blocks_updated = operation.blocks_updated();
worldedit_send_operation(ctx.plot, operation);
ctx.player.send_worldedit_message(&format!(
"Operation completed: {} block(s) affected ({:?})",
blocks_updated,
start_time.elapsed()
));
}
fn execute_count(ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let filter = ctx.arguments[0].unwrap_pattern();
let mut blocks_counted = 0;
let operation = worldedit_start_operation(ctx.player);
for x in operation.x_range() {
for y in operation.y_range() {
for z in operation.z_range() {
let block_pos = BlockPos::new(x, y, z);
if filter.matches(ctx.plot.get_block(block_pos)) {
blocks_counted += 1;
}
}
}
}
ctx.player.send_worldedit_message(&format!(
"Counted {} block(s) ({:?})",
blocks_counted,
start_time.elapsed()
));
}
fn create_clipboard(
plot: &mut PlotWorld,
origin: BlockPos,
first_pos: BlockPos,
second_pos: BlockPos,
) -> WorldEditClipboard {
let start_pos = first_pos.min(second_pos);
let end_pos = first_pos.max(second_pos);
let size_x = (end_pos.x - start_pos.x) as u32 + 1;
let size_y = (end_pos.y - start_pos.y) as u32 + 1;
let size_z = (end_pos.z - start_pos.z) as u32 + 1;
let offset = origin - start_pos;
let mut cb = WorldEditClipboard {
offset_x: offset.x,
offset_y: offset.y,
offset_z: offset.z,
size_x,
size_y,
size_z,
data: PalettedBitBuffer::with_entries((size_x * size_y * size_z) as usize),
block_entities: HashMap::new(),
};
let mut i = 0;
for y in start_pos.y..=end_pos.y {
for z in start_pos.z..=end_pos.z {
for x in start_pos.x..=end_pos.x {
let pos = BlockPos::new(x, y, z);
let id = plot.get_block_raw(pos);
let block = plot.get_block(BlockPos::new(x, y, z));
if block.has_block_entity() {
if let Some(block_entity) = plot.get_block_entity(pos) {
cb.block_entities
.insert(pos - start_pos, block_entity.clone());
}
}
cb.data.set_entry(i, id);
i += 1;
}
}
}
cb
}
fn clear_area(plot: &mut PlotWorld, first_pos: BlockPos, second_pos: BlockPos) {
let start_pos = first_pos.min(second_pos);
let end_pos = first_pos.max(second_pos);
for y in start_pos.y..=end_pos.y {
for z in start_pos.z..=end_pos.z {
for x in start_pos.x..=end_pos.x {
plot.set_block_raw(BlockPos::new(x, y, z), 0);
}
}
}
// Send modified chunks
for chunk_x in (start_pos.x >> 4)..=(end_pos.x >> 4) {
for chunk_z in (start_pos.z >> 4)..=(end_pos.z >> 4) {
if let Some(chunk) = plot.get_chunk(chunk_x, chunk_z) {
let chunk_data = chunk.encode_packet();
for player in &mut plot.packet_senders {
player.send_packet(&chunk_data);
}
}
}
}
}
fn paste_clipboard(plot: &mut PlotWorld, cb: &WorldEditClipboard, pos: BlockPos, ignore_air: bool) {
let offset_x = pos.x - cb.offset_x;
let offset_y = pos.y - cb.offset_y;
let offset_z = pos.z - cb.offset_z;
let mut i = 0;
// This can be made better, but right now it's not D:
let x_range = offset_x..offset_x + cb.size_x as i32;
let y_range = offset_y..offset_y + cb.size_y as i32;
let z_range = offset_z..offset_z + cb.size_z as i32;
let entries = cb.data.entries();
// I have no clue if these clones are going to cost anything noticeable.
'top_loop: for y in y_range.clone() {
for z in z_range.clone() {
for x in x_range.clone() {
if i >= entries {
break 'top_loop;
}
let entry = cb.data.get_entry(i);
i += 1;
if ignore_air && entry == 0 {
continue;
}
plot.set_block_raw(BlockPos::new(x, y, z), entry);
}
}
}
// Calculate the ranges of chunks that might have been modified
let chunk_x_range = offset_x >> 4..=(offset_x + cb.size_x as i32) >> 4;
let chunk_z_range = offset_z >> 4..=(offset_z + cb.size_z as i32) >> 4;
for chunk_x in chunk_x_range {
for chunk_z in chunk_z_range.clone() {
if let Some(chunk) = plot.get_chunk(chunk_x, chunk_z) {
let chunk_data = chunk.encode_packet();
for player in &mut plot.packet_senders {
player.send_packet(&chunk_data);
}
}
}
}
for (pos, block_entity) in &cb.block_entities {
let new_pos = BlockPos {
x: pos.x + offset_x,
y: pos.y + offset_y,
z: pos.z + offset_z,
};
plot.set_block_entity(new_pos, block_entity.clone());
}
}
fn capture_undo(
plot: &mut PlotWorld,
player: &mut Player,
first_pos: BlockPos,
second_pos: BlockPos,
) {
let origin = first_pos.min(second_pos);
let cb = create_clipboard(plot, origin, first_pos, second_pos);
let undo = WorldEditUndo {
clipboards: vec![cb],
pos: origin,
plot_x: plot.x,
plot_z: plot.z,
};
player.worldedit_undo.push(undo);
player.worldedit_redo.clear();
}
fn execute_copy(mut ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let origin = ctx.player.pos.block_pos();
let clipboard = create_clipboard(
ctx.plot,
origin,
ctx.player.first_position.unwrap(),
ctx.player.second_position.unwrap(),
);
ctx.player.worldedit_clipboard = Some(clipboard);
ctx.player.send_worldedit_message(&format!(
"Your selection was copied. ({:?})",
start_time.elapsed()
));
}
fn execute_cut(mut ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let first_pos = ctx.player.first_position.unwrap();
let second_pos = ctx.player.second_position.unwrap();
capture_undo(ctx.plot, ctx.player, first_pos, second_pos);
let origin = ctx.player.pos.block_pos();
let clipboard = create_clipboard(ctx.plot, origin, first_pos, second_pos);
ctx.player.worldedit_clipboard = Some(clipboard);
clear_area(ctx.plot, first_pos, second_pos);
ctx.player.send_worldedit_message(&format!(
"Your selection was cut. ({:?})",
start_time.elapsed()
));
}
fn execute_move(mut ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let move_amt = ctx.arguments[0].unwrap_uint();
let direction = ctx.arguments[1].unwrap_direction();
let first_pos = ctx.player.first_position.unwrap();
let second_pos = ctx.player.second_position.unwrap();
let zero_pos = BlockPos::new(0, 0, 0);
let undo = WorldEditUndo {
clipboards: vec![
create_clipboard(ctx.plot, first_pos.min(second_pos), first_pos, second_pos),
create_clipboard(
ctx.plot,
first_pos.min(second_pos),
direction.offset_pos(first_pos, move_amt as i32),
direction.offset_pos(second_pos, move_amt as i32),
),
],
pos: first_pos.min(second_pos),
plot_x: ctx.plot.x,
plot_z: ctx.plot.z,
};
ctx.player.worldedit_undo.push(undo);
let clipboard = create_clipboard(ctx.plot, zero_pos, first_pos, second_pos);
clear_area(ctx.plot, first_pos, second_pos);
paste_clipboard(
ctx.plot,
&clipboard,
direction.offset_pos(zero_pos, move_amt as i32),
ctx.has_flag('a'),
);
if ctx.has_flag('s') {
let first_pos = direction.offset_pos(first_pos, move_amt as i32);
let second_pos = direction.offset_pos(second_pos, move_amt as i32);
let player = &mut ctx.player;
player.worldedit_set_first_position(first_pos);
player.worldedit_set_second_position(second_pos);
}
ctx.player.send_worldedit_message(&format!(
"Your selection was moved. ({:?})",
start_time.elapsed()
));
}
fn execute_paste(ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
if ctx.player.worldedit_clipboard.is_some() {
// Here I am cloning the clipboard. This is bad. Don't do this.
let cb = &ctx.player.worldedit_clipboard.clone().unwrap();
let pos = ctx.player.pos.block_pos();
let offset_x = pos.x - cb.offset_x;
let offset_y = pos.y - cb.offset_y;
let offset_z = pos.z - cb.offset_z;
capture_undo(
ctx.plot,
ctx.player,
BlockPos::new(offset_x, offset_y, offset_z),
BlockPos::new(
offset_x + cb.size_x as i32,
offset_y + cb.size_y as i32,
offset_z + cb.size_z as i32,
),
);
paste_clipboard(ctx.plot, cb, pos, ctx.has_flag('a'));
ctx.player.send_worldedit_message(&format!(
"Your clipboard was pasted. ({:?})",
start_time.elapsed()
));
} else {
ctx.player.send_system_message("Your clipboard is empty!");
}
}
fn execute_load(mut ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let file_name = ctx.arguments[0].unwrap_string();
let clipboard = load_schematic(file_name);
match clipboard {
Ok(cb) => {
ctx.player.worldedit_clipboard = Some(cb);
ctx.player.send_worldedit_message(&format!(
"The schematic was loaded to your clipboard. Do //paste to birth it into the world. ({:?})",
start_time.elapsed()
));
}
Err(e) => {
error!("There was an error loading a schematic:");
error!("{}", e);
ctx.player
.send_error_message("There was an error loading the schematic.");
}
}
}
fn execute_save(ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let file_name = ctx.arguments[0].unwrap_string();
let clipboard = ctx.player.worldedit_clipboard.as_ref().unwrap();
match save_schematic(file_name, clipboard) {
Ok(_) => {
ctx.player.send_worldedit_message(&format!(
"The schematic was saved sucessfuly. ({:?})",
start_time.elapsed()
));
}
Err(err) => {
error!("There was an error saving a schematic: ");
error!("{:?}", err);
ctx.player
.send_error_message("There was an error saving the schematic.");
}
}
}
fn execute_stack(ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let stack_amt = ctx.arguments[0].unwrap_uint();
let direction = ctx.arguments[1].unwrap_direction();
let pos1 = ctx.player.first_position.unwrap();
let pos2 = ctx.player.second_position.unwrap();
let clipboard = create_clipboard(ctx.plot, pos1, pos1, pos2);
let stack_offset = match direction {
BlockFacing::North | BlockFacing::South => clipboard.size_z,
BlockFacing::East | BlockFacing::West => clipboard.size_x,
BlockFacing::Up | BlockFacing::Down => clipboard.size_y,
};
let mut undo_cbs = Vec::new();
for i in 1..stack_amt + 1 {
let offset = (i * stack_offset) as i32;
let block_pos = direction.offset_pos(pos1, offset);
undo_cbs.push(create_clipboard(
ctx.plot,
pos1,
block_pos,
direction.offset_pos(pos2, offset),
));
paste_clipboard(ctx.plot, &clipboard, block_pos, ctx.has_flag('a'));
}
let undo = WorldEditUndo {
clipboards: undo_cbs,
pos: pos1,
plot_x: ctx.plot.x,
plot_z: ctx.plot.z,
};
ctx.player.worldedit_undo.push(undo);
ctx.player.send_worldedit_message(&format!(
"Your selection was stacked. ({:?})",
start_time.elapsed()
));
}
fn execute_undo(mut ctx: CommandExecuteContext<'_>) {
if ctx.player.worldedit_undo.is_empty() {
ctx.player
.send_error_message("There is nothing left to undo.");
return;
}
let undo = ctx.player.worldedit_undo.pop().unwrap();
if undo.plot_x != ctx.plot.x || undo.plot_z != ctx.plot.z {
ctx.player
.send_error_message("Cannot undo outside of your current plot.");
return;
}
let redo = WorldEditUndo {
clipboards: undo
.clipboards
.iter()
.map(|clipboard| {
let first_pos = BlockPos {
x: undo.pos.x - clipboard.offset_x,
y: undo.pos.y - clipboard.offset_y,
z: undo.pos.z - clipboard.offset_z,
};
let second_pos = BlockPos {
x: first_pos.x + clipboard.size_x as i32 - 1,
y: first_pos.y + clipboard.size_y as i32 - 1,
z: first_pos.z + clipboard.size_z as i32 - 1,
};
create_clipboard(&mut ctx.plot, undo.pos, first_pos, second_pos)
})
.collect(),
..undo
};
for clipboard in &undo.clipboards {
paste_clipboard(ctx.plot, clipboard, undo.pos, false);
}
ctx.player.worldedit_redo.push(redo);
}
fn execute_redo(mut ctx: CommandExecuteContext<'_>) {
if ctx.player.worldedit_redo.is_empty() {
ctx.player
.send_error_message("There is nothing left to redo.");
return;
}
let redo = ctx.player.worldedit_redo.pop().unwrap();
if redo.plot_x != ctx.plot.x || redo.plot_z != ctx.plot.z {
ctx.player
.send_error_message("Cannot redo outside of your current plot.");
return;
}
let undo = WorldEditUndo {
clipboards: redo
.clipboards
.iter()
.map(|clipboard| {
let first_pos = BlockPos {
x: redo.pos.x - clipboard.offset_x,
y: redo.pos.y - clipboard.offset_y,
z: redo.pos.z - clipboard.offset_z,
};
let second_pos = BlockPos {
x: first_pos.x + clipboard.size_x as i32 - 1,
y: first_pos.y + clipboard.size_y as i32 - 1,
z: first_pos.z + clipboard.size_z as i32 - 1,
};
create_clipboard(&mut ctx.plot, redo.pos, first_pos, second_pos)
})
.collect(),
..redo
};
for clipboard in &redo.clipboards {
paste_clipboard(ctx.plot, clipboard, redo.pos, false);
}
ctx.player.worldedit_undo.push(undo);
}
fn execute_sel(ctx: CommandExecuteContext<'_>) {
let player = ctx.player;
player.first_position = None;
player.second_position = None;
player.send_worldedit_message("Selection cleared.");
player.worldedit_send_cui("s|cuboid");
}
fn execute_pos1(ctx: CommandExecuteContext<'_>) {
let pos = ctx.player.pos.block_pos();
ctx.player.worldedit_set_first_position(pos);
}
fn execute_pos2(ctx: CommandExecuteContext<'_>) {
let pos = ctx.player.pos.block_pos();
ctx.player.worldedit_set_second_position(pos);
}
fn execute_hpos1(mut ctx: CommandExecuteContext<'_>) {
let player = &mut ctx.player;
let pitch = player.pitch as f64;
let yaw = player.yaw as f64;
let result = ray_trace_block(ctx.plot, player.pos, pitch, yaw, 300.0);
let player = ctx.player;
match result {
Some(pos) => player.worldedit_set_first_position(pos),
None => player.send_error_message("No block in sight!"),
}
}
fn execute_hpos2(mut ctx: CommandExecuteContext<'_>) {
let player = &mut ctx.player;
let pitch = player.pitch as f64;
let yaw = player.yaw as f64;
let result = ray_trace_block(ctx.plot, player.pos, pitch, yaw, 300.0);
let player = &mut ctx.player;
match result {
Some(pos) => player.worldedit_set_second_position(pos),
None => player.send_error_message("No block in sight!"),
}
}
fn expand_selection(player: &mut Player, amount: BlockPos, contract: bool) {
let mut p1 = player.first_position.unwrap();
let mut p2 = player.second_position.unwrap();
fn get_pos_axis(pos: &mut BlockPos, axis: u8) -> &mut i32 {
match axis {
0 => &mut pos.x,
1 => &mut pos.y,
2 => &mut pos.z,
_ => unreachable!(),
}
}
let mut expand_axis = |axis: u8| {
let amount = *get_pos_axis(&mut amount.clone(), axis);
let p1 = get_pos_axis(&mut p1, axis);
let p2 = get_pos_axis(&mut p2, axis);
#[allow(clippy::comparison_chain)]
if amount > 0 {
if (p1 > p2) ^ contract {
*p1 += amount;
} else {
*p2 += amount;
}
} else if amount < 0 {
if (p1 < p2) ^ contract {
*p1 += amount;
} else {
*p2 += amount;
}
}
};
for axis in 0..=2 {
expand_axis(axis);
}
if Some(p1) != player.first_position {
player.worldedit_set_first_position(p1);
}
if Some(p2) != player.second_position {
player.worldedit_set_second_position(p2);
}
}
fn execute_expand(ctx: CommandExecuteContext<'_>) {
let amount = ctx.arguments[0].unwrap_uint();
let direction = ctx.arguments[1].unwrap_direction();
let player = ctx.player;
expand_selection(
player,
direction.offset_pos(BlockPos::zero(), amount as i32),
false,
);
player.send_worldedit_message(&format!("Region expanded {} block(s).", amount));
}
fn execute_contract(ctx: CommandExecuteContext<'_>) {
let amount = ctx.arguments[0].unwrap_uint();
let direction = ctx.arguments[1].unwrap_direction();
let player = ctx.player;
expand_selection(
player,
direction.offset_pos(BlockPos::zero(), amount as i32),
true,
);
player.send_worldedit_message(&format!("Region contracted {} block(s).", amount));
}
fn execute_shift(ctx: CommandExecuteContext<'_>) {
let amount = ctx.arguments[0].unwrap_uint();
let direction = ctx.arguments[1].unwrap_direction();
let player = ctx.player;
let first_pos = player.first_position.unwrap();
let second_pos = player.second_position.unwrap();
let mut move_both_points = |x, y, z| {
player.worldedit_set_first_position(BlockPos::new(
first_pos.x + x,
first_pos.y + y,
first_pos.z + z,
));
player.worldedit_set_second_position(BlockPos::new(
second_pos.x + x,
second_pos.y + y,
second_pos.z + z,
));
};
match direction {
BlockFacing::Up => move_both_points(0, amount as i32, 0),
BlockFacing::Down => move_both_points(0, -(amount as i32), 0),
BlockFacing::East => move_both_points(amount as i32, 0, 0),
BlockFacing::West => move_both_points(-(amount as i32), 0, 0),
BlockFacing::South => move_both_points(0, 0, amount as i32),
BlockFacing::North => move_both_points(0, 0, -(amount as i32)),
}
player.send_worldedit_message(&format!("Region shifted {} block(s).", amount));
}
fn execute_flip(mut ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let direction = ctx.arguments[0].unwrap_direction();
let clipboard = ctx.player.worldedit_clipboard.as_ref().unwrap();
let size_x = clipboard.size_x;
let size_y = clipboard.size_y;
let size_z = clipboard.size_z;
let volume = size_x * size_y * size_z;
let flip_pos = |mut pos: BlockPos| {
match direction {
BlockFacing::East | BlockFacing::West => pos.x = size_x as i32 - 1 - pos.x,
BlockFacing::North | BlockFacing::South => pos.z = size_z as i32 - 1 - pos.z,
BlockFacing::Up | BlockFacing::Down => pos.y = size_y as i32 - 1 - pos.y,
}
pos
};
let mut newcpdata = PalettedBitBuffer::with_entries((volume) as usize);
let mut c_x = 0;
let mut c_y = 0;
let mut c_z = 0;
for i in 0..volume {
let BlockPos {
x: n_x,
y: n_y,
z: n_z,
} = flip_pos(BlockPos::new(c_x, c_y, c_z));
let n_i = (n_y as u32 * size_x * size_z) + (n_z as u32 * size_x) + n_x as u32;
let mut block = Block::from_id(clipboard.data.get_entry(i as usize));
match direction {
BlockFacing::East | BlockFacing::West => block.flip(FlipDirection::FlipX),
BlockFacing::North | BlockFacing::South => block.flip(FlipDirection::FlipZ),
_ => {}
}
newcpdata.set_entry(n_i as usize, block.get_id());
// Ok now lets increment the coordinates for the next block
c_x += 1;
if c_x as u32 == size_x {
c_x = 0;
c_z += 1;
if c_z as u32 == size_z {
c_z = 0;
c_y += 1;
}
}
}
let offset = flip_pos(BlockPos::new(
clipboard.offset_x,
clipboard.offset_y,
clipboard.offset_z,
));
let cb = WorldEditClipboard {
offset_x: offset.x,
offset_y: offset.y,
offset_z: offset.z,
size_x,
size_y,
size_z,
data: newcpdata,
block_entities: clipboard
.block_entities
.iter()
.map(|(pos, e)| (flip_pos(*pos), e.clone()))
.collect(),
};
ctx.player.worldedit_clipboard = Some(cb);
ctx.player.send_worldedit_message(&format!(
"The clipboard copy has been flipped. ({:?})",
start_time.elapsed()
));
}
fn execute_rotate(mut ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let rotate_amt = ctx.arguments[0].unwrap_uint();
let rotate_amt = match rotate_amt % 360 {
0 => {
ctx.player
.send_worldedit_message("Successfully rotated by 0! That took a lot of work.");
return;
}
90 => RotateAmt::Rotate90,
180 => RotateAmt::Rotate180,
270 => RotateAmt::Rotate270,
_ => {
ctx.player
.send_error_message("Rotate amount must be a multiple of 90.");
return;
}
};
let clipboard = ctx.player.worldedit_clipboard.as_ref().unwrap();
let size_x = clipboard.size_x;
let size_y = clipboard.size_y;
let size_z = clipboard.size_z;
let volume = size_x * size_y * size_z;
let (n_size_x, n_size_z) = match rotate_amt {
RotateAmt::Rotate90 | RotateAmt::Rotate270 => (size_z, size_x),
_ => (size_x, size_z),
};
let rotate_pos = |pos: BlockPos| match rotate_amt {
RotateAmt::Rotate90 => BlockPos {
x: n_size_x as i32 - 1 - pos.z,
y: pos.y,
z: pos.x,
},
RotateAmt::Rotate180 => BlockPos {
x: n_size_x as i32 - 1 - pos.x,
y: pos.y,
z: n_size_z as i32 - 1 - pos.z,
},
RotateAmt::Rotate270 => BlockPos {
x: pos.z,
y: pos.y,
z: n_size_z as i32 - 1 - pos.x,
},
};
let mut newcpdata = PalettedBitBuffer::with_entries((volume) as usize);
let mut c_x = 0;
let mut c_y = 0;
let mut c_z = 0;
for i in 0..volume {
let BlockPos {
x: n_x,
y: n_y,
z: n_z,
} = rotate_pos(BlockPos::new(c_x, c_y, c_z));
let n_i = (n_y as u32 * n_size_x * n_size_z) + (n_z as u32 * n_size_x) + n_x as u32;
let mut block = Block::from_id(clipboard.data.get_entry(i as usize));
block.rotate(rotate_amt);
newcpdata.set_entry(n_i as usize, block.get_id());
// Ok now lets increment the coordinates for the next block
c_x += 1;
if c_x as u32 == size_x {
c_x = 0;
c_z += 1;
if c_z as u32 == size_z {
c_z = 0;
c_y += 1;
}
}
}
let offset = rotate_pos(BlockPos::new(
clipboard.offset_x,
clipboard.offset_y,
clipboard.offset_z,
));
let cb = WorldEditClipboard {
offset_x: offset.x,
offset_y: offset.y,
offset_z: offset.z,
size_x: n_size_x,
size_y,
size_z: n_size_z,
data: newcpdata,
block_entities: clipboard
.block_entities
.iter()
.map(|(pos, e)| (rotate_pos(*pos), e.clone()))
.collect(),
};
ctx.player.worldedit_clipboard = Some(cb);
ctx.player.send_worldedit_message(&format!(
"The clipboard copy has been rotated. ({:?})",
start_time.elapsed()
));
}
fn execute_help(mut ctx: CommandExecuteContext<'_>) {
let command_name = ctx.arguments[0].unwrap_string().clone();
let slash_command_name = "/".to_owned() + &command_name;
let player = &mut ctx.player;
let maybe_command = COMMANDS
.get(command_name.as_str())
.or_else(|| COMMANDS.get(slash_command_name.as_str()));
let command = match maybe_command {
Some(command) => command,
None => {
player.send_error_message(&format!("Unknown command: {}", command_name));
return;
}
};
let mut message = vec![
ChatComponentBuilder::new("--------------".to_owned())
.color_code(ColorCode::Yellow)
.strikethrough(true)
.finish(),
ChatComponentBuilder::new(format!(" Help for /{} ", command_name)).finish(),
ChatComponentBuilder::new("--------------\n".to_owned())
.color_code(ColorCode::Yellow)
.strikethrough(true)
.finish(),
ChatComponentBuilder::new(command.description.to_owned())
.color_code(ColorCode::Gray)
.finish(),
ChatComponentBuilder::new("\nUsage: ".to_owned())
.color_code(ColorCode::Gray)
.finish(),
ChatComponentBuilder::new(format!("/{}", command_name))
.color_code(ColorCode::Gold)
.finish(),
];
for arg in command.arguments {
message.append(&mut vec![
ChatComponentBuilder::new(" [".to_owned())
.color_code(ColorCode::Yellow)
.finish(),
ChatComponentBuilder::new(arg.name.to_owned())
.color_code(ColorCode::Gold)
.finish(),
ChatComponentBuilder::new("]".to_owned())
.color_code(ColorCode::Yellow)
.finish(),
]);
}
message.push(
ChatComponentBuilder::new("\nArguments:".to_owned())
.color_code(ColorCode::Gray)
.finish(),
);
for arg in command.arguments {
message.append(&mut vec![
ChatComponentBuilder::new("\n [".to_owned())
.color_code(ColorCode::Yellow)
.finish(),
ChatComponentBuilder::new(arg.name.to_owned())
.color_code(ColorCode::Gold)
.finish(),
ChatComponentBuilder::new("]".to_owned())
.color_code(ColorCode::Yellow)
.finish(),
]);
let default = if let Some(arg) = &arg.default {
match arg {
Argument::UnsignedInteger(int) => Some(int.to_string()),
_ => None,
}
} else {
match arg.argument_type {
ArgumentType::Direction | ArgumentType::DirectionVector => Some("me".to_string()),
ArgumentType::UnsignedInteger => Some("1".to_string()),
_ => None,
}
};
if let Some(default) = default {
message.push(
ChatComponentBuilder::new(format!(" (defaults to {})", default))
.color_code(ColorCode::Gray)
.finish(),
);
}
message.push(
ChatComponentBuilder::new(format!(": {}", arg.description))
.color_code(ColorCode::Gray)
.finish(),
);
}
if !command.flags.is_empty() {
message.push(
ChatComponentBuilder::new("\nFlags:".to_owned())
.color_code(ColorCode::Gray)
.finish(),
);
for flag in command.flags {
message.append(&mut vec![
ChatComponentBuilder::new(format!("\n -{}", flag.letter))
.color_code(ColorCode::Gold)
.finish(),
ChatComponentBuilder::new(format!(": {}", flag.description))
.color_code(ColorCode::Gray)
.finish(),
]);
}
}
player.send_chat_message(0, &message);
}
fn execute_up(ctx: CommandExecuteContext<'_>) {
let distance = ctx.arguments[0].unwrap_uint();
let player = ctx.player;
let mut pos = player.pos;
pos.y += distance as f64;
let block_pos = pos.block_pos();
let platform_pos = block_pos.offset(BlockFace::Bottom);
if matches!(ctx.plot.get_block(platform_pos), Block::Air {}) {
ctx.plot.set_block(platform_pos, Block::Glass {});
}
player.teleport(pos);
}
fn execute_rstack(ctx: CommandExecuteContext<'_>) {
let start_time = Instant::now();
let stack_amt = ctx.arguments[0].unwrap_uint();
let stack_spacing = ctx.arguments[1].unwrap_uint();
let direction = ctx.arguments[2].unwrap_direction_vec();
let pos1 = ctx.player.first_position.unwrap();
let pos2 = ctx.player.second_position.unwrap();
let clipboard = create_clipboard(ctx.plot, pos1, pos1, pos2);
let mut undo_cbs = Vec::new();
for i in 1..stack_amt + 1 {
let offset = (i * stack_spacing) as i32;
let block_pos = pos1 + direction * offset;
undo_cbs.push(create_clipboard(
ctx.plot,
pos1,
block_pos,
pos2 + direction * offset,
));
paste_clipboard(ctx.plot, &clipboard, block_pos, !ctx.has_flag('a'));
}
let undo = WorldEditUndo {
clipboards: undo_cbs,
pos: pos1,
plot_x: ctx.plot.x,
plot_z: ctx.plot.z,
};
if ctx.has_flag('e') {
expand_selection(
ctx.player,
direction * (stack_amt * stack_spacing) as i32,
false,
);
}
let player = ctx.player;
player.worldedit_undo.push(undo);
player.send_worldedit_message(&format!(
"Your selection was stacked successfully. ({:?})",
start_time.elapsed()
));
}
fn execute_unimplemented(_ctx: CommandExecuteContext<'_>) {
unimplemented!("Unimplimented worldedit command");
}
|
//! tests/health_check.rs
use std::{net::TcpListener};
fn spawn_app() -> String {
// let server = zero2prod::run("127.0.0.1:0").expect("Failed to bind address");
// let _ = tokio::spawn(server);
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
// we retrieve the port assigned to us by the OS
let port = listener.local_addr().unwrap().port();
let server = zero2prod::run(listener).expect("Failed to bind address");
let _ = tokio::spawn(server);
// we return the application address to the caller!
format!("http://127.0.0.1:{}", port)
}
// use zero2prod::main;
#[tokio::test]
async fn health_check_works() {
// Arrange
let address = spawn_app();
// We need to bring in 'reqwest'
// to perform HTTP requests against our application
let client = reqwest::Client::new();
// Act
let response = client
.get(&format!("{}/health_check", &address))
.send()
.await
.expect("Failed to execute request.");
// Assert
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}
|
use crate::{BoxFuture, Result};
pub trait AsyncTryFrom<'a, T>: Sized {
fn async_try_from(t: T) -> BoxFuture<'a, Result<Self>>;
}
|
use byteorder::{LittleEndian, WriteBytesExt};
use failure::{format_err, Error};
use crate::model::{owned::OwnedBuf, TableType};
mod configuration;
mod entry;
pub use self::{
configuration::ConfigurationBuf,
entry::{ComplexEntry, Entry, EntryHeader, SimpleEntry},
};
#[derive(Debug)]
pub struct TableTypeBuf {
id: u8,
config: ConfigurationBuf,
entries: Vec<Entry>,
}
impl TableTypeBuf {
pub fn new(id: u8, config: ConfigurationBuf) -> Self {
Self {
id,
config,
entries: Vec::new(),
}
}
pub fn add_entry(&mut self, entry: Entry) {
self.entries.push(entry);
}
}
impl OwnedBuf for TableTypeBuf {
fn get_token(&self) -> u16 {
0x201
}
fn get_body_data(&self) -> Result<Vec<u8>, Error> {
let mut out = Vec::new();
let mut i = 0;
let mut entries_body = Vec::new();
for e in &self.entries {
let current_entry = e.to_vec()?;
if e.is_empty() {
out.write_u32::<LittleEndian>(0xFFFF_FFFF)?;
} else {
out.write_u32::<LittleEndian>(i)?;
i += current_entry.len() as u32;
}
entries_body.extend(¤t_entry);
}
out.extend(&entries_body);
Ok(out)
}
fn get_header(&self) -> Result<Vec<u8>, Error> {
let mut out = Vec::new();
let vec_config = self.config.to_vec()?;
let header_size = (5 * 4) + vec_config.len() as u32;
out.write_u32::<LittleEndian>(u32::from(self.id))?;
out.write_u32::<LittleEndian>(self.entries.len() as u32)?;
out.write_u32::<LittleEndian>(header_size + (self.entries.len() as u32 * 4))?;
out.extend(&vec_config);
Ok(out)
}
}
impl TableType for TableTypeBuf {
type Configuration = ConfigurationBuf;
fn get_id(&self) -> Result<u8, Error> {
Ok(self.id)
}
fn get_amount(&self) -> Result<u32, Error> {
Ok(self.entries.len() as u32)
}
fn get_configuration(&self) -> Result<Self::Configuration, Error> {
Ok(self.config.clone())
}
fn get_entry(&self, index: u32) -> Result<Entry, Error> {
self.entries
.get(index as usize)
.cloned()
.ok_or_else(|| format_err!("entry out of bound"))
}
}
#[cfg(test)]
mod tests {
use super::{ComplexEntry, ConfigurationBuf, Entry, SimpleEntry, TableTypeBuf};
use crate::{
chunks::TableTypeWrapper,
model::{owned::OwnedBuf, TableType},
raw_chunks,
test::compare_chunks,
};
#[test]
fn it_can_generate_a_chunk_with_the_given_data() {
let mut table_type = TableTypeBuf::new(5, ConfigurationBuf::default());
let entry = Entry::Simple(SimpleEntry::new(1, 2, 3, 4));
let sub_entry = SimpleEntry::new(5, 6, 7, 8);
let sub_entry2 = SimpleEntry::new(9, 0, 1, 2);
let entry2 = Entry::Complex(ComplexEntry::new(10, 11, 12, vec![sub_entry, sub_entry2]));
let entry3 = Entry::Simple(SimpleEntry::new(20, 21, 22, 23));
table_type.add_entry(entry);
table_type.add_entry(entry2);
table_type.add_entry(entry3);
assert_eq!(5, table_type.get_id().unwrap());
assert_eq!(3, table_type.get_amount().unwrap());
assert_eq!(
10,
table_type.get_entry(1).unwrap().complex().unwrap().get_id()
)
}
#[test]
fn identity() {
let wrapper = TableTypeWrapper::new(raw_chunks::EXAMPLE_TABLE_TYPE, 68);
let _ = wrapper.get_entries();
let owned = wrapper.to_buffer().unwrap();
let new_raw = owned.to_vec().unwrap();
compare_chunks(&new_raw, &raw_chunks::EXAMPLE_TABLE_TYPE);
}
#[test]
fn identity_with_mixed_complex_and_simple_entries() {
let wrapper = TableTypeWrapper::new(raw_chunks::EXAMPLE_TABLE_TYPE_WITH_COMPLEX, 76);
let _ = wrapper.get_entries();
let owned = wrapper.to_buffer().unwrap();
let new_raw = owned.to_vec().unwrap();
compare_chunks(&new_raw, &raw_chunks::EXAMPLE_TABLE_TYPE_WITH_COMPLEX);
}
}
|
extern crate clap;
#[macro_use]
extern crate lazy_static;
mod lexer;
use clap::{App, Arg};
use lexer::Scanner;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, Read};
fn main() {
let matches = App::new("Lox")
.version("0.1")
.about("A programming language")
.arg(
Arg::with_name("script")
.help("A lox script to be executed")
.index(1),
)
.get_matches();
if let Some(s) = matches.value_of("script") {
match run_file(s) {
Ok(()) => println!(),
Err(e) => println!("Error while running script \"{}\": {}", s, e),
}
} else {
match run_prompt() {
Ok(()) => (),
Err(e) => println!("Error in interpreter: {}", e),
}
}
}
fn run_file(path: &str) -> std::io::Result<()> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
run(&contents)
}
fn run_prompt() -> std::io::Result<()> {
print!("> ");
io::stdout().flush()?;
let stdin = io::stdin();
let iterator = stdin.lock().lines();
for line in iterator {
match line {
Ok(l) => run(&l)?,
Err(e) => {
return Err(e);
}
}
print!("> ");
io::stdout().flush()?;
}
Ok(())
}
fn run(program: &str) -> std::io::Result<()> {
println!("-- {}", program);
// Scanner scans program into tokens
let mut scanner = Scanner::from_source(program);
let tokens = scanner.scan_tokens();
// For now, print the tokens
for token in tokens.iter() {
println!("{:?}", token);
}
Ok(())
}
|
use std::io::Error;
use std::net::{SocketAddr, ToSocketAddrs, TcpStream};
use std::time::{Duration, Instant};
use rayon::prelude::*;
use sealpir::client::PirClient;
use sealpir::PirReply;
use raidpir::client::RaidPirClient;
use raidpir::types::RaidPirData;
use hybridpir::client::HybridPirClient;
use hybridpir::types::*;
use log::*;
const NUM_SERVERS: usize = 2;
const QUEUE_SIZE: usize = 32;
const N: usize = 50;
const DEFAULT_SEALPIR: BenchmarkParams = BenchmarkParams::SealPir {
db_size: 1 << 14,
element_size: 1 << 4,
poly_degree: 2048,
log: 12,
d: 2
};
const DEFAULT_RAIDPIR: BenchmarkParams = BenchmarkParams::RaidPir {
db_size: 1 << 14,
element_size: 1 << 4,
servers: 2,
redundancy: 2,
russians: false
};
const DEFAULT_HYBRIDPIR: BenchmarkParams = BenchmarkParams::HybridPir {
db_size: 1 << 14,
element_size: 1 << 4,
raidpir_servers: 2,
raidpir_redundancy: 2,
raidpir_size: 1 << 10,
raidpir_russians: false,
sealpir_poly_degree: 2048,
sealpir_log: 24,
sealpir_d: 1,
};
fn run_query(streams: &mut Vec<TcpStream>, params: &BenchmarkParams) -> Result<(), Error> {
match params {
BenchmarkParams::SealPir {
db_size,
element_size,
poly_degree,
log,
d
} => {
let index = (db_size >> 1) as u32;
let client = PirClient::new(
*db_size as u32,
*element_size as u32,
*poly_degree,
*log,
*d
);
let key = client.get_key().clone();
let t = std::time::Instant::now();
let query = client.gen_query(index);
debug!("Query size: {:?}", query.query.len());
debug!("Query time: {:?}", t.elapsed().as_secs_f64() * 1000.0);
let msg = BenchmarkMessage::Protocol(ProtocolMessage::SealPir(SealPirMessage::Query(key, query)));
msg.write_to(&mut streams[0])?;
let response = BenchmarkMessage::read_from(&mut streams[0])?;
if let BenchmarkMessage::Protocol(ProtocolMessage::SealPir(SealPirMessage::Response(reply))) = response {
debug!("Response size: {:?}", reply.reply.len());
let t = std::time::Instant::now();
client.decode_reply(index, &reply);
debug!("Decode time: {:?}", t.elapsed().as_secs_f64() * 1000.0);
} else {
unreachable!();
}
},
BenchmarkParams::RaidPir {
db_size,
element_size: _,
servers,
redundancy,
russians: _
} => {
let index = db_size >> 1;
let seeds = streams
.par_iter()
.map(|ref mut stream| {
BenchmarkMessage::Protocol(ProtocolMessage::RaidPir(RaidPirMessage::Hello)).write_to(stream)?;
let response = BenchmarkMessage::read_from(stream)?;
if let BenchmarkMessage::Protocol(ProtocolMessage::RaidPir(RaidPirMessage::Seed(seed))) = response {
Ok(seed)
} else {
unreachable!();
}
})
.with_max_len(1)
.collect::<Result<Vec<u128>, Error>>()?;
let client = RaidPirClient::new(*db_size, *servers, *redundancy);
let t = std::time::Instant::now();
let queries = client.query(index, &seeds);
debug!("Query size: {:?}", queries[0].len());
debug!("Query time: {:?}", t.elapsed().as_secs_f64() * 1000.0);
let responses = streams
.par_iter()
.zip(queries.par_iter())
.map(|(ref mut stream, query)| {
BenchmarkMessage::Protocol(ProtocolMessage::RaidPir(RaidPirMessage::Query(query.clone().into_vec()))).write_to(stream)?;
let response = BenchmarkMessage::read_from(stream)?;
if let BenchmarkMessage::Protocol(ProtocolMessage::RaidPir(RaidPirMessage::Response(resp))) = response {
Ok(resp)
} else {
unreachable!();
}
})
.with_max_len(1)
.collect::<Result<Vec<Vec<u8>>, Error>>()?;
debug!("Response size: {:?}", responses[0].len());
let t = std::time::Instant::now();
client.combine(responses.into_iter().map(|r| RaidPirData::new(r)).collect());
debug!("Decode time: {:?}", t.elapsed().as_secs_f64() * 1000.0);
},
BenchmarkParams::HybridPir {
db_size,
element_size,
raidpir_servers,
raidpir_redundancy,
raidpir_size,
raidpir_russians: _,
sealpir_poly_degree,
sealpir_log,
sealpir_d
} => {
let index = db_size >> 1;
let seeds = streams
.par_iter()
.map(|ref mut stream| {
BenchmarkMessage::Protocol(ProtocolMessage::HybridPir(HybridPirMessage::Hello)).write_to(stream)?;
let response = BenchmarkMessage::read_from(stream)?;
if let BenchmarkMessage::Protocol(ProtocolMessage::HybridPir(HybridPirMessage::Seed(seed))) = response {
Ok(seed)
} else {
unreachable!();
}
})
.with_max_len(1)
.collect::<Result<Vec<u128>, Error>>()?;
let client = HybridPirClient::new(
*db_size,
*element_size,
*raidpir_servers,
*raidpir_redundancy,
*raidpir_size,
*sealpir_poly_degree,
*sealpir_log,
*sealpir_d
);
let sealpir_key = client.sealpir_key();
let t = std::time::Instant::now();
let (raidpir_queries, sealpir_query) = client.query(index, &seeds);
debug!("Query size: {:?} (SealPIR)", sealpir_query.query.len());
debug!("Query size: {:?} (RaidPIR)", raidpir_queries[0].len());
debug!("Query time: {:?}", t.elapsed().as_secs_f64() * 1000.0);
let responses = streams
.par_iter()
.zip(raidpir_queries.par_iter())
.map(|(ref mut stream, raidpir_query)| {
BenchmarkMessage::Protocol(ProtocolMessage::HybridPir(HybridPirMessage::Query(
raidpir_query.clone().into_vec(),
sealpir_key.clone(),
sealpir_query.clone()
))).write_to(stream)?;
let response = BenchmarkMessage::read_from(stream)?;
if let BenchmarkMessage::Protocol(ProtocolMessage::HybridPir(HybridPirMessage::Response(resp))) = response {
Ok(resp)
} else {
unreachable!();
}
})
.with_max_len(1)
.collect::<Result<Vec<PirReply>, Error>>()?;
debug!("Response size: {:?}", responses[0].reply.len());
let t = std::time::Instant::now();
client.combine(index, responses);
debug!("Decode time: {:?}", t.elapsed().as_secs_f64() * 1000.0);
},
}
Ok(())
}
fn run_series(streams: &mut Vec<TcpStream>, params: BenchmarkParams, iterations: usize) -> Result<f64, Error> {
streams
.par_iter()
.map(|ref mut stream| {
let msg = BenchmarkMessage::Setup(params.clone());
msg.write_to(stream)?;
BenchmarkMessage::read_from(stream)?;
Ok(())
})
.with_max_len(1)
.collect::<Result<(), Error>>()?;
let mut times: Vec<f64> = Vec::with_capacity(iterations);
for i in 0..iterations {
if i % QUEUE_SIZE == 0 {
streams.par_iter()
.map(|ref mut stream| {
let msg = BenchmarkMessage::RefreshQueue;
msg.write_to(stream)?;
BenchmarkMessage::read_from(stream)?;
Ok(())
})
.with_max_len(1)
.collect::<Result<(), Error>>()?;
}
let t = Instant::now();
run_query(streams, ¶ms)?;
let elapsed = t.elapsed().as_secs_f64() * 1000.0;
times.push(elapsed);
}
times.sort_by(|a, b| a.partial_cmp(b).unwrap());
let mean = times.iter().fold(0.0, |sum, val| sum + val) / (iterations as f64);
eprintln!("min: {:?}, mean: {:?}, max: {:?}", times[0], mean, times[iterations - 1]);
Ok(mean)
}
fn run_different_element_counts(streams: &mut Vec<TcpStream>, ns: &Vec<usize>, s: usize, b: usize) {
println!("n;raidpir;sealpir;hybridpir");
for n in ns.iter() {
eprintln!("{:?}", n);
let mut params_raidpir = DEFAULT_RAIDPIR.clone();
if let BenchmarkParams::RaidPir{
ref mut db_size,
ref mut element_size,
servers: _,
redundancy: _,
russians: _
} = params_raidpir {
*db_size = *n;
*element_size = s;
}
let time_raidpir = run_series(streams, params_raidpir, N).unwrap();
//let time_raidpir = 0;
let mut params_sealpir = DEFAULT_SEALPIR.clone();
if let BenchmarkParams::SealPir{
ref mut db_size,
ref mut element_size,
poly_degree: _,
log: _,
d: _
} = params_sealpir {
*db_size = *n;
*element_size = s;
}
let time_sealpir = run_series(streams, params_sealpir, N).unwrap();
//let time_sealpir = 0;
if (*n / b) >= 2 * 8 {
let mut params_hybridpir = DEFAULT_HYBRIDPIR.clone();
if let BenchmarkParams::HybridPir{
ref mut db_size,
ref mut element_size,
raidpir_servers: _,
raidpir_redundancy: _,
ref mut raidpir_size,
raidpir_russians: _,
sealpir_poly_degree: _,
sealpir_log: _,
sealpir_d: _,
} = params_hybridpir {
*db_size = *n;
*element_size = s;
*raidpir_size = n / b;
}
let time_hybridpir = run_series(streams, params_hybridpir, N).unwrap();
println!("{:?};{:?};{:?};{:?}", n, time_raidpir, time_sealpir, time_hybridpir);
} else {
println!("{:?};{:?};{:?};", n, time_raidpir, time_sealpir);
}
}
}
fn run_different_shapes(streams: &mut Vec<TcpStream>, element_sizes: &Vec<usize>, total: usize, b: usize) {
println!("s;raidpir;sealpir;hybridpir");
for s in element_sizes.iter() {
eprintln!("{:?}", s);
let mut params_raidpir = DEFAULT_RAIDPIR.clone();
if let BenchmarkParams::RaidPir{
ref mut db_size,
ref mut element_size,
servers: _,
redundancy: _,
russians: _
} = params_raidpir {
*db_size = total / *s;
*element_size = *s;
}
let time_raidpir = run_series(streams, params_raidpir, N).unwrap();
//let time_raidpir = 0;
let mut params_sealpir = DEFAULT_SEALPIR.clone();
if let BenchmarkParams::SealPir{
ref mut db_size,
ref mut element_size,
poly_degree: _,
log: _,
d: _
} = params_sealpir {
*db_size = total / *s;
*element_size = *s;
}
let time_sealpir = run_series(streams, params_sealpir, N).unwrap();
//let time_sealpir = 0;
if ((total / *s) / b) >= 2 * 8 {
//if false {
let mut params_hybridpir = DEFAULT_HYBRIDPIR.clone();
if let BenchmarkParams::HybridPir{
ref mut db_size,
ref mut element_size,
raidpir_servers: _,
raidpir_redundancy: _,
ref mut raidpir_size,
raidpir_russians: _,
sealpir_poly_degree: _,
sealpir_log: _,
sealpir_d: _,
} = params_hybridpir {
*db_size = total / *s;
*element_size = *s;
*raidpir_size = (total / *s) / b;
}
let time_hybridpir = run_series(streams, params_hybridpir, N).unwrap();
println!("{:?};{:?};{:?};{:?}", s, time_raidpir, time_sealpir, time_hybridpir);
} else {
println!("{:?};{:?};{:?};", s, time_raidpir, time_sealpir);
}
}
}
fn run_benchmarks(mut streams: Vec<TcpStream>) -> Result<(), Error> {
// Benchmarks at different numbers of elements at the same size
let ns: Vec<usize> = (10..30).step_by(2).map(|x| 1 << x).collect();
//run_different_element_counts(&mut streams, &ns, 4, 1024);
//run_different_element_counts(&mut streams, &ns, 4, 2048);
//run_different_element_counts(&mut streams, &ns, 1024, 64);
let ss: Vec<usize> = (2..22).step_by(2).map(|x| 1 << x).collect();
//run_different_shapes(&mut streams, &ss, 1 << 33, 32);
//run_different_shapes(&mut streams, &ss, 1 << 33, 128);
//run_different_shapes(&mut streams, &ss, 1 << 33, 512);
//run_different_shapes(&mut streams, &ss, 1 << 33, 2048);
// PEM (100K,1M, 10M users, eps=100)
let ns: Vec<usize> = [10027008, 100007936, 1000013824].to_vec();
//run_different_element_counts(&mut streams, &ns, 4, 2048);
Ok(())
}
fn main() {
env_logger::init();
let mut servers: Vec<SocketAddr> = Vec::with_capacity(NUM_SERVERS);
for i in 0..NUM_SERVERS {
let arg = std::env::args().nth(i+1).unwrap();
let split: Vec<&str> = arg.split(":").collect();
let addr = (split[0], split[1].parse::<u16>().unwrap()).to_socket_addrs().unwrap().next().unwrap();
servers.push(addr);
}
let streams: Vec<TcpStream> = servers
.par_iter() // Establish connections in parallel
.map(|target| {
let stream = TcpStream::connect(target)?;
stream.set_read_timeout(Some(Duration::from_secs(3600)))?;
stream.set_write_timeout(Some(Duration::from_secs(3600)))?;
stream.set_nodelay(true);
Ok(stream)
})
.with_max_len(1) // Ensure each iteration gets a thread
.collect::<Result<Vec<TcpStream>, Error>>()
.unwrap();
if let Err(e) = run_benchmarks(streams) {
error!("{:?}", e);
}
}
|
// error-pattern:squirrelcupcake
fn cmp() -> int {
alt(option::some('a'), option::none::<char>) {
(option::some(_), _) { fail "squirrelcupcake"; }
(_, option::some(_)) { fail; }
}
}
fn main() { log(error, cmp()); }
|
//! All the logic behind the editor UI is contained within this module.
//!
//! Fundamentally, the UI is split into graphics rendering and state management in response to
//! input events, both of which are managed within the `EditorInterface` type.
use std::sync::mpsc::Receiver;
use vst_window::{EditorWindow, EventSource};
use crate::plugin_state::StateUpdate;
mod graphics;
mod state;
use super::EditorRemoteState;
pub(super) use state::InterfaceState;
/// Dimensions and layout of image assets.
mod image_consts {
/// Original horizontal dimension of the background image, in pixels.
pub const ORIG_BG_SIZE_X: usize = 1200;
/// Original vertical dimension of the background image, in pixels.
pub const ORIG_BG_SIZE_Y: usize = 800;
/// Original radius of the knob image, in pixels.
pub const ORIG_KNOB_RADIUS: usize = 200;
/// Original center x-coordinate of the knob image, in pixels.
pub const ORIG_KNOB_X: usize = 800;
/// Original center y-coordinate of the knob image, in pixels.
pub const ORIG_KNOB_Y: usize = 500;
}
/// Display scale of the entire UI.
const SCALE: f64 = 0.5;
/// Actual pixel width of the editor window.
pub(super) const SIZE_X: usize = (image_consts::ORIG_BG_SIZE_X as f64 * SCALE) as usize;
/// Actual pixel height of the editor window.
pub(super) const SIZE_Y: usize = (image_consts::ORIG_BG_SIZE_Y as f64 * SCALE) as usize;
/// Represents a window containing an editor interface. A new one is used each time the parent
/// window provided by the host DAW is opened or closed.
pub(super) struct EditorInterface {
renderer: graphics::Renderer,
event_source: EventSource,
state: InterfaceState,
}
impl EditorInterface {
/// Setup the `EditorInterface` within the provided parent `EditorWindow` to respond to events
/// from the corresponding `EventSource`.
pub fn new(
window: EditorWindow,
event_source: EventSource,
initial_state: InterfaceState,
) -> Self {
let renderer = graphics::Renderer::new(window);
Self {
renderer,
event_source,
state: initial_state,
}
}
/// Run as much as possible of the editor interface without blocking. This means acting on any
/// pending state change events from remote state storage, responding to any new window input
/// events, and then rendering the new state of the UI.
pub fn run_tasks<S: EditorRemoteState>(
&mut self,
remote_state: &S,
incoming: &mut Receiver<StateUpdate>,
) {
while let Ok(event) = incoming.try_recv() {
self.state.react_to_control_event(event);
}
while let Some(event) = self.event_source.poll_event() {
self.state.react_to_window_event(event, remote_state);
}
self.renderer.draw_frame(&self.state);
}
}
|
mod common;
use crate::common::{destroy, new, BitFlags as BF, Register, BASE_ADDR};
use embedded_hal_mock::i2c::Transaction as I2cTrans;
use hdc20xx::MeasurementMode;
#[test]
fn can_create_and_destroy() {
let sensor = new(&[]);
destroy(sensor);
}
#[test]
fn can_get_device_id() {
let dev_id = 0xABCD;
let mut sensor = new(&[I2cTrans::write_read(
BASE_ADDR,
vec![Register::DEVICE_ID_L],
vec![0xCD, 0xAB],
)]);
let id = sensor.device_id().unwrap();
assert_eq!(dev_id, id);
destroy(sensor);
}
#[test]
fn can_get_manufacturer_id() {
let manuf_id = 0xABCD;
let mut sensor = new(&[I2cTrans::write_read(
BASE_ADDR,
vec![Register::MANUFACTURER_ID_L],
vec![0xCD, 0xAB],
)]);
let id = sensor.manufacturer_id().unwrap();
assert_eq!(manuf_id, id);
destroy(sensor);
}
macro_rules! set_test {
($name:ident, $method:ident, $reg:ident, $value:expr $(, $arg:expr)*) => {
#[test]
fn $name() {
let mut sensor = new(&[I2cTrans::write(BASE_ADDR, vec![Register::$reg, $value])]);
sensor.$method($($arg),*).unwrap();
destroy(sensor);
}
};
}
set_test!(sw_reset_one_shot, software_reset, MEAS_CONF, BF::SOFT_RESET);
set_test!(
set_temp_and_humidity_mode,
set_measurement_mode,
MEAS_CONF,
0,
MeasurementMode::TemperatureAndHumidity
);
set_test!(
set_temp_only_mode,
set_measurement_mode,
MEAS_CONF,
BF::TEMP_ONLY,
MeasurementMode::TemperatureOnly
);
#[test]
fn can_make_one_shot_measurement_temp_and_humidity() {
let transactions = [
I2cTrans::write(BASE_ADDR, vec![Register::MEAS_CONF, BF::MEAS_TRIG]),
I2cTrans::write_read(BASE_ADDR, vec![Register::DRDY], vec![0]),
I2cTrans::write_read(BASE_ADDR, vec![Register::DRDY], vec![BF::DRDY_STATUS]),
I2cTrans::write_read(
BASE_ADDR,
vec![Register::TEMP_L],
vec![0xD9, 0x64, 0xEC, 0x91],
),
];
let mut sensor = new(&transactions);
sensor.read().expect_err("should block");
sensor.read().expect_err("should block");
let data = sensor.read().unwrap();
assert!(data.temperature < 25.5);
assert!(data.temperature > 24.5);
let rh = data.humidity.unwrap();
assert!(rh < 57.5);
assert!(rh > 56.5);
assert!(data.status.data_ready);
destroy(sensor);
}
#[test]
fn can_make_one_shot_measurement_temp_only() {
let transactions = [
I2cTrans::write(BASE_ADDR, vec![Register::MEAS_CONF, BF::TEMP_ONLY]),
I2cTrans::write(
BASE_ADDR,
vec![Register::MEAS_CONF, BF::TEMP_ONLY | BF::MEAS_TRIG],
),
I2cTrans::write_read(BASE_ADDR, vec![Register::DRDY], vec![0]),
I2cTrans::write_read(BASE_ADDR, vec![Register::DRDY], vec![BF::DRDY_STATUS]),
I2cTrans::write_read(BASE_ADDR, vec![Register::TEMP_L], vec![0xD9, 0x64]),
];
let mut sensor = new(&transactions);
sensor
.set_measurement_mode(MeasurementMode::TemperatureOnly)
.unwrap();
sensor.read().expect_err("should block");
sensor.read().expect_err("should block");
let data = sensor.read().unwrap();
assert!(data.temperature < 25.5);
assert!(data.temperature > 24.5);
assert!(data.humidity.is_none());
assert!(data.status.data_ready);
destroy(sensor);
}
|
mod yahoo;
use clap::{App, Arg};
use colored::*;
fn main() {
let matches = App::new("Quoter")
.about("Stock quotes on the CLI")
.arg(
Arg::with_name("symbols")
.long("symbols")
.short("s")
.multiple(true)
.takes_value(true)
.required(true)
.help("space separated list of stock symbols"),
)
.get_matches();
let symbols = matches.values_of("symbols").unwrap().collect();
let value: serde_json::Value = request(symbols).expect("failed to call Yahoo finance");
let mut typed: yahoo::QuoteResponseWrapper =
serde_json::from_value(value).expect("failed to deserialize to type");
typed
.quote_response
.result
.sort_unstable_by(|l, r| l.symbol.cmp(&r.symbol));
for result in typed.quote_response.result.iter() {
let color = get_change_color(result.regular_market_change_percent);
println!(
"{0} {1} {2}",
format!("{:<5}", result.symbol),
format!("{:>10}", format!("${:.2}", result.regular_market_price)),
format!(
"{:>10}",
format!("{:.2}%", result.regular_market_change_percent).color(color)
)
);
}
}
fn get_change_color(change: f32) -> &'static str {
if change > 0.0 {
return "green";
}
return "red";
}
fn request(symbols: Vec<&str>) -> Result<serde_json::Value, std::io::Error> {
let response = ureq::get("https://query1.finance.yahoo.com/v7/finance/quote")
.query("symbols", &symbols.join(","))
.query("fields", "regularMarketPrice,regularMarketChangePercent")
.call();
return response.into_json();
}
|
use imgui::{ImGuiStyle, ImVec2, ImVec4};
use rand::distributions::{IndependentSample, Range};
use rand;
use std::fs::File;
use std::io::Cursor;
use std::io::Read;
use show_message::UnwrapOrShow;
const FILENAME: &str = "assets/config.ron";
lazy_static! {
pub static ref CONFIG: Config = {
let file = if cfg!(feature = "packed") {
Box::new(Cursor::new(include_bytes!("../assets/config.ron").iter())) as Box<Read>
} else {
Box::new(File::open(FILENAME)
.unwrap_or_else_show(|e| format!("Failed to open config file at {}: {}", FILENAME, e)))
as Box<Read>
};
let mut config: Config = ::ron::de::from_reader(file)
.unwrap_or_else_show(|e| format!("Failed to parse config file {}: {}", FILENAME, e));
if let Ok(Ok(val)) = ::std::env::var("HYPERZEN_TRAINING_SHOW_WEAPON").map(|val| val.parse::<bool>()) {
config.player_show_weapon = val;
}
if let Ok(Ok(val)) = ::std::env::var("HYPERZEN_TRAINING_VELOCITY").map(|val| val.parse::<f32>()) {
config.player_velocity = val;
}
config
};
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Config {
pub max_distance_sound_2: f32,
pub field_of_view: f32,
pub start_color: ::graphics::Color,
pub end_color: ::graphics::Color,
pub activated_color: ::graphics::Color,
pub depth_coef_divider: f32,
pub depth_coef_velocity: f32,
pub depth_coef_min: f32,
pub ear_distance: f32,
pub pale_gen_color_division: usize,
pub pale_gen_color_black: f32,
pub pale_gen_color_white: f32,
pub pale_gen_color_delta: f32,
pub gen_color_division: usize,
pub gen_color_black: f32,
pub gen_color_white: f32,
pub gen_color_delta: f32,
pub menu_width: f32,
pub menu_height: f32,
pub font_global_scale: f32,
pub death_duration: f32,
pub hook_links: usize,
pub style: ImGuiStyleSave,
pub mouse_sensibility: f32,
pub fps: u32,
pub eraser_time: f32,
pub physic_max_step_time: f32,
pub physic_min_step_time: f32,
pub accumulated_impulse_solver_step: f32,
pub correction_mode_a: f32,
pub correction_mode_b: f32,
pub correction_mode_c: f32,
pub accumulated_impulse_solver_joint_corr_factor: f32,
pub accumulated_impulse_solver_rest_eps: f32,
pub accumulated_impulse_solver_num_first_order_iter: usize,
pub accumulated_impulse_solver_num_second_order_iter: usize,
pub avoider_size: f32,
pub avoider_velocity: f32,
pub avoider_time_to_reach_vmax: f32,
pub avoider_ang_damping: f32,
pub avoider_color: ::graphics::Color,
pub avoider_avoid_norm: f32,
pub bouncer_size: f32,
pub bouncer_velocity: f32,
pub bouncer_time_to_reach_vmax: f32,
pub bouncer_ang_damping: f32,
pub bouncer_color: ::graphics::Color,
pub motionless_size: f32,
pub motionless_density: f32,
pub motionless_color: ::graphics::Color,
pub depth_ball_size: f32,
pub depth_ball_velocity: f32,
pub depth_ball_time_to_reach_vmax: f32,
pub depth_ball_ang_damping: f32,
pub depth_ball_color: ::graphics::Color,
pub attracted_size: f32,
pub attracted_velocity: f32,
pub attracted_time_to_reach_vmax: f32,
pub attracted_ang_damping: f32,
pub attracted_color: ::graphics::Color,
pub attracted_update_time: f32,
pub avoider_generator_salvo: usize,
pub avoider_generator_eraser_probability: f32,
pub avoider_generator_time_between_salvo: f32,
pub bouncer_generator_salvo: usize,
pub bouncer_generator_eraser_probability: f32,
pub bouncer_generator_time_between_salvo: f32,
pub player_height: f32,
pub player_radius: f32,
pub player_velocity: f32,
pub player_time_to_reach_vmax: f32,
pub player_hook_velocity: f32,
pub player_hook_time_to_reach_vmax: f32,
pub player_ang_damping: f32,
pub player_gravity: f32,
pub player_hook_force: f32,
pub player_hook_color: ::graphics::Color,
pub player_hook_size: f32,
pub player_show_weapon: bool,
pub teleport_dl: f32,
pub laser_size: f32,
pub laser_velocity: f32,
pub laser_time_to_reach_vmax: f32,
pub laser_ang_damping: f32,
pub laser_amortization: f32,
pub laser_color: ::graphics::Color,
pub turret_size: f32,
pub turret_color: ::graphics::Color,
pub turret_density: f32,
pub turret_reload_time: f32,
pub wall_color: Vec<::graphics::Color>,
pub weapon_reload_time: f32,
pub weapon_bullet_nbr: usize,
pub weapon_bullet_radius: f32,
pub weapon_bullet_length: f32,
pub weapon_bullet_x: f32,
pub weapon_bullet_dx: f32,
pub weapon_bullet_color: ::graphics::Color,
pub weapon_bullet_empty_color: ::graphics::Color,
pub weapon_six_color: ::graphics::Color,
pub weapon_angle_color: ::graphics::Color,
pub weapon_light_ray_duration: f32,
pub levels: Vec<Vec<::level::Level>>,
}
impl Config {
#[inline]
pub fn dt(&self) -> f32 {
1.0 / self.fps as f32
}
pub fn random_wall_color(&self) -> ::graphics::Color {
let mut rng = rand::thread_rng();
let between = Range::new(0, self.wall_color.len());
self.wall_color[between.ind_sample(&mut rng)]
}
}
#[derive(Serialize, Deserialize)]
#[serde(remote = "ImVec2")]
pub struct ImVec2Def {
pub x: f32,
pub y: f32,
}
impl From<ImVec2Def> for ImVec2 {
fn from(def: ImVec2Def) -> Self {
ImVec2 { x: def.x, y: def.y }
}
}
#[derive(Serialize, Deserialize)]
#[serde(remote = "ImVec4")]
pub struct ImVec4Def {
pub x: f32,
pub y: f32,
pub z: f32,
pub w: f32,
}
impl From<ImVec4Def> for ImVec4 {
fn from(def: ImVec4Def) -> Self {
ImVec4 {
x: def.x,
y: def.y,
z: def.z,
w: def.w,
}
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct ImColorsSave {
#[serde(with = "ImVec4Def")] pub text: ImVec4,
#[serde(with = "ImVec4Def")] pub text_disabled: ImVec4,
#[serde(with = "ImVec4Def")] pub window_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub child_window_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub popup_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub border: ImVec4,
#[serde(with = "ImVec4Def")] pub border_shadow: ImVec4,
#[serde(with = "ImVec4Def")] pub frame_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub frame_bg_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub frame_bg_active: ImVec4,
#[serde(with = "ImVec4Def")] pub title_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub title_bg_collapsed: ImVec4,
#[serde(with = "ImVec4Def")] pub title_bg_active: ImVec4,
#[serde(with = "ImVec4Def")] pub menu_bar_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub scrollbar_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub scrollbar_grab: ImVec4,
#[serde(with = "ImVec4Def")] pub scrollbar_grab_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub scrollbar_grab_active: ImVec4,
#[serde(with = "ImVec4Def")] pub combo_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub check_mark: ImVec4,
#[serde(with = "ImVec4Def")] pub slider_grab: ImVec4,
#[serde(with = "ImVec4Def")] pub slider_grab_active: ImVec4,
#[serde(with = "ImVec4Def")] pub button: ImVec4,
#[serde(with = "ImVec4Def")] pub button_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub button_active: ImVec4,
#[serde(with = "ImVec4Def")] pub header: ImVec4,
#[serde(with = "ImVec4Def")] pub header_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub header_active: ImVec4,
#[serde(with = "ImVec4Def")] pub separator: ImVec4,
#[serde(with = "ImVec4Def")] pub separator_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub separator_active: ImVec4,
#[serde(with = "ImVec4Def")] pub resize_grip: ImVec4,
#[serde(with = "ImVec4Def")] pub resize_grip_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub resize_grip_active: ImVec4,
#[serde(with = "ImVec4Def")] pub close_button: ImVec4,
#[serde(with = "ImVec4Def")] pub close_button_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub close_button_active: ImVec4,
#[serde(with = "ImVec4Def")] pub plot_lines: ImVec4,
#[serde(with = "ImVec4Def")] pub plot_lines_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub plot_histogram: ImVec4,
#[serde(with = "ImVec4Def")] pub plot_histogram_hovered: ImVec4,
#[serde(with = "ImVec4Def")] pub text_selected_bg: ImVec4,
#[serde(with = "ImVec4Def")] pub modal_window_darkening: ImVec4,
}
impl From<ImColorsSave> for [ImVec4; 43] {
fn from(def: ImColorsSave) -> Self {
[
def.text,
def.text_disabled,
def.window_bg,
def.child_window_bg,
def.popup_bg,
def.border,
def.border_shadow,
def.frame_bg,
def.frame_bg_hovered,
def.frame_bg_active,
def.title_bg,
def.title_bg_collapsed,
def.title_bg_active,
def.menu_bar_bg,
def.scrollbar_bg,
def.scrollbar_grab,
def.scrollbar_grab_hovered,
def.scrollbar_grab_active,
def.combo_bg,
def.check_mark,
def.slider_grab,
def.slider_grab_active,
def.button,
def.button_hovered,
def.button_active,
def.header,
def.header_hovered,
def.header_active,
def.separator,
def.separator_hovered,
def.separator_active,
def.resize_grip,
def.resize_grip_hovered,
def.resize_grip_active,
def.close_button,
def.close_button_hovered,
def.close_button_active,
def.plot_lines,
def.plot_lines_hovered,
def.plot_histogram,
def.plot_histogram_hovered,
def.text_selected_bg,
def.modal_window_darkening,
]
}
}
impl From<[ImVec4; 43]> for ImColorsSave {
fn from(def: [ImVec4; 43]) -> Self {
ImColorsSave {
text: def[0],
text_disabled: def[1],
window_bg: def[2],
child_window_bg: def[3],
popup_bg: def[4],
border: def[5],
border_shadow: def[6],
frame_bg: def[7],
frame_bg_hovered: def[8],
frame_bg_active: def[9],
title_bg: def[10],
title_bg_collapsed: def[11],
title_bg_active: def[12],
menu_bar_bg: def[13],
scrollbar_bg: def[14],
scrollbar_grab: def[15],
scrollbar_grab_hovered: def[16],
scrollbar_grab_active: def[17],
combo_bg: def[18],
check_mark: def[19],
slider_grab: def[20],
slider_grab_active: def[21],
button: def[22],
button_hovered: def[23],
button_active: def[24],
header: def[25],
header_hovered: def[26],
header_active: def[27],
separator: def[28],
separator_hovered: def[29],
separator_active: def[30],
resize_grip: def[31],
resize_grip_hovered: def[32],
resize_grip_active: def[33],
close_button: def[34],
close_button_hovered: def[35],
close_button_active: def[36],
plot_lines: def[37],
plot_lines_hovered: def[38],
plot_histogram: def[39],
plot_histogram_hovered: def[40],
text_selected_bg: def[41],
modal_window_darkening: def[42],
}
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct ImGuiStyleSave {
pub alpha: f32,
#[serde(with = "ImVec2Def")] pub window_padding: ImVec2,
#[serde(with = "ImVec2Def")] pub window_min_size: ImVec2,
pub window_rounding: f32,
#[serde(with = "ImVec2Def")] pub window_title_align: ImVec2,
pub child_window_rounding: f32,
#[serde(with = "ImVec2Def")] pub frame_padding: ImVec2,
pub frame_rounding: f32,
#[serde(with = "ImVec2Def")] pub item_spacing: ImVec2,
#[serde(with = "ImVec2Def")] pub item_inner_spacing: ImVec2,
#[serde(with = "ImVec2Def")] pub touch_extra_padding: ImVec2,
pub indent_spacing: f32,
pub columns_min_spacing: f32,
pub scrollbar_size: f32,
pub scrollbar_rounding: f32,
pub grab_min_size: f32,
pub grab_rounding: f32,
#[serde(with = "ImVec2Def")] pub button_text_align: ImVec2,
#[serde(with = "ImVec2Def")] pub display_window_padding: ImVec2,
#[serde(with = "ImVec2Def")] pub display_safe_area_padding: ImVec2,
pub anti_aliased_lines: bool,
pub anti_aliased_shapes: bool,
pub curve_tessellation_tol: f32,
pub colors: ImColorsSave,
}
impl ImGuiStyleSave {
pub fn set_style(&self, style: &mut ImGuiStyle) {
style.alpha = self.alpha;
style.window_padding = self.window_padding;
style.window_min_size = self.window_min_size;
style.window_rounding = self.window_rounding;
style.window_title_align = self.window_title_align;
style.child_window_rounding = self.child_window_rounding;
style.frame_padding = self.frame_padding;
style.frame_rounding = self.frame_rounding;
style.item_spacing = self.item_spacing;
style.item_inner_spacing = self.item_inner_spacing;
style.touch_extra_padding = self.touch_extra_padding;
style.indent_spacing = self.indent_spacing;
style.columns_min_spacing = self.columns_min_spacing;
style.scrollbar_size = self.scrollbar_size;
style.scrollbar_rounding = self.scrollbar_rounding;
style.grab_min_size = self.grab_min_size;
style.grab_rounding = self.grab_rounding;
style.button_text_align = self.button_text_align;
style.display_window_padding = self.display_window_padding;
style.display_safe_area_padding = self.display_safe_area_padding;
style.anti_aliased_lines = self.anti_aliased_lines;
style.anti_aliased_shapes = self.anti_aliased_shapes;
style.curve_tessellation_tol = self.curve_tessellation_tol;
style.colors = self.colors.clone().into();
}
}
|
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2016 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT.
#[repr(C)]
pub struct ibv_cq_ex
{
pub context: *mut ibv_context,
pub channel: *mut ibv_comp_channel,
pub cq_context: *mut c_void,
pub handle: u32,
pub cqe: c_int,
pub mutex: pthread_mutex_t,
pub cond: pthread_cond_t,
pub comp_events_completed: u32,
pub async_events_completed: u32,
pub comp_mask: u32,
pub status: ibv_wc_status,
pub wr_id: u64,
pub start_poll: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex, attr: *mut ibv_poll_cq_attr) -> c_int>,
pub next_poll: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> c_int>,
pub end_poll: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex)>,
pub read_opcode: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> ibv_wc_opcode>,
pub read_vendor_err: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u32>,
pub read_byte_len: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u32>,
pub read_imm_data: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> __be32>,
pub read_qp_num: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u32>,
pub read_src_qp: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u32>,
pub read_wc_flags: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> c_uint>,
pub read_slid: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u32>,
pub read_sl: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u8>,
pub read_dlid_path_bits: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u8>,
pub read_completion_ts: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u64>,
pub read_cvlan: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u16>,
pub read_flow_tag: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u32>,
pub read_tm_info: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex, tm_info: *mut ibv_wc_tm_info)>,
pub read_completion_wallclock_ns: Option<unsafe extern "C" fn(current: *mut ibv_cq_ex) -> u64>,
}
impl Default for ibv_cq_ex
{
#[inline(always)]
fn default() -> Self
{
unsafe { zeroed() }
}
}
impl Debug for ibv_cq_ex
{
#[inline(always)]
fn fmt(&self, f: &mut Formatter) -> Result
{
write!(f, "ibv_cq_ex {{ context: {:?}, channel: {:?}, cq_context: {:?}, status: {:?}, start_poll: {:?}, next_poll: {:?}, end_poll: {:?}, read_opcode: {:?}, read_vendor_err: {:?}, read_byte_len: {:?}, read_imm_data: {:?}, read_qp_num: {:?}, read_src_qp: {:?}, read_wc_flags: {:?}, read_slid: {:?}, read_sl: {:?}, read_dlid_path_bits: {:?}, read_completion_ts: {:?}, read_cvlan: {:?}, read_flow_tag: {:?}, read_tm_info: {:?}, read_completion_wallclock_ns: {:?} }}", self.context, self.channel, self.cq_context, self.status, self.start_poll, self.next_poll, self.end_poll, self.read_opcode, self.read_vendor_err, self.read_byte_len, self.read_imm_data, self.read_qp_num, self.read_src_qp, self.read_wc_flags, self.read_slid, self.read_sl, self.read_dlid_path_bits, self.read_completion_ts, self.read_cvlan, self.read_flow_tag, self.read_tm_info, self.read_completion_wallclock_ns)
}
}
|
use skulpin::skia_safe::*;
use crate::ui::*;
pub struct Button;
pub struct ButtonColors {
pub outline: Color,
pub text: Color,
pub hover: Color,
pub pressed: Color,
}
#[derive(Clone, Copy)]
pub struct ButtonArgs<'a> {
pub height: f32,
pub colors: &'a ButtonColors,
}
pub struct ButtonProcessResult {
clicked: bool,
}
impl Button {
pub fn process(
ui: &mut Ui,
canvas: &mut Canvas,
input: &Input,
ButtonArgs { height, colors }: ButtonArgs,
width_hint: Option<f32>,
extra: impl FnOnce(&mut Ui, &mut Canvas),
) -> ButtonProcessResult {
// horizontal because we need to fit() later
ui.push_group((width_hint.unwrap_or(0.0), height), Layout::Horizontal);
extra(ui, canvas);
ui.fit();
let mut clicked = false;
ui.outline(canvas, colors.outline, 1.0);
if ui.has_mouse(input) {
let fill_color = if input.mouse_button_is_down(MouseButton::Left) {
colors.pressed
} else {
colors.hover
};
ui.fill(canvas, fill_color);
clicked = input.mouse_button_just_released(MouseButton::Left);
}
ui.pop_group();
ButtonProcessResult { clicked }
}
pub fn with_text(
ui: &mut Ui,
canvas: &mut Canvas,
input: &Input,
args: ButtonArgs,
text: &str,
) -> ButtonProcessResult {
Self::process(ui, canvas, input, args, None, |ui, canvas| {
let text_width = ui.text_size(text).0;
let padding = args.height;
ui.push_group((text_width + padding, ui.height()), Layout::Freeform);
ui.text(canvas, text, args.colors.text, (AlignH::Center, AlignV::Middle));
ui.pop_group();
})
}
pub fn with_icon(
ui: &mut Ui,
canvas: &mut Canvas,
input: &Input,
args: ButtonArgs,
icon: &Image,
) -> ButtonProcessResult {
Self::process(ui, canvas, input, args, Some(args.height), |ui, canvas| {
ui.icon(canvas, icon, args.colors.text, Some((args.height, args.height)));
})
}
}
impl ButtonProcessResult {
pub fn clicked(self) -> bool {
self.clicked
}
}
|
mod gameplugin;
pub use gameplugin::GamePlugin;
|
use serde::Deserialize;
/// Basic structure of a Reddit response.
/// See: https://github.com/reddit-archive/reddit/wiki/JSON
#[derive(Deserialize, Debug)]
pub struct BasicThing<T> {
/// An identifier that specifies the type of object that this is.
pub kind: String,
/// The data contained by this struct. This will vary depending on the type parameter
/// because each endpoint returns different contents.
pub data: T,
}
/// JSON list response.
#[derive(Deserialize, Debug)]
pub struct Listing<T> {
/// Modhash
pub modhash: Option<String>,
/// The fullname of the listing that follows after this page.
pub after: Option<String>,
/// The fullname of the listing that follows before this page.
pub before: Option<String>,
/// A list of `things` that this Listing wraps.
pub children: Vec<T>,
}
/// Often times a basic thing will have this structure.
pub type BasicListing<T> = BasicThing<Listing<BasicThing<T>>>;
|
$NetBSD: patch-vendor_rustc-ap-rustc__target_src_spec_mod.rs,v 1.1 2021/05/26 09:21:39 he Exp $
Add aarch64_be NetBSD target.
--- vendor/rustc-ap-rustc_target/src/spec/mod.rs.orig 2021-03-23 16:54:53.000000000 +0000
+++ vendor/rustc-ap-rustc_target/src/spec/mod.rs
@@ -695,6 +695,7 @@ supported_targets! {
("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
+ ("aarch64_be-unknown-netbsd", aarch64_be_unknown_netbsd),
("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
("i686-unknown-netbsd", i686_unknown_netbsd),
|
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::error::Error;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct Logger {
out: Arc<Mutex<String>>,
}
impl Logger {
pub fn log(&self, msg: &str, level: Level) -> Result<(), Box<dyn Error>> {
let level = match level {
Level::Note => "Note".to_string(),
Level::Error => "Error".to_string(),
Level::Warn => "Warn".to_string(),
_ => "".to_string(),
};
let mut file = OpenOptions::new().append(true)
.create(true).open("log.txt").unwrap();
writeln!(file, "{}: {}", level, msg)?;
Ok(())
}
}
pub enum Level {
Note,
Error,
Warn,
Empty,
}
impl Level {
fn from_str(level: &str) -> Self {
match level {
"note" | "Note" | "NOTE" => Level::Note,
"error" | "Error" | "ERROR" => Level::Error,
"warn" | "Warn" | "WARN" => Level::Error,
_ => Level::Empty,
}
}
fn from_int(level: u32) -> Self {
match level {
0 => Level::Note,
1 => Level::Error,
2 => Level::Warn,
_ => Level::Empty,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn create_logger() {
let log = Logger::new("Hello there");
assert_eq!(1, 1);
}
} |
//! `git.rs` serves as a demonstration of how to use subcommands,
//! as well as a demonstration of adding documentation to subcommands.
//! Documentation can be added either through doc comments or
//! `help`/`about` attributes.
//!
//! Running this example with --help prints this message:
//! -----------------------------------------------------
//! git 0.3.25
//! the stupid content tracker
//!
//! USAGE:
//! git <SUBCOMMAND>
//!
//! FLAGS:
//! -h, --help Prints help information
//! -V, --version Prints version information
//!
//! SUBCOMMANDS:
//! add
//! fetch fetch branches from remote repository
//! help Prints this message or the help of the given subcommand(s)
//! -----------------------------------------------------
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "git")]
/// the stupid content tracker
enum Opt {
/// fetch branches from remote repository
Fetch {
#[structopt(long)]
dry_run: bool,
#[structopt(long)]
all: bool,
#[structopt(default_value = "origin")]
repository: String,
},
#[structopt(help = "add files to the staging area")]
Add {
#[structopt(short)]
interactive: bool,
#[structopt(short)]
all: bool,
files: Vec<String>,
},
}
fn main() {
let matches = Opt::from_args();
println!("{:?}", matches);
}
|
use crate::errors::{ErrorKind, Result, ResultExt};
use crate::message::{
Message, MessagePacket, VerackMessage, PongMessage, PingMessage
};
use async_std::{
prelude::*,
};
use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
pub async fn start() {
}
|
fn main() {
if time::now().tm_wday == 2 {
println!("cargo:rustc-cfg=tuesday");
}
}
|
use clap::{crate_description, crate_version, App, AppSettings, Arg, SubCommand};
fn main() -> Result<(), rasar::Error> {
let args = App::new("Rasar")
.version(crate_version!())
.about(crate_description!())
.settings(&[
AppSettings::ArgRequiredElseHelp,
AppSettings::VersionlessSubcommands,
])
.subcommand(
SubCommand::with_name("list")
.visible_alias("l")
.visible_alias("ls")
.about("List all files included in an asar archive")
.arg(
Arg::with_name("ARCHIVE")
.required(true)
.help("Target asar archive"),
),
)
.subcommand(
SubCommand::with_name("pack")
.visible_alias("p")
.about("Pack a directory into an asar archive")
.arg(
Arg::with_name("DIR")
.required(true)
.help("Target directory path or glob"),
)
.arg(
Arg::with_name("DEST")
.required(true)
.help("Asar archive file destination"),
),
)
.subcommand(
SubCommand::with_name("extract")
.visible_alias("e")
.about("Extract all files from an asar archive")
.arg(
Arg::with_name("ARCHIVE")
.required(true)
.help("Target asar archive"),
)
.arg(
Arg::with_name("DEST")
.required(true)
.help("Destination folder"),
),
)
.subcommand(
SubCommand::with_name("extract-file")
.visible_alias("ef")
.about("Extract a single files from an asar archive")
.arg(
Arg::with_name("ARCHIVE")
.required(true)
.help("Target asar archive"),
)
.arg(
Arg::with_name("DEST")
.required(true)
.help("File destination"),
),
)
.get_matches();
match args.subcommand() {
("list", Some(cmd)) => {
for entry in rasar::list(cmd.value_of("ARCHIVE").unwrap())? {
println!(
"{}",
entry.to_str().expect("Error converting OS path to string")
);
}
}
("pack", Some(cmd)) => {
rasar::pack(cmd.value_of("DIR").unwrap(), cmd.value_of("DEST").unwrap())?
}
("extract", Some(cmd)) => rasar::extract(
cmd.value_of("ARCHIVE").unwrap(),
cmd.value_of("DEST").unwrap(),
)?,
("extract-file", Some(cmd)) => rasar::extract_file(
cmd.value_of("ARCHIVE").unwrap(),
cmd.value_of("DEST").unwrap(),
)?,
_ => unreachable!(),
}
Ok(())
}
|
use crate::{components, components::player::PlayerType, config, resources, utils};
use amethyst::{
animation::AnimationSetPrefab,
assets::{AssetStorage, Loader, PrefabData, PrefabLoader, ProgressCounter, RonFormat},
core::transform::Transform,
derive::PrefabData,
ecs::{Entity, Read, ReadExpect},
error::Error,
prelude::*,
renderer::{
sprite::{prefab::SpriteScenePrefab, SpriteRender},
Camera,
},
ui,
};
use serde::{Deserialize, Serialize};
/// Animation ids used in a AnimationSet
#[derive(Eq, PartialOrd, PartialEq, Hash, Debug, Copy, Clone, Deserialize, Serialize)]
pub enum AnimationId {
PlayerRun,
PlayerStand,
}
#[derive(Debug, Clone, Deserialize, PrefabData)]
pub enum FieldSceneExtras {
PlayerData {
/// Player info.
player: components::Player,
/// Human component. None if not human.
human: Option<components::Human>,
/// Robot component. None if not robot.
robot: Option<components::Robot>,
},
BallData {
/// Ball component.
ball: components::Ball,
},
NetData {
/// Net component.
net: components::Net,
},
StaticData,
}
/// Data for entities in the Field (Pitch?) scene.
#[derive(Debug, Clone, Deserialize, PrefabData)]
pub struct FieldSceneData {
/// Information for rendering a scene with sprites
sprite_scene: SpriteScenePrefab,
/// Аll animations that can be run on the entity
animation_set: AnimationSetPrefab<AnimationId, SpriteRender>,
/// Information about collision box. None if no collisions.
collision_box: Option<components::CollisionBox>,
/// Other information including special components.
extras: FieldSceneExtras,
/// To describe how the object is moving.
movement_state: Option<components::MovementState>,
}
fn initialize_field(world: &mut World, progress_counter: &mut ProgressCounter) {
let spritename = "sprites/field_ichi_1.ron";
let prefab = world.exec(|loader: PrefabLoader<'_, FieldSceneData>| {
loader.load(spritename, RonFormat, &mut *progress_counter)
});
world.create_entity().with(prefab.clone()).build();
// Create players.
let prefab_files = [
(5, "sprites/enemy.ron", utils::Side::LowerSide),
(5, "sprites/player.ron", utils::Side::UpperSide),
];
for (number, name, side) in &prefab_files {
let prefab = world.exec(|loader: PrefabLoader<'_, FieldSceneData>| {
loader.load(*name, RonFormat, &mut *progress_counter)
});
for i in 0..*number {
let position = utils::player_position(i, *side);
let player_type = PlayerType::from_index(i);
let mut transform = Transform::default();
transform.set_translation_xyz(position[0], position[1], 0.0);
world
.create_entity()
.with(prefab.clone())
.with(transform)
.with(player_type.unwrap())
.build();
}
}
}
fn initialize_score(world: &mut World, progress_counter: &mut ProgressCounter) {
// If we can't load the font just let it crash.
let font = world.exec(
|(loader, asset_storage): (
ReadExpect<'_, Loader>,
Read<'_, AssetStorage<ui::FontAsset>>,
)| {
loader.load(
"fonts/slkscr.ttf",
ui::TtfFormat,
progress_counter,
&asset_storage,
)
},
);
let text = ui::UiText::new(
font,
"0 - 0".to_string(),
[0.0, 0.0, 0.0, 1.0],
25.0,
ui::LineMode::Single,
ui::Anchor::BottomLeft,
);
let ui_transform = ui::UiTransform::new(
String::from("scoreboard"), // id
ui::Anchor::TopLeft, // anchor
ui::Anchor::TopLeft, // pivot
20.0, // x
0.0, // y
0.4, // z
100.0, // width
30.0, // height
);
world.create_entity().with(text).with(ui_transform).build();
}
fn initialize_engine_registry(world: &mut World) {
let registry = resources::EngineRegistry::default();
world.insert(registry);
}
fn initialize_camera(world: &mut World) {
let mut transform = Transform::default();
transform.set_translation_xyz(config::SCREEN_WIDTH / 2.0, config::SCREEN_HEIGHT / 2.0, 1.0);
world
.create_entity()
.with(Camera::standard_2d(
config::SCREEN_WIDTH,
config::SCREEN_HEIGHT,
))
.with(transform)
.build();
}
// Define the game state.
#[derive(Default)]
pub struct FieldState {
pub progress_counter: ProgressCounter,
}
impl FieldState {
pub fn new() -> Self {
FieldState {
progress_counter: ProgressCounter::new(),
}
}
}
impl SimpleState for FieldState {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let world = data.world;
initialize_field(world, &mut self.progress_counter);
initialize_camera(world);
initialize_score(world, &mut self.progress_counter);
initialize_engine_registry(world);
}
}
|
fn main() {
let s = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().to_owned()
};
let mut count = 0;
for c in s.chars() {
if c == '1' {
count = count + 1;
}
}
println!("{}", count);
}
|
use std::env;
use regex::Regex;
use std::io;
use std::fs::File;
use std::io::prelude::*;
use std::path;
// use std::io::Read;
fn adjust_x(x:usize, big_r:f64) -> f64 {
let _x = if x % 2 == 1 {
// x is odd
big_r * 2.5
}else{
big_r
};
_x + x as f64 * 3.0 * big_r
}
fn adjust_y(y:usize, r:f64) -> f64 {
(y as f64 + 1.0) * r
}
// To decode save game files
use xz2::read::XzDecoder;
fn read_save_file(file_name: &String) -> io::Result<String> {
let path = path::Path::new(file_name.as_str());
let mut file = File::open(&path)?;
let mut buffer = Vec::new();
// read the whole file
file.read_to_end(&mut buffer)?;
let mut decompressor = XzDecoder::new(&buffer[..]);
let mut contents = String::new();
decompressor.read_to_string(&mut contents).unwrap();
Ok(contents)
}
/// Return the SVG string defining a hexagon
fn hexagon(centrex:f64, centrey:f64, big_r:f64,
r:f64, fill:&str, stroke_width:usize) -> String
{
let x1 = centrex - big_r;
let y1 = centrey;
let x2 = centrex- big_r*0.5;
let y2 = centrey + r;
let x3 = centrex + big_r*0.5;
let y3 = y2;
let x4 = centrex + big_r;
let y4 = centrey;
let x5 = x3;
let y5 = centrey - r;
let x6 = x2;
let y6 = y5;
format!("<polyline points='{}, {} {}, {} {}, {} {}, {} {}, {} {}, {} {}, {}' stroke='black' fill='{}' stroke-width='{}'/>\n",
x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6, x1, y1,
fill, stroke_width)
}
fn _explorer(x:f64, y:f64, diam:f64, colour:&String) -> String {
println!("Explorer");
format!("<text x='{}' y='{}' textLength='{}' lengthAdjust='spacingAndGlyphs' font-size='5em' fill='{}'>{}</text> ",
x, y, diam, colour, "E").to_string()
}
fn _default_unit(x:f64, y:f64, diam:f64, colour:&String, t:&String) -> String {
let t = t.as_str().chars().filter(|x| *x != '"').next().unwrap();
println!("Unit: {}", t);
format!("<text x='{}' y='{}' textLength='{}' lengthAdjust='spacingAndGlyphs' font-size='5em' fill='{}' >{}</text>",
x, y, diam, colour, t).to_string()
}
fn svg_unit(x:f64, y:f64, big_r:f64, colour:&String, t:&String) -> String {
let unit_diameter = big_r/3.0;
format!("{}\n",
match t.as_str() {
"Explorer" => _explorer(x, y, unit_diameter, colour),
_ => _default_unit(x, y, unit_diameter, colour, t),
})
}
fn svg_city(x:f64, y:f64, big_r:f64, colour:&str, name:&str) -> String {
format!("<circle cx='{}' cy='{}' r='{}' stroke='black' fill='{}' stroke-width='1'/>\n <text x='{}' y='{}'> {} </text>",
x, y, big_r*0.33333, colour, x, y, name)
}
fn main() -> io::Result<()> {
let args: Vec<String> = env::args().collect();
let arg = &args[1];
// let text = read_save_file(arg).unwrap();
// let lines = text.as_str().split("\n");
// Lines is a iterator over lines in the original file
// Use a state machine to process the file
#[derive(PartialEq)]
enum State {
Initial,
Map,
Settings,
Player,
Units,
Cities,
};
let mut state = State::Initial;
// Colect player names and colours
let mut menu = Vec::new();
// Variables used in parsing
// Describe a player's data
// let mut player_n:usize; // Player number
let mut player_name = String::new();
let mut colour_r:usize = 0;
let mut colour_g:usize = 0;
let mut colour_b:usize = 0;
// Regular expressions for parsing the file
let re_player_n = Regex::new(r"\[player(\d+)\]$").unwrap();
let re_terrain = Regex::new(r"t\d{4}=.(.+).$").unwrap();
let re_xysize = Regex::new(r"([xy])size.,(\d+),(\d+)$").unwrap();
let re_cities = Regex::new(r"^c=").unwrap();
let re_units = Regex::new(r"^u=").unwrap();
let re_colour = Regex::new(r"^color.([rgb])=(\d+)$").unwrap();
let re_blankline = Regex::new(r"^[ \t]*$").unwrap();
let re_name = Regex::new(r"^name=(.+)$").unwrap();
let mut terrain_rows = Vec::new();
let mut units = Vec::new();
let mut cities = Vec::new();
let mut xsize:usize = 0;
let mut ysize:usize = 0;
// let mut player_n; // Current player
let contents = read_save_file(arg).unwrap(); //let file = File::open(arg.as_str())?;
for line in contents.lines() {
// Each line of the save file
let line = line.to_string();
//println!("{}", line);
if line == "" {
state = State::Initial;
continue;
}
match state {
State::Initial => {
if line == "[map]" {
state = State::Map;
continue;
}else if line == "[settings]"{
state = State::Settings;
continue;
}else if re_player_n.is_match(line.as_str()) {
// let cap = re_player_n.captures(line.as_str()).unwrap();
// player_n =
// cap.get(1).unwrap().as_str().parse::<usize>().unwrap();
state = State::Player;
continue;
}
},
State::Map => {
if re_terrain.is_match(line.as_str()) {
let cap = re_terrain.captures(line.as_str()).unwrap();
let row:Vec<char> = cap.get(1).unwrap().as_str().split("").
filter(|x| x.len() == 1).
map(|x| {
assert!(x.len() == 1);
x.chars().next().unwrap()
}).collect();
terrain_rows.push(row);
}
},
State::Settings=> {
if re_xysize.is_match(line.as_str()){
let cap = re_xysize.captures(line.as_str()).unwrap();
assert!(cap.get(2).unwrap().as_str().
parse::<usize>().unwrap()
==
cap.get(3).unwrap().as_str().
parse::<usize>().unwrap());
match cap.get(1).unwrap().as_str() {
"x" => xsize =
cap.get(2).unwrap().as_str().
parse::<usize>().unwrap(),
"y" => ysize =
cap.get(2).unwrap().as_str().
parse::<usize>().unwrap(),
_ => panic!(line),
};
}
},
State::Player=> {
if re_units.is_match(line.as_str()){
state = State::Units;
continue;
}else if re_cities.is_match(line.as_str()) {
state = State::Cities;
continue;
}else if re_name.is_match(line.as_str()) {
let cap = re_name.captures(line.as_str()).unwrap();
player_name = cap.get(1).unwrap().as_str().to_string();
}else if re_colour.is_match(line.as_str()) {
let cap = re_colour.captures(line.as_str()).unwrap();
let colour = cap.get(2).unwrap().as_str().
parse::<usize>().unwrap();
match cap.get(1).unwrap().as_str() {
"r" => colour_r = colour,
"g" => colour_g = colour,
"b" => colour_b = colour,
_ => panic!(line),
};
}else if re_blankline.is_match(line.as_str()) {
// Menu item for this player
menu.push((colour_r, colour_g, colour_b, player_name.clone()));
}
},
State::Units=> {
if line == "}" {
state = State::Player;
continue;
}
// id,x,y,facing,nationality,veteran,hp,homecity,type_by_name,activity,activity_count,activity_tgt,changed_from,changed_from_count,changed_from_tgt,done_moving,moves,fuel,born,battlegroup,go,goto_x,goto_y,server_side_agent,passenger,ferryboat,charge,bodyguard,texaipassenger,texaiferryboat,texaicharge,texaibodyguard,passenger,ferryboat,charge,bodyguard,ord_map,ord_city,moved,paradropped,transported_by,carrying,action_decision,action_decision_tile_x,action_decision_tile_y,stay,orders_length,orders_index,orders_repeat,orders_vigilant,orders_list,dir_list,activity_list,action_vec,tgt_vec,sub_tgt_vec
let v:Vec<String> =
line.split(",").map(|x| x.to_string()).collect();
assert!(v.len() > 9);
units.push((v[1].parse::<f64>().unwrap(),
v[2].parse::<f64>().unwrap(),
format!("rgb({}, {}, {})",
colour_r, colour_g, colour_b),
v[8].clone()));
},
State::Cities=> {
if line == "}" {
state = State::Player;
continue;
}
let v:Vec<String> = line.split(",").
map(|x| x.to_string()).collect();
println!("v.len() {} Line: '{}'", v.len(), line);
assert!(v.len() > 37);
cities.push((v[1].parse::<usize>().unwrap(), // x
v[0].parse::<usize>().unwrap(), // y
format!("rgb({}, {}, {})",
colour_r, colour_g, colour_b),
v[36].to_string(), // Name
));
}
}
}
// let scale = 6;
let big_r:f64 = 56.0; //28.0;
let r = big_r * 30.0_f64.to_radians().cos();
let repeatx = xsize;
let repeaty = ysize;
let stroke_width = 2;
// Leave room for some writing at the top
// FIXME: Where do the constants 4.0 and 2.5 come from here?
let maxx = 4.0 * repeatx as f64 * big_r;
let maxy = 2.5 * repeaty as f64 * r;
// let maxx = repeatx as f64 * big_r;
// let maxy = repeaty as f64 * r;
let mut odd = false;
let terrain_colour = [('i', "black"), // Inaccessible
('+', "#848ce9"), // Lake
(' ', "#3e46a7"), // Ocean
(':', "#060d69"), // Deep Ocean
('a', "white"), // Glacier
('d', "#f0e7a1"), // Desert
('f', "#039c14"), // Forest
('g', "#15d42b"), // Grassland
('h', "#2a7c34"), // Hills
('j', "#056710"), // Jungle
('m', "grey"), // Mountains
('p', "#078315"), // Plains
('s', "#a0c3a4"), // Swamp
('t', "#3a4b04"), // Tundra
];
let mut svg = format!("<svg version='1.1' width='{}' height='{}' xmlns='http://www.w3.org/2000/svg'>\n", maxx, maxy);
// svg += format!("<rect x='{}' y='{}' width='{}' height='{}' stroke='black' fill='transparent' stroke-width='5'/>",
// 0, 0, maxx, maxy
// ).as_str();
// Put writing at the top
let font_size = 30.0; // The size of font in pixels
let weight_adjust = 0.8; // The multilier to set the width of string
let text = format!(" <style> .small {{ font: italic 13px sans-serif; }}
.heavy {{ font: bold {}px sans-serif; }}
</style>
<text x='0' y='{}' textLength='{}px' class='heavy' >
This is the heading</text>\n",
30,
0,
weight_adjust*font_size*20.0);
svg += text.as_str();
let mut y = 0;
for row in terrain_rows.iter(){
let mut x = 0;
let y1 = (1.0 + y as f64) * r;
for t in row.iter() {
let fill = terrain_colour.iter().
filter(|_t| &_t.0 == t).
next().unwrap().1;
let x1 = match odd {
true => big_r*2.5,
false => big_r,
} + 3.0 * big_r * x as f64;
let h = hexagon(x1, y1, big_r, r, fill, stroke_width);
svg += h.as_str();
x += 1;
}
odd = !odd;
y += 1;
}
for u in units {
let x = u.0;
let y = u.1;
print!("x_in: {} y_in: {} ", x, y);
let x = adjust_x(x as usize, big_r);
let y = adjust_y(y as usize, r);
println!("x_out: {} y_out: {} ", x, y);
let colour = u.2;
let t = u.3;
println!("Unit x: {}", x);
let u = svg_unit(x,
y,
big_r,
&colour, &t);
//println!("Unit: {}", u);
svg += u.as_str();
}
for c in cities {
// The x/y coordinates in game space and the players colour
let x = c.0;
let y = c.1;
let colour = &c.2;
let name = &c.3;
// Convert coordinates to hexagon/SVG space
let x = if x % 2 == 1 {
// x is odd
big_r * 2.5
}else{
big_r
} + x as f64 * 3.0 * big_r;
let y = (y as f64 + 1.0) * r;
// Get svg city
let city = svg_city(x, y, big_r, colour.as_str(), name.as_str());
svg += city.as_str();
}
svg += "</svg>\n";
let path = path::Path::new(arg.as_str());
let path = path.with_extension("svg");
let mut file = File::create(path.as_path().to_str().unwrap())?;
file.write_all(svg.as_bytes())?;
Ok(())
}
|
use std::collections::{VecDeque};
use crate::sudoku;
use crate::sudoku::{Sudoku};
type CellCollection = [sudoku::Index; sudoku::SIZE as usize];
fn box_indexes(n : u32) -> CellCollection {
let x0 = sudoku::ORDER * (n % sudoku::ORDER);
let y0 = sudoku::ORDER * (n / sudoku::ORDER);
let mut indexes : CellCollection = [0; sudoku::SIZE as usize];
let mut i : usize = 0;
for y in y0..(y0 + sudoku::ORDER) {
for x in x0..(x0 + sudoku::ORDER) {
let index = sudoku::index(&sudoku::Point::new(x, y));
indexes[i] = index as usize;
i += 1;
}
}
return indexes;
}
fn row_indexes(y : u32) -> CellCollection {
let mut indexes : CellCollection = [0; sudoku::SIZE as usize];
for i in 0..sudoku::SIZE {
indexes[i as usize] = sudoku::index(&sudoku::Point::new(i, y));
}
return indexes;
}
fn col_indexes(x : u32) -> CellCollection {
let mut indexes : CellCollection = [0; sudoku::SIZE as usize];
for i in 0..sudoku::SIZE {
indexes[i as usize] = sudoku::index(&sudoku::Point::new(x, i));
}
return indexes;
}
fn clean(puzzle : & mut Sudoku, indexes : CellCollection) {
let mut index_queue : VecDeque<sudoku::Index> = VecDeque::new();
let mut value_queue : VecDeque<sudoku::Value> = VecDeque::new();
for index in indexes.iter() {
let value = puzzle.view(*index);
if value == 0 {
index_queue.push_front(*index);
} else {
value_queue.push_front(value);
}
}
for index in index_queue.iter() {
for value in value_queue.iter() {
puzzle.eliminate(*index, *value);
}
}
}
fn fill(puzzle : & mut Sudoku, indexes : CellCollection) {
let mut target : sudoku::Index = 0;
let mut set = sudoku::candidate_set();
let mut empty_count = 0_u32;
for index in indexes.iter() {
let value = puzzle.view(*index);
if value > 0 {
set.remove(&value);
} else {
if empty_count > 0 {
return;
} else {
empty_count += 1;
target = *index;
}
}
}
if empty_count == 1 {
for val in set.iter() {
puzzle.fill(target, *val);
}
}
}
fn value_fill(puzzle : &mut Sudoku, indexes : CellCollection) {
for value in 1..=sudoku::SIZE {
let mut occurences = 0_u32;
let mut target : sudoku::Index = 0;
for index in indexes.iter() {
if puzzle.is_candidate(*index, value) {
occurences += 1;
if occurences > 1 {
break;
} else {
target = *index;
}
}
}
if occurences == 1 {
puzzle.fill(target, value);
}
}
}
fn do_fills(puzzle : &mut Sudoku) {
for i in 0..sudoku::SIZE {
fill(puzzle, box_indexes(i));
fill(puzzle, row_indexes(i));
fill(puzzle, col_indexes(i));
}
}
fn do_value_fills(puzzle : &mut Sudoku) {
for i in 0..sudoku::SIZE {
value_fill(puzzle, box_indexes(i));
value_fill(puzzle, row_indexes(i));
value_fill(puzzle, col_indexes(i));
}
}
fn do_clean(puzzle : &mut Sudoku) {
for i in 0..sudoku::SIZE {
clean(puzzle, box_indexes(i));
clean(puzzle, row_indexes(i));
clean(puzzle, col_indexes(i));
}
}
pub fn solve(puzzle : &mut Sudoku) -> bool {
loop {
let progress = puzzle.progress();
do_clean(puzzle);
do_fills(puzzle);
do_value_fills(puzzle);
if puzzle.complete() {
return true;
}
if puzzle.progress() == progress {
return false;
}
}
}
|
/**
--- Day 1: Chronal Calibration ---
"We've detected some temporal anomalies," one of Santa's Elves at the Temporal Anomaly Research and Detection Instrument Station tells you. She sounded pretty worried when she called you down here. "At 500-year intervals into the past, someone has been changing Santa's history!"
"The good news is that the changes won't propagate to our time stream for another 25 days, and we have a device" - she attaches something to your wrist - "that will let you fix the changes with no such propagation delay. It's configured to send you 500 years further into the past every few days; that was the best we could do on such short notice."
"The bad news is that we are detecting roughly fifty anomalies throughout time; the device will indicate fixed anomalies with stars. The other bad news is that we only have one device and you're the best person for the job! Good lu--" She taps a button on the device and you suddenly feel like you're falling. To save Christmas, you need to get all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
After feeling like you've been falling for a few minutes, you look at the device's tiny screen. "Error: Device must be calibrated before first use. Frequency drift detected. Cannot maintain destination lock." Below the message, the device shows a sequence of changes in frequency (your puzzle input). A value like +6 means the current frequency increases by 6; a value like -3 means the current frequency decreases by 3.
For example, if the device displays frequency changes of +1, -2, +3, +1, then starting from a frequency of zero, the following changes would occur:
Current frequency 0, change of +1; resulting frequency 1.
Current frequency 1, change of -2; resulting frequency -1.
Current frequency -1, change of +3; resulting frequency 2.
Current frequency 2, change of +1; resulting frequency 3.
In this example, the resulting frequency is 3.
Here are other example situations:
+1, +1, +1 results in 3
+1, +1, -2 results in 0
-1, -2, -3 results in -6
Starting with a frequency of zero, what is the resulting frequency after all of the changes in frequency have been applied?
*/
fn main() -> std::io::Result<()> {
let file = include_str!("../input");
let mut sum: i32 = 0;
for line in file.lines() {
let value = line.parse::<i32>().expect("Expected lines to be ints");
sum += value;
}
println!("Frequency: {:?}", sum);
Ok(())
}
|
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::str::FromStr;
use failure::{format_err, Error};
use regex::Regex;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Opcode {
Addr,
Addi,
Mulr,
Muli,
Banr,
Bani,
Borr,
Bori,
Setr,
Seti,
Gtir,
Gtri,
Gtrr,
Eqir,
Eqri,
Eqrr,
}
impl FromStr for Opcode {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"addr" => Ok(Opcode::Addr),
"addi" => Ok(Opcode::Addi),
"mulr" => Ok(Opcode::Mulr),
"muli" => Ok(Opcode::Muli),
"banr" => Ok(Opcode::Banr),
"bani" => Ok(Opcode::Bani),
"borr" => Ok(Opcode::Borr),
"bori" => Ok(Opcode::Bori),
"setr" => Ok(Opcode::Setr),
"seti" => Ok(Opcode::Seti),
"gtir" => Ok(Opcode::Gtir),
"gtri" => Ok(Opcode::Gtri),
"gtrr" => Ok(Opcode::Gtrr),
"eqir" => Ok(Opcode::Eqir),
"eqri" => Ok(Opcode::Eqri),
"eqrr" => Ok(Opcode::Eqrr),
_ => Err(format_err!("unknown opcode {}", s)),
}
}
}
#[derive(Debug, Copy, Clone)]
struct Instruction {
opcode: Opcode,
a: i32,
b: i32,
c: i32,
}
#[derive(Debug, Clone)]
struct Machine {
registers: [i32; 6],
pc: i32,
instructions: Vec<Instruction>,
}
impl Machine {
fn new() -> Machine {
Machine {
registers: [0, 0, 0, 0, 0, 0],
pc: 0,
instructions: Vec::new(),
}
}
fn reg(&mut self, n: i32) -> &mut i32 {
&mut self.registers[n as usize]
}
fn execute(&mut self, opcode: Opcode, a: i32, b: i32, c: i32) {
match opcode {
Opcode::Addr => *self.reg(c) = *self.reg(a) + *self.reg(b),
Opcode::Addi => *self.reg(c) = *self.reg(a) + b,
Opcode::Mulr => *self.reg(c) = *self.reg(a) * *self.reg(b),
Opcode::Muli => *self.reg(c) = *self.reg(a) * b,
Opcode::Banr => *self.reg(c) = *self.reg(a) & *self.reg(b),
Opcode::Bani => *self.reg(c) = *self.reg(a) & b,
Opcode::Borr => *self.reg(c) = *self.reg(a) | *self.reg(b),
Opcode::Bori => *self.reg(c) = *self.reg(a) | b,
Opcode::Setr => *self.reg(c) = *self.reg(a),
Opcode::Seti => *self.reg(c) = a,
Opcode::Gtir => *self.reg(c) = if a > *self.reg(b) { 1 } else { 0 },
Opcode::Gtri => *self.reg(c) = if *self.reg(a) > b { 1 } else { 0 },
Opcode::Gtrr => *self.reg(c) = if *self.reg(a) > *self.reg(b) { 1 } else { 0 },
Opcode::Eqir => *self.reg(c) = if a == *self.reg(b) { 1 } else { 0 },
Opcode::Eqri => *self.reg(c) = if *self.reg(a) == b { 1 } else { 0 },
Opcode::Eqrr => *self.reg(c) = if *self.reg(a) == *self.reg(b) { 1 } else { 0 },
}
}
}
fn main() -> Result<(), Error> {
let args: Vec<String> = env::args().collect();
let file = File::open(&args[1])?;
let directive = Regex::new(r"#ip (\d+)")?;
let instruction = Regex::new(r"([a-z]+) (\d+) (\d+) (\d+)")?;
let mut machine = Machine::new();
for line in BufReader::new(file).lines().map(|l| l.unwrap()) {
if let Some(captures) = directive.captures(&line) {
machine.pc = captures[1].parse()?;
} else if let Some(captures) = instruction.captures(&line) {
machine.instructions.push(Instruction {
opcode: captures[1].parse()?,
a: captures[2].parse()?,
b: captures[3].parse()?,
c: captures[4].parse()?,
});
}
}
// This is a hand-reverse-engineered implementation of the tight loop for part 2.
// I suppose you could let the emulator below figure everything out, but...
let mut r0 = 0;
let r4 = 10551389;
for r5 in 1..=r4 {
if r4 % r5 == 0 {
r0 += r5;
}
}
println!("second answer: {}", r0);
loop {
let ip = *machine.reg(machine.pc) as usize;
if let Some(instruction) = machine.instructions.get(ip) {
machine.execute(
instruction.opcode,
instruction.a,
instruction.b,
instruction.c,
);
*machine.reg(machine.pc) += 1;
} else {
break;
}
}
println!("answer: {}", machine.registers[0]);
Ok(())
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.