text stringlengths 8 4.13M |
|---|
//! A library to drive web browsers using the webdriver
//! interface.
use std::convert::From;
use std::io::Read;
use std::io;
use std::fmt;
use std::marker::PhantomData;
extern crate hyper;
use hyper::client::*;
use hyper::Url;
extern crate serde;
use serde::{Serialize, Deserialize};
extern crate serde_json;
pub use serde_json::Value as JsonValue;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
extern crate rand;
pub mod messages;
use messages::*;
pub mod firefox;
#[derive(Debug)]
pub enum Error {
FailedToLaunchDriver,
InvalidUrl,
ConnectionError,
Io(io::Error),
JsonDecodeError(serde_json::Error),
WebDriverError(WebDriverError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::FailedToLaunchDriver => write!(f, "Unable to start browser driver"),
Error::InvalidUrl => write!(f, "Invalid URL"),
Error::ConnectionError => write!(f, "Error connecting to browser"),
Error::Io(ref err) => err.fmt(f),
Error::JsonDecodeError(ref s) => write!(f, "Received invalid response from browser: {}", s),
Error::WebDriverError(ref err) => write!(f, "Error: {}", err.message),
}
}
}
impl From<hyper::Error> for Error {
fn from(_: hyper::Error) -> Error {
Error::ConnectionError
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Error {
Error::JsonDecodeError(e)
}
}
pub trait Driver {
/// The url used to connect to this driver
fn url(&self) -> &str;
/// Start a session for this driver
fn session<'a>(&'a self) -> Result<DriverSession<'a>, Error> {
DriverSession::create_session(self.url())
}
}
/// A WebDriver session.
///
/// By default the session is removed on `Drop`
pub struct DriverSession<'a> {
driver: PhantomData<&'a Driver>,
baseurl: Url,
client: Client,
session_id: String,
drop_session: bool,
}
impl<'a> DriverSession<'a> {
pub fn create_session(url: &str) -> Result<DriverSession<'a>, Error> {
let baseurl = try!(Url::parse(url).map_err(|_| Error::InvalidUrl));
let mut s = DriverSession {
driver: PhantomData,
baseurl: baseurl,
client: Client::new(),
session_id: String::new(),
drop_session: true,
};
info!("Creating session at {}", url);
let sess = try!(s.new_session(&NewSessionCmd::new()));
s.session_id = sess.sessionId;
Ok(s)
}
/// Use an existing session
pub fn attach(url: &str, session_id: &str) -> Result<DriverSession<'a>, Error> {
let baseurl = try!(Url::parse(url).map_err(|_| Error::InvalidUrl));
let mut s = DriverSession {
driver: PhantomData,
baseurl: baseurl,
client: Client::new(),
session_id: session_id.to_owned(),
drop_session: true,
};
// FIXME /status would be preferable here to test the connection, but
// it does not seem to work for the current geckodriver
let _ = s.get_current_url()?;
Ok(s)
}
pub fn session_id(&self) -> &str {
&self.session_id
}
/// Whether to remove the session on Drop, the default is true
pub fn drop_session(&mut self, drop: bool) {
self.drop_session = drop;
}
fn get<D: Deserialize>(&self, path: &str) -> Result<D, Error> {
let url = try!(self.baseurl.join(path)
.map_err(|_| Error::InvalidUrl));
let mut res = try!(self.client.get(url)
.send());
Self::decode(&mut res)
}
fn delete<D: Deserialize>(&self, path: &str) -> Result<D, Error> {
let url = try!(self.baseurl.join(path)
.map_err(|_| Error::InvalidUrl));
let mut res = try!(self.client.delete(url)
.send());
Self::decode(&mut res)
}
fn decode<D: Deserialize>(res: &mut Response) -> Result<D, Error> {
let mut data = String::new();
try!(res.read_to_string(&mut data));
debug!("{}", data);
if !res.status.is_success() {
let err = try!(serde_json::from_str(&data));
return Err(Error::WebDriverError(err));
}
let response = try!(serde_json::from_str(&data));
Ok(response)
}
fn post<D: Deserialize, E: Serialize>(&self, path: &str, body: &E) -> Result<D, Error> {
let url = try!(self.baseurl.join(path)
.map_err(|_| Error::InvalidUrl));
let mut res = try!(self.client.post(url)
.body(&try!(serde_json::to_string(body)))
.send());
Self::decode(&mut res)
}
/// Create a new webdriver session
fn new_session(&mut self, params: &NewSessionCmd) -> Result<Session, Error> {
let resp: Session = try!(self.post("/session", ¶ms));
Ok(resp)
}
/// Navigate to the given URL
pub fn go(&self, url: &str) -> Result<(), Error> {
let params = GoCmd { url: url.to_string() };
let _: Empty = try!(self.post(&format!("/session/{}/url", &self.session_id), ¶ms));
Ok(())
}
pub fn get_current_url(&self) -> Result<String, Error> {
let v: Value<_> = try!(self.get(&format!("/session/{}/url", self.session_id)));
Ok(v.value)
}
pub fn back(&self) -> Result<(), Error> {
let _: Empty = try!(self.post(&format!("/session/{}/back", self.session_id), &Empty {}));
Ok(())
}
pub fn forward(&self) -> Result<(), Error> {
let _: Empty = try!(self.post(&format!("/session/{}/forward", self.session_id), &Empty {}));
Ok(())
}
pub fn refresh(&self) -> Result<(), Error> {
let _: Empty = try!(self.post(&format!("/session/{}/refresh", self.session_id), &Empty {}));
Ok(())
}
pub fn get_page_source(&self) -> Result<String, Error> {
let v: Value<_> = try!(self.get(&format!("/session/{}/source", self.session_id)));
Ok(v.value)
}
pub fn get_title(&self) -> Result<String, Error> {
let v: Value<_> = try!(self.get(&format!("/session/{}/title", self.session_id)));
Ok(v.value)
}
/// Get all cookies
pub fn get_cookies(&self) -> Result<Vec<Cookie>, Error> {
let v: Value<_> = try!(self.get(&format!("/session/{}/cookie", self.session_id)));
Ok(v.value)
}
pub fn get_window_handle(&self) -> Result<String, Error> {
let v: Value<_> = try!(self.get(&format!("/session/{}/window", self.session_id)));
Ok(v.value)
}
pub fn switch_window(&mut self, handle: &str) -> Result<(), Error> {
let _: Empty = try!(self.post(&format!("/session/{}/window", self.session_id), &SwitchWindowCmd::from(handle)));
Ok(())
}
pub fn close_window(&mut self) -> Result<(), Error> {
let _: Empty = try!(self.delete(&format!("/session/{}/window", self.session_id)));
Ok(())
}
pub fn get_window_handles(&self) -> Result<Vec<String>, Error> {
let v: Value<_> = try!(self.get(&format!("/session/{}/window/handles", self.session_id)));
Ok(v.value)
}
pub fn find_element(&self, selector: &str, strategy: LocationStrategy) -> Result<Element, Error> {
let cmd = FindElementCmd { using: strategy, value: selector};
let v: Value<ElementReference> = try!(self.post(&format!("/session/{}/element", self.session_id), &cmd));
Ok(Element::new(self, v.value.reference))
}
pub fn find_elements(&self, selector: &str, strategy: LocationStrategy) -> Result<Vec<Element>, Error> {
let cmd = FindElementCmd { using: strategy, value: selector};
let mut v: Value<Vec<ElementReference>> = try!(self.post(&format!("/session/{}/elements", self.session_id), &cmd));
let mut elems = Vec::new();
while let Some(er) = v.value.pop() {
elems.push(Element::new(self, er.reference))
}
Ok(elems)
}
pub fn execute(&self, script: ExecuteCmd) -> Result<JsonValue, Error> {
let v: Value<JsonValue> = try!(self.post(&format!("/session/{}/execute/sync", self.session_id), &script));
Ok(v.value)
}
pub fn switch_to_frame(&self, handle: JsonValue) -> Result<(), Error> {
let _: Empty = try!(self.post(&format!("/session/{}/frame", self.session_id), &SwitchFrameCmd::from(handle)));
Ok(())
}
}
impl<'a> Drop for DriverSession<'a> {
fn drop(&mut self) {
if self.drop_session {
let _: Result<Empty,_> = self.delete(&format!("/session/{}", self.session_id));
}
}
}
pub struct Element<'a> {
session: &'a DriverSession<'a>,
reference: String,
}
impl<'a> Element<'a> {
fn new(s: &'a DriverSession, reference: String) -> Self {
Element { session: s, reference: reference }
}
pub fn attribute(&self, name: &str) -> Result<String, Error> {
let v: Value<_> = try!(self.session.get(&format!("/session/{}/element/{}/attribute/{}", self.session.session_id(), self.reference, name)));
Ok(v.value)
}
// pub fn property(&self, name: &str) -> Result<String, Error> {
// let v: Value<_> = try!(self.get(&format!("/session/{}/element/{}/property/{}", self.session_id, el.reference, name)));
// Ok(v.value)
// }
pub fn css_value(&self, name: &str) -> Result<String, Error> {
let v: Value<_> = try!(self.session.get(&format!("/session/{}/element/{}/css/{}", self.session.session_id(), self.reference, name)));
Ok(v.value)
}
pub fn text(&self) -> Result<String, Error> {
let v: Value<_> = try!(self.session.get(&format!("/session/{}/element/{}/text", self.session.session_id(), self.reference)));
Ok(v.value)
}
/// Returns the tag name for this element
pub fn name(&self) -> Result<String, Error> {
let v: Value<_> = try!(self.session.get(&format!("/session/{}/element/{}/name", self.session.session_id(), self.reference)));
Ok(v.value)
}
pub fn reference(&self) -> Result<JsonValue, Error> {
serde_json::to_value(&ElementReference::from_str(&self.reference))
.map_err(|err| Error::from(err))
}
/// Gets the `innerHTML` javascript attribute for this element. Some drivers can get
/// this using regular attributes, in others it does not work. This method gets it
/// executing a bit of javascript.
pub fn inner_html(&self) -> Result<JsonValue, Error> {
let script = ExecuteCmd {
script: "return arguments[0].innerHTML;".to_owned(),
args: vec![self.reference()?],
};
self.session.execute(script)
}
pub fn outer_html(&self) -> Result<JsonValue, Error> {
let script = ExecuteCmd {
script: "return arguments[0].outerHTML;".to_owned(),
args: vec![self.reference()?],
};
self.session.execute(script)
}
}
/// Switch the context of the current session to the given frame reference.
///
/// This structure implements Drop, and restores the session context
/// to the current top level window.
pub struct FrameContext<'a> {
session: &'a DriverSession<'a>,
}
impl<'a> FrameContext<'a> {
pub fn new(session: &'a DriverSession, frameref: JsonValue) -> Result<FrameContext<'a>, Error> {
session.switch_to_frame(frameref)?;
Ok(FrameContext { session: session })
}
}
impl<'a> Drop for FrameContext<'a> {
fn drop(&mut self) {
let _ = self.session.switch_to_frame(JsonValue::Null);
}
}
#[cfg(test)]
mod tests {
use super::firefox::GeckoDriver;
use super::messages::LocationStrategy;
use super::{DriverSession, Driver};
#[test]
fn test_geckodriver() {
let gecko = GeckoDriver::build()
.kill_on_drop(true)
.spawn()
.unwrap();
}
#[test]
fn test() {
let gecko = GeckoDriver::build()
.kill_on_drop(true)
.spawn()
.unwrap();
let mut sess = gecko.session().unwrap();
sess.go("https://www.youtube.com/watch?v=dQw4w9WgXcQ").unwrap();
sess.get_current_url().unwrap();
sess.back().unwrap();
sess.forward().unwrap();
sess.refresh().unwrap();
sess.get_page_source().unwrap();
{
let el = sess.find_element("a", LocationStrategy::Css).unwrap();
el.attribute("href").unwrap();
el.css_value("color").unwrap();
el.text().unwrap();
assert_eq!(el.name().unwrap(), "a");
let imgs = sess.find_elements("img", LocationStrategy::Css).unwrap();
for img in &imgs {
println!("{}", img.attribute("src").unwrap());
}
sess.get_cookies().unwrap();
sess.get_title().unwrap();
sess.get_window_handle().unwrap();
let handles = sess.get_window_handles().unwrap();
assert_eq!(handles.len(), 1);
}
sess.close_window().unwrap();
}
}
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:pub-use-extern-macros.rs
#![feature(use_extern_macros)]
extern crate macros;
// @has pub_use_extern_macros/macro.bar.html
// @!has pub_use_extern_macros/index.html '//code' 'pub use macros::bar;'
pub use macros::bar;
// @has pub_use_extern_macros/macro.baz.html
// @!has pub_use_extern_macros/index.html '//code' 'pub use macros::baz;'
#[doc(inline)]
pub use macros::baz;
// @!has pub_use_extern_macros/macro.quux.html
// @!has pub_use_extern_macros/index.html '//code' 'pub use macros::quux;'
#[doc(hidden)]
pub use macros::quux;
|
use thiserror::Error;
#[derive(Error, Debug, PartialEq)]
pub enum ReadValueError {
#[error("Attempted to read {0} bytes when parsing {1}")]
BufferToShort(usize, &'static str),
#[error("Could not parse utf8 string")]
StringParseError,
#[error("Invalid packet index: {0}")]
InvalidPacketIndex(u16),
}
|
extern crate cairo;
extern crate fontconfig;
extern crate pango;
use std::convert::TryInto;
use std::collections::HashMap;
use std::str;
use harfbuzz_rs::*;
use pangocairo;
use pangocairo::prelude::FontMapExt;
use regex::Regex;
use std::str::FromStr;
///
///
/// storing line data.
/// - content : the vec of the line content of Option<BoxCoodInfo>
/// - div_text_offset: the offset between div width and text width
#[derive(Debug)]
struct Line<'a>{
content: Vec<&'a BoxCoodInfo>,
div_text_offset: f64
}
pub struct MinRaggedLayouter {
hashmap_cost: HashMap<u32, f64>,
hashmap_route: HashMap<u32, u32>,
words: String,
path: Vec<u32>
}
/*
impl MinRaggedLayouter {
///
/// counting total_cost of a line ragged cost.
/// - words : the words listed here.
/// - dest : destination (k)
/// - maxwidth: in pt.
pub fn total(&mut self, words : Vec<Option<BoxCoodInfo>>, dest : u32, maxwidth : f64 ) -> f64 {
}
}*/
///
///
/// Get the infomation of a coodinrate of a box (text slice).
/// - text: the text of it.
/// - width: the x length of moving in pt.
/// - height: the y length of moving in pt
/// - x_offset: the x moving from the baseline in pt
/// - y_offset: the y moving from the baseline in pt
///
#[derive(Debug)]
struct BoxCoodInfo {
text: String,
width: f64,
height: f64,
x_offset: f64,
y_offset: f64
}
///
/// RgbColor: storing 0~255 rgb color code
/// - red: 0 ~ 255
/// - green: 0 ~ 255
/// - blue: 0 ~ 255
#[derive(Debug)]
struct RgbColor{
red: u32,
green: u32,
blue: u32
}
///
/// The structure storing a font and its attribution.
/// - name : font name . eg. "FreeSans"
/// - style : font style. eg. "Italic"
/// - size : in pt. eg. "32" for 32pt
/// - variations. variation of a opentype font. eg. `vec![Variation::new(b"wght", 800.0);]`
/// - features. features of a opentype font. eg. `vec![Feature::new(b"calt", 1, 0..)]`
///
#[derive(Debug)]
struct FontStruct<'a> {
name: &'a str,
style: &'a str,
size: u32,
variations : &'a [Variation],
features: &'a [Feature]
}
/// a Div text layout block. unit: pt
/// - x: x-axis in pt (from left)
/// - y: y-axis in pt (from top)
/// - width: Div width in pt
/// - height: Div height in pt
/// - lineskip: the skip between the baseline of 2 lines in pt
/// - direction: Rtl, Ltr, Btt, Ttb
/// - color: #ffffff -like hex html color code
#[derive(Debug)]
struct Div<'a>{
x: f64,
y: f64,
width:f64,
height: f64,
lineskip: f64,
language: &'a str,
direction: harfbuzz_rs::Direction,
color: String
}
/// get the cood infomation of the input box.
/// - text : the render text
/// - font_name: "FreeSans", etc
/// - font_style: "Bold", etc
/// - font_size_pt: 16, etc
/// - direction: Ltr, Rtl, etc,
/// - variations: Opentype variation axis list
/// - features: Opentype feature list
fn get_box_cood_info(text : &str, font_name : &str, font_style : &str, font_size_pt : u32, language: &str,
direction : harfbuzz_rs::Direction, variations : &[Variation], features: & [Feature])
-> Option<BoxCoodInfo> {
// let font_combined = format!("{} {}", font_name, font_style);
let fc = fontconfig::Fontconfig::new()?;
let font = fc.find(font_name, Some(font_style))?;
let path = font.path.to_str()?;
// println!("{}", path);;
let index = 0; //< face index in the font file
let face = Face::from_file(path, index).ok()?;
let mut font = Font::new(face); // setting the font
if !variations.is_empty(){
font.set_variations(&variations);
}
font.set_scale((font_size_pt*64).try_into().unwrap(), (font_size_pt*64).try_into().unwrap()); // setting the pt size
let hb_language = harfbuzz_rs::Language::from_str(language).unwrap();
let mut buffer = UnicodeBuffer::new().set_direction(direction).set_language(hb_language).add_str(text);
// shape the text box
let output = shape(&font, buffer, &features);
// The results of the shaping operation are stored in the `output` buffer.
let positions = output.get_glyph_positions();
let infos = output.get_glyph_infos();
assert_eq!(positions.len(), infos.len());
let mut box_cood = BoxCoodInfo{text: text.to_string(), width: 0.0, height : 0.0, x_offset: 0.0, y_offset : 0.0};
for position in positions{
let x_advance = (position.x_advance) as f64/64.0;
let y_advance = (position.y_advance) as f64/64.0;
let x_offset = (position.x_offset) as f64/64.0;
let y_offset = (position.y_offset) as f64/64.0;
// set the max_x(y)_advance as the box_cood.x(y)_advance
if box_cood.x_offset<x_offset{
box_cood.x_offset = x_offset
}
if box_cood.y_offset<y_offset{
box_cood.y_offset = y_offset
}
box_cood.width += x_advance;
box_cood.height += y_advance;
}
// convert to pt
box_cood.width;
box_cood.height;
box_cood.x_offset;
box_cood.y_offset;
return Some(box_cood);
}
///
///
/// converting font variant list to string. eg.
/// `font_variant_list_to_string(vec![Variation::new(b"wght", 800.0), Variation::new(b"wdth", 50.0)]);`
/// ==> `"wght=800.0,wdth=50.0,"`
/// - vars: variation list
fn font_variant_list_to_string(vars : &[Variation]) -> String{
let mut string : String;
string = "".to_string();
for i in vars{
let var_combined = format!("{}={},", i.tag(), i.value());
string.push_str(&var_combined);
}
return string;
}
///
///
/// convert hex color code to rgb 256 number. eg.
/// #ffffff -> RgbColor{red:256, green:256, blue:256}
/// - hex : the hex color code to be input
fn hex_color_code_to_int(hex : &str)->Option<RgbColor>{
let pattern = Regex::new(r"#(?P<r>[0-9a-fA-F]{2})(?P<g>[0-9a-fA-F]{2})(?P<b>[0-9a-fA-F]{2})").unwrap();
let caps = pattern.captures(hex).unwrap();
let mut rgb = RgbColor{red:0, green:0, blue:0};
let r = caps.name("r")?;
rgb.red = u32::from_str_radix(r.as_str(),16).ok()?;
let g = caps.name("g")?;
rgb.green = u32::from_str_radix(g.as_str(),16).ok()?;
let b = caps.name("b")?;
rgb.blue = u32::from_str_radix(b.as_str(),16).ok()?;
return Some(rgb);
}
///
///
/// show `text` in `canva` at `x` and `y` with `font_struct`
/// text : the text to be rendered.
/// font_sruct: font and its attributes
/// x : x-axis coord in pt.
/// y : y-axis coord in pt.
/// color : hex color `#000000`, etc
/// lang: string eg. "en", "zh", etc.
/// direction: harfbuzz_rs::Direction
/// canva : cairo canvas
/// return box_cood if it runs successfully.
fn layout_text(text : &str, mut font_struct: &FontStruct, x : f64, y: f64,color: &str, lang: &str, direction: harfbuzz_rs::Direction, mut canva: &cairo::Context)
->Option<()>
{
let fontmap = pangocairo::FontMap::default().unwrap();
// you have to multiply 0.75 or you'll get a bug.
let font_combined = format!("{} {} {}", font_struct.name, font_struct.style, (font_struct.size as f64) * 0.75);
let mut font_with_style = pango::FontDescription::from_string(&font_combined);
// pango_font_style.set_absolute_size((font_struct.size * 1024).into());
font_with_style.set_variations(&font_variant_list_to_string(font_struct.variations));
let pango_cxt = pango::Context::new();
// println!("{:?}", pango::AttrType::Fallback);
let _pango_cairo_font = fontmap.load_font(&pango_cxt, &font_with_style);
//let box_cood = get_box_cood_info(text, font_struct.name, font_struct.style, font_struct.size, direction, font_struct.variations, &[])?;
pango_cxt.set_language(&pango::language::Language::from_string(lang));
pango_cxt.set_font_map(&fontmap);
let pango_layout = pango::Layout::new(&pango_cxt);
pango_layout.set_font_description(Some(&font_with_style));
pango_layout.set_text(text);
// setting the color
canva.save().ok();
let color_rgb = hex_color_code_to_int(color)?;
canva.set_source_rgb(color_rgb.red as f64/256.0, color_rgb.green as f64/256.0, color_rgb.blue as f64/256.0);
canva.move_to(x, y);
pangocairo::show_layout(&canva, &pango_layout);
canva.restore().ok();
canva.move_to(0.0, 0.0);
return Some(());
}
///
/// typesetting for greedy algorithm using unragged.
/// for arguments, see `greedy_typesetting`
fn greedy_typesetting(box_coord_vec : Vec<Option<BoxCoodInfo>>, block: Div, font: FontStruct, cxt : &cairo::Context, ragged : bool){
//get the space width.
let mut space_width = 0.0;
let space_box_cood = get_box_cood_info(" ", font.name, font.style, font.size, block.language, block.direction, font.variations, font.features);
match space_box_cood {
Some(inner) =>{
space_width = inner.width;
}
None=>println!("The space width can't be defined. Set it to 0.")
}
let mut lines = vec![]; // store lines
let mut line = vec![]; // store a line
let mut current_x = block.x;
let mut current_y = block.y;
let mut div_txt_offset = 0.0; // the offset between div width and text width
let mut is_overflowed = false;
for i in &box_coord_vec{
match i {
Some(inner) =>{
let mut inner_width = inner.width;
if Regex::new(r"[ \t\n]+").unwrap().is_match(&(inner.text)){
inner_width = space_width;
}
if (current_x + inner_width) <= block.x + block.width {
line.push(inner);
// if inner is not space, set the div_txt_offset
if !is_space(&inner.text){
div_txt_offset = block.x + block.width - (current_x + inner.width);
}
current_x += inner_width;
// try to add a new line
}else{
current_x = block.x;
current_y += block.lineskip;
let div_txt_offset_clone = div_txt_offset.clone();
let line_clone = line.clone();
let line_content = Line{
content: line_clone,
div_text_offset: div_txt_offset_clone};
lines.push(line_content);
// if beneath the margin of the botton, don't layout it and break
if current_y > block.y + block.height{
is_overflowed = true;
break;
}
else{
/*println!("{:?}", space_width);
println!("{:?}", div_txt_offset);
println!("{:?}", block.x + block.width);*/
line = vec![];
div_txt_offset = 0.0;
// if it's non space, add it.
if !Regex::new(r"[ \t\n]+").unwrap().is_match(&(inner.text)){
line.push(inner);
current_x += inner_width;
}
}
}
}
None => println!("The text segment can't be layouted."),
}
}
// if it's not overflowed, push the last line.
if !is_overflowed{
let div_txt_offset_clone = div_txt_offset.clone();
let line_clone = line.clone();
let line_content = Line{
content: line_clone,
div_text_offset: div_txt_offset_clone};
lines.push(line_content);
}else{
}
// layout the characters
if ragged == true{
current_y = block.y;
current_x = block.x;
for i in 0..lines.len(){
for j in 0..lines[i].content.len(){
let con = lines[i].content[j];
let mut content_width = con.width;
// if it's space, set it to space_width.
if is_space(&(con.text)){
content_width = space_width;
}
layout_text(&(con.text), &font, current_x, current_y, &(block.color) ,block.language, block.direction , &cxt);
current_x += content_width;
}
current_y += block.lineskip;
current_x = block.x;
}
// unragged.
}else{
current_y = block.y;
current_x = block.x;
for i in 0..lines.len(){
let mut line_word_len_without_space = 0;
// count line word actually len (without spaces)
for j in 0..lines[i].content.len(){
if !is_space(&(lines[i].content[j].text)){
line_word_len_without_space += 1;
}
}
// non last line
if (i < lines.len() - 1) || (is_overflowed) {
let line_space_width = space_width + lines[i].div_text_offset / (line_word_len_without_space as f64 - 1.0);
for j in 0..lines[i].content.len(){
let con = lines[i].content[j];
if is_space(&(con.text)){
current_x += line_space_width;
}else{
layout_text(&(con.text), &font, current_x, current_y, &(block.color) , block.language, block.direction , &cxt);
current_x += con.width;
}
}
current_y += block.lineskip;
current_x = block.x;
}
// last line and if it's not overflowed
else{
for j in 0..lines[i].content.len(){
let con = lines[i].content[j];
let mut content_width = con.width;
// if it's space, set it to space_width.
if is_space(&(con.text)){
content_width = space_width;
}
layout_text(&(con.text), &font, current_x, current_y, &(block.color) , block.language, block.direction , &cxt);
current_x += content_width;
}
}
}
}
}
/// check if it's a space of not.
///
///
fn is_space(txt : &str) -> bool{
return Regex::new(r"[ \t]+").unwrap().is_match(&txt)
}
fn main(){
let font_pt = 20;
/*let font_name = "Amstelvar";
let font_style = "Italic";*/
let font_name = "Noto Sans CJK TC";
let font_style = "Light";
const PDF_WIDTH_IN_PX : f64 = 595.0;
const PDF_HEIGHT_IN_PX : f64 = 842.0;
let pdf_path = "/tmp/a.pdf";
let mut regex_pattern1 = r"([^\s\p{Bopomofo}\p{Han}\p{Hangul}\p{Hiragana}\p{Katakana}。,、;:「」『』()?!─……《》〈〉.~~゠‥{}[]〔〕〘〙〈〉《》【】〖〗※〳〵〴〲〱〽〃]{1,}|".to_string();
let regex_pattern2 = r"[ \p{Bopomofo}\p{Han}\p{Hangul}\p{Hiragana}\p{Katakana}。,、;:「」『』()?!─……《》〈〉.~~゠‥{}[]〔〕〘〙〈〉《》【】〖〗※〳〵〴〲〱〽〃]|──|〴〵|〳〵|[ \t]+)";
regex_pattern1.push_str(®ex_pattern2);
let regex_pattern = Regex::new(®ex_pattern1).unwrap();
//let input_text = "我kā lí講這件——代誌彼は아버지 감사합니다といいます。It's true. happier. Ta̍k-ke. ٱلسَّلَامُ عَلَيْكُمْ שָׁלוֹם עֲלֵיכֶם";
let input_text = "And why all this?d’aoís Certainly not because I believe that the land or the region has anything to do with it, for in any place and in any climate subjection is bitter and to be free is pleasant; but merely because I am of the opinion that one should pity those who, at birth, arrive with the yoke upon their necks. We should exonerate and forgive them, since they have not seen even the shadow of liberty, and, being quite unaware of it, cannot perceive the evil endured through their own slavery. If there were actually a country like that of the Cimmerians mentioned by Homer,";
// 翻譯:在主後1602年,戰爭爆發於兩個以之間——以.歐尼爾和以.如瓦.歐唐納,在金特塞里附近,那時愛爾蘭人民在戰場激烈的耗了九年,對抗他們的敵人,為了……
let mut input_text_vec = vec!();
let block = Div{x:100.0,y:100.0,width:450.0, height: 250.0, lineskip: 30.0, language: "en", direction: harfbuzz_rs::Direction::Ltr, color: "#198964".to_string()};
let mut text : String;
for cap in regex_pattern.captures_iter(input_text){
let text = cap[0].to_string().clone();
input_text_vec.push(text);
}
let mut font_struct1 = FontStruct{size:font_pt, name:font_name, style:font_style, variations : &[Variation::new(b"wght", 200.0),
Variation::new(b"wdth", 20.0)], features : &[]};
let box_coord_vec : Vec<Option<BoxCoodInfo>> = input_text_vec.into_iter().map(|x| get_box_cood_info(&x, font_struct1.name, font_struct1.style, font_struct1.size, block.language, harfbuzz_rs::Direction::Ltr, &[], &[])).collect();
let surface = cairo::PdfSurface::new(PDF_WIDTH_IN_PX, PDF_HEIGHT_IN_PX, pdf_path).expect("Couldn’t create surface"); // A4 size
let cxt = cairo::Context::new(&surface).expect("running error");
cxt.set_source_rgba(0.8, 1.0, 1.0, 0.5); // 設定顏色
cxt.paint().ok();// 設定背景顏色
cxt.set_source_rgba(0.0, 0.0, 1.0, 1.0); // 設定顏色
let font_struct2 = FontStruct{size:30, name:"Noto Sans CJK TC", style:"Bold", variations : &[], features : &[]};
let font_struct3 = FontStruct{size:30, name:"Noto Nastaliq Urdu", style:"Bold", variations : &[], features : &[]};
//layout_text("Tá grá agam duit", font_struct1, 100.0, 100.0,"#198964",harfbuzz_rs::Direction::Ltr, &cxt);
//layout_text("انا احبك ", &font_struct3, 100.0, 300.0,"#198964",harfbuzz_rs::Direction::Rtl, &cxt);
// println!("{:?}", result);
greedy_typesetting(box_coord_vec, block, font_struct1, &cxt, false);
}
|
/*
* @lc app=leetcode.cn id=443 lang=rust
*
* [443] 压缩字符串
*
* https://leetcode-cn.com/problems/string-compression/description/
*
* algorithms
* Easy (32.93%)
* Total Accepted: 2.9K
* Total Submissions: 8.8K
* Testcase Example: '['a','a','b','b','c','c','c']'
*
* 给定一组字符,使用原地算法将其压缩。
*
* 压缩后的长度必须始终小于或等于原数组长度。
*
* 数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。
*
* 在完成原地修改输入数组后,返回数组的新长度。
*
*
*
* 进阶:
* 你能否仅使用O(1) 空间解决问题?
*
*
*
* 示例 1:
*
*
* 输入:
* ['a','a','b','b','c','c','c']
*
* 输出:
* 返回6,输入数组的前6个字符应该是:['a','2','b','2','c','3']
*
* 说明:
* 'aa'被'a2'替代。'bb'被'b2'替代。'ccc'被'c3'替代。
*
*
* 示例 2:
*
*
* 输入:
* ['a']
*
* 输出:
* 返回1,输入数组的前1个字符应该是:['a']
*
* 说明:
* 没有任何字符串被替代。
*
*
* 示例 3:
*
*
* 输入:
* ['a','b','b','b','b','b','b','b','b','b','b','b','b']
*
* 输出:
* 返回4,输入数组的前4个字符应该是:['a','b','1','2']。
*
* 说明:
* 由于字符'a'不重复,所以不会被压缩。'bbbbbbbbbbbb'被“b12”替代。
* 注意每个数字在数组中都有它自己的位置。
*
*
* 注意:
*
*
* 所有字符都有一个ASCII值在[35, 126]区间内。
* 1 <= len(chars) <= 1000。
*
*
*/
impl Solution {
pub fn compress(chars: &mut Vec<char>) -> i32 {
if chars.is_empty() {
return 0;
}
if chars.len() == 1 {
return 1;
}
let mut write_idx = 0;
let mut pre_char = chars[0];
let mut count = 1;
for idx in 1..chars.len() {
if chars[idx] == pre_char {
count += 1;
} else {
chars[write_idx] = pre_char;
write_idx = Solution::write(chars, write_idx, count);
pre_char = chars[idx];
count = 1;
}
}
chars[write_idx] = pre_char;
write_idx = Solution::write(chars, write_idx, count);
write_idx as i32
}
fn write(chars: &mut Vec<char>, write_idx: usize, count: i32) -> usize {
let mut write_idx = write_idx;
write_idx += 1;
if count > 1 {
let s = format!("{}", count);
for c in s.chars() {
chars[write_idx] = c;
write_idx += 1;
}
}
return write_idx;
}
}
fn main() {
let mut chars = vec!['a', 'a', 'a', 'b', 'b', 'a', 'a'];
let idx = Solution::compress(&mut chars);
dbg!(idx);
dbg!(&chars);
}
struct Solution {}
|
// Copyright 2021 Datafuse Labs.
//
// 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 common_meta_stoerr::MetaStorageError;
use serde::Deserialize;
use serde::Serialize;
use thiserror::Error;
use crate::InvalidReply;
use crate::MetaAPIError;
use crate::MetaClientError;
use crate::MetaNetworkError;
/// Top level error MetaNode would return.
#[derive(Error, Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum MetaError {
/// Errors occurred when accessing remote meta store service.
#[error(transparent)]
NetworkError(#[from] MetaNetworkError),
#[error(transparent)]
StorageError(#[from] MetaStorageError),
#[error(transparent)]
ClientError(#[from] MetaClientError),
#[error(transparent)]
APIError(#[from] MetaAPIError),
}
impl From<tonic::Status> for MetaError {
fn from(status: tonic::Status) -> Self {
let net_err = MetaNetworkError::from(status);
MetaError::NetworkError(net_err)
}
}
impl From<InvalidReply> for MetaError {
fn from(e: InvalidReply) -> Self {
let api_err = MetaAPIError::from(e);
Self::APIError(api_err)
}
}
|
#[doc = "Reader of register FPR2"]
pub type R = crate::R<u32, super::FPR2>;
#[doc = "Writer for register FPR2"]
pub type W = crate::W<u32, super::FPR2>;
#[doc = "Register FPR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::FPR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `FPIF35`"]
pub type FPIF35_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FPIF35`"]
pub struct FPIF35_W<'a> {
w: &'a mut W,
}
impl<'a> FPIF35_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `FPIF36`"]
pub type FPIF36_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FPIF36`"]
pub struct FPIF36_W<'a> {
w: &'a mut W,
}
impl<'a> FPIF36_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `FPIF37`"]
pub type FPIF37_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FPIF37`"]
pub struct FPIF37_W<'a> {
w: &'a mut W,
}
impl<'a> FPIF37_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `FPIF38`"]
pub type FPIF38_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FPIF38`"]
pub struct FPIF38_W<'a> {
w: &'a mut W,
}
impl<'a> FPIF38_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
impl R {
#[doc = "Bit 3 - FPIF35"]
#[inline(always)]
pub fn fpif35(&self) -> FPIF35_R {
FPIF35_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - FPIF36"]
#[inline(always)]
pub fn fpif36(&self) -> FPIF36_R {
FPIF36_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - FPIF37"]
#[inline(always)]
pub fn fpif37(&self) -> FPIF37_R {
FPIF37_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - FPIF38"]
#[inline(always)]
pub fn fpif38(&self) -> FPIF38_R {
FPIF38_R::new(((self.bits >> 6) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 3 - FPIF35"]
#[inline(always)]
pub fn fpif35(&mut self) -> FPIF35_W {
FPIF35_W { w: self }
}
#[doc = "Bit 4 - FPIF36"]
#[inline(always)]
pub fn fpif36(&mut self) -> FPIF36_W {
FPIF36_W { w: self }
}
#[doc = "Bit 5 - FPIF37"]
#[inline(always)]
pub fn fpif37(&mut self) -> FPIF37_W {
FPIF37_W { w: self }
}
#[doc = "Bit 6 - FPIF38"]
#[inline(always)]
pub fn fpif38(&mut self) -> FPIF38_W {
FPIF38_W { w: self }
}
}
|
use super::math::*;
use super::vec3;
#[derive(Copy,Clone)]
pub enum Axis { X, Y, Z }
#[derive(Clone, Copy)]
pub struct Ray {
pub origin: Vec3,
pub direction: Vec3,
}
impl Ray {
pub fn new(origin: Vec3, direction: Vec3) -> Ray {
Ray { origin, direction }
}
pub fn at(&self, t: f32) -> Vec3 {
self.origin + self.direction * t
}
}
// TODO should this be in spatial.rs?
// TODO this needs a better name eg RayCastResult
pub struct HitRecord {
pub point: Vec3,
pub normal: Vec3,
pub obj_id: usize,
pub t: f32,
pub front_face: bool,
}
impl HitRecord {
pub fn new() -> HitRecord {
HitRecord {
point: vec3![0.0, 0.0, 0.0],
normal: vec3![0.0, 0.0, 0.0],
obj_id: 0,
t: 0.0,
front_face: false,
}
}
pub fn set_face_and_normal(&mut self, r: Ray, outward_normal: Vec3) {
self.front_face = dot(r.direction, outward_normal) < 0.0;
self.normal = if self.front_face { outward_normal } else { -outward_normal };
}
}
#[derive(Copy, Clone)]
pub struct AABB {
pub min: Vec3,
pub max: Vec3,
}
impl AABB {
pub fn longest_axis(&self) -> Axis {
let d = self.max - self.min;
if (d.x > d.y) && (d.x > d.z) {
Axis::X
}
else if d.y > d.z {
Axis::Y
}
else {
Axis::Z
}
}
fn at_axis(&self, v: &Vec3, axis: Axis) -> f32 {
match axis {
Axis::X => v.x,
Axis::Y => v.y,
Axis::Z => v.z,
}
}
pub fn get_center(&self) -> Vec3 {
(self.min + self.max) * 0.5
}
pub fn min_at_axis(&self, axis: Axis) -> f32 {
self.at_axis(&self.min, axis)
}
pub fn max_at_axis(&self, axis: Axis) -> f32 {
self.at_axis(&self.max, axis)
}
pub fn merge(a: &AABB, b: &AABB) -> AABB {
let min_x = f32::min(a.min.x, b.min.x);
let min_y = f32::min(a.min.y, b.min.y);
let min_z = f32::min(a.min.z, b.min.z);
let max_x = f32::max(a.max.x, b.max.x);
let max_y = f32::max(a.max.y, b.max.y);
let max_z = f32::max(a.max.z, b.max.z);
AABB { min: vec3![min_x, min_y, min_z],
max: vec3![max_x, max_y, max_z] }
}
pub fn hit(&self, r: Ray, mut t_min: f32, mut t_max: f32) -> bool {
let inv_rd = 1.0 / r.direction;
let mut t0 = (self.min.x - r.origin.x) * inv_rd.x;
let mut t1 = (self.max.x - r.origin.x) * inv_rd.x;
if inv_rd.x < 0.0 { std::mem::swap(&mut t0, &mut t1); }
t_min = f32::max(t_min, t0);
t_max = f32::min(t_max, t1);
if t_max <= t_min { return false };
t0 = (self.min.y - r.origin.y) * inv_rd.y;
t1 = (self.max.y - r.origin.y) * inv_rd.y;
if inv_rd.y < 0.0 { std::mem::swap(&mut t0, &mut t1); }
t_min = f32::max(t_min, t0);
t_max = f32::min(t_max, t1);
if t_max <= t_min { return false };
t0 = (self.min.z - r.origin.z) * inv_rd.z;
t1 = (self.max.z - r.origin.z) * inv_rd.z;
if inv_rd.z < 0.0 { std::mem::swap(&mut t0, &mut t1); }
t_min = f32::max(t_min, t0);
t_max = f32::min(t_max, t1);
t_max > t_min
}
}
pub struct Sphere {
pub center: Vec3,
pub velocity: Vec3,
pub radius: f32,
pub material_id: u32
}
impl Sphere {
pub fn calc_aabb(&self) -> AABB {
AABB {
min: self.center - self.radius,
max: self.center + self.radius,
}
}
}
|
use std::hash::Hash;
use std::mem;
use std::sync::{Condvar, Mutex};
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::collections::VecDeque;
pub trait ToKey {
type Key: Hash + Eq;
fn to_key(&self) -> Self::Key;
}
pub struct RunQueue<T: ToKey> {
cvar: Condvar,
inner: Mutex<Inner<T>>,
}
struct Inner<T: ToKey> {
stop: bool,
queue: VecDeque<T>,
members: HashMap<T::Key, usize>,
}
impl<T: ToKey> RunQueue<T> {
pub fn close(&self) {
let mut inner = self.inner.lock().unwrap();
inner.stop = true;
self.cvar.notify_all();
}
pub fn new() -> RunQueue<T> {
RunQueue {
cvar: Condvar::new(),
inner: Mutex::new(Inner {
stop: false,
queue: VecDeque::new(),
members: HashMap::new(),
}),
}
}
pub fn insert(&self, v: T) {
let key = v.to_key();
let mut inner = self.inner.lock().unwrap();
match inner.members.entry(key) {
Entry::Occupied(mut elem) => {
*elem.get_mut() += 1;
}
Entry::Vacant(spot) => {
// add entry to back of queue
spot.insert(0);
inner.queue.push_back(v);
// wake a thread
self.cvar.notify_one();
}
}
}
/// Run (consume from) the run queue using the provided function.
/// The function should return wheter the given element should be rescheduled.
///
/// # Arguments
///
/// - `f` : function to apply to every element
///
/// # Note
///
/// The function f may be called again even when the element was not inserted back in to the
/// queue since the last applciation and no rescheduling was requested.
///
/// This happens then the function handles all work for T,
/// but T is added to the run queue while the function is running.
pub fn run<F: Fn(&T) -> bool>(&self, f: F) {
let mut inner = self.inner.lock().unwrap();
loop {
// fetch next element
let elem = loop {
// run-queue closed
if inner.stop {
return;
}
// try to pop from queue
match inner.queue.pop_front() {
Some(elem) => {
break elem;
}
None => (),
};
// wait for an element to be inserted
inner = self.cvar.wait(inner).unwrap();
};
// fetch current request number
let key = elem.to_key();
let old_n = *inner.members.get(&key).unwrap();
mem::drop(inner); // drop guard
// handle element
let rerun = f(&elem);
// if the function requested a re-run add the element to the back of the queue
inner = self.inner.lock().unwrap();
if rerun {
inner.queue.push_back(elem);
continue;
}
// otherwise check if new requests have come in since we ran the function
match inner.members.entry(key) {
Entry::Occupied(occ) => {
if *occ.get() == old_n {
// no new requests since last, remove entry.
occ.remove();
} else {
// new requests, reschedule.
inner.queue.push_back(elem);
}
}
Entry::Vacant(_) => {
unreachable!();
}
}
}
}
}
|
#[doc = "Reader of register CR"]
pub type R = crate::R<u32, super::CR>;
#[doc = "Writer for register CR"]
pub type W = crate::W<u32, super::CR>;
#[doc = "Register CR `reset()`'s with value 0x80"]
impl crate::ResetValue for super::CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x80
}
}
#[doc = "Force option byte loading\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FORCE_OPTLOAD_A {
#[doc = "0: Force option byte loading inactive"]
INACTIVE = 0,
#[doc = "1: Force option byte loading active"]
ACTIVE = 1,
}
impl From<FORCE_OPTLOAD_A> for bool {
#[inline(always)]
fn from(variant: FORCE_OPTLOAD_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `FORCE_OPTLOAD`"]
pub type FORCE_OPTLOAD_R = crate::R<bool, FORCE_OPTLOAD_A>;
impl FORCE_OPTLOAD_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> FORCE_OPTLOAD_A {
match self.bits {
false => FORCE_OPTLOAD_A::INACTIVE,
true => FORCE_OPTLOAD_A::ACTIVE,
}
}
#[doc = "Checks if the value of the field is `INACTIVE`"]
#[inline(always)]
pub fn is_inactive(&self) -> bool {
*self == FORCE_OPTLOAD_A::INACTIVE
}
#[doc = "Checks if the value of the field is `ACTIVE`"]
#[inline(always)]
pub fn is_active(&self) -> bool {
*self == FORCE_OPTLOAD_A::ACTIVE
}
}
#[doc = "Write proxy for field `FORCE_OPTLOAD`"]
pub struct FORCE_OPTLOAD_W<'a> {
w: &'a mut W,
}
impl<'a> FORCE_OPTLOAD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FORCE_OPTLOAD_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Force option byte loading inactive"]
#[inline(always)]
pub fn inactive(self) -> &'a mut W {
self.variant(FORCE_OPTLOAD_A::INACTIVE)
}
#[doc = "Force option byte loading active"]
#[inline(always)]
pub fn active(self) -> &'a mut W {
self.variant(FORCE_OPTLOAD_A::ACTIVE)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "End of operation interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EOPIE_A {
#[doc = "0: End of operation interrupt disabled"]
DISABLED = 0,
#[doc = "1: End of operation interrupt enabled"]
ENABLED = 1,
}
impl From<EOPIE_A> for bool {
#[inline(always)]
fn from(variant: EOPIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EOPIE`"]
pub type EOPIE_R = crate::R<bool, EOPIE_A>;
impl EOPIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EOPIE_A {
match self.bits {
false => EOPIE_A::DISABLED,
true => EOPIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EOPIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EOPIE_A::ENABLED
}
}
#[doc = "Write proxy for field `EOPIE`"]
pub struct EOPIE_W<'a> {
w: &'a mut W,
}
impl<'a> EOPIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EOPIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "End of operation interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(EOPIE_A::DISABLED)
}
#[doc = "End of operation interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(EOPIE_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Error interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ERRIE_A {
#[doc = "0: Error interrupt generation disabled"]
DISABLED = 0,
#[doc = "1: Error interrupt generation enabled"]
ENABLED = 1,
}
impl From<ERRIE_A> for bool {
#[inline(always)]
fn from(variant: ERRIE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `ERRIE`"]
pub type ERRIE_R = crate::R<bool, ERRIE_A>;
impl ERRIE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ERRIE_A {
match self.bits {
false => ERRIE_A::DISABLED,
true => ERRIE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == ERRIE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == ERRIE_A::ENABLED
}
}
#[doc = "Write proxy for field `ERRIE`"]
pub struct ERRIE_W<'a> {
w: &'a mut W,
}
impl<'a> ERRIE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ERRIE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Error interrupt generation disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(ERRIE_A::DISABLED)
}
#[doc = "Error interrupt generation enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(ERRIE_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Option bytes write enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OPTWRE_A {
#[doc = "0: Option byte write enabled"]
DISABLED = 0,
#[doc = "1: Option byte write disabled"]
ENABLED = 1,
}
impl From<OPTWRE_A> for bool {
#[inline(always)]
fn from(variant: OPTWRE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `OPTWRE`"]
pub type OPTWRE_R = crate::R<bool, OPTWRE_A>;
impl OPTWRE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OPTWRE_A {
match self.bits {
false => OPTWRE_A::DISABLED,
true => OPTWRE_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == OPTWRE_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == OPTWRE_A::ENABLED
}
}
#[doc = "Write proxy for field `OPTWRE`"]
pub struct OPTWRE_W<'a> {
w: &'a mut W,
}
impl<'a> OPTWRE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OPTWRE_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Option byte write enabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(OPTWRE_A::DISABLED)
}
#[doc = "Option byte write disabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(OPTWRE_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Lock\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LOCK_A {
#[doc = "0: FLASH_CR register is unlocked"]
UNLOCKED = 0,
#[doc = "1: FLASH_CR register is locked"]
LOCKED = 1,
}
impl From<LOCK_A> for bool {
#[inline(always)]
fn from(variant: LOCK_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `LOCK`"]
pub type LOCK_R = crate::R<bool, LOCK_A>;
impl LOCK_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> LOCK_A {
match self.bits {
false => LOCK_A::UNLOCKED,
true => LOCK_A::LOCKED,
}
}
#[doc = "Checks if the value of the field is `UNLOCKED`"]
#[inline(always)]
pub fn is_unlocked(&self) -> bool {
*self == LOCK_A::UNLOCKED
}
#[doc = "Checks if the value of the field is `LOCKED`"]
#[inline(always)]
pub fn is_locked(&self) -> bool {
*self == LOCK_A::LOCKED
}
}
#[doc = "Write proxy for field `LOCK`"]
pub struct LOCK_W<'a> {
w: &'a mut W,
}
impl<'a> LOCK_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LOCK_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "FLASH_CR register is unlocked"]
#[inline(always)]
pub fn unlocked(self) -> &'a mut W {
self.variant(LOCK_A::UNLOCKED)
}
#[doc = "FLASH_CR register is locked"]
#[inline(always)]
pub fn locked(self) -> &'a mut W {
self.variant(LOCK_A::LOCKED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Start\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum STRT_A {
#[doc = "1: Trigger an erase operation"]
START = 1,
}
impl From<STRT_A> for bool {
#[inline(always)]
fn from(variant: STRT_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `STRT`"]
pub type STRT_R = crate::R<bool, STRT_A>;
impl STRT_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, STRT_A> {
use crate::Variant::*;
match self.bits {
true => Val(STRT_A::START),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `START`"]
#[inline(always)]
pub fn is_start(&self) -> bool {
*self == STRT_A::START
}
}
#[doc = "Write proxy for field `STRT`"]
pub struct STRT_W<'a> {
w: &'a mut W,
}
impl<'a> STRT_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: STRT_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Trigger an erase operation"]
#[inline(always)]
pub fn start(self) -> &'a mut W {
self.variant(STRT_A::START)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Option byte erase\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OPTER_A {
#[doc = "1: Erase option byte activated"]
OPTIONBYTEERASE = 1,
}
impl From<OPTER_A> for bool {
#[inline(always)]
fn from(variant: OPTER_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `OPTER`"]
pub type OPTER_R = crate::R<bool, OPTER_A>;
impl OPTER_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, OPTER_A> {
use crate::Variant::*;
match self.bits {
true => Val(OPTER_A::OPTIONBYTEERASE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `OPTIONBYTEERASE`"]
#[inline(always)]
pub fn is_option_byte_erase(&self) -> bool {
*self == OPTER_A::OPTIONBYTEERASE
}
}
#[doc = "Write proxy for field `OPTER`"]
pub struct OPTER_W<'a> {
w: &'a mut W,
}
impl<'a> OPTER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OPTER_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Erase option byte activated"]
#[inline(always)]
pub fn option_byte_erase(self) -> &'a mut W {
self.variant(OPTER_A::OPTIONBYTEERASE)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Option byte programming\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OPTPG_A {
#[doc = "1: Program option byte activated"]
OPTIONBYTEPROGRAMMING = 1,
}
impl From<OPTPG_A> for bool {
#[inline(always)]
fn from(variant: OPTPG_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `OPTPG`"]
pub type OPTPG_R = crate::R<bool, OPTPG_A>;
impl OPTPG_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, OPTPG_A> {
use crate::Variant::*;
match self.bits {
true => Val(OPTPG_A::OPTIONBYTEPROGRAMMING),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `OPTIONBYTEPROGRAMMING`"]
#[inline(always)]
pub fn is_option_byte_programming(&self) -> bool {
*self == OPTPG_A::OPTIONBYTEPROGRAMMING
}
}
#[doc = "Write proxy for field `OPTPG`"]
pub struct OPTPG_W<'a> {
w: &'a mut W,
}
impl<'a> OPTPG_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OPTPG_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Program option byte activated"]
#[inline(always)]
pub fn option_byte_programming(self) -> &'a mut W {
self.variant(OPTPG_A::OPTIONBYTEPROGRAMMING)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Mass erase\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MER_A {
#[doc = "1: Erase activated for all user sectors"]
MASSERASE = 1,
}
impl From<MER_A> for bool {
#[inline(always)]
fn from(variant: MER_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `MER`"]
pub type MER_R = crate::R<bool, MER_A>;
impl MER_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, MER_A> {
use crate::Variant::*;
match self.bits {
true => Val(MER_A::MASSERASE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `MASSERASE`"]
#[inline(always)]
pub fn is_mass_erase(&self) -> bool {
*self == MER_A::MASSERASE
}
}
#[doc = "Write proxy for field `MER`"]
pub struct MER_W<'a> {
w: &'a mut W,
}
impl<'a> MER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MER_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Erase activated for all user sectors"]
#[inline(always)]
pub fn mass_erase(self) -> &'a mut W {
self.variant(MER_A::MASSERASE)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Page erase\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PER_A {
#[doc = "1: Erase activated for selected page"]
PAGEERASE = 1,
}
impl From<PER_A> for bool {
#[inline(always)]
fn from(variant: PER_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PER`"]
pub type PER_R = crate::R<bool, PER_A>;
impl PER_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, PER_A> {
use crate::Variant::*;
match self.bits {
true => Val(PER_A::PAGEERASE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PAGEERASE`"]
#[inline(always)]
pub fn is_page_erase(&self) -> bool {
*self == PER_A::PAGEERASE
}
}
#[doc = "Write proxy for field `PER`"]
pub struct PER_W<'a> {
w: &'a mut W,
}
impl<'a> PER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PER_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Erase activated for selected page"]
#[inline(always)]
pub fn page_erase(self) -> &'a mut W {
self.variant(PER_A::PAGEERASE)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Programming\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PG_A {
#[doc = "1: Flash programming activated"]
PROGRAM = 1,
}
impl From<PG_A> for bool {
#[inline(always)]
fn from(variant: PG_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PG`"]
pub type PG_R = crate::R<bool, PG_A>;
impl PG_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<bool, PG_A> {
use crate::Variant::*;
match self.bits {
true => Val(PG_A::PROGRAM),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PROGRAM`"]
#[inline(always)]
pub fn is_program(&self) -> bool {
*self == PG_A::PROGRAM
}
}
#[doc = "Write proxy for field `PG`"]
pub struct PG_W<'a> {
w: &'a mut W,
}
impl<'a> PG_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PG_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Flash programming activated"]
#[inline(always)]
pub fn program(self) -> &'a mut W {
self.variant(PG_A::PROGRAM)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 13 - Force option byte loading"]
#[inline(always)]
pub fn force_optload(&self) -> FORCE_OPTLOAD_R {
FORCE_OPTLOAD_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 12 - End of operation interrupt enable"]
#[inline(always)]
pub fn eopie(&self) -> EOPIE_R {
EOPIE_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 10 - Error interrupt enable"]
#[inline(always)]
pub fn errie(&self) -> ERRIE_R {
ERRIE_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - Option bytes write enable"]
#[inline(always)]
pub fn optwre(&self) -> OPTWRE_R {
OPTWRE_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 7 - Lock"]
#[inline(always)]
pub fn lock(&self) -> LOCK_R {
LOCK_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - Start"]
#[inline(always)]
pub fn strt(&self) -> STRT_R {
STRT_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - Option byte erase"]
#[inline(always)]
pub fn opter(&self) -> OPTER_R {
OPTER_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - Option byte programming"]
#[inline(always)]
pub fn optpg(&self) -> OPTPG_R {
OPTPG_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 2 - Mass erase"]
#[inline(always)]
pub fn mer(&self) -> MER_R {
MER_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - Page erase"]
#[inline(always)]
pub fn per(&self) -> PER_R {
PER_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - Programming"]
#[inline(always)]
pub fn pg(&self) -> PG_R {
PG_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 13 - Force option byte loading"]
#[inline(always)]
pub fn force_optload(&mut self) -> FORCE_OPTLOAD_W {
FORCE_OPTLOAD_W { w: self }
}
#[doc = "Bit 12 - End of operation interrupt enable"]
#[inline(always)]
pub fn eopie(&mut self) -> EOPIE_W {
EOPIE_W { w: self }
}
#[doc = "Bit 10 - Error interrupt enable"]
#[inline(always)]
pub fn errie(&mut self) -> ERRIE_W {
ERRIE_W { w: self }
}
#[doc = "Bit 9 - Option bytes write enable"]
#[inline(always)]
pub fn optwre(&mut self) -> OPTWRE_W {
OPTWRE_W { w: self }
}
#[doc = "Bit 7 - Lock"]
#[inline(always)]
pub fn lock(&mut self) -> LOCK_W {
LOCK_W { w: self }
}
#[doc = "Bit 6 - Start"]
#[inline(always)]
pub fn strt(&mut self) -> STRT_W {
STRT_W { w: self }
}
#[doc = "Bit 5 - Option byte erase"]
#[inline(always)]
pub fn opter(&mut self) -> OPTER_W {
OPTER_W { w: self }
}
#[doc = "Bit 4 - Option byte programming"]
#[inline(always)]
pub fn optpg(&mut self) -> OPTPG_W {
OPTPG_W { w: self }
}
#[doc = "Bit 2 - Mass erase"]
#[inline(always)]
pub fn mer(&mut self) -> MER_W {
MER_W { w: self }
}
#[doc = "Bit 1 - Page erase"]
#[inline(always)]
pub fn per(&mut self) -> PER_W {
PER_W { w: self }
}
#[doc = "Bit 0 - Programming"]
#[inline(always)]
pub fn pg(&mut self) -> PG_W {
PG_W { w: self }
}
}
|
use crate::libbb::default_error_retval::xfunc_error_retval;
use libc;
/* Keeping it separate allows to NOT pull in stdio for VERY small applets.
* Try building busybox with only "true" enabled... */
pub static mut die_func: Option<unsafe extern "C" fn() -> ()> = None;
pub unsafe fn xfunc_die() -> ! {
match die_func {
Some(df) => df(),
None => (),
}
::std::process::exit(xfunc_error_retval as libc::c_int);
}
|
use game::*;
pub fn step_debug(_game: &mut Game1){
}
|
/*! Compression operation, using gzip in default implementatino !*/
use std::{
fs::File,
io::{BufRead, BufReader, Read, Write},
path::{Path, PathBuf},
};
use flate2::{write::GzEncoder, Compression};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use crate::error::Error;
pub trait Compress {
/// Compress a file located at `src` to `dst`.
/// If `del_src` is set to `true`, removes the file at `src` upon compression completion.
///
/// `src` has to exist and be a file, and `dst` should not exist.
fn compress_file(src: &Path, dst: &Path, del_src: bool) -> Result<(), Error> {
if !src.is_file() {
warn!("{:?} is not a file: ignoring", src);
return Ok(());
}
let src_file = File::open(src)?;
// gen filename
let filename = src.file_name().unwrap();
let mut dst: PathBuf = [dst.as_os_str(), filename].iter().collect();
if let Some(ext) = dst.extension() {
//TODO remove unwrapping here
let extension = String::from(ext.to_str().unwrap());
if extension == ".gz" {
warn!("{:?} is already compressed! Skipping.", dst);
return Ok(());
}
dst.set_extension(extension + ".gz");
} else {
warn!("File {0:?} has no extension! Fallback to {0:?}.txt.gz", dst);
let extension = "txt.gz";
dst.set_extension(extension);
}
info!("compressing {:?} to {:?}", src, dst);
if dst.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
format!("{:?}", dst),
)
.into());
}
let mut dest_file = File::create(dst)?;
compress(&mut dest_file, src_file)?;
if del_src {
info!("removing {:?}", src);
std::fs::remove_file(src)?;
}
Ok(())
}
/// Compress files in provided folder.
/// If `del_src` is set to `true`, removes the compressed files at `src` upon compression completion.
/// The compression is only done at depth=1.
/// `src` has to exist and be a file, and `dst` should not exist.
fn compress_folder(src: &Path, dst: &Path, del_src: bool) -> Result<(), Error> {
//TODO: read dir
// if file, error+ignore
// if dir, read dir
// if file, compress
// if dir, error+ignore
// There should be an easier way to do that.
let files_to_compress: Result<Vec<_>, std::io::Error> = std::fs::read_dir(src)?.collect();
let files_to_compress: Vec<PathBuf> =
files_to_compress?.into_iter().map(|x| x.path()).collect();
let files_to_compress = files_to_compress.into_par_iter();
if !dst.exists() {
debug!("Creating {:?}", dst);
std::fs::create_dir(&dst)?;
}
// construct vector of errors
let errors: Vec<Error> = files_to_compress
.filter_map(|filepath| Self::compress_file(&filepath, dst, del_src).err())
.collect();
if !errors.is_empty() {
for error in &errors {
error!("{:?}", error);
}
};
Ok(())
}
fn compress_corpus(
src: &Path,
dst: &Path,
del_src: bool,
num_threads: usize,
) -> Result<(), Error> {
if num_threads != 1 {
rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build_global()?;
debug!("Built rayon threadpool with num_threads={num_threads}");
}
if !dst.exists() {
std::fs::create_dir(dst)?;
}
let language_directories: Result<Vec<_>, std::io::Error> =
std::fs::read_dir(src)?.collect();
let language_directories: Vec<PathBuf> = language_directories?
.into_iter()
.map(|x| x.path())
.collect();
let languages_to_compress = language_directories.into_par_iter();
let results: Vec<Result<_, Error>> = languages_to_compress
.map(|language_dir| {
let file_stem = language_dir.file_name().ok_or_else(|| {
Error::Custom(format!("Bad file name {:?}", language_dir.file_name()))
})?;
let dst_folder = dst.clone().join(file_stem);
debug!("compressing {:?} into{:?}", &language_dir, &dst_folder);
// transform source + language
// into dest + language
Self::compress_folder(&language_dir, &dst_folder, del_src)
})
.collect();
for result in results.into_iter().filter(|r| r.is_err()) {
error!("{:?}", result);
}
Ok(())
}
}
/// Compress a reader into a writer.
/// Consumes the whole reader.
// TODO: should it be inside the compress trait?
fn compress<T: Read>(dest_file: &mut impl Write, r: T) -> Result<(), Error> {
let mut b = BufReader::new(r);
let mut enc = GzEncoder::new(dest_file, Compression::default());
let mut length = 1;
while length > 0 {
let buffer = b.fill_buf()?;
enc.write_all(buffer)?;
length = buffer.len();
b.consume(length);
}
enc.try_finish()?;
Ok(())
}
#[cfg(test)]
mod test {
use std::{fs::File, io::Read, io::Write};
use tempfile::tempdir;
use crate::ops::Compress;
use super::compress;
#[test]
fn test_compress() {
// create content and compress
let content = "foo";
let mut compressed = Vec::new();
compress(&mut compressed, content.as_bytes()).unwrap();
let mut reader = flate2::read::GzDecoder::new(&*compressed);
let mut decompressed = String::with_capacity(content.len());
reader.read_to_string(&mut decompressed).unwrap();
assert_eq!(content, decompressed);
}
#[test]
fn test_dst_not_directory() {
struct Dummy;
impl Compress for Dummy {}
let src = tempfile::NamedTempFile::new().unwrap();
let dst = tempfile::NamedTempFile::new().unwrap();
match Dummy::compress_file(src.path(), dst.path(), false).err() {
None => panic!("Should fail!"),
Some(error) => match error {
crate::error::Error::Io(_) => {
//when #86442 is merged
// assert_eq!(error.kind(), std::io::ErrorKind::NotADirectory)
assert!(true)
}
_ => panic!("wrong error type!"),
},
}
}
#[test]
fn test_dst_exists() {
struct Dummy;
impl Compress for Dummy {}
let dir = tempdir().unwrap();
let src = dir.path().join("test.txt");
let mut file = File::create(&src).unwrap();
writeln!(file, "Brian was here. Briefly.").unwrap();
let mut dst = src.clone();
dst.set_extension("txt.gz");
File::create(&dst).unwrap();
match Dummy::compress_file(&src, dir.path(), false).err() {
None => panic!("Should fail!"),
Some(error) => match error {
crate::error::Error::Io(error) => {
assert_eq!(
error.kind(),
std::io::ErrorKind::AlreadyExists,
"{:?}",
error
)
}
_ => panic!("wrong error type!"),
},
}
}
}
|
use super::raw_model::RawModel;
use crate::textures::model_texture::ModelTexture;
pub struct TexturedModel {
raw_model: RawModel,
texture: ModelTexture,
}
impl TexturedModel {
pub fn new(raw_model: RawModel, texture: ModelTexture) -> TexturedModel {
TexturedModel { raw_model, texture }
}
pub fn get_raw_model(&self) -> &RawModel {
&self.raw_model
}
pub fn get_texture(&self) -> &ModelTexture {
&self.texture
}
}
|
use input_i_scanner::{scan_with, InputIScanner};
fn inv(a: i64, m: i64) -> i64 {
let (x, _, _) = ext_gcd::ext_gcd(a, m);
(x + m) % m
}
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
let t = scan_with!(_i_i, i64);
let m = 998244353;
let mut ans = 0;
for i in 1..=t {
ans += inv(i + 1, m);
ans %= m;
}
println!("{}", ans);
}
|
#![forbid(unsafe_code)]
mod lexer;
mod parser;
mod types;
use lexer::Token;
use logos::Logos;
use parser::parse_expressions;
use types::Var;
fn main() {
let src = "(+ (* x x) (* 2 x))";
let lex = Token::lexer(src);
let lexed: Vec<_> = lex.collect();
let var = Var::new(String::from("x"));
match parse_expressions(&lexed) {
Some((exprs, _)) => {
for e in exprs {
println!("{e}");
println!(" => {}", e.derivative(&var).simplify());
}
}
None => eprintln!("Failed to parse expressions"),
}
}
|
// Copyright 2021 Datafuse Labs.
//
// 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 std::cmp;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::sync::Arc;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::types::number::NumberScalar;
use common_expression::types::DataType;
use common_expression::types::NumberDataType;
use common_expression::BlockEntry;
use common_expression::DataBlock;
use common_expression::RemoteExpr;
use common_expression::Scalar;
use common_expression::TableDataType;
use common_expression::TableField;
use common_expression::TableSchema;
use common_expression::TableSchemaRefExt;
use common_expression::Value;
use jsonb::Value as JsonbValue;
use serde_json::json;
use serde_json::Value as JsonValue;
use storages_common_table_meta::meta::BlockMeta;
use crate::io::SegmentsIO;
use crate::sessions::TableContext;
use crate::FuseTable;
use crate::Table;
pub struct ClusteringInformation<'a> {
pub ctx: Arc<dyn TableContext>,
pub table: &'a FuseTable,
pub plain_cluster_keys: String,
pub cluster_keys: Vec<RemoteExpr<String>>,
}
struct ClusteringStatistics {
total_block_count: u64,
total_constant_block_count: u64,
average_overlaps: f64,
average_depth: f64,
block_depth_histogram: JsonValue,
}
impl Default for ClusteringStatistics {
fn default() -> Self {
ClusteringStatistics {
total_block_count: 0,
total_constant_block_count: 0,
average_overlaps: 0.0,
average_depth: 0.0,
block_depth_histogram: json!({}),
}
}
}
impl<'a> ClusteringInformation<'a> {
pub fn new(
ctx: Arc<dyn TableContext>,
table: &'a FuseTable,
plain_cluster_keys: String,
cluster_keys: Vec<RemoteExpr<String>>,
) -> Self {
Self {
ctx,
table,
plain_cluster_keys,
cluster_keys,
}
}
pub async fn get_clustering_info(&self) -> Result<DataBlock> {
let snapshot = self.table.read_table_snapshot().await?;
let mut info = ClusteringStatistics::default();
if let Some(snapshot) = snapshot {
let segment_locations = &snapshot.segments;
let segments_io = SegmentsIO::create(
self.ctx.clone(),
self.table.operator.clone(),
self.table.schema(),
);
let segments = segments_io
.read_segments(segment_locations)
.await?
.into_iter()
.collect::<Result<Vec<_>>>()?;
if !segments.is_empty() {
let blocks = segments.iter().flat_map(|s| s.blocks.iter());
info = self.get_clustering_stats(blocks)?
}
};
let cluster_by_keys = self.plain_cluster_keys.clone();
Ok(DataBlock::new(
vec![
BlockEntry {
data_type: DataType::String,
value: Value::Scalar(Scalar::String(cluster_by_keys.as_bytes().to_vec())),
},
BlockEntry {
data_type: DataType::Number(NumberDataType::UInt64),
value: Value::Scalar(Scalar::Number(NumberScalar::UInt64(
info.total_block_count,
))),
},
BlockEntry {
data_type: DataType::Number(NumberDataType::UInt64),
value: Value::Scalar(Scalar::Number(NumberScalar::UInt64(
info.total_constant_block_count,
))),
},
BlockEntry {
data_type: DataType::Number(NumberDataType::Float64),
value: Value::Scalar(Scalar::Number(NumberScalar::Float64(
info.average_overlaps.into(),
))),
},
BlockEntry {
data_type: DataType::Number(NumberDataType::Float64),
value: Value::Scalar(Scalar::Number(NumberScalar::Float64(
info.average_depth.into(),
))),
},
BlockEntry {
data_type: DataType::Variant,
value: Value::Scalar(Scalar::Variant(
JsonbValue::from(&info.block_depth_histogram).to_vec(),
)),
},
],
1,
))
}
fn get_min_max_stats(&self, block: &BlockMeta) -> Result<(Vec<Scalar>, Vec<Scalar>)> {
if self.table.cluster_keys(self.ctx.clone()) != self.cluster_keys
|| block.cluster_stats.is_none()
{
// Todo(zhyass): support manually specifying the cluster key.
return Err(ErrorCode::Unimplemented("Unimplemented"));
}
let cluster_key_id = block.cluster_stats.clone().unwrap().cluster_key_id;
let default_cluster_key_id = self.table.cluster_key_meta.clone().unwrap().0;
if cluster_key_id != default_cluster_key_id {
return Err(ErrorCode::Unimplemented("Unimplemented"));
}
let cluster_stats = block.cluster_stats.clone().unwrap();
Ok((cluster_stats.min, cluster_stats.max))
}
fn get_clustering_stats<'b>(
&self,
blocks: impl Iterator<Item = &'b Arc<BlockMeta>>,
) -> Result<ClusteringStatistics> {
// Gather all cluster statistics points to a sorted Map.
// Key: The cluster statistics points.
// Value: 0: The block indexes with key as min value;
// 1: The block indexes with key as max value;
let mut points_map: BTreeMap<Vec<Scalar>, (Vec<usize>, Vec<usize>)> = BTreeMap::new();
let mut total_constant_block_count = 0;
let mut total_block_count = 0;
for (i, block) in blocks.enumerate() {
let (min, max) = self.get_min_max_stats(block.as_ref())?;
if min.eq(&max) {
total_constant_block_count += 1;
}
points_map
.entry(min.clone())
.and_modify(|v| v.0.push(i))
.or_insert((vec![i], vec![]));
points_map
.entry(max.clone())
.and_modify(|v| v.1.push(i))
.or_insert((vec![], vec![i]));
total_block_count += 1;
}
// calculate overlaps and depth.
let mut statis = Vec::new();
// key: the block index.
// value: (overlaps, depth).
let mut unfinished_parts: HashMap<usize, (usize, usize)> = HashMap::new();
for (start, end) in points_map.values() {
let point_depth = unfinished_parts.len() + start.len();
for (_, val) in unfinished_parts.iter_mut() {
val.0 += start.len();
val.1 = cmp::max(val.1, point_depth);
}
start.iter().for_each(|&idx| {
unfinished_parts.insert(idx, (point_depth - 1, point_depth));
});
end.iter().for_each(|&idx| {
let stat = unfinished_parts.remove(&idx).unwrap();
statis.push(stat);
});
}
assert_eq!(unfinished_parts.len(), 0);
let mut sum_overlap = 0;
let mut sum_depth = 0;
let length = statis.len();
let mp = statis
.into_iter()
.fold(BTreeMap::new(), |mut acc, (overlap, depth)| {
sum_overlap += overlap;
sum_depth += depth;
let bucket = get_buckets(depth);
acc.entry(bucket).and_modify(|v| *v += 1).or_insert(1u32);
acc
});
// round the float to 4 decimal places.
let average_depth = (10000.0 * sum_depth as f64 / length as f64).round() / 10000.0;
let average_overlaps = (10000.0 * sum_overlap as f64 / length as f64).round() / 10000.0;
let objects = mp.iter().fold(
serde_json::Map::with_capacity(mp.len()),
|mut acc, (bucket, count)| {
acc.insert(format!("{:05}", bucket), json!(count));
acc
},
);
let block_depth_histogram = JsonValue::Object(objects);
Ok(ClusteringStatistics {
total_block_count,
total_constant_block_count,
average_overlaps,
average_depth,
block_depth_histogram,
})
}
pub fn schema() -> Arc<TableSchema> {
TableSchemaRefExt::create(vec![
TableField::new("cluster_by_keys", TableDataType::String),
TableField::new(
"total_block_count",
TableDataType::Number(NumberDataType::UInt64),
),
TableField::new(
"total_constant_block_count",
TableDataType::Number(NumberDataType::UInt64),
),
TableField::new(
"average_overlaps",
TableDataType::Number(NumberDataType::Float64),
),
TableField::new(
"average_depth",
TableDataType::Number(NumberDataType::Float64),
),
TableField::new("block_depth_histogram", TableDataType::Variant),
])
}
}
// The histogram contains buckets with widths:
// 1 to 16 with increments of 1.
// For buckets larger than 16, increments of twice the width of the previous bucket (e.g. 32, 64, 128, …).
// e.g. If val is 2, the bucket is 2. If val is 18, the bucket is 32.
fn get_buckets(val: usize) -> u32 {
let mut val = val as u32;
if val <= 16 || val & (val - 1) == 0 {
return val;
}
val |= val >> 1;
val |= val >> 2;
val |= val >> 4;
val |= val >> 8;
val |= val >> 16;
val + 1
}
|
use crate::codec::{Decode, Encode};
use crate::{remote_type, Quaternion, RemoteObject, Vector3};
remote_type!(
/// Represents a reference frame for positions, rotations and velocities. Contains:
///
/// * The position of the origin.
/// * The directions of the x, y and z axes.
/// * The linear velocity of the frame.
/// * The angular velocity of the frame.
///
/// # Note
/// This struct does not contain any class methods. It is only to be used as a parameter to
/// other functions.
object SpaceCenter.ReferenceFrame {
static_methods: {
{
/// Create a relative reference frame. This is a custom reference frame whose components
/// offset the components of a parent reference frame.
///
/// **Game Scenes***: All
///
/// # Arguments
/// * `client` - The krpc client.
/// * `reference_frame` - The parent reference frame on which to base this reference frame.
/// * `position` - The offset of the position of the origin, as a position vector. If `None`,
/// (0,0,0) is used.
/// * `rotation` - The rotation to apply to the parent frames rotation, as a quaternion of the
/// form (x,y,z,w). If `None`, (0,0,0,1) is used (i.e. no rotation)
/// * `velocity` - The linear velocity to offset the parent frame by, as a vector pointing in
/// the direction of travel, whose magnitude is the speed in meters per second. If `None`,
/// (0,0,0) is used.
/// * `angular_velocity` - The angular velocity to offset the parent frame by, as a vector.
/// This vector points in the direction of the axis of rotation, and its magnitude is the
/// speed of the rotation in radians per second. If `None`, (0,0,0) is used.
fn create_relative(reference_frame: &ReferenceFrame,
position: Option<Vector3>,
rotation: Option<Quaternion>,
velocity: Option<Vector3>,
angular_velocity: Option<Vector3>) -> ReferenceFrame<'a> {
CreateRelative(reference_frame,
position.unwrap_or((0.0, 0.0, 0.0)),
rotation.unwrap_or((0.0, 0.0, 0.0, 1.0)),
velocity.unwrap_or((0.0, 0.0, 0.0)),
angular_velocity.unwrap_or((0.0, 0.0, 0.0)))
}
}
{
/// Create a hybrid reference frame. This is a custom reference frame whose components
/// inherited from other reference frames.
///
/// **Game Scenes***: All
///
/// # Arguments
/// * `client` - The krpc client.
/// * `reference_frame` - The parent reference frame on which to base this reference frame.
/// * `position` - The reference frame providing the position of the origin.
/// * `rotation` - The reference frame providing the rotation of the frame. If `None`,
/// the rotation of the `position` frame is used.
/// * `velocity` - The reference frame providing the linear velocity of the frame. If `None`,
/// the linear velocity of the `position` frame is used.
/// * `angular_velocity` - The reference frame providing the angular velocity of the frame.
/// If `None`, the angular velocity of the `position` frame is used.
fn create_hybrid(position: &ReferenceFrame,
rotation: Option<&ReferenceFrame>,
velocity: Option<&ReferenceFrame>,
angular_velocity: Option<&ReferenceFrame>) -> ReferenceFrame<'a> {
CreateHybrid(position, rotation, velocity, angular_velocity)
}
}
}
});
|
//! linux_raw syscalls supporting `rustix::termios`.
//!
//! # Safety
//!
//! See the `rustix::backend` module documentation for details.
#![allow(unsafe_code)]
#![allow(clippy::undocumented_unsafe_blocks)]
use crate::backend::c;
use crate::backend::conv::{by_ref, c_uint, ret};
use crate::fd::BorrowedFd;
use crate::io;
use crate::pid::Pid;
#[cfg(feature = "procfs")]
use crate::procfs;
use crate::termios::{
Action, ControlModes, InputModes, LocalModes, OptionalActions, OutputModes, QueueSelector,
SpecialCodeIndex, Termios, Winsize,
};
#[cfg(feature = "procfs")]
use crate::{ffi::CStr, fs::FileType, path::DecInt};
use core::mem::MaybeUninit;
use linux_raw_sys::general::IBSHIFT;
use linux_raw_sys::ioctl::{
TCFLSH, TCSBRK, TCXONC, TIOCEXCL, TIOCGPGRP, TIOCGSID, TIOCGWINSZ, TIOCNXCL, TIOCSPGRP,
TIOCSWINSZ,
};
#[inline]
pub(crate) fn tcgetwinsize(fd: BorrowedFd<'_>) -> io::Result<Winsize> {
unsafe {
let mut result = MaybeUninit::<Winsize>::uninit();
ret(syscall!(__NR_ioctl, fd, c_uint(TIOCGWINSZ), &mut result))?;
Ok(result.assume_init())
}
}
#[inline]
pub(crate) fn tcgetattr(fd: BorrowedFd<'_>) -> io::Result<Termios> {
unsafe {
let mut result = MaybeUninit::<Termios>::uninit();
ret(syscall!(__NR_ioctl, fd, c_uint(c::TCGETS2), &mut result))?;
Ok(result.assume_init())
}
}
#[inline]
pub(crate) fn tcgetpgrp(fd: BorrowedFd<'_>) -> io::Result<Pid> {
unsafe {
let mut result = MaybeUninit::<c::pid_t>::uninit();
ret(syscall!(__NR_ioctl, fd, c_uint(TIOCGPGRP), &mut result))?;
let pid = result.assume_init();
Ok(Pid::from_raw_unchecked(pid))
}
}
#[inline]
pub(crate) fn tcsetattr(
fd: BorrowedFd,
optional_actions: OptionalActions,
termios: &Termios,
) -> io::Result<()> {
// Translate from `optional_actions` into an ioctl request code. On MIPS,
// `optional_actions` already has `TCGETS` added to it.
let request = linux_raw_sys::ioctl::TCSETS2
+ if cfg!(any(
target_arch = "mips",
target_arch = "mips32r6",
target_arch = "mips64",
target_arch = "mips64r6"
)) {
optional_actions as u32 - linux_raw_sys::ioctl::TCSETS
} else {
optional_actions as u32
};
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(request),
by_ref(termios)
))
}
}
#[inline]
pub(crate) fn tcsendbreak(fd: BorrowedFd) -> io::Result<()> {
unsafe { ret(syscall_readonly!(__NR_ioctl, fd, c_uint(TCSBRK), c_uint(0))) }
}
#[inline]
pub(crate) fn tcdrain(fd: BorrowedFd) -> io::Result<()> {
unsafe { ret(syscall_readonly!(__NR_ioctl, fd, c_uint(TCSBRK), c_uint(1))) }
}
#[inline]
pub(crate) fn tcflush(fd: BorrowedFd, queue_selector: QueueSelector) -> io::Result<()> {
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(TCFLSH),
c_uint(queue_selector as u32)
))
}
}
#[inline]
pub(crate) fn tcflow(fd: BorrowedFd, action: Action) -> io::Result<()> {
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(TCXONC),
c_uint(action as u32)
))
}
}
#[inline]
pub(crate) fn tcgetsid(fd: BorrowedFd) -> io::Result<Pid> {
unsafe {
let mut result = MaybeUninit::<c::pid_t>::uninit();
ret(syscall!(__NR_ioctl, fd, c_uint(TIOCGSID), &mut result))?;
let pid = result.assume_init();
Ok(Pid::from_raw_unchecked(pid))
}
}
#[inline]
pub(crate) fn tcsetwinsize(fd: BorrowedFd, winsize: Winsize) -> io::Result<()> {
unsafe {
ret(syscall!(
__NR_ioctl,
fd,
c_uint(TIOCSWINSZ),
by_ref(&winsize)
))
}
}
#[inline]
pub(crate) fn tcsetpgrp(fd: BorrowedFd<'_>, pid: Pid) -> io::Result<()> {
unsafe { ret(syscall!(__NR_ioctl, fd, c_uint(TIOCSPGRP), pid)) }
}
#[inline]
pub(crate) fn ioctl_tiocexcl(fd: BorrowedFd<'_>) -> io::Result<()> {
unsafe { ret(syscall_readonly!(__NR_ioctl, fd, c_uint(TIOCEXCL))) }
}
#[inline]
pub(crate) fn ioctl_tiocnxcl(fd: BorrowedFd<'_>) -> io::Result<()> {
unsafe { ret(syscall_readonly!(__NR_ioctl, fd, c_uint(TIOCNXCL))) }
}
/// A wrapper around a conceptual `cfsetspeed` which handles an arbitrary
/// integer speed value.
#[inline]
pub(crate) fn set_speed(termios: &mut Termios, arbitrary_speed: u32) -> io::Result<()> {
let encoded_speed = crate::termios::speed::encode(arbitrary_speed).unwrap_or(c::BOTHER);
debug_assert_eq!(encoded_speed & !c::CBAUD, 0);
termios.control_modes -= ControlModes::from_bits_retain(c::CBAUD | c::CIBAUD);
termios.control_modes |=
ControlModes::from_bits_retain(encoded_speed | (encoded_speed << IBSHIFT));
termios.input_speed = arbitrary_speed;
termios.output_speed = arbitrary_speed;
Ok(())
}
/// A wrapper around a conceptual `cfsetospeed` which handles an arbitrary
/// integer speed value.
#[inline]
pub(crate) fn set_output_speed(termios: &mut Termios, arbitrary_speed: u32) -> io::Result<()> {
let encoded_speed = crate::termios::speed::encode(arbitrary_speed).unwrap_or(c::BOTHER);
debug_assert_eq!(encoded_speed & !c::CBAUD, 0);
termios.control_modes -= ControlModes::from_bits_retain(c::CBAUD);
termios.control_modes |= ControlModes::from_bits_retain(encoded_speed);
termios.output_speed = arbitrary_speed;
Ok(())
}
/// A wrapper around a conceptual `cfsetispeed` which handles an arbitrary
/// integer speed value.
#[inline]
pub(crate) fn set_input_speed(termios: &mut Termios, arbitrary_speed: u32) -> io::Result<()> {
let encoded_speed = crate::termios::speed::encode(arbitrary_speed).unwrap_or(c::BOTHER);
debug_assert_eq!(encoded_speed & !c::CBAUD, 0);
termios.control_modes -= ControlModes::from_bits_retain(c::CIBAUD);
termios.control_modes |= ControlModes::from_bits_retain(encoded_speed << IBSHIFT);
termios.input_speed = arbitrary_speed;
Ok(())
}
#[inline]
pub(crate) fn cfmakeraw(termios: &mut Termios) {
// From the Linux [`cfmakeraw` manual page]:
//
// [`cfmakeraw` manual page]: https://man7.org/linux/man-pages/man3/cfmakeraw.3.html
termios.input_modes -= InputModes::IGNBRK
| InputModes::BRKINT
| InputModes::PARMRK
| InputModes::ISTRIP
| InputModes::INLCR
| InputModes::IGNCR
| InputModes::ICRNL
| InputModes::IXON;
termios.output_modes -= OutputModes::OPOST;
termios.local_modes -= LocalModes::ECHO
| LocalModes::ECHONL
| LocalModes::ICANON
| LocalModes::ISIG
| LocalModes::IEXTEN;
termios.control_modes -= ControlModes::CSIZE | ControlModes::PARENB;
termios.control_modes |= ControlModes::CS8;
// Musl and glibc also do these:
termios.special_codes[SpecialCodeIndex::VMIN] = 1;
termios.special_codes[SpecialCodeIndex::VTIME] = 0;
}
#[inline]
pub(crate) fn isatty(fd: BorrowedFd<'_>) -> bool {
// On error, Linux will return either `EINVAL` (2.6.32) or `ENOTTY`
// (otherwise), because we assume we're never passing an invalid
// file descriptor (which would get `EBADF`). Either way, an error
// means we don't have a tty.
tcgetwinsize(fd).is_ok()
}
#[cfg(feature = "procfs")]
#[allow(unsafe_code)]
pub(crate) fn ttyname(fd: BorrowedFd<'_>, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
let fd_stat = crate::backend::fs::syscalls::fstat(fd)?;
// Quick check: if `fd` isn't a character device, it's not a tty.
if FileType::from_raw_mode(fd_stat.st_mode) != FileType::CharacterDevice {
return Err(io::Errno::NOTTY);
}
// Check that `fd` is really a tty.
tcgetwinsize(fd)?;
// Get a fd to '/proc/self/fd'.
let proc_self_fd = procfs::proc_self_fd()?;
// Gather the ttyname by reading the 'fd' file inside 'proc_self_fd'.
let r = crate::backend::fs::syscalls::readlinkat(
proc_self_fd,
DecInt::from_fd(fd).as_c_str(),
buf,
)?;
// If the number of bytes is equal to the buffer length, truncation may
// have occurred. This check also ensures that we have enough space for
// adding a NUL terminator.
if r == buf.len() {
return Err(io::Errno::RANGE);
}
// `readlinkat` returns the number of bytes placed in the buffer.
// NUL-terminate the string at that offset.
buf[r].write(b'\0');
// Check that the path we read refers to the same file as `fd`.
{
// SAFETY: We just wrote the NUL byte above
let path = unsafe { CStr::from_ptr(buf.as_ptr().cast()) };
let path_stat = crate::backend::fs::syscalls::stat(path)?;
if path_stat.st_dev != fd_stat.st_dev || path_stat.st_ino != fd_stat.st_ino {
return Err(io::Errno::NODEV);
}
}
Ok(r)
}
|
use cpython::{py_fn, py_module_initializer, PyList, PySet, PyResult, Python};
py_module_initializer!(libmyrustlib, |py, m| {
m.add(py, "__doc__", "This module is implemented in Rust.")?;
m.add(
py,
"sum_as_string",
py_fn!(py, sum_as_string_py(a: i64, b: i64)),
)?;
m.add(py, "length_list", py_fn!(py, length_list(list: PyList)))?;
m.add(
py,
"length_list_rust",
py_fn!(py, length_list_rust(list: Vec<i64>)),
)?;
m.add(py, "sort_list", py_fn!(py, sort_list(list: Vec<i64>)))?;
m.add(py, "list_to_set", py_fn!(py, list_to_set(list: PyList)))?;
Ok(())
});
// logic implemented as a normal rust function
fn sum_as_string(a: i64, b: i64) -> String {
format!("{}", a + b).to_string()
}
fn sum_as_string_py(_: Python, a: i64, b: i64) -> PyResult<String> {
let out = sum_as_string(a, b);
Ok(out)
}
fn length_list(py: Python, list: PyList) -> PyResult<usize> {
let length = list.len(py);
Ok(length)
}
fn length_list_rust(_: Python, list: Vec<i64>) -> PyResult<usize> {
let length = list.len();
Ok(length)
}
fn sort_list(_: Python, mut list: Vec<i64>) -> PyResult<Vec<i64>> {
list.sort();
Ok(list)
}
fn list_to_set(py: Python, list: PyList) -> PyResult<PySet> {
PySet::new(py, list)
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - FLASH access control register"]
pub acr: ACR,
_reserved_1_bank1: [u8; 96usize],
_reserved2: [u8; 160usize],
#[doc = "0x104 - Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"]
pub bank2: BANK,
}
impl RegisterBlock {
#[doc = "0x04 - Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"]
#[inline(always)]
pub fn bank1(&self) -> &BANK {
unsafe { &*(((self as *const Self) as *const u8).add(4usize) as *const BANK) }
}
#[doc = "0x04 - Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"]
#[inline(always)]
pub fn bank1_mut(&self) -> &mut BANK {
unsafe { &mut *(((self as *const Self) as *mut u8).add(4usize) as *mut BANK) }
}
#[doc = "0x08 - FLASH option key register"]
#[inline(always)]
pub fn optkeyr(&self) -> &OPTKEYR {
unsafe { &*(((self as *const Self) as *const u8).add(8usize) as *const OPTKEYR) }
}
#[doc = "0x08 - FLASH option key register"]
#[inline(always)]
pub fn optkeyr_mut(&self) -> &mut OPTKEYR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(8usize) as *mut OPTKEYR) }
}
#[doc = "0x18 - FLASH option control register"]
#[inline(always)]
pub fn optcr(&self) -> &OPTCR {
unsafe { &*(((self as *const Self) as *const u8).add(24usize) as *const OPTCR) }
}
#[doc = "0x18 - FLASH option control register"]
#[inline(always)]
pub fn optcr_mut(&self) -> &mut OPTCR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(24usize) as *mut OPTCR) }
}
#[doc = "0x1c - FLASH option status register"]
#[inline(always)]
pub fn optsr_cur(&self) -> &OPTSR_CUR {
unsafe { &*(((self as *const Self) as *const u8).add(28usize) as *const OPTSR_CUR) }
}
#[doc = "0x1c - FLASH option status register"]
#[inline(always)]
pub fn optsr_cur_mut(&self) -> &mut OPTSR_CUR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(28usize) as *mut OPTSR_CUR) }
}
#[doc = "0x20 - FLASH option status register"]
#[inline(always)]
pub fn optsr_prg(&self) -> &OPTSR_PRG {
unsafe { &*(((self as *const Self) as *const u8).add(32usize) as *const OPTSR_PRG) }
}
#[doc = "0x20 - FLASH option status register"]
#[inline(always)]
pub fn optsr_prg_mut(&self) -> &mut OPTSR_PRG {
unsafe { &mut *(((self as *const Self) as *mut u8).add(32usize) as *mut OPTSR_PRG) }
}
#[doc = "0x24 - FLASH option clear control register"]
#[inline(always)]
pub fn optccr(&self) -> &OPTCCR {
unsafe { &*(((self as *const Self) as *const u8).add(36usize) as *const OPTCCR) }
}
#[doc = "0x24 - FLASH option clear control register"]
#[inline(always)]
pub fn optccr_mut(&self) -> &mut OPTCCR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(36usize) as *mut OPTCCR) }
}
#[doc = "0x40 - FLASH register boot address for Arm Cortex-M7 core"]
#[inline(always)]
pub fn boot7_curr(&self) -> &BOOT7_CURR {
unsafe { &*(((self as *const Self) as *const u8).add(64usize) as *const BOOT7_CURR) }
}
#[doc = "0x40 - FLASH register boot address for Arm Cortex-M7 core"]
#[inline(always)]
pub fn boot7_curr_mut(&self) -> &mut BOOT7_CURR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(64usize) as *mut BOOT7_CURR) }
}
#[doc = "0x44 - FLASH register boot address for Arm Cortex-M7 core"]
#[inline(always)]
pub fn boot7_prgr(&self) -> &BOOT7_PRGR {
unsafe { &*(((self as *const Self) as *const u8).add(68usize) as *const BOOT7_PRGR) }
}
#[doc = "0x44 - FLASH register boot address for Arm Cortex-M7 core"]
#[inline(always)]
pub fn boot7_prgr_mut(&self) -> &mut BOOT7_PRGR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(68usize) as *mut BOOT7_PRGR) }
}
#[doc = "0x48 - FLASH register boot address for Arm Cortex-M4 core"]
#[inline(always)]
pub fn boot4_curr(&self) -> &BOOT4_CURR {
unsafe { &*(((self as *const Self) as *const u8).add(72usize) as *const BOOT4_CURR) }
}
#[doc = "0x48 - FLASH register boot address for Arm Cortex-M4 core"]
#[inline(always)]
pub fn boot4_curr_mut(&self) -> &mut BOOT4_CURR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(72usize) as *mut BOOT4_CURR) }
}
#[doc = "0x4c - FLASH register boot address for Arm Cortex-M4 core"]
#[inline(always)]
pub fn boot4_prgr(&self) -> &BOOT4_PRGR {
unsafe { &*(((self as *const Self) as *const u8).add(76usize) as *const BOOT4_PRGR) }
}
#[doc = "0x4c - FLASH register boot address for Arm Cortex-M4 core"]
#[inline(always)]
pub fn boot4_prgr_mut(&self) -> &mut BOOT4_PRGR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(76usize) as *mut BOOT4_PRGR) }
}
#[doc = "0x5c - FLASH CRC data register"]
#[inline(always)]
pub fn crcdatar(&self) -> &CRCDATAR {
unsafe { &*(((self as *const Self) as *const u8).add(92usize) as *const CRCDATAR) }
}
#[doc = "0x5c - FLASH CRC data register"]
#[inline(always)]
pub fn crcdatar_mut(&self) -> &mut CRCDATAR {
unsafe { &mut *(((self as *const Self) as *mut u8).add(92usize) as *mut CRCDATAR) }
}
}
#[doc = r"Register block"]
#[repr(C)]
pub struct BANK {
#[doc = "0x00 - FLASH key register for bank 1"]
pub keyr: self::bank::KEYR,
_reserved1: [u8; 4usize],
#[doc = "0x08 - FLASH control register for bank 1"]
pub cr: self::bank::CR,
#[doc = "0x0c - FLASH status register for bank 1"]
pub sr: self::bank::SR,
#[doc = "0x10 - FLASH clear control register for bank 1"]
pub ccr: self::bank::CCR,
_reserved4: [u8; 16usize],
#[doc = "0x24 - FLASH protection address for bank 1"]
pub prar_cur: self::bank::PRAR_CUR,
#[doc = "0x28 - FLASH protection address for bank 1"]
pub prar_prg: self::bank::PRAR_PRG,
#[doc = "0x2c - FLASH secure address for bank 1"]
pub scar_cur: self::bank::SCAR_CUR,
#[doc = "0x30 - FLASH secure address for bank 1"]
pub scar_prg: self::bank::SCAR_PRG,
#[doc = "0x34 - FLASH write sector protection for bank 1"]
pub wpsn_curr: self::bank::WPSN_CURR,
#[doc = "0x38 - FLASH write sector protection for bank 1"]
pub wpsn_prgr: self::bank::WPSN_PRGR,
_reserved10: [u8; 16usize],
#[doc = "0x4c - FLASH CRC control register for bank 1"]
pub crccr: self::bank::CRCCR,
#[doc = "0x50 - FLASH CRC start address register for bank 1"]
pub crcsaddr: self::bank::CRCSADDR,
#[doc = "0x54 - FLASH CRC end address register for bank 1"]
pub crceaddr: self::bank::CRCEADDR,
_reserved13: [u8; 4usize],
#[doc = "0x5c - FLASH ECC fail address for bank 1"]
pub far: self::bank::FAR,
}
#[doc = r"Register block"]
#[doc = "Cluster BANK%s, containing KEYR?, CR?, SR?, CCR?, PRAR_CUR?, PRAR_PRG?, SCAR_CUR?, SCAR_PRG?, WPSN_CUR?R, WPSN_PRG?R, CRCCR?, CRCSADD?R, CRCEADD?R, ECC_FA?R"]
pub mod bank;
#[doc = "FLASH access control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [acr](acr) module"]
pub type ACR = crate::Reg<u32, _ACR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ACR;
#[doc = "`read()` method returns [acr::R](acr::R) reader structure"]
impl crate::Readable for ACR {}
#[doc = "`write(|w| ..)` method takes [acr::W](acr::W) writer structure"]
impl crate::Writable for ACR {}
#[doc = "FLASH access control register"]
pub mod acr;
#[doc = "FLASH option key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optkeyr](optkeyr) module"]
pub type OPTKEYR = crate::Reg<u32, _OPTKEYR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTKEYR;
#[doc = "`write(|w| ..)` method takes [optkeyr::W](optkeyr::W) writer structure"]
impl crate::Writable for OPTKEYR {}
#[doc = "FLASH option key register"]
pub mod optkeyr;
#[doc = "FLASH option control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optcr](optcr) module"]
pub type OPTCR = crate::Reg<u32, _OPTCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTCR;
#[doc = "`read()` method returns [optcr::R](optcr::R) reader structure"]
impl crate::Readable for OPTCR {}
#[doc = "`write(|w| ..)` method takes [optcr::W](optcr::W) writer structure"]
impl crate::Writable for OPTCR {}
#[doc = "FLASH option control register"]
pub mod optcr;
#[doc = "FLASH option status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optsr_cur](optsr_cur) module"]
pub type OPTSR_CUR = crate::Reg<u32, _OPTSR_CUR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTSR_CUR;
#[doc = "`read()` method returns [optsr_cur::R](optsr_cur::R) reader structure"]
impl crate::Readable for OPTSR_CUR {}
#[doc = "`write(|w| ..)` method takes [optsr_cur::W](optsr_cur::W) writer structure"]
impl crate::Writable for OPTSR_CUR {}
#[doc = "FLASH option status register"]
pub mod optsr_cur;
#[doc = "FLASH option status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optsr_prg](optsr_prg) module"]
pub type OPTSR_PRG = crate::Reg<u32, _OPTSR_PRG>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTSR_PRG;
#[doc = "`read()` method returns [optsr_prg::R](optsr_prg::R) reader structure"]
impl crate::Readable for OPTSR_PRG {}
#[doc = "`write(|w| ..)` method takes [optsr_prg::W](optsr_prg::W) writer structure"]
impl crate::Writable for OPTSR_PRG {}
#[doc = "FLASH option status register"]
pub mod optsr_prg;
#[doc = "FLASH option clear control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optccr](optccr) module"]
pub type OPTCCR = crate::Reg<u32, _OPTCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTCCR;
#[doc = "`read()` method returns [optccr::R](optccr::R) reader structure"]
impl crate::Readable for OPTCCR {}
#[doc = "`write(|w| ..)` method takes [optccr::W](optccr::W) writer structure"]
impl crate::Writable for OPTCCR {}
#[doc = "FLASH option clear control register"]
pub mod optccr;
#[doc = "FLASH register boot address for Arm Cortex-M7 core\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [boot7_curr](boot7_curr) module"]
pub type BOOT7_CURR = crate::Reg<u32, _BOOT7_CURR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BOOT7_CURR;
#[doc = "`read()` method returns [boot7_curr::R](boot7_curr::R) reader structure"]
impl crate::Readable for BOOT7_CURR {}
#[doc = "`write(|w| ..)` method takes [boot7_curr::W](boot7_curr::W) writer structure"]
impl crate::Writable for BOOT7_CURR {}
#[doc = "FLASH register boot address for Arm Cortex-M7 core"]
pub mod boot7_curr;
#[doc = "FLASH register boot address for Arm Cortex-M7 core\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [boot7_prgr](boot7_prgr) module"]
pub type BOOT7_PRGR = crate::Reg<u32, _BOOT7_PRGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BOOT7_PRGR;
#[doc = "`read()` method returns [boot7_prgr::R](boot7_prgr::R) reader structure"]
impl crate::Readable for BOOT7_PRGR {}
#[doc = "`write(|w| ..)` method takes [boot7_prgr::W](boot7_prgr::W) writer structure"]
impl crate::Writable for BOOT7_PRGR {}
#[doc = "FLASH register boot address for Arm Cortex-M7 core"]
pub mod boot7_prgr;
#[doc = "FLASH register boot address for Arm Cortex-M4 core\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [boot4_curr](boot4_curr) module"]
pub type BOOT4_CURR = crate::Reg<u32, _BOOT4_CURR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BOOT4_CURR;
#[doc = "`read()` method returns [boot4_curr::R](boot4_curr::R) reader structure"]
impl crate::Readable for BOOT4_CURR {}
#[doc = "`write(|w| ..)` method takes [boot4_curr::W](boot4_curr::W) writer structure"]
impl crate::Writable for BOOT4_CURR {}
#[doc = "FLASH register boot address for Arm Cortex-M4 core"]
pub mod boot4_curr;
#[doc = "FLASH register boot address for Arm Cortex-M4 core\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [boot4_prgr](boot4_prgr) module"]
pub type BOOT4_PRGR = crate::Reg<u32, _BOOT4_PRGR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BOOT4_PRGR;
#[doc = "`read()` method returns [boot4_prgr::R](boot4_prgr::R) reader structure"]
impl crate::Readable for BOOT4_PRGR {}
#[doc = "`write(|w| ..)` method takes [boot4_prgr::W](boot4_prgr::W) writer structure"]
impl crate::Writable for BOOT4_PRGR {}
#[doc = "FLASH register boot address for Arm Cortex-M4 core"]
pub mod boot4_prgr;
#[doc = "FLASH CRC data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [crcdatar](crcdatar) module"]
pub type CRCDATAR = crate::Reg<u32, _CRCDATAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CRCDATAR;
#[doc = "`read()` method returns [crcdatar::R](crcdatar::R) reader structure"]
impl crate::Readable for CRCDATAR {}
#[doc = "`write(|w| ..)` method takes [crcdatar::W](crcdatar::W) writer structure"]
impl crate::Writable for CRCDATAR {}
#[doc = "FLASH CRC data register"]
pub mod crcdatar;
|
use std::io::{Read, Result as IOResult};
use crate::PrimitiveRead;
pub struct StripGroupHeader {
pub verts_count: i32,
pub vert_offset: i32,
pub indices_count: i32,
pub indices_offset: i32,
pub strips_count: i32,
pub strips_offset: i32,
pub flags: u8
}
impl StripGroupHeader {
pub fn read(read: &mut dyn Read) -> IOResult<Self> {
let verts_count = read.read_i32()?;
let vert_offset = read.read_i32()?;
let indices_count = read.read_i32()?;
let indices_offset = read.read_i32()?;
let strips_count = read.read_i32()?;
let strips_offset = read.read_i32()?;
let flags = read.read_u8()?;
let _padding = read.read_u8()?; // maybe wrong?
Ok(Self {
vert_offset,
verts_count,
indices_count,
indices_offset,
strips_count,
strips_offset,
flags
})
}
}
|
#![allow(dead_code)]
use track::*;
use token::{NumberLiteral, Name};
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Semi {
Inserted,
Explicit(Option<Posn>)
}
impl Untrack for Semi {
fn untrack(&mut self) {
*self = Semi::Explicit(None);
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct IdData {
pub name: Name
}
impl Untrack for IdData {
fn untrack(&mut self) { }
}
pub type Id = Tracked<IdData>;
impl Id {
pub fn new(name: Name, location: Option<Span>) -> Id {
Id {
value: IdData { name: name },
location: location
}
}
pub fn into_patt(self) -> Patt {
Patt::Simple(self)
}
pub fn into_expr(self) -> Expr {
self.map_self(ExprData::Id)
}
pub fn into_dtor(self) -> Dtor {
Dtor {
location: self.location,
value: DtorData::Simple(self, None)
}
}
}
#[derive(Debug, PartialEq)]
pub struct ParamsData {
pub list: Vec<Patt>
}
pub type Params = Tracked<ParamsData>;
impl Untrack for ParamsData {
fn untrack(&mut self) {
self.list.untrack();
}
}
#[derive(Debug, PartialEq)]
pub struct FunData {
pub id: Option<Id>,
pub params: Params,
pub body: Vec<StmtListItem>
}
impl Untrack for FunData {
fn untrack(&mut self) {
self.id.untrack();
self.params.untrack();
self.body.untrack();
}
}
pub type Fun = Tracked<FunData>;
#[derive(Debug, PartialEq)]
pub enum StmtData {
Empty,
Block(Vec<StmtListItem>),
Var(Vec<Dtor>, Semi),
Expr(Expr, Semi),
If(Expr, Box<Stmt>, Option<Box<Stmt>>),
Label(Id, Box<Stmt>),
Break(Option<Id>, Semi),
Cont(Option<Id>, Semi),
With(Expr, Box<Stmt>),
Switch(Expr, Vec<Case>),
Return(Option<Expr>, Semi),
Throw(Expr, Semi),
Try(Vec<StmtListItem>, Option<Box<Catch>>, Option<Vec<StmtListItem>>),
While(Expr, Box<Stmt>),
DoWhile(Box<Stmt>, Expr, Semi),
For(Option<Box<ForHead>>, Option<Expr>, Option<Expr>, Box<Stmt>),
ForIn(Box<ForInHead>, Expr, Box<Stmt>),
ForOf(Box<ForOfHead>, Expr, Box<Stmt>),
Debugger(Semi)
}
impl Untrack for StmtData {
fn untrack(&mut self) {
match *self {
StmtData::Empty => { }
StmtData::Block(ref mut items) => { items.untrack(); }
StmtData::Var(ref mut dtors, ref mut semi) => { dtors.untrack(); semi.untrack(); }
StmtData::Expr(ref mut expr, ref mut semi) => { expr.untrack(); semi.untrack(); }
StmtData::If(ref mut test, ref mut cons, ref mut alt) => { test.untrack(); cons.untrack(); alt.untrack(); }
StmtData::Label(ref mut lab, ref mut stmt) => { lab.untrack(); stmt.untrack(); }
StmtData::Break(ref mut lab, ref mut semi) => { lab.untrack(); semi.untrack(); }
StmtData::Cont(ref mut lab, ref mut semi) => { lab.untrack(); semi.untrack(); }
StmtData::With(ref mut expr, ref mut stmt) => { expr.untrack(); stmt.untrack(); }
StmtData::Switch(ref mut expr, ref mut cases) => { expr.untrack(); cases.untrack(); }
StmtData::Return(ref mut expr, ref mut semi) => { expr.untrack(); semi.untrack(); }
StmtData::Throw(ref mut expr, ref mut semi) => { expr.untrack(); semi.untrack(); }
StmtData::Try(ref mut body, ref mut catch, ref mut finally) => { body.untrack(); catch.untrack(); finally.untrack(); }
StmtData::While(ref mut expr, ref mut stmt) => { expr.untrack(); stmt.untrack(); }
StmtData::DoWhile(ref mut stmt, ref mut expr, ref mut semi) => { stmt.untrack(); expr.untrack(); semi.untrack(); }
StmtData::For(ref mut init, ref mut test, ref mut incr, ref mut body) => { init.untrack(); test.untrack(); incr.untrack(); body.untrack(); }
StmtData::ForIn(ref mut lhs, ref mut rhs, ref mut body) => { lhs.untrack(); rhs.untrack(); body.untrack(); }
StmtData::ForOf(ref mut lhs, ref mut rhs, ref mut body) => { lhs.untrack(); rhs.untrack(); body.untrack(); }
StmtData::Debugger(ref mut semi) => { semi.untrack(); }
}
}
}
pub type Stmt = Tracked<StmtData>;
#[derive(Debug, PartialEq)]
pub enum ForHeadData {
Var(Vec<Dtor>),
Let(Vec<Dtor>),
Expr(Expr)
}
impl Untrack for ForHeadData {
fn untrack(&mut self) {
match *self {
ForHeadData::Var(ref mut vec) => { vec.untrack(); }
ForHeadData::Let(ref mut vec) => { vec.untrack(); }
ForHeadData::Expr(ref mut expr) => { expr.untrack(); }
}
}
}
pub type ForHead = Tracked<ForHeadData>;
#[derive(Debug, PartialEq)]
pub enum ForInHeadData {
VarInit(Id, Expr),
Var(Patt),
Let(Patt),
Expr(Expr)
}
impl Untrack for ForInHeadData {
fn untrack(&mut self) {
match *self {
ForInHeadData::VarInit(ref mut id, ref mut expr) => { id.untrack(); expr.untrack(); }
ForInHeadData::Var(ref mut patt) => { patt.untrack(); }
ForInHeadData::Let(ref mut patt) => { patt.untrack(); }
ForInHeadData::Expr(ref mut expr) => { expr.untrack(); }
}
}
}
pub type ForInHead = Tracked<ForInHeadData>;
#[derive(Debug, PartialEq)]
pub enum ForOfHeadData {
Var(Patt),
Let(Patt),
Expr(Expr)
}
impl Untrack for ForOfHeadData {
fn untrack(&mut self) {
match *self {
ForOfHeadData::Var(ref mut patt) => { patt.untrack(); }
ForOfHeadData::Let(ref mut patt) => { patt.untrack(); }
ForOfHeadData::Expr(ref mut expr) => { expr.untrack(); }
}
}
}
pub type ForOfHead = Tracked<ForOfHeadData>;
#[derive(Debug, PartialEq)]
pub enum DeclData {
Fun(Fun)
}
impl Untrack for DeclData {
fn untrack(&mut self) {
match *self {
DeclData::Fun(ref mut fun) => { fun.untrack(); }
}
}
}
pub type Decl = Tracked<DeclData>;
#[derive(Debug, PartialEq)]
pub enum DtorData {
Simple(Id, Option<Expr>),
Compound(CompoundPatt, Expr)
}
impl Untrack for DtorData {
fn untrack(&mut self) {
match *self {
DtorData::Simple(ref mut id, ref mut init) => { id.untrack(); init.untrack(); }
DtorData::Compound(ref mut patt, ref mut init) => { patt.untrack(); init.untrack(); }
}
}
}
pub type Dtor = Tracked<DtorData>;
pub trait DtorExt {
fn from_simple_init(Id, Expr) -> Dtor;
fn from_compound_init(CompoundPatt, Expr) -> Dtor;
fn from_init(Patt, Expr) -> Dtor;
fn from_init_opt(Patt, Option<Expr>) -> Result<Dtor, CompoundPatt>;
}
impl DtorExt for Dtor {
fn from_compound_init(lhs: CompoundPatt, rhs: Expr) -> Dtor {
Dtor {
location: span(&lhs, &rhs),
value: DtorData::Compound(lhs, rhs)
}
}
fn from_simple_init(lhs: Id, rhs: Expr) -> Dtor {
Dtor {
location: span(&lhs, &rhs),
value: DtorData::Simple(lhs, Some(rhs))
}
}
fn from_init(lhs: Patt, rhs: Expr) -> Dtor {
Dtor {
location: span(&lhs, &rhs),
value: match lhs {
Patt::Simple(id) => DtorData::Simple(id, Some(rhs)),
Patt::Compound(patt) => DtorData::Compound(patt, rhs)
}
}
}
fn from_init_opt(lhs: Patt, rhs: Option<Expr>) -> Result<Dtor, CompoundPatt> {
match (lhs, rhs) {
(Patt::Simple(id), rhs) => {
let location = id.location();
Ok(Dtor {
value: DtorData::Simple(id, rhs),
location: location
})
}
(Patt::Compound(patt), None) => Err(patt),
(Patt::Compound(patt), Some(rhs)) => {
let location = span(&patt, &rhs);
Ok(Dtor {
value: DtorData::Compound(patt, rhs),
location: location
})
}
}
}
}
#[derive(Debug, PartialEq)]
pub struct CatchData {
pub param: Patt,
pub body: Vec<StmtListItem>
}
impl Untrack for CatchData {
fn untrack(&mut self) {
self.param.untrack();
self.body.untrack();
}
}
pub type Catch = Tracked<CatchData>;
#[derive(Debug, PartialEq)]
pub struct CaseData {
pub test: Option<Expr>,
pub body: Vec<StmtListItem>
}
impl Untrack for CaseData {
fn untrack(&mut self) {
self.test.untrack();
self.body.untrack();
}
}
pub type Case = Tracked<CaseData>;
#[derive(Debug, Eq, PartialEq)]
pub enum UnopTag {
Minus,
Plus,
Not,
BitNot,
Typeof,
Void,
Delete
}
pub type Unop = Tracked<UnopTag>;
impl Untrack for Unop {
fn untrack(&mut self) {
self.location = None;
}
}
pub trait Precedence {
fn precedence(&self) -> u32;
}
impl<T: Precedence> Precedence for Tracked<T> {
fn precedence(&self) -> u32 {
self.value.precedence()
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum BinopTag {
Eq,
NEq,
StrictEq,
StrictNEq,
Lt,
LEq,
Gt,
GEq,
LShift,
RShift,
URShift,
Plus,
Minus,
Times,
Div,
Mod,
BitOr,
BitXor,
BitAnd,
In,
Instanceof,
}
impl Precedence for BinopTag {
fn precedence(&self) -> u32 {
match *self {
BinopTag::Eq => 7,
BinopTag::NEq => 7,
BinopTag::StrictEq => 7,
BinopTag::StrictNEq => 7,
BinopTag::Lt => 8,
BinopTag::LEq => 8,
BinopTag::Gt => 8,
BinopTag::GEq => 8,
BinopTag::LShift => 9,
BinopTag::RShift => 9,
BinopTag::URShift => 9,
BinopTag::Plus => 10,
BinopTag::Minus => 10,
BinopTag::Times => 11,
BinopTag::Div => 11,
BinopTag::Mod => 11,
BinopTag::BitOr => 4,
BinopTag::BitXor => 5,
BinopTag::BitAnd => 6,
BinopTag::In => 8,
BinopTag::Instanceof => 8,
}
}
}
pub type Binop = Tracked<BinopTag>;
impl Binop {
pub fn pretty(&self) -> String {
match self.value {
BinopTag::Eq => format!("=="),
BinopTag::NEq => format!("!="),
BinopTag::StrictEq => format!("==="),
BinopTag::StrictNEq => format!("!=="),
BinopTag::Lt => format!("<"),
BinopTag::LEq => format!("<="),
BinopTag::Gt => format!(">"),
BinopTag::GEq => format!(">="),
BinopTag::LShift => format!("<<"),
BinopTag::RShift => format!(">>"),
BinopTag::URShift => format!(">>>"),
BinopTag::Plus => format!("+"),
BinopTag::Minus => format!("-"),
BinopTag::Times => format!("*"),
BinopTag::Div => format!("/"),
BinopTag::Mod => format!("%"),
BinopTag::BitOr => format!("|"),
BinopTag::BitXor => format!("^"),
BinopTag::BitAnd => format!("&"),
BinopTag::In => format!("in"),
BinopTag::Instanceof => format!("instanceof")
}
}
}
impl Untrack for Binop {
fn untrack(&mut self) {
self.location = None;
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum LogopTag {
Or,
And
}
impl Precedence for LogopTag {
fn precedence(&self) -> u32 {
match *self {
LogopTag::Or => 2,
LogopTag::And => 3
}
}
}
pub type Logop = Tracked<LogopTag>;
impl Logop {
pub fn pretty(&self) -> String {
match self.value {
LogopTag::Or => format!("||"),
LogopTag::And => format!("&&")
}
}
}
impl Untrack for Logop {
fn untrack(&mut self) {
self.location = None;
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum AssopTag {
Eq,
PlusEq,
MinusEq,
TimesEq,
DivEq,
ModEq,
LShiftEq,
RShiftEq,
URShiftEq,
BitOrEq,
BitXorEq,
BitAndEq
}
impl Precedence for AssopTag {
fn precedence(&self) -> u32 { 0 }
}
pub type Assop = Tracked<AssopTag>;
impl Assop {
pub fn pretty(&self) -> String {
match self.value {
AssopTag::Eq => format!("="),
AssopTag::PlusEq => format!("+="),
AssopTag::MinusEq => format!("-="),
AssopTag::TimesEq => format!("*="),
AssopTag::DivEq => format!("/="),
AssopTag::ModEq => format!("%="),
AssopTag::LShiftEq => format!("<<="),
AssopTag::RShiftEq => format!(">>="),
AssopTag::URShiftEq => format!(">>>="),
AssopTag::BitOrEq => format!("|="),
AssopTag::BitXorEq => format!("^="),
AssopTag::BitAndEq => format!("&=")
}
}
}
impl Untrack for Assop {
fn untrack(&mut self) {
self.location = None;
}
}
#[derive(Debug)]
pub enum ExprData {
This,
Id(Id),
Arr(Vec<Option<Expr>>),
Obj(Vec<Prop>),
Fun(Fun),
Seq(Vec<Expr>),
Unop(Unop, Box<Expr>),
Binop(Binop, Box<Expr>, Box<Expr>),
Logop(Logop, Box<Expr>, Box<Expr>),
PreInc(Box<Expr>),
PostInc(Box<Expr>),
PreDec(Box<Expr>),
PostDec(Box<Expr>),
Assign(Assop, APatt, Box<Expr>),
Cond(Box<Expr>, Box<Expr>, Box<Expr>),
Call(Box<Expr>, Vec<Expr>),
New(Box<Expr>, Option<Vec<Expr>>),
Dot(Box<Expr>, Id),
Brack(Box<Expr>, Box<Expr>),
NewTarget,
True,
False,
Null,
Number(NumberLiteral),
RegExp(String, Vec<char>),
String(String)
}
impl PartialEq for ExprData {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(&ExprData::This, &ExprData::This) => true,
(&ExprData::Id(ref id_l), &ExprData::Id(ref id_r)) => id_l.eq(id_r),
(&ExprData::Arr(ref elts_l), &ExprData::Arr(ref elts_r)) => elts_l.eq(elts_r),
(&ExprData::Obj(ref props_l), &ExprData::Obj(ref props_r)) => props_l.eq(props_r),
(&ExprData::Fun(ref fun_l), &ExprData::Fun(ref fun_r)) => fun_l.eq(fun_r),
(&ExprData::Seq(ref exprs_l), &ExprData::Seq(ref exprs_r)) => exprs_l.eq(exprs_r),
(&ExprData::Unop(ref op_l, ref arg_l), &ExprData::Unop(ref op_r, ref arg_r)) => op_l.eq(op_r) && arg_l.eq(arg_r),
(&ExprData::Binop(ref op_l, ref arg1_l, ref arg2_l), &ExprData::Binop(ref op_r, ref arg1_r, ref arg2_r)) => op_l.eq(op_r) && arg1_l.eq(arg1_r) && arg2_l.eq(arg2_r),
(&ExprData::Logop(ref op_l, ref arg1_l, ref arg2_l), &ExprData::Logop(ref op_r, ref arg1_r, ref arg2_r)) => op_l.eq(op_r) && arg1_l.eq(arg1_r) && arg2_l.eq(arg2_r),
(&ExprData::PreInc(ref arg_l), &ExprData::PreInc(ref arg_r))
| (&ExprData::PostInc(ref arg_l), &ExprData::PostInc(ref arg_r))
| (&ExprData::PreDec(ref arg_l), &ExprData::PreDec(ref arg_r))
| (&ExprData::PostDec(ref arg_l), &ExprData::PostDec(ref arg_r)) => arg_l.eq(arg_r),
(&ExprData::Assign(ref op_l, ref patt_l, ref arg_l), &ExprData::Assign(ref op_r, ref patt_r, ref arg_r)) => op_l.eq(op_r) && patt_l.eq(patt_r) && arg_l.eq(arg_r),
(&ExprData::Cond(ref test_l, ref cons_l, ref alt_l), &ExprData::Cond(ref test_r, ref cons_r, ref alt_r)) => test_l.eq(test_r) && cons_l.eq(cons_r) && alt_l.eq(alt_r),
(&ExprData::Call(ref callee_l, ref args_l), &ExprData::Call(ref callee_r, ref args_r)) => callee_l.eq(callee_r) && args_l.eq(args_r),
(&ExprData::New(ref callee_l, None), &ExprData::New(ref callee_r, None)) => callee_l.eq(callee_r),
(&ExprData::New(ref callee_l, None), &ExprData::New(ref callee_r, Some(ref args_r))) => callee_l.eq(callee_r) && args_r.is_empty(),
(&ExprData::New(ref callee_l, Some(ref args_l)), &ExprData::New(ref callee_r, None)) => callee_l.eq(callee_r) && args_l.is_empty(),
(&ExprData::New(ref callee_l, Some(ref args_l)), &ExprData::New(ref callee_r, Some(ref args_r))) => callee_l.eq(callee_r) && args_l.eq(args_r),
(&ExprData::Dot(ref obj_l, ref id_l), &ExprData::Dot(ref obj_r, ref id_r)) => obj_l.eq(obj_r) && id_l.eq(id_r),
(&ExprData::Brack(ref obj_l, ref prop_l), &ExprData::Brack(ref obj_r, ref prop_r)) => obj_l.eq(obj_r) && prop_l.eq(prop_r),
(&ExprData::NewTarget, &ExprData::NewTarget) => true,
(&ExprData::True, &ExprData::True) => true,
(&ExprData::False, &ExprData::False) => true,
(&ExprData::Null, &ExprData::Null) => true,
(&ExprData::Number(ref lit_l), &ExprData::Number(ref lit_r)) => lit_l.value() == lit_r.value(),
(&ExprData::RegExp(ref src_l, ref flags_l), &ExprData::RegExp(ref src_r, ref flags_r)) => src_l.eq(src_r) && flags_l.eq(flags_r),
(&ExprData::String(ref lit_l), &ExprData::String(ref lit_r)) => lit_l.eq(lit_r),
(_, _) => false
}
}
}
// FIXME: should produce more detailed error information
impl Expr {
pub fn into_assignment_pattern(self) -> Result<APatt, Option<Span>> {
match self.value {
ExprData::Id(id) => Ok(APatt::Simple(AssignTargetData::Id(id).tracked(self.location))),
ExprData::Dot(obj, prop) => Ok(APatt::Simple(AssignTargetData::Dot(obj, prop).tracked(self.location))),
ExprData::Brack(obj, prop) => Ok(APatt::Simple(AssignTargetData::Brack(obj, prop).tracked(self.location))),
ExprData::Obj(props) => {
let mut prop_patts = Vec::with_capacity(props.len());
for prop in props {
prop_patts.push(try!(prop.into_assignment_property()));
}
Ok(APatt::Compound(CompoundAPattData::Obj(prop_patts).tracked(self.location)))
}
ExprData::Arr(exprs) => {
let mut patts = Vec::with_capacity(exprs.len());
for expr in exprs {
patts.push(match expr {
Some(expr) => Some(try!(expr.into_assignment_pattern())),
None => None
});
}
Ok(APatt::Compound(CompoundAPattData::Arr(patts).tracked(self.location)))
}
_ => Err(self.location)
}
}
}
impl Untrack for ExprData {
fn untrack(&mut self) {
match *self {
ExprData::This => { }
ExprData::Id(ref mut id) => { id.untrack(); }
ExprData::Arr(ref mut exprs) => { exprs.untrack(); }
ExprData::Obj(ref mut props) => { props.untrack(); }
ExprData::Fun(ref mut fun) => { fun.untrack(); }
ExprData::Seq(ref mut exprs) => { exprs.untrack(); }
ExprData::Unop(ref mut op, ref mut expr) => { op.untrack(); expr.untrack(); }
ExprData::Binop(ref mut op, ref mut left, ref mut right) => { op.untrack(); left.untrack(); right.untrack(); }
ExprData::Logop(ref mut op, ref mut left, ref mut right) => { op.untrack(); left.untrack(); right.untrack(); }
ExprData::PreInc(ref mut expr) => { expr.untrack(); }
ExprData::PostInc(ref mut expr) => { expr.untrack(); }
ExprData::PreDec(ref mut expr) => { expr.untrack(); }
ExprData::PostDec(ref mut expr) => { expr.untrack(); }
ExprData::Assign(ref mut op, ref mut patt, ref mut expr) => { op.untrack(); patt.untrack(); expr.untrack(); }
ExprData::Cond(ref mut test, ref mut cons, ref mut alt) => { test.untrack(); cons.untrack(); alt.untrack(); }
ExprData::Call(ref mut callee, ref mut args) => { callee.untrack(); args.untrack(); }
ExprData::New(ref mut ctor, ref mut args) => { ctor.untrack(); args.untrack(); }
ExprData::Dot(ref mut obj, ref mut prop) => { obj.untrack(); prop.untrack(); }
ExprData::Brack(ref mut obj, ref mut prop) => { obj.untrack(); prop.untrack(); }
ExprData::NewTarget => { }
ExprData::True => { }
ExprData::False => { }
ExprData::Null => { }
ExprData::Number(_) => { } // FIXME: lit.untrack()
ExprData::RegExp(_, _) => { }
ExprData::String(_) => { }
}
}
}
pub type Expr = Tracked<ExprData>;
#[derive(Debug, PartialEq)]
pub struct PropData {
pub key: PropKey,
pub val: PropVal
}
impl Untrack for PropData {
fn untrack(&mut self) {
self.key.untrack();
self.val.untrack();
}
}
pub type Prop = Tracked<PropData>;
impl Prop {
pub fn into_assignment_property(self) -> Result<PropAPatt, Option<Span>> {
let key = self.value.key;
let patt = match self.value.val.value {
PropValData::Init(expr) => try!(expr.into_assignment_pattern()),
_ => { return Err(self.value.val.location); }
};
Ok((PropAPattData { key: key, patt: patt }).tracked(self.location))
}
}
#[derive(Debug, PartialEq)]
pub enum PropKeyData {
Id(String),
String(String),
Number(NumberLiteral)
}
impl Untrack for PropKeyData {
fn untrack(&mut self) { }
}
pub type PropKey = Tracked<PropKeyData>;
#[derive(Debug, PartialEq)]
pub enum PropValData {
Init(Expr),
Get(Vec<StmtListItem>),
Set(Patt, Vec<StmtListItem>)
}
impl Untrack for PropValData {
fn untrack(&mut self) {
match *self {
PropValData::Init(ref mut expr) => { expr.untrack(); }
PropValData::Get(ref mut stmts) => { stmts.untrack(); }
PropValData::Set(ref mut patt, ref mut stmts) => { patt.untrack(); stmts.untrack(); }
}
}
}
pub type PropVal = Tracked<PropValData>;
// FIXME: abstract Patt and APatt by parameterizing over the leaf node type
#[derive(Debug, PartialEq)]
pub enum CompoundPattData {
Arr(Vec<Option<Patt>>),
Obj(Vec<PropPatt>)
}
impl Untrack for CompoundPattData {
fn untrack(&mut self) {
match *self {
CompoundPattData::Arr(ref mut patts) => { patts.untrack(); }
CompoundPattData::Obj(ref mut props) => { props.untrack(); }
}
}
}
pub type CompoundPatt = Tracked<CompoundPattData>;
#[derive(Debug, PartialEq)]
pub struct PropPattData {
pub key: PropKey,
pub patt: Patt
}
impl Untrack for PropPattData {
fn untrack(&mut self) {
self.key.untrack();
self.patt.untrack();
}
}
pub type PropPatt = Tracked<PropPattData>;
#[derive(Debug, PartialEq)]
pub enum Patt {
Simple(Id),
Compound(CompoundPatt)
}
impl Patt {
pub fn is_simple(&self) -> bool {
match *self {
Patt::Simple(_) => true,
Patt::Compound(_) => false
}
}
}
impl Track for Patt {
fn location(&self) -> Option<Span> {
match *self {
Patt::Simple(ref id) => id.location(),
Patt::Compound(ref patt) => patt.location()
}
}
}
impl Untrack for Patt {
fn untrack(&mut self) {
match *self {
Patt::Simple(ref mut id) => { id.untrack(); }
Patt::Compound(ref mut patt) => { patt.untrack(); }
}
}
}
#[derive(Debug, PartialEq)]
pub enum APatt {
Simple(AssignTarget),
Compound(CompoundAPatt)
}
impl Track for APatt {
fn location(&self) -> Option<Span> {
match *self {
APatt::Simple(ref target) => target.location(),
APatt::Compound(ref patt) => patt.location()
}
}
}
impl Untrack for APatt {
fn untrack(&mut self) {
match *self {
APatt::Simple(ref mut target) => { target.untrack(); }
APatt::Compound(ref mut patt) => { patt.untrack(); }
}
}
}
#[derive(Debug, PartialEq)]
pub enum AssignTargetData {
Id(Id),
Dot(Box<Expr>, Id),
Brack(Box<Expr>, Box<Expr>)
}
impl Untrack for AssignTargetData {
fn untrack(&mut self) {
match *self {
AssignTargetData::Id(ref mut id) => { id.untrack(); }
AssignTargetData::Dot(ref mut obj, ref mut prop) => { obj.untrack(); prop.untrack(); }
AssignTargetData::Brack(ref mut obj, ref mut prop) => { obj.untrack(); prop.untrack(); }
}
}
}
pub type AssignTarget = Tracked<AssignTargetData>;
#[derive(Debug, PartialEq)]
pub enum CompoundAPattData {
Arr(Vec<Option<APatt>>),
Obj(Vec<PropAPatt>)
}
impl Untrack for CompoundAPattData {
fn untrack(&mut self) {
match *self {
CompoundAPattData::Arr(ref mut patts) => { patts.untrack(); }
CompoundAPattData::Obj(ref mut props) => { props.untrack(); }
}
}
}
pub type CompoundAPatt = Tracked<CompoundAPattData>;
#[derive(Debug, PartialEq)]
pub struct PropAPattData {
pub key: PropKey,
pub patt: APatt
}
impl Untrack for PropAPattData {
fn untrack(&mut self) {
self.key.untrack();
self.patt.untrack();
}
}
pub type PropAPatt = Tracked<PropAPattData>;
#[derive(Debug, PartialEq)]
pub struct ScriptData {
pub body: Vec<StmtListItem>
}
impl Untrack for ScriptData {
fn untrack(&mut self) {
self.body.untrack();
}
}
pub type Script = Tracked<ScriptData>;
#[derive(Debug, PartialEq)]
pub enum StmtListItem {
Decl(Decl),
Stmt(Stmt)
}
impl Untrack for StmtListItem {
fn untrack(&mut self) {
match *self {
StmtListItem::Decl(ref mut decl) => { decl.untrack(); }
StmtListItem::Stmt(ref mut stmt) => { stmt.untrack(); }
}
}
}
impl Track for StmtListItem {
fn location(&self) -> Option<Span> {
match *self {
StmtListItem::Decl(ref decl) => decl.location(),
StmtListItem::Stmt(ref stmt) => stmt.location()
}
}
}
/*
#[derive(Debug, PartialEq)]
pub struct ModuleData {
pub body: Vec<ModItem>
}
pub type Module = Tracked<ModuleData>;
*/
|
//! Provides the Splits Component and relevant types for using it. The Splits
//! Component is the main component for visualizing all the split times. Each
//! segment is shown in a tabular fashion showing the segment icon, segment
//! name, the delta compared to the chosen comparison, and the split time. The
//! list provides scrolling functionality, so not every segment needs to be
//! shown all the time.
use analysis::split_color;
use serde_json::{to_writer, Result};
use settings::{Color, Field, Gradient, ListGradient, SemanticColor, SettingsDescription, Value};
use std::borrow::Cow;
use std::cmp::{max, min};
use std::io::Write;
use timing::formatter::none_wrapper::{DashWrapper, EmptyWrapper};
use timing::formatter::{Delta, Regular, TimeFormatter};
use {analysis, CachedImageId, GeneralLayoutSettings, Timer};
#[cfg(test)]
mod tests;
/// The Splits Component is the main component for visualizing all the split
/// times. Each segment is shown in a tabular fashion showing the segment icon,
/// segment name, the delta compared to the chosen comparison, and the split
/// time. The list provides scrolling functionality, so not every segment needs
/// to be shown all the time.
#[derive(Default, Clone)]
pub struct Component {
icon_ids: Vec<CachedImageId>,
settings: Settings,
current_split_index: Option<usize>,
scroll_offset: isize,
}
/// The Settings for this component.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
/// The background shown behind the splits.
pub background: ListGradient,
/// The amount of segments to show in the list at any given time. If this is
/// set to 0, all the segments are shown. If this is set to a number lower
/// than the total amount of segments, only a certain window of all the
/// segments is shown. This window can scroll up or down.
pub visual_split_count: usize,
/// If there's more segments than segments that are shown, the window
/// showing the segments automatically scrolls up and down when the current
/// segment changes. This count determines the minimum number of future
/// segments to be shown in this scrolling window when it automatically
/// scrolls.
pub split_preview_count: usize,
/// Specifies whether thin separators should be shown between the individual
/// segments shown by the component.
pub show_thin_separators: bool,
/// If the last segment is to always be shown, this determines whether to
/// show a more pronounced separator in front of the last segment, if it is
/// not directly adjacent to the segment shown right before it in the
/// scrolling window.
pub separator_last_split: bool,
/// If not every segment is shown in the scrolling window of segments, then
/// this determines whether the final segment is always to be shown, as it
/// contains valuable information about the total duration of the chosen
/// comparison, which is often the runner's Personal Best.
pub always_show_last_split: bool,
/// If there's not enough segments to fill the list of splits, this option
/// allows filling the remaining splits with blank space in order to
/// maintain the visual split count specified. Otherwise the visual split
/// count is reduced to the actual amount of segments.
pub fill_with_blank_space: bool,
/// Specifies whether to display each split as two rows, with the segment
/// name being in one row and the times being in the other.
pub display_two_rows: bool,
/// The gradient to show behind the current segment as an indicator of it
/// being the current segment.
pub current_split_gradient: Gradient,
}
/// The state object that describes a single segment's information to visualize.
#[derive(Serialize, Deserialize)]
pub struct SplitState {
/// The name of the segment.
pub name: String,
/// The delta to show for this segment.
pub delta: String,
/// The split time to show for this segment.
pub time: String,
/// The semantic coloring information the delta time carries.
pub semantic_color: SemanticColor,
/// The visual color of the delta time.
pub visual_color: Color,
/// Describes if this segment is the segment the active attempt is currently
/// on.
pub is_current_split: bool,
/// The index of the segment based on all the segments of the run. This may
/// differ from the index of this `SplitState` in the `State` object, as
/// there can be a scrolling window, showing only a subset of segments.
pub index: usize,
}
/// Describes the icon to be shown for a certain segment. This is provided
/// whenever a segment is first shown or whenever its icon changes. If
/// necessary, you may remount this component to reset the component into a
/// state where these icons are provided again.
#[derive(Serialize, Deserialize)]
pub struct IconChange {
/// The index of the segment of which the icon changed. This is based on the
/// index in the run, not on the index of the `SplitState` in the `State`
/// object. The corresponding index is the `index` field of the `SplitState`
/// object.
pub segment_index: usize,
/// The segment's icon encoded as a Data URL. The String itself may be
/// empty. This indicates that there is no icon.
pub icon: String,
}
/// The state object describes the information to visualize for this component.
#[derive(Serialize, Deserialize)]
pub struct State {
/// The background shown behind the splits.
pub background: ListGradient,
/// The list of all the segments to visualize.
pub splits: Vec<SplitState>,
/// This list describes all the icon changes that happened. Each time a
/// segment is first shown or its icon changes, the new icon is provided in
/// this list. If necessary, you may remount this component to reset the
/// component into a state where these icons are provided again.
pub icon_changes: Vec<IconChange>,
/// Specifies whether thin separators should be shown between the individual
/// segments shown by the component.
pub show_thin_separators: bool,
/// Describes whether a more pronounced separator should be shown in front
/// of the last segment provided.
pub show_final_separator: bool,
/// Specifies whether to display each split as two rows, with the segment
/// name being in one row and the times being in the other.
pub display_two_rows: bool,
/// The gradient to show behind the current segment as an indicator of it
/// being the current segment.
pub current_split_gradient: Gradient,
}
impl Default for Settings {
fn default() -> Self {
Settings {
background: ListGradient::Alternating(
Color::transparent(),
Color::from((1.0, 1.0, 1.0, 0.04)),
),
visual_split_count: 16,
split_preview_count: 1,
show_thin_separators: true,
separator_last_split: true,
always_show_last_split: true,
fill_with_blank_space: true,
display_two_rows: false,
current_split_gradient: Gradient::Vertical(
Color::from((51.0 / 255.0, 115.0 / 255.0, 244.0 / 255.0, 1.0)),
Color::from((21.0 / 255.0, 53.0 / 255.0, 116.0 / 255.0, 1.0)),
),
}
}
}
impl State {
/// Encodes the state object's information as JSON.
pub fn write_json<W>(&self, writer: W) -> Result<()>
where
W: Write,
{
to_writer(writer, self)
}
}
impl Component {
/// Creates a new Splits Component.
pub fn new() -> Self {
Default::default()
}
/// Creates a new Splits Component with the given settings.
pub fn with_settings(settings: Settings) -> Self {
Self {
settings,
..Default::default()
}
}
/// Accesses the settings of the component.
pub fn settings(&self) -> &Settings {
&self.settings
}
/// Grants mutable access to the settings of the component.
pub fn settings_mut(&mut self) -> &mut Settings {
&mut self.settings
}
/// Scrolls up the window of the segments that are shown. Doesn't move the
/// scroll window if it reaches the top of the segments.
pub fn scroll_up(&mut self) {
self.scroll_offset = self.scroll_offset.saturating_sub(1);
}
/// Scrolls down the window of the segments that are shown. Doesn't move the
/// scroll window if it reaches the bottom of the segments.
pub fn scroll_down(&mut self) {
self.scroll_offset = self.scroll_offset.saturating_add(1);
}
/// Remounts the component as if it was freshly initialized. The segment
/// icons shown by this component are only provided in the state objects
/// whenever the icon changes or whenever the component's state is first
/// queried. Remounting returns the segment icons again, whenever its state
/// is queried the next time.
pub fn remount(&mut self) {
self.icon_ids.clear();
}
/// Accesses the name of the component.
pub fn name(&self) -> Cow<str> {
"Splits".into()
}
/// Calculates the component's state based on the timer and layout settings
/// provided.
pub fn state(&mut self, timer: &Timer, layout_settings: &GeneralLayoutSettings) -> State {
// Reset Scroll Offset when any movement of the split index is observed.
if self.current_split_index != timer.current_split_index() {
self.current_split_index = timer.current_split_index();
self.scroll_offset = 0;
}
let run = timer.run();
self.icon_ids.resize(run.len(), CachedImageId::default());
let mut visual_split_count = self.settings.visual_split_count;
if visual_split_count == 0 {
visual_split_count = run.len();
}
let current_split = timer.current_split_index();
let method = timer.current_timing_method();
let comparison = timer.current_comparison();
let always_show_last_split = if self.settings.always_show_last_split {
0
} else {
1
};
let skip_count = min(
current_split.map_or(0, |c_s| {
c_s.saturating_sub(
visual_split_count
.saturating_sub(2)
.saturating_sub(self.settings.split_preview_count)
.saturating_add(always_show_last_split),
) as isize
}),
run.len() as isize - visual_split_count as isize,
);
self.scroll_offset = min(
max(self.scroll_offset, -skip_count),
run.len() as isize - skip_count - visual_split_count as isize,
);
let skip_count = max(0, skip_count + self.scroll_offset) as usize;
let take_count = visual_split_count + always_show_last_split as usize - 1;
let always_show_last_split = self.settings.always_show_last_split;
let show_final_separator = self.settings.separator_last_split
&& always_show_last_split
&& skip_count + take_count + 1 < run.len();
let Settings {
show_thin_separators,
fill_with_blank_space,
display_two_rows,
..
} = self.settings;
let mut icon_changes = Vec::new();
let mut splits: Vec<_> = run
.segments()
.iter()
.enumerate()
.zip(self.icon_ids.iter_mut())
.skip(skip_count)
.filter(|&((i, _), _)| {
i - skip_count < take_count || (always_show_last_split && i + 1 == run.len())
}).map(|((i, segment), icon_id)| {
let split = segment.split_time()[method];
let comparison_time = segment.comparison(comparison)[method];
let (time, delta, semantic_color) = if current_split > Some(i) {
let delta = catch! { split? - comparison_time? };
(
split,
delta,
split_color(timer, delta, i, true, true, comparison, method),
)
} else if current_split == Some(i) {
(
comparison_time,
analysis::check_live_delta(timer, true, comparison, method),
SemanticColor::Default,
)
} else {
(comparison_time, None, SemanticColor::Default)
};
let delta = if current_split > Some(i) {
DashWrapper::new(Delta::with_decimal_dropping())
.format(delta)
.to_string()
} else {
EmptyWrapper::new(Delta::with_decimal_dropping())
.format(delta)
.to_string()
};
let visual_color = semantic_color.visualize(layout_settings);
if let Some(icon_change) = icon_id.update_with(Some(segment.icon())) {
icon_changes.push(IconChange {
segment_index: i,
icon: icon_change.to_owned(),
});
}
SplitState {
name: segment.name().to_string(),
delta,
time: Regular::new().format(time).to_string(),
semantic_color,
visual_color,
is_current_split: Some(i) == current_split,
index: i,
}
}).collect();
if fill_with_blank_space && splits.len() < visual_split_count {
let blank_split_count = visual_split_count - splits.len();
for _ in 0..blank_split_count {
splits.push(SplitState {
name: String::from(""),
delta: String::from(""),
time: String::from(""),
semantic_color: SemanticColor::Default,
visual_color: SemanticColor::Default.visualize(layout_settings),
is_current_split: false,
index: ::std::usize::MAX ^ 1,
});
}
}
State {
background: self.settings.background,
splits,
icon_changes,
show_thin_separators,
show_final_separator,
display_two_rows,
current_split_gradient: self.settings.current_split_gradient,
}
}
/// Accesses a generic description of the settings available for this
/// component and their current values.
pub fn settings_description(&self) -> SettingsDescription {
SettingsDescription::with_fields(vec![
Field::new("Background".into(), self.settings.background.into()),
Field::new(
"Total Splits".into(),
Value::UInt(self.settings.visual_split_count as _),
),
Field::new(
"Upcoming Splits".into(),
Value::UInt(self.settings.split_preview_count as _),
),
Field::new(
"Show Thin Separators".into(),
self.settings.show_thin_separators.into(),
),
Field::new(
"Show Separator Before Last Split".into(),
self.settings.separator_last_split.into(),
),
Field::new(
"Always Show Last Split".into(),
self.settings.always_show_last_split.into(),
),
Field::new(
"Fill with Blank Space if Not Enough Splits".into(),
self.settings.fill_with_blank_space.into(),
),
Field::new(
"Display 2 Rows".into(),
self.settings.display_two_rows.into(),
),
Field::new(
"Current Split Gradient".into(),
self.settings.current_split_gradient.into(),
),
])
}
/// Sets a setting's value by its index to the given value.
///
/// # Panics
///
/// This panics if the type of the value to be set is not compatible with
/// the type of the setting's value. A panic can also occur if the index of
/// the setting provided is out of bounds.
pub fn set_value(&mut self, index: usize, value: Value) {
match index {
0 => self.settings.background = value.into(),
1 => self.settings.visual_split_count = value.into_uint().unwrap() as _,
2 => self.settings.split_preview_count = value.into_uint().unwrap() as _,
3 => self.settings.show_thin_separators = value.into(),
4 => self.settings.separator_last_split = value.into(),
5 => self.settings.always_show_last_split = value.into(),
6 => self.settings.fill_with_blank_space = value.into(),
7 => self.settings.display_two_rows = value.into(),
8 => self.settings.current_split_gradient = value.into(),
_ => panic!("Unsupported Setting Index"),
}
}
}
|
#![allow(unused_imports, dead_code)]
extern crate fnv;
#[macro_use]
extern crate nom;
extern crate rand;
extern crate rayon;
use fnv::FnvHashSet;
use nom::line_ending;
use std::fs::File;
use std::io::{Read, Write};
use std::mem;
mod scs;
mod trie;
use trie::{ACdat, DATrie, Trie};
named!(point<&str, u8>,
map!(opt!(one_of!("0123456789")), |x| x.unwrap_or('0').to_digit(10).unwrap() as u8)
);
named!(pchar<&str, char>,
one_of!(".abcdefghijklmnopqrstuvwxyz")
);
named!(parse<&str, Vec<(std::string::String, std::vec::Vec<u8>)> >,
many0!(
terminated!(
do_parse!(
init: point >>
pair: many0!(pair!(pchar, point)) >>
(
pair.iter().fold(
(String::new(),vec![init]),
|mut r, &(x, n): &(char, u8)| {
r.0.push(x);
r.1.push(n);
r
}
)
)
),
line_ending
)
)
);
fn main() {
let mut data = String::new();
let mut file = File::open("hyph-en-us.pat").unwrap();
file.read_to_string(&mut data).unwrap();
let mut t = Trie::new();
for &(ref text, ref points) in parse(&data).to_result().unwrap().iter() {
t.insert(text, points.clone());
}
let mut r = DATrie::new();
r.convert(&mut t);
r.prepare(&t);
println!("Fillrate {:.2}%", r.fillrate());
println!("New Pattern Generated");
let raw = scs::process(r.datalist());
let g = ACdat::new(r, &raw);
let dfa = g.pack();
let mut f = File::create("EN_dfa.in").unwrap();
write!(f, "{:?}", dfa).unwrap();
let mut f = File::create("EN_raw.in").unwrap();
write!(f, "{:?}", raw).unwrap();
println!("New Pattern Compressed");
}
|
#![allow(non_snake_case)]
#![cfg(test)]
fn _someFunc<'shorter, 'longer, TA, TB>(shorter: &'shorter TA, b: &'longer TB) where 'longer: 'shorter {}
struct MyRec {}
#[test]
fn Creating_vector_of_references()
{
let longer = MyRec {};
{
let shorter = MyRec {};
_someFunc(&longer, &shorter);
}
}
fn anotherFunc<'a, 'b, T: 'a>(a: &'b T) {}
fn anotherFunc2<'a, 'b, T>(arg: &'b T) where T: 'a {}
|
use crate::snapshot::RoomSnapshot;
#[derive(Debug)]
#[allow(dead_code)]
pub enum Command {
MakeSdpOffer {
peer_id: u64,
sdp_offer: String,
},
MakeSdpAnswer {
peer_id: u64,
sdp_answer: String,
},
UpdateTrack {
peer_id: u64,
track_id: u64,
is_muted: bool,
},
SynchronizeMe {
snapshot: RoomSnapshot,
},
}
#[derive(Debug)]
pub enum Event {
SnapshotSynchronized {
snapshot: RoomSnapshot,
},
SdpAnswerMade {
peer_id: u64,
sdp_answer: String,
},
#[allow(dead_code)]
PeersRemoved {
peers_ids: Vec<u64>,
},
}
|
mod bench;
mod cli;
use crate::bench::{do_bench_tps, generate_and_fund_keypairs, Config, NUM_DIFS_PER_ACCOUNT};
use morgan::gossipService::{discover_cluster, get_clients};
use std::process::exit;
fn main() {
morgan_logger::setup();
morgan_metricbot::set_panic_hook("bench-tps");
let matches = cli::build_args().get_matches();
let cli_config = cli::extract_args(&matches);
let cli::Config {
entrypoint_addr,
drone_addr,
id,
threads,
num_nodes,
duration,
tx_count,
thread_batch_sleep_ms,
sustained,
} = cli_config;
println!("Connecting to the cluster");
let (nodes, _replicators) =
discover_cluster(&entrypoint_addr, num_nodes).unwrap_or_else(|err| {
eprintln!("Failed to discover {} nodes: {:?}", num_nodes, err);
exit(1);
});
if nodes.len() < num_nodes {
eprintln!(
"Error: Insufficient nodes discovered. Expecting {} or more",
num_nodes
);
exit(1);
}
let clients = get_clients(&nodes);
let (keypairs, keypair_balance) = generate_and_fund_keypairs(
&clients[0],
Some(drone_addr),
&id,
tx_count,
NUM_DIFS_PER_ACCOUNT,
);
let config = Config {
id,
threads,
thread_batch_sleep_ms,
duration,
tx_count,
sustained,
};
do_bench_tps(clients, config, keypairs, keypair_balance);
}
|
/// Implementation of tabular
///
use core::*;
use into_tab::*;
use latex_file::LatexFile;
use std::io::BufWriter;
use std::io::Write;
use writable::Writable;
#[derive(Clone)]
pub struct Tabular {
/// Content
content: Vec<Vec<Core>>,
}
impl Tabular {
pub fn new<T: IntoTab>(content: &T) -> Self {
Tabular {
content: content.into_tab(),
}
}
fn align(&self) -> String {
let size = self.content[0].len();
let mut cols = String::from("|");
for _ in 0..size {
cols.push_str(" c |");
}
cols
}
}
impl Writable for Tabular {
fn write_latex(&self, file: &mut LatexFile) {
let mut writer = BufWriter::new(file);
self.write_to_buffer(&mut writer);
}
fn write_to_buffer(&self, mut buf: &mut BufWriter<&mut LatexFile>) {
writeln!(&mut buf, "\\begin{{tabular}}{{{}}}", self.align()).unwrap();
for line in self.content.iter() {
writeln!(&mut buf, " \\hline").unwrap();
line[0].write_to_buffer(&mut buf);
for elem in line.iter().skip(1) {
write!(&mut buf, " & ").unwrap();
elem.write_to_buffer(&mut buf);
}
writeln!(&mut buf, " \\\\").unwrap();
}
writeln!(&mut buf, " \\hline").unwrap();
writeln!(&mut buf, "\\end{{tabular}}").unwrap();
}
}
|
pub fn reply(phrase: &str) -> String {
PhraseKind::from(phrase).reply()
}
enum PhraseKind {
Normal,
Shout,
Question,
Empty
}
impl PhraseKind {
fn reply(self) -> String {
match self {
PhraseKind::Normal => "Whatever.",
PhraseKind::Shout => "Whoa, chill out!",
PhraseKind::Question => "Sure.",
PhraseKind::Empty => "Fine. Be that way!",
}
.to_string()
}
}
impl<'a> From<&'a str> for PhraseKind {
fn from(phrase: &str) -> PhraseKind {
if phrase.is_empty() {
return PhraseKind::Empty
} else if phrase == phrase.to_uppercase() {
return PhraseKind::Shout
} else if phrase.ends_with("?") {
return PhraseKind::Question
}
PhraseKind::Normal
}
}
|
//! The [`is_read_write`] function.
//!
//! [`is_read_write`]: https://docs.rs/rustix/*/rustix/io/fn.is_read_write.html
use crate::{backend, io};
use backend::fd::AsFd;
/// Returns a pair of booleans indicating whether the file descriptor is
/// readable and/or writable, respectively.
///
/// Unlike [`is_file_read_write`], this correctly detects whether sockets
/// have been shutdown, partially or completely.
///
/// [`is_file_read_write`]: crate::fs::is_file_read_write
#[inline]
#[cfg_attr(doc_cfg, doc(cfg(all(feature = "fs", feature = "net"))))]
pub fn is_read_write<Fd: AsFd>(fd: Fd) -> io::Result<(bool, bool)> {
backend::io::syscalls::is_read_write(fd.as_fd())
}
|
macro_rules! read_csr {
($csr_number:expr) => {
/// Reads the CSR
#[inline]
unsafe fn _read() -> usize {
let r: usize;
asm!("csrr {}, {}", out(reg) r, const $csr_number);
r
}
};
}
macro_rules! read_csr_as {
($register:ident, $csr_number:expr) => {
read_csr!($csr_number);
/// Reads the CSR
#[inline]
pub fn read() -> $register {
$register {
bits: unsafe { _read() },
}
}
};
}
macro_rules! write_csr {
($csr_number:expr) => {
/// Writes the CSR
#[inline]
unsafe fn _write(val: usize) {
asm!("csrw {}, {}", const $csr_number, in(reg) val)
}
};
}
macro_rules! set {
($csr_number:expr) => {
/// Set the CSR
#[inline]
unsafe fn _set(bits: usize) {
asm!("csrs {1}, {0}", in(reg) bits, const $csr_number)
}
};
}
macro_rules! clear {
($csr_number:expr) => {
/// Clear the CSR
#[inline]
unsafe fn _clear(bits: usize) {
asm!("csrc {1}, {0}", in(reg) bits, const $csr_number)
}
};
}
macro_rules! set_csr {
($(#[$attr:meta])*, $set_field:ident, $e:expr) => {
$(#[$attr])*
#[inline]
pub unsafe fn $set_field() {
_set($e);
}
}
}
macro_rules! clear_csr {
($(#[$attr:meta])*, $clear_field:ident, $e:expr) => {
$(#[$attr])*
#[inline]
pub unsafe fn $clear_field() {
_clear($e);
}
}
}
macro_rules! set_clear_csr {
($(#[$attr:meta])*, $set_field:ident, $clear_field:ident, $e:expr) => {
set_csr!($(#[$attr])*, $set_field, $e);
clear_csr!($(#[$attr])*, $clear_field, $e);
}
}
macro_rules! get_csr_value {
($csr_number:expr) => {
{
let r: usize;
asm!("csrr {}, {}", out(reg) r, const $csr_number);
r
}
};
} |
use anyhow::{Result, Error, format_err};
use futures::Future;
use tokio::time::{Duration, timeout};
use serde::de::{IntoDeserializer, Deserialize};
use std::path::Path;
use std::str::FromStr;
use std::{io, fs};
pub fn key_val<K: FromStr, V: FromStr>(s: &str) -> Result<(K, V)> where
K::Err: Into<Error>,
V::Err: Into<Error>,
{
let pos = s.find('=')
.ok_or_else(|| format_err!("invalid KEY=value: no `=` found in `{}`", s))?;
Ok((
s[..pos].parse().map_err(Into::into)?,
s[pos + 1..].parse().map_err(Into::into)?
))
}
#[derive(Debug, Clone)]
pub struct Pair<K, V> {
pub key: K,
pub value: V,
}
impl Pair<String, String> {
pub fn object_pair(self) -> (String, qapi::Any) {
(self.key, object_value(self.value))
}
}
impl<K: FromStr, V: FromStr> FromStr for Pair<K, V> where
K::Err: Into<Error>,
V::Err: Into<Error>,
{
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
key_val(s).map(Into::into)
}
}
impl<K, V> From<(K, V)> for Pair<K, V> {
fn from((key, value): (K, V)) -> Self {
Pair {
key,
value,
}
}
}
pub type Arguments = Vec<Pair<String, String>>;
pub fn object_value(value: String) -> qapi::Any {
qapi::Any::String(value) // TODO: determine how to parse numbers and so on
}
pub fn args_options(id: Option<String>, args: Arguments) -> Result<qapi::qmp::ObjectOptions> {
let props = args.into_iter()
.map(Pair::object_pair)
.chain(id.map(|id| ("id".into(), object_value(id))))
.collect::<qapi::Dictionary>();
let props = qapi::Any::Object(props).into_deserializer();
Deserialize::deserialize(props).map_err(Into::into)
}
pub async fn wait<O, E, F: Future<Output=std::result::Result<O, E>>>(duration: Option<Duration>, future: F) -> Result<O> where
E: Into<Error>
{
match duration {
None => future.await.map_err(Into::into),
Some(duration) => match timeout(duration, future).await {
Err(e) => Err(e.into()),
Ok(res) => res.map_err(Into::into),
}
}
}
pub async fn wait_for_socket(socket: &Path) -> Result<()> {
use futures::StreamExt;
use inotify::{
EventMask,
WatchMask,
Inotify,
};
match fs::metadata(socket) {
Err(e) if e.kind() == io::ErrorKind::NotFound => (),
Err(e) => return Err(e.into()),
Ok(_) => return Ok(()),
}
let (parent, file_name) = socket.parent()
.and_then(|p| socket.file_name().map(|n| (p, n)))
.ok_or_else(|| format_err!("socket path {} could not be parsed", socket.display()))?;
let mut inotify = Inotify::init()?;
inotify.add_watch(parent, WatchMask::CREATE)?;
let mut buffer = [0u8; 4096];
let mut events = inotify.event_stream(&mut buffer)?;
while let Some(event) = events.next().await {
let event = event?;
if event.mask.contains(EventMask::CREATE) {
if event.name.as_ref().map(|n| &n[..]) == Some(file_name) {
return Ok(())
} else {
log::info!("ignoring inotify event for {:?}", event);
}
} else {
log::warn!("unexpected inotify event {:?}", event);
}
}
Err(format_err!("inotify ran out of events?"))
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// core
mod message;
mod node;
mod power_manager;
mod types;
// nodes
mod cpu_control_handler;
mod cpu_stats_handler;
mod temperature_handler;
mod thermal_policy;
use crate::power_manager::PowerManager;
use failure::{err_msg, Error, ResultExt};
use fdio;
use fidl_fuchsia_sysinfo as fsysinfo;
use fuchsia_async as fasync;
use fuchsia_syslog::fx_log_info;
use fuchsia_zircon as zx;
use futures::future;
async fn get_board_name() -> Result<String, Error> {
let (client, server) = zx::Channel::create()?;
fdio::service_connect("/dev/misc/sysinfo", server)?;
let svc = fsysinfo::DeviceProxy::new(fasync::Channel::from_channel(client)?);
let (status, name_opt) = svc.get_board_name().await.context("get_board_name failed")?;
zx::Status::ok(status).context("get_board_name returned error status")?;
name_opt.ok_or(err_msg("Failed to get board name"))
}
#[fasync::run_singlethreaded]
async fn main() -> Result<(), Error> {
fuchsia_syslog::init_with_tags(&["power_manager"])?;
fuchsia_syslog::set_verbosity(1);
fx_log_info!("started");
let board = get_board_name().await?;
let mut pm = PowerManager::new(board).context("failed to create PowerManager")?;
pm.init().context("failed to init PowerManager")?;
// At this point, the core nodes and power manager logic should be up and running. We
// now block here forever to allow the nodes to execute their tasks. At any given moment,
// the PowerManager most likely does not have any runnable tasks. The PowerManager will run
// once any of its tasks are made runnable by an event such as a timer or stream event
// from an external source.
future::pending::<()>().await;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[fasync::run_singlethreaded(test)]
async fn test_get_board_name() {
let board = get_board_name().await.context("Failed to get board name").unwrap();
assert_ne!(board, "");
}
#[fasync::run_singlethreaded(test)]
async fn test_power_manager_init() {
let board = get_board_name().await.context("Failed to get board name").unwrap();
let mut pm = PowerManager::new(board).context("Failed to create PowerManager").unwrap();
assert!(pm.init().is_ok());
}
}
|
#[macro_use] extern crate log;
extern crate multipart;
extern crate rand;
use multipart::server::Multipart;
use rand::{Rng, ThreadRng};
use std::fs::File;
use std::env;
use std::io::{self, Read};
const LOG_LEVEL: log::LevelFilter = log::LevelFilter::Debug;
struct SimpleLogger;
impl log::Log for SimpleLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
LOG_LEVEL.to_level()
.map_or(false, |level| metadata.level() <= level)
}
fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
println!("{} - {}", record.level(), record.args());
}
}
fn flush(&self) {}
}
static LOGGER: SimpleLogger = SimpleLogger;
fn main() {
log::set_logger(&LOGGER).expect("Could not initialize logger");
let mut args = env::args().skip(1);
let boundary = args.next().expect("Boundary must be provided as the first argument");
let file = args.next().expect("Filename must be provided as the second argument");
let file = File::open(file).expect("Could not open file");
let reader = RandomReader {
inner: file,
rng: rand::thread_rng()
};
let mut multipart = Multipart::with_body(reader, boundary);
while let Some(field) = multipart.read_entry().unwrap() {
println!("Read field: {:?}", field.headers.name);
}
println!("All entries read!");
}
struct RandomReader<R> {
inner: R,
rng: ThreadRng,
}
impl<R: Read> Read for RandomReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if buf.len() == 0 {
debug!("RandomReader::read() passed a zero-sized buffer.");
return Ok(0);
}
let len = self.rng.gen_range(1, buf.len() + 1);
self.inner.read(&mut buf[..len])
}
}
|
use bytes::buf::BufMut;
use bytes::BytesMut;
use failure::Error;
use futures_03::prelude::*;
use futures_03::ready;
use futures_03::task::{Context, Poll};
use std::io;
use std::net::SocketAddr;
use std::os::unix::io::AsRawFd;
use std::os::unix::io::RawFd;
use std::pin::Pin;
use tokio::io::PollEvented;
const INITIAL_RD_CAPACITY: usize = 640;
pub struct UdpSocketEx {
io: PollEvented<mio::net::UdpSocket>,
rawfd: RawFd,
rd: BytesMut,
}
impl UdpSocketEx {
pub fn new(raw_sock: std::net::UdpSocket) -> Self {
let sys = mio::net::UdpSocket::from_socket(raw_sock).unwrap();
let rawfd = sys.as_raw_fd();
super::set_ip_recv_origdstaddr(rawfd).unwrap();
UdpSocketEx {
io: PollEvented::new(sys).unwrap(),
rawfd,
rd: BytesMut::with_capacity(INITIAL_RD_CAPACITY),
}
}
pub fn poll_recv_from(
&self,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<(usize, SocketAddr, SocketAddr), io::Error>> {
ready!(self.io.poll_read_ready(cx, mio::Ready::readable()))?;
let rawfd = self.rawfd;
match super::recv_sas(rawfd, buf) {
Ok((n, src_addr, dst_addr)) => {
let src_addr = src_addr.unwrap();
let dst_addr = dst_addr.unwrap();
Poll::Ready(Ok((n, src_addr, dst_addr)))
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
self.io.clear_read_ready(cx, mio::Ready::readable())?;
Poll::Pending
} else {
Poll::Ready(Err(e))
}
}
}
}
}
impl Stream for UdpSocketEx {
type Item = std::result::Result<(BytesMut, SocketAddr, SocketAddr), Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let pin = self.get_mut();
pin.rd.reserve(INITIAL_RD_CAPACITY);
let (_, saddr, daddr) = unsafe {
// Read into the buffer without having to initialize the memory.
//
// safety: we know tokio::net::UdpSocket never reads from the memory
// during a recv
let res = {
let bytes = &mut *(pin.rd.bytes_mut() as *mut _ as *mut [u8]);
ready!(pin.poll_recv_from(cx, bytes))
};
let (n, saddr, daddr) = res?;
pin.rd.advance_mut(n);
(n, saddr, daddr)
};
let len = pin.rd.len();
let rd = pin.rd.split_to(len);
pin.rd.clear();
Poll::Ready(Some(Ok((rd, saddr, daddr))))
}
}
|
use std::rc::Rc;
use std::cell::RefCell;
use rustbox::Color;
use rendering::renderer_ascii::Representation;
pub trait Element {
fn get_x(&self) -> i64;
fn get_y(&self) -> i64;
fn get_z(&self) -> i64;
fn set_x(&mut self, x: i64);
fn set_y(&mut self, x: i64);
fn set_z(&mut self, x: i64);
fn get_representation(&self) -> &Representation;
fn get_color(&self) -> Color;
}
pub struct World{
objects: Vec<Rc<RefCell<Element>>>
}
pub struct Tree {
x: i64,
y: i64,
z: i64,
representation: Representation
}
impl Tree {
pub fn new(x: i64, y: i64, z: i64) -> Tree{
//Tree{x: x, y: y, z: z, representation: Representation::new('T')}
Tree{x: x, y: y, z: z, representation: Representation::new_composed(vec![(2, 0, ','), (1, 1, '/'), (2, 1, 'X'), (3, 1, '\\'), (0, 2, '/'), (1, 2, 'X'), (2, 2, 'X'), (3, 2, 'X'), (4, 2, '\\'),(2, 3, 'I')])}
}
pub fn get_x(&self) -> i64{
self.x
}
pub fn get_y(&self) -> i64{
self.y
}
pub fn get_z(&self) -> i64{
self.z
}
pub fn set_x(&mut self, x: i64){
self.x = x;
}
pub fn set_y(&mut self, y: i64){
self.y = y;
}
pub fn set_z(&mut self, z: i64){
self.z = z;
}
pub fn get_representation(&self) -> &Representation{
&self.representation
}
fn get_color(&self) -> Color{
Color::Green
}
}
impl Element for Tree{
fn get_x(&self) -> i64{
self.get_x()
}
fn get_y(&self) -> i64{
self.get_y()
}
fn get_z(&self) -> i64{
self.get_z()
}
fn set_x(&mut self, x: i64){
self.set_x(x);
}
fn set_y(&mut self, y: i64){
self.set_y(y);
}
fn set_z(&mut self, z: i64){
self.set_z(z);
}
fn get_representation(&self) -> &Representation{
self.get_representation()
}
fn get_color(&self) -> Color{
self.get_color()
}
}
impl World{
pub fn new() -> World{
World{objects: Vec::new()}
}
pub fn add_object(&mut self, o: Rc<RefCell<Element>>){
self.objects.push(o)
}
pub fn get_object(&self, index: usize) -> Option<Rc<RefCell<Element>>>{
if index >= self.objects.len() {
return None
}
Some(self.objects[index].clone())
}
pub fn get_object_amount(&self) -> usize{
self.objects.len()
}
}
|
pub mod app;
pub mod config;
pub use app::app::App;
pub use app::config::Config; |
pub mod block;
pub mod builders;
pub mod constants;
pub mod dataflow;
pub mod function;
pub mod instructions;
pub mod layout;
pub mod module;
pub mod value;
pub use self::block::{Block, BlockData};
pub use self::builders::{InstBuilder, InstBuilderBase};
pub use self::constants::{
Constant, ConstantData, ConstantItem, ConstantPool, Immediate, ImmediateTerm, IntoBytes,
};
pub use self::dataflow::DataFlowGraph;
pub use self::function::{FuncRef, Function};
pub use self::instructions::*;
pub use self::layout::{ArenaMap, LayoutAdapter, LayoutNode, OrderedArenaMap};
pub use self::module::Module;
pub use self::value::{Value, ValueData, ValueList, ValueListPool, Values};
|
// Inspired by https://github.com/dutchcoders/transfer.sh
//
// #![allow(unused_imports)]
// #![allow(unused_variables)]
// #![allow(dead_code)]
// #![allow(unused_must_use)]
// externs
//
#[macro_use]
extern crate log;
extern crate log4rs;
extern crate clap;
extern crate rand;
extern crate regex;
extern crate num_cpus;
extern crate url;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate hyper;
extern crate iron;
extern crate router;
extern crate multipart;
#[macro_use]
extern crate quick_error;
extern crate mime_guess;
extern crate openssl;
// modules
//
mod handler;
mod codec;
mod storage;
mod errors;
mod sanitize;
mod server;
// use
//
// extern
use clap::{Arg, ArgMatches, App};
use iron::Chain;
use router::Router;
use log::LogLevelFilter;
use log4rs::config::{Config, Logger, Root, Appender};
use log4rs::append::console::ConsoleAppender;
use log4rs::encode::pattern::PatternEncoder;
use std::env;
use std::path::{Path, PathBuf};
use std::str::FromStr;
// intern
use handler::*;
use storage::*;
use server::*;
use errors::{TransferError, Result};
fn main() {
let temp_dir = env::temp_dir();
let temp_dir_str = temp_dir.to_str().expect("Temp dir not found");
if let Err(err) = init_server(match_cmd_arguments(temp_dir_str)) {
error!("{}", err);
}
}
fn match_cmd_arguments<'a>(temp_dir: &'a str) -> ArgMatches<'a> {
App::new("transfer.rs")
.version("0.1.0")
.about("Easy file sharing from the command line")
.arg(Arg::with_name("port")
.short("p")
.long("port")
.value_name("PORT")
.takes_value(true)
.help("Sets the server port"))
.arg(Arg::with_name("basedir")
.short("b")
.long("basedir")
.value_name("BASEDIR")
.takes_value(true)
.default_value(temp_dir)
.help("Sets the base directory"))
.arg(Arg::with_name("loglevel")
.long("loglevel")
.value_name("LOGLEVEL")
.takes_value(true)
.possible_values(&["error", "warn", "info", "debug", "trace"])
.default_value("info")
.help("Sets the log level"))
.arg(Arg::with_name("storage")
.long("storage")
.value_name("STORAGE")
.takes_value(true)
.possible_values(&["local"])
.default_value("local")
.help("Sets the storage provider"))
.arg(Arg::with_name("ssl")
.long("ssl")
.requires_all(&["ssl-cert", "ssl-key"])
.help("Enables ssl"))
.arg(Arg::with_name("ssl-cert")
.long("ssl-cert")
.value_name("SSL-CERTIFICATE")
.takes_value(true)
.help("Sets the ssl certificate"))
.arg(Arg::with_name("ssl-key")
.long("ssl-key")
.value_name("SSL-PRIVATE-KEY")
.takes_value(true)
.help("Sets the ssl private key"))
.arg(Arg::with_name("ssl-cert-chain")
.long("ssl-cert-chain")
.value_name("SSL-CERTIFICATE-CHAIN")
.takes_value(true)
.help("Sets the ssl certificate chain"))
.get_matches()
}
fn init_server(arg_matches: ArgMatches) -> Result<()> {
let loglevel = try!(init_logger(arg_matches.value_of("loglevel")));
let use_ssl = arg_matches.is_present("ssl");
let port: u16 = try!(get_port(arg_matches.value_of("port"), use_ssl));
let basedir: &str = try!(get_directory(arg_matches.value_of("basedir")));
let storage_provider = try!(arg_matches.value_of("storage")
.ok_or(TransferError::from("Unknown storage")));
let addr = ("0.0.0.0", port);
let protocol = try!(to_protocol(use_ssl,
arg_matches.value_of("ssl-cert"),
arg_matches.value_of("ssl-key"),
arg_matches.value_of("ssl-cert-chain")));
let chain = try!(init_chain_from_storage(storage_provider, basedir));
info!("#####################################################");
info!("# transfer.rs #");
info!("#####################################################");
info!("");
info!("Listening on port: '{}'.", port);
info!("Using log level: '{}'.", loglevel);
info!("Using storage provider '{}' with base directory '{}'.",
storage_provider,
basedir);
info!("Using ssl: '{}'.", use_ssl);
try!(TransferServer::new(chain, addr, protocol)).init().unwrap();
Ok(())
}
fn init_chain_from_storage(storage: &str, basedir: &str) -> Result<Chain> {
match storage {
"local" => Ok(try!(init_handler_chain(LocalStorage::new(basedir)))),
_ => Err(TransferError::from(format!("Invalid storage '{}'", storage))),
}
}
fn to_protocol(ssl: bool,
ssl_cert: Option<&str>,
ssl_key: Option<&str>,
ssl_cert_chain: Option<&str>)
-> Result<ExtIronProtocol> {
if ssl {
let cert = PathBuf::from(try!(get_directory(ssl_cert)));
let key = PathBuf::from(try!(get_directory(ssl_key)));
let cert_chain = if ssl_cert_chain.is_some() {
Some(PathBuf::from(try!(get_directory(ssl_cert_chain))))
} else {
None
};
Ok(ExtIronProtocol::with_https(cert, key, cert_chain))
} else {
Ok(ExtIronProtocol::Http)
}
}
fn get_port(port: Option<&str>, ssl: bool) -> Result<u16> {
port.map(|port_str| port_str.parse::<u16>().map_err(|err| TransferError::from(err)))
.unwrap_or_else(|| {
if ssl {
Ok(443u16)
} else {
Ok(80u16)
}
})
}
fn get_directory<'a>(directory: Option<&'a str>) -> Result<&'a str> {
directory.map(|dir| {
if Path::new(dir).exists() {
Ok(dir)
} else {
Err(TransferError::from(format!("Invalid directory '{}'", dir)))
}
})
.unwrap()
}
fn init_logger(log_level: Option<&str>) -> Result<LogLevelFilter> {
let level = try!(LogLevelFilter::from_str(log_level.unwrap_or("info"))
.map_err(|_| TransferError::from("Unknown log level")));
// Appender
let stdout_appender = Appender::builder()
.build("stdout".to_owned(),
Box::new(ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new("{h({l})} {m}{n}")))
.build()));
// Root logger
let root = Root::builder().appender("stdout".to_owned()).build(level);
// Logger
let transerrs_logger = Logger::builder().build("transfer_rs".to_owned(), level);
let multipart_logger = Logger::builder().build("multipart".to_owned(), LogLevelFilter::Error);
let config = Config::builder()
.appender(stdout_appender)
.logger(transerrs_logger)
.logger(multipart_logger)
.build(root)
.unwrap();
log4rs::init_config(config).and(Ok(level)).map_err(|err| TransferError::from(err))
}
fn init_handler_chain<S: Storage>(storage: S) -> Result<Chain> {
let mut router = Router::new();
// Routes
// ** Health handler
router.get(r"/health.html", health_handler);
// ** PUT upload handler
let put_handler = PutHandler::new(storage.clone());
router.put(r"/upload/:filename", put_handler.clone());
// ** POST
let post_handler = PostHandler::new(storage.clone());
router.post(r"/upload", post_handler.clone()); // multipart/form
// ** GET handler
router.get(r"/download/:token/:filename",
GetHandler::new(storage.clone()));
// ** View handler
let view_handler = StaticViewHandler::new();
router.get(r"/", view_handler.clone());
router.get(r"/:static_resource", view_handler.clone());
router.get(r"/js/:static_resource", view_handler.clone());
router.get(r"/css/:static_resource", view_handler.clone());
// Chain
let mut chain = Chain::new(router);
chain.link_before(CheckHostHeaderMiddleware);
chain.link_before(MultipartMiddleware);
chain.link_after(NotFoundMiddleware);
chain.link_after(InfoMiddleware);
Ok(chain)
} |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![feature(async_await, await_macro, futures_api)]
#![deny(warnings)]
use failure::{Error, ResultExt};
use fdio;
use fidl_fuchsia_hardware_ethernet as zx_eth;
use fidl_fuchsia_net as net;
use fidl_fuchsia_net_stack::{self as netstack, StackMarker, StackProxy};
use fidl_fuchsia_net_stack_ext as pretty;
use fuchsia_app::client::connect_to_service;
use fuchsia_async as fasync;
use fuchsia_zircon as zx;
use std::fs::File;
use std::os::unix::io::AsRawFd;
use structopt::StructOpt;
mod opts;
use crate::opts::*;
fn main() -> Result<(), Error> {
let opt = Opt::from_args();
let mut exec = fasync::Executor::new().context("error creating event loop")?;
let stack = connect_to_service::<StackMarker>().context("failed to connect to netstack")?;
let fut = async {
match opt {
Opt::If(cmd) => await!(do_if(cmd, stack)),
Opt::Fwd(cmd) => await!(do_fwd(cmd, stack)),
}
};
exec.run_singlethreaded(fut)
}
async fn do_if(cmd: opts::IfCmd, stack: StackProxy) -> Result<(), Error> {
match cmd {
IfCmd::List => {
let response = await!(stack.list_interfaces()).context("error getting response")?;
for info in response {
println!("{}", pretty::InterfaceInfo::from(info));
}
}
IfCmd::Add { path } => {
let dev = File::open(&path).context("failed to open device")?;
let topological_path =
fdio::device_get_topo_path(&dev).context("failed to get topological path")?;
let fd = dev.as_raw_fd();
let mut client = 0;
zx::Status::ok(unsafe { fdio::fdio_sys::fdio_get_service_handle(fd, &mut client) })
.context("failed to get fdio service handle")?;
let dev = fidl::endpoints::ClientEnd::<zx_eth::DeviceMarker>::new(
// Safe because we checked the return status above.
zx::Channel::from(unsafe { zx::Handle::from_raw(client) }),
);
let (err, id) = await!(stack.add_ethernet_interface(&topological_path, dev))
.context("error adding device")?;
if let Some(e) = err {
println!("Error adding interface {}: {:?}", path, e)
} else {
println!("Added interface {}", id)
}
}
IfCmd::Del { id } => {
let response =
await!(stack.del_ethernet_interface(id)).context("error removing device")?;
if let Some(e) = response {
println!("Error removing interface {}: {:?}", id, e)
}
}
IfCmd::Get { id } => {
let response =
await!(stack.get_interface_info(id)).context("error getting response")?;
if let Some(e) = response.1 {
println!("Error getting interface {}: {:?}", id, e)
} else {
println!("{}", pretty::InterfaceInfo::from(*response.0.unwrap()))
}
}
IfCmd::Enable { id } => {
let response = await!(stack.enable_interface(id)).context("error getting response")?;
if let Some(e) = response {
println!("Error enabling interface {}: {:?}", id, e)
} else {
println!("Interface {} enabled", id)
}
}
IfCmd::Disable { id } => {
let response = await!(stack.disable_interface(id)).context("error getting response")?;
if let Some(e) = response {
println!("Error disabling interface {}: {:?}", id, e)
} else {
println!("Interface {} disabled", id)
}
}
IfCmd::Addr(AddrCmd::Add { id, addr, prefix }) => {
let parsed_addr = parse_ip_addr(&addr)?;
let mut fidl_addr =
netstack::InterfaceAddress { ip_address: parsed_addr, prefix_len: prefix };
let response = await!(stack.add_interface_address(id, &mut fidl_addr))
.context("error setting interface address")?;
if let Some(e) = response {
println!("Error adding interface address {}: {:?}", id, e)
} else {
println!(
"Address {} added to interface {}",
pretty::InterfaceAddress::from(fidl_addr),
id
)
}
}
IfCmd::Addr(AddrCmd::Del { .. }) => {
println!("{:?} not implemented!", cmd);
}
}
Ok(())
}
async fn do_fwd(cmd: opts::FwdCmd, stack: StackProxy) -> Result<(), Error> {
match cmd {
FwdCmd::List => {
let response = await!(stack.get_forwarding_table())
.context("error retrieving forwarding table")?;
for entry in response {
println!("{}", pretty::ForwardingEntry::from(entry));
}
}
FwdCmd::AddDevice { id, addr, prefix } => {
let response =
await!(stack.add_forwarding_entry(&mut fidl_fuchsia_net_stack::ForwardingEntry {
subnet: net::Subnet { addr: parse_ip_addr(&addr)?, prefix_len: prefix },
destination: fidl_fuchsia_net_stack::ForwardingDestination::DeviceId(id),
}))
.context("error adding forwarding entry")?;
if let Some(e) = response {
println!("Error adding forwarding entry: {:?}", e);
} else {
println!("Added forwarding entry for {}/{} to device {}", addr, prefix, id);
}
}
FwdCmd::AddHop { next_hop, addr, prefix } => {
let response =
await!(stack.add_forwarding_entry(&mut fidl_fuchsia_net_stack::ForwardingEntry {
subnet: net::Subnet { addr: parse_ip_addr(&addr)?, prefix_len: prefix },
destination: fidl_fuchsia_net_stack::ForwardingDestination::NextHop(
parse_ip_addr(&next_hop)?
),
}))
.context("error adding forwarding entry")?;
if let Some(e) = response {
println!("Error adding forwarding entry: {:?}", e);
} else {
println!("Added forwarding entry for {}/{} to {}", addr, prefix, next_hop);
}
}
FwdCmd::Del { addr, prefix } => {
let response = await!(stack.del_forwarding_entry(&mut net::Subnet {
addr: parse_ip_addr(&addr)?,
prefix_len: prefix,
}))
.context("error removing forwarding entry")?;
if let Some(e) = response {
println!("Error removing forwarding entry: {:?}", e);
} else {
println!("Removed forwarding entry for {}/{}", addr, prefix);
}
}
}
Ok(())
}
fn parse_ip_addr(addr: &str) -> Result<net::IpAddress, Error> {
match addr.parse()? {
::std::net::IpAddr::V4(ipv4) => {
Ok(net::IpAddress::Ipv4(net::IPv4Address { addr: ipv4.octets() }))
}
::std::net::IpAddr::V6(ipv6) => {
Ok(net::IpAddress::Ipv6(net::IPv6Address { addr: ipv6.octets() }))
}
}
}
|
use crate::sim::SimTime;
use std::collections::HashMap;
#[derive(Default)]
pub struct RecastExpirations {
actions: HashMap<u32, SimTime>,
gcd_expiration: SimTime,
}
impl RecastExpirations {
pub fn check_ready(&self, action_id: u32, ogcd: bool, sim_time: SimTime) -> bool {
let ready = (ogcd || self.check_gcd_ready(sim_time))
&& match self.actions.get(&action_id) {
Some(expiration) => *expiration <= sim_time,
None => true,
};
ready
}
pub fn set(&mut self, action_id: u32, expiration: SimTime) {
self.actions.insert(action_id, expiration);
}
pub fn check_gcd_ready(&self, sim_time: SimTime) -> bool {
self.gcd_expiration <= sim_time
}
pub fn set_gcd(&mut self, expiration: SimTime) {
self.gcd_expiration = expiration;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct TestCheckReadyData {
action_id: u32,
sim_time: SimTime,
expiration: SimTime,
ogcd: bool,
gcd_expiration: SimTime,
}
macro_rules! test_check_ready {
($test_name:ident, $test_data:expr, $expected:expr) => {
#[test]
fn $test_name() {
let data = $test_data;
let mut recast_expirations = RecastExpirations {
gcd_expiration: data.gcd_expiration,
..Default::default()
};
recast_expirations.set(data.action_id, data.expiration);
assert_eq!(
$expected,
recast_expirations.check_ready(data.action_id, data.ogcd, data.sim_time)
);
}
};
}
test_check_ready!(
check_ready,
TestCheckReadyData {
..Default::default()
},
true
);
test_check_ready!(
check_ready_false,
TestCheckReadyData {
expiration: 10,
sim_time: 9,
..Default::default()
},
false
);
test_check_ready!(
check_ready_true_greater_sim_time,
TestCheckReadyData {
expiration: 10,
sim_time: 11,
..Default::default()
},
true
);
test_check_ready!(
check_ready_true_equal_sim_time,
TestCheckReadyData {
expiration: 10,
sim_time: 10,
..Default::default()
},
true
);
test_check_ready!(
check_ready_gcd,
TestCheckReadyData {
expiration: 10,
sim_time: 10,
gcd_expiration: 11,
ogcd: false,
..Default::default()
},
false
);
test_check_ready!(
check_ready_gcd_with_ogcd,
TestCheckReadyData {
expiration: 10,
sim_time: 10,
gcd_expiration: 11,
ogcd: true,
..Default::default()
},
true
);
#[test]
fn check_ready_no_recast_with_gcd() {
let recast_expirations = RecastExpirations {
gcd_expiration: 10,
..Default::default()
};
assert_eq!(false, recast_expirations.check_ready(0, false, 9));
}
}
|
//! Synchronous native rust database driver for SAP HANA (TM).
//!
//! `hdbconnect` provides a lean, fast, and easy-to-use rust-API for working with
//! SAP HANA. The driver is written completely in rust.
//! It interoperates elegantly with all data types that implement the standard
//! `serde::Serialize` and/or `serde::Deserialize` traits, for input and output respectively.
//! So, instead of iterating over a resultset by rows and columns, you can
//! assign the complete resultset directly to any rust structure that fits the data
//! semantics.
//!
//! `hdbconnect` implements this with the help of [`serde_db`](https://docs.rs/serde_db),
//! a reusable library for simplifying the data exchange between application code
//! and database drivers, both for input parameters (e.g. to prepared statements)
//! and for results that are returned from the database.
//!
//! In contrast to typical ORM mapping variants, this approach allows
//! using the full flexibility of SQL (projection lists, all kinds of joins,
//! unions, nested queries, etc). Whatever query you need, you just use it, without further ado
//! for defining object models etc., and whatever result structure you want to read,
//! you just use a corresponding rust structure into
//! which you deserialize the data. It's hard to use less code!
//!
//! See [code examples](crate::code_examples) for an overview.
//!
// only enables the `doc_cfg` feature when the `docsrs` configuration attribute is defined
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_debug_implementations)]
#![deny(clippy::all)]
#![deny(clippy::pedantic)]
pub use hdbconnect_impl::{
time, url, ConnectParams, ConnectParamsBuilder, ExecutionResult, FieldMetadata, HdbError,
HdbResult, HdbValue, IntoConnectParams, IntoConnectParamsBuilder, OutputParameters,
ParameterBinding, ParameterDescriptor, ParameterDescriptors, ParameterDirection, Row,
ServerCerts, ServerError, ServerUsage, Severity, Tls, ToHana, TypeId, DEFAULT_FETCH_SIZE,
DEFAULT_LOB_READ_LENGTH, DEFAULT_LOB_WRITE_LENGTH,
};
pub use hdbconnect_impl::sync::{
Connection, HdbResponse, HdbReturnValue, PreparedStatement, ResultSet,
};
#[cfg_attr(docsrs, doc(cfg(feature = "r2d2_pool")))]
#[cfg(feature = "r2d2_pool")]
pub use hdbconnect_impl::sync::ConnectionManager;
pub mod code_examples;
/// Non-standard types that are used to represent database values.
///
/// A `ResultSet` contains a sequence of `Row`s, each row is a sequence of `HdbValue`s.
/// Some variants of `HdbValue` are implemented using plain rust types,
/// others are based on the types in this module.
pub mod types {
pub use hdbconnect_impl::sync::{BLob, CLob, NCLob};
pub use hdbconnect_impl::types::*;
}
|
//! End to end test of catalog configurations
use std::{io::Write, path::Path};
use tempfile::TempDir;
use test_helpers_end_to_end::{maybe_skip_integration, MiniCluster, Step, StepTest};
#[tokio::test]
async fn dsn_file() {
test_helpers::maybe_start_logging();
let database_url = maybe_skip_integration!();
// dsn-file only supported for postgres dsns, so skip if not postgres
if !database_url.starts_with("postgres") {
println!("SKIPPING dsn file test. Requires postgres catalog, but got {database_url}");
return;
}
// tests using the special `dsn-file://` url for catalog
// used in IDPE / InfluxCloud production
//
// In this case the dsn is `dsn-file://<filename>` and the actual
// catalog url is stored in <filename> (which is updated from time
// to time with rotated credentials).
let tmpdir = TempDir::new().unwrap();
let dsn_file_path = tmpdir.path().join("catalog.dsn");
// Write the actual database url to the temporary file
write_to_file(&dsn_file_path, &database_url);
let database_url = format!("dsn-file://{}", dsn_file_path.display());
println!("databse_url is {database_url}");
// Set up the cluster ====================================
let mut cluster = MiniCluster::create_non_shared(database_url).await;
StepTest::new(
&mut cluster,
vec![
Step::WriteLineProtocol("my_table val=42i 123456".to_string()),
Step::Query {
sql: "select * from my_table".to_string(),
expected: vec![
"+--------------------------------+-----+",
"| time | val |",
"+--------------------------------+-----+",
"| 1970-01-01T00:00:00.000123456Z | 42 |",
"+--------------------------------+-----+",
],
},
],
)
.run()
.await
}
fn write_to_file(path: &Path, contents: &str) {
let mut file = std::fs::File::create(path).unwrap();
file.write_all(contents.as_bytes()).unwrap();
file.flush().unwrap();
}
|
fn fib(x: i32) -> i32{
if x<=2{
return 1;
}
return fib(x-1)+fib(x-2);
}
fn main(){
let mut sum: i32=0;
let mut count=0;
loop{
let f=fib(count);
if f > 4000000{
break;
}
if f%2==0{
sum+=f;
}
count+=1;
}
println!("{}", sum);
}
|
use surface::{Surface, SurfaceSession};
pub struct CpuSurface {}
impl CpuSurface {
pub fn new() -> CpuSurface {
CpuSurface {}
}
}
impl Surface for CpuSurface {
type SurfaceSessionType = CpuSurfaceSession;
fn draw_session() -> CpuSurfaceSession {
CpuSurfaceSession {}
}
}
pub struct CpuSurfaceSession {}
impl SurfaceSession for CpuSurfaceSession {}
|
mod keys;
mod parsing;
mod protocols;
use crate::devices::Controller;
use crate::protocol::Command::Terminate;
pub use keys::*;
use libusb::Error;
pub struct Protocol {
init_packets: Vec<InitPacket>,
}
struct InitPacket {
order: Option<usize>,
after_packet: Option<Vec<u8>>,
content: Vec<u8>,
}
impl Protocol {
pub fn for_ids(vendor_id: u16, product_id: u16) -> Option<Protocol> {
match (vendor_id, product_id) {
(0x045e, 0x02ea) => Some(protocols::create_xbox_one_s()),
(vendor, product) => {
println!(
"Unknown vendor_id and product_id pair: {:04x}:{:04x}",
vendor, product
);
None
}
}
}
pub fn init(&self, controller: &mut Controller) -> Option<Command> {
let mut index = 0;
while index < self.init_packets.len() {
match controller.read() {
Ok(data) => {
let packets = self.find_response_packet(data, index);
for packet in packets {
if controller.write(&packet).is_err() {
return Some(Terminate);
}
index += 1;
}
}
Err(Error::Timeout) => return None,
Err(error) => {
println!("Unable to read: {}", error);
return Some(Command::Terminate);
}
};
}
None
}
pub fn read_command(&self, controller: &mut Controller) -> Option<Command> {
match controller.read() {
Ok(data) => parsing::parse_packet(&data),
Err(Error::Timeout) => None,
Err(_) => Some(Terminate),
}
}
fn find_response_packet(&self, data: Vec<u8>, index: usize) -> Vec<&Vec<u8>> {
self.init_packets
.iter()
.filter(|p| {
if let Some(after) = &p.after_packet {
after.iter().zip(&data).filter(|&(a, b)| a == b).count() == after.len()
} else if let Some(order) = p.order {
index == order
} else {
false
}
})
.map(|p| &p.content)
.collect()
}
}
|
fn main() {
yew::start_app::<node_refs_std_web::Model>();
}
|
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
//
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use clap::{crate_authors, crate_version, App, Arg};
#[derive(Debug, PartialEq)]
pub enum Verbosity {
Quiet,
Normal,
Verbose,
}
#[derive(Debug)]
pub struct WorkOrder {
pub source_assets: SourceAssets,
pub output_path: PathBuf,
pub verbosity: Verbosity,
}
impl WorkOrder {
pub fn verbose(&self) -> bool {
self.verbosity == Verbosity::Verbose
}
pub fn quiet(&self) -> bool {
self.verbosity == Verbosity::Quiet
}
}
#[derive(Debug)]
pub struct SourceAssets {
pub base: SourceAsset,
pub melds: Vec<SourceAsset>,
}
#[derive(Debug)]
pub struct SourceAsset {
pub path: PathBuf,
pub tag: Option<String>,
}
pub fn parse_args() -> WorkOrder {
let matches = App::new("glTFVariantMeld")
.author(crate_authors!())
.version(crate_version!())
.arg(
Arg::with_name("base")
.short("b")
.long("base")
.required(true)
.takes_value(true)
.value_name("FILE")
.help("the base source asset into which to meld"),
)
.arg(
Arg::with_name("tag")
.short("t")
.long("tagged-as")
.takes_value(true)
.multiple(true)
.value_name("TAG")
.help("a variant tag representing the preceding source asset"),
)
.arg(
Arg::with_name("meld")
.short("m")
.long("meld")
.takes_value(true)
.multiple(true)
.value_name("FILE")
.help("a source asset to meld into the base"),
)
.arg(
Arg::with_name("output")
.short("o")
.long("output")
.required(true)
.takes_value(true)
.value_name("FILE")
.help("the name of the output file"),
)
.arg(
Arg::with_name("force")
.short("f")
.long("force")
.takes_value(false)
.help("overwrite output file if it exists"),
)
.arg(
Arg::with_name("verbose")
.short("v")
.long("verbose")
.takes_value(false)
.help("output more detailed progress"),
)
.arg(
Arg::with_name("quiet")
.short("q")
.long("quiet")
.takes_value(false)
.help("output nothing"),
)
.get_matches();
let source_assets = parse_source_assets(&matches);
let force = matches.occurrences_of("force") > 0;
let output_path = &matches.value_of("output").unwrap();
if let Ok(metadata) = fs::metadata(output_path) {
if metadata.is_dir() {
eprintln!("Error: Output path is a directory: {}", output_path);
std::process::exit(1);
} else if metadata.is_file() && !force {
eprintln!(
"Error: Output path exists (use -f to overwrite): {}",
output_path
);
std::process::exit(1);
}
}
let output_path = PathBuf::from(output_path);
let verbosity = if matches.occurrences_of("verbose") > 0 {
Verbosity::Verbose
} else if matches.occurrences_of("quiet") > 0 {
Verbosity::Quiet
} else {
Verbosity::Normal
};
WorkOrder {
source_assets,
output_path,
verbosity,
}
}
fn parse_source_assets(matches: &clap::ArgMatches) -> SourceAssets {
let base = matches.value_of("base").unwrap();
let base_ix = matches.index_of("base").unwrap();
let tag_map = if let Some(tags) = matches.values_of("tag") {
let ix = matches.indices_of("tag").unwrap();
ix.zip(tags).collect()
} else {
HashMap::new()
};
let mk_asset = |pathstr, ix| {
let path = PathBuf::from(pathstr);
if path.exists() {
let tag = tag_map.get(&(ix + 2)).map(|t| (*t).to_owned());
SourceAsset { path, tag }
} else {
eprintln!("Error: Couldn't open file: {}", pathstr);
std::process::exit(1);
}
};
let base = mk_asset(base, base_ix);
let melds = if let Some(melds) = matches.values_of("meld") {
let ix = matches.indices_of("meld").unwrap();
melds
.zip(ix)
.map(|(meld, meld_ix)| mk_asset(meld, meld_ix))
.collect()
} else {
vec![]
};
SourceAssets { base, melds }
}
|
extern crate simple_examples;
use simple_examples::topic::Topic;
use simple_examples::*;
use std::io;
fn main() {
let map = populate_map();
loop {
println!("Choose an example ('topic, number')");
let mut choice = String::new();
io::stdin().read_line(&mut choice)
.expect("Failed to read line");
let choice = choice.trim();
if choice == "q" || choice == "Q" {
break;
}
let (topic, example) = match parse_input(&choice) {
Ok(tuple) => tuple,
Err(e) => {
println!("Error when parsing: {}", e);
continue;
}
};
let topic = match map.get(&topic.to_lowercase()) {
Some(t) => t,
None => {
println!("Didn't find matching topic: {}", topic);
continue;
}
};
topic.run_example(example);
}
println!("Goodbye!");
}
|
use crate::lexer::*;
pub(crate) mod array;
pub(crate) mod numeric;
pub(crate) mod regex;
pub(crate) mod string;
pub(crate) mod symbol;
pub(crate) use array::array_literal;
pub(crate) use numeric::numeric_literal;
pub(crate) use regex::regular_expression_literal;
pub(crate) use string::string_literal;
pub(crate) use symbol::symbol;
/// *numeric_literal* | *string_literal* | *array_literal* | *regular_expression_literal* | *symbol*
pub(crate) fn literal(i: Input) -> NodeResult {
alt((
numeric_literal,
string_literal,
array_literal,
regular_expression_literal,
symbol,
))(i)
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::log_error::log_error_discard_result;
use crate::session::Session;
use crate::session_id_rights;
use crate::Result;
use crate::CHANNEL_BUFFER_SIZE;
use fidl::endpoints::ServerEnd;
use fidl_fuchsia_mediasession::{ActiveSession, ControllerMarker, ControllerRegistryControlHandle};
use fuchsia_async as fasync;
use fuchsia_zircon as zx;
use futures::{
channel::mpsc::{channel, Receiver, Sender},
SinkExt, StreamExt,
};
use std::collections::{HashMap, VecDeque};
use zx::AsHandleRef;
/// Tracks which session most recently reported an active status.
struct ActiveSessionQueue {
active_sessions: VecDeque<zx::Koid>,
}
impl ActiveSessionQueue {
pub fn new() -> Self {
Self { active_sessions: VecDeque::new() }
}
/// Returns session which most recently reported an active status if it
/// exists.
pub fn active_session(&self) -> Option<zx::Koid> {
self.active_sessions.front().cloned()
}
/// Promotes a session to the front of the queue and returns whether
/// the front of the queue was changed.
pub fn promote_session(&mut self, session_id: zx::Koid) -> bool {
if self.active_session() == Some(session_id) {
return false;
}
self.remove_session(session_id);
self.active_sessions.push_front(session_id);
return true;
}
/// Removes a session from the queue and returns whether the front of the
/// queue was changed.
pub fn remove_session(&mut self, session_id: zx::Koid) -> bool {
if self.active_session() == Some(session_id) {
self.active_sessions.pop_front();
true
} else {
if let Some(i) = self.active_sessions.iter().position(|&id| id == session_id) {
self.active_sessions.remove(i);
}
false
}
}
}
pub enum ServiceEvent {
NewSession((Session, zx::Event)),
SessionClosed(zx::Koid),
SessionActivity(zx::Koid),
NewControllerRequest { session_id: zx::Koid, request: ServerEnd<ControllerMarker> },
NewActiveSessionChangeListener(ControllerRegistryControlHandle),
}
/// The Media Session service.
pub struct Service {
published_sessions: HashMap<zx::Koid, (Sender<ServerEnd<ControllerMarker>>, zx::Event)>,
active_session_listeners: Vec<ControllerRegistryControlHandle>,
/// The most recent sessions to broadcast activity.
active_session_queue: ActiveSessionQueue,
}
impl Service {
pub fn new() -> Self {
Self {
published_sessions: HashMap::new(),
active_session_listeners: Vec::new(),
active_session_queue: ActiveSessionQueue::new(),
}
}
pub async fn serve(mut self, mut fidl_stream: Receiver<ServiceEvent>) -> Result<()> {
while let Some(service_event) = await!(fidl_stream.next()) {
match service_event {
ServiceEvent::NewSession((session, session_id_handle)) => {
let session_id = session.id();
let (request_sink, request_stream) = channel(CHANNEL_BUFFER_SIZE);
self.published_sessions.insert(session_id, (request_sink, session_id_handle));
fasync::spawn(session.serve(request_stream));
}
ServiceEvent::SessionClosed(session_id) => {
self.published_sessions.remove(&session_id);
let active_session_changed =
self.active_session_queue.remove_session(session_id);
if active_session_changed {
self.broadcast_active_session()?;
}
}
ServiceEvent::NewControllerRequest { session_id, request } => {
if let Some((request_sink, _)) = self.published_sessions.get_mut(&session_id) {
log_error_discard_result(await!(request_sink.send(request)));
}
}
ServiceEvent::NewActiveSessionChangeListener(listener) => {
if self.send_active_session(&listener).is_ok() {
self.active_session_listeners.push(listener);
}
}
ServiceEvent::SessionActivity(session_id) => {
let active_session_changed =
self.active_session_queue.promote_session(session_id);
if active_session_changed {
self.broadcast_active_session()?;
}
}
}
}
Ok(())
}
/// Broadcasts the active session to all listeners and drops those which are
/// no longer connected.
fn broadcast_active_session(&mut self) -> Result<()> {
let mut active_session_listeners = Vec::new();
std::mem::swap(&mut self.active_session_listeners, &mut active_session_listeners);
active_session_listeners.retain(|listener| self.send_active_session(listener).is_ok());
std::mem::swap(&mut self.active_session_listeners, &mut active_session_listeners);
Ok(())
}
fn send_active_session(&self, recipient: &ControllerRegistryControlHandle) -> Result<()> {
recipient.send_on_active_session(self.active_session_update()?).map_err(Into::into)
}
fn active_session_update(&self) -> Result<ActiveSession> {
Ok(ActiveSession {
session_id: self
.active_session_queue
.active_session()
.and_then(|koid| self.published_sessions.get(&koid))
.map(|(_, session_id)| -> Result<zx::Event> {
Ok(session_id.as_handle_ref().duplicate(session_id_rights())?.into())
})
.transpose()?,
})
}
}
|
//! Netinject provides a high level API for creating and deleting iptables rules which drop
//! packets. It's designed to help you test network failure scenarios.
//!
//! It can be used as a library, a script, and has a cleanup method which is specifically designed
//! for use from a daemon which can clean up after itself on exit.
mod error;
mod iptables_helpers;
extern crate iptables;
use error::{ipt_to_netinject_err, NetinjectResult};
use iptables::error::IPTResult;
use iptables::IPTables;
use iptables_helpers::{append_unique, delete, delete_chain, new_chain};
/// Specifies the protocol of the dropped packet. To drop multiple protocols, multiple rules should
/// be created.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum Protocol {
TCP,
UDP,
}
/// Specifies whether an inbound our outbound packet should be dropped. To drop in both directions,
/// two rules should be created.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum Direction {
Inbound,
Outbound,
}
/// Used to identify a packet to be dropped. When a rule is created, only packets for that
/// protocol, port, and direction will be dropped.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub struct Ident {
pub protocol: Protocol,
pub port: u16,
pub direction: Direction,
}
// The filter table is a system defined iptables table where packet dropping rules are inserted.
const FILTER_TABLE: &str = "filter";
// The INPUT and OUTPUT chains are system defined iptables chains on the filter table. All inbound
// and outbound packets will pass by these chains.
const FILTER_INPUT_CHAIN: &str = "INPUT";
const FILTER_OUTPUT_CHAIN: &str = "OUTPUT";
// The NETINJECT_INPUT and NETINJECT_OUTPUT chains are defined by netinject. This is where
// netinject inserts rules for dropping inbound and outbound packets.
const NETINJECT_INPUT_CHAIN: &str = "NETINJECT_INPUT";
const NETINJECT_OUTPUT_CHAIN: &str = "NETINJECT_OUTPUT";
impl Ident {
fn rule(&self) -> String {
let protocol = match self.protocol {
Protocol::TCP => "tcp",
Protocol::UDP => "udp",
};
format!("-p {} --dport {} -j DROP", protocol, self.port.to_string())
}
fn chain(&self) -> &str {
match self.direction {
Direction::Inbound => NETINJECT_INPUT_CHAIN,
Direction::Outbound => NETINJECT_OUTPUT_CHAIN,
}
}
}
/// Defines an API for creating and deleting iptables rules for dropping packets.
pub struct Netinject {
ipt: IPTables,
}
impl Netinject {
/// Initializes a Netinject for either IPv4 or IPv6 packets. Creating a new Netinject will
/// mutate the systems iptables by adding chains and rules to the filter table.
pub fn new(is_ipv6: bool) -> NetinjectResult<Netinject> {
let ipt = iptables::new(is_ipv6).map_err(ipt_to_netinject_err)?;
// Create our custom input chain.
new_chain(&ipt, FILTER_TABLE, NETINJECT_INPUT_CHAIN).map_err(ipt_to_netinject_err)?;
// Hook our custom input chain into the system's input chain so that all inbound packets
// pass by our custom input chain.
append_unique(
&ipt,
FILTER_TABLE,
FILTER_INPUT_CHAIN,
&format!("-j {}", NETINJECT_INPUT_CHAIN),
)
.map_err(ipt_to_netinject_err)?;
// Create our custom output chain.
new_chain(&ipt, FILTER_TABLE, NETINJECT_OUTPUT_CHAIN).map_err(ipt_to_netinject_err)?;
// Hook our custom output chain into the system's output chain so that all outbound packets
// pass by our custom output chain.
append_unique(
&ipt,
FILTER_TABLE,
FILTER_OUTPUT_CHAIN,
&format!("-j {}", NETINJECT_OUTPUT_CHAIN),
)
.map_err(ipt_to_netinject_err)?;
Ok(Netinject { ipt: ipt })
}
/// Creates an iptables rule which drops all packets matching the provided identifier.
pub fn create(&self, ident: Ident) -> IPTResult<()> {
self.ipt
.append_unique(FILTER_TABLE, ident.chain(), &ident.rule())
}
/// Deletes a previously created iptables rule matching the provided identifier.
pub fn delete(&self, ident: Ident) -> IPTResult<()> {
self.ipt.delete(FILTER_TABLE, ident.chain(), &ident.rule())
}
/// Deletes all previously created iptables rules.
pub fn delete_all(&self) -> IPTResult<()> {
self.ipt.flush_chain(FILTER_TABLE, NETINJECT_INPUT_CHAIN)?;
self.ipt.flush_chain(FILTER_TABLE, NETINJECT_OUTPUT_CHAIN)
}
/// Removes all chains and rules that this program has created, leaving the system how it was
/// to begin with.
pub fn cleanup(&self) -> IPTResult<()> {
delete(
&self.ipt,
FILTER_TABLE,
FILTER_INPUT_CHAIN,
&format!("-j {}", NETINJECT_INPUT_CHAIN),
)?;
delete_chain(&self.ipt, FILTER_TABLE, NETINJECT_INPUT_CHAIN)?;
delete(
&self.ipt,
FILTER_TABLE,
FILTER_OUTPUT_CHAIN,
&format!("-j {}", NETINJECT_OUTPUT_CHAIN),
)?;
delete_chain(&self.ipt, FILTER_TABLE, NETINJECT_OUTPUT_CHAIN)
}
}
#[cfg(test)]
mod tests {
use super::*;
const IPV4: bool = false;
#[test]
fn test_init_and_cleanup() {
let ipt = iptables::new(IPV4).unwrap();
// Ensure test environment didn't leak from last test run.
assert_exists(&ipt, false);
let n1 = Netinject::new(IPV4).unwrap();
assert_exists(&ipt, true);
// Init a second time to make sure it doesn't error.
let n2 = Netinject::new(IPV4).unwrap();
assert_exists(&ipt, true);
n1.cleanup().unwrap();
assert_exists(&ipt, false);
// Cleanup a second time to make sure it doesn't error.
n2.cleanup().unwrap();
assert_exists(&ipt, false);
}
#[test]
fn test_create_and_delete() {
let ipt = iptables::new(IPV4).unwrap();
// Ensure test environment didn't leak from last test run.
assert_exists(&ipt, false);
let n = Netinject::new(IPV4).unwrap();
let ident1 = Ident {
protocol: Protocol::TCP,
port: 5555,
direction: Direction::Inbound,
};
let ident2 = Ident {
protocol: Protocol::TCP,
port: 5555,
direction: Direction::Outbound,
};
let ident1_rule = ident1.rule();
let ident2_rule = ident2.rule();
n.create(ident1).unwrap();
n.create(ident2).unwrap();
assert_eq!(
ipt.exists(FILTER_TABLE, NETINJECT_INPUT_CHAIN, &ident1_rule)
.unwrap(),
true
);
assert_eq!(
ipt.exists(FILTER_TABLE, NETINJECT_OUTPUT_CHAIN, &ident2_rule)
.unwrap(),
true
);
n.delete(ident1).unwrap();
n.delete(ident2).unwrap();
assert_eq!(
ipt.exists(FILTER_TABLE, NETINJECT_INPUT_CHAIN, &ident1_rule)
.unwrap(),
false
);
assert_eq!(
ipt.exists(FILTER_TABLE, NETINJECT_OUTPUT_CHAIN, &ident2_rule)
.unwrap(),
false
);
n.cleanup().unwrap();
assert_exists(&ipt, false);
}
#[test]
fn test_create_and_delete_all() {
let ipt = iptables::new(IPV4).unwrap();
// Ensure test environment didn't leak from last test run.
assert_exists(&ipt, false);
let n = Netinject::new(IPV4).unwrap();
let ident1 = Ident {
protocol: Protocol::TCP,
port: 5555,
direction: Direction::Inbound,
};
let ident2 = Ident {
protocol: Protocol::TCP,
port: 5555,
direction: Direction::Outbound,
};
let ident1_rule = ident1.rule();
let ident2_rule = ident2.rule();
n.create(ident1).unwrap();
n.create(ident2).unwrap();
assert_eq!(
ipt.exists(FILTER_TABLE, NETINJECT_INPUT_CHAIN, &ident1_rule)
.unwrap(),
true
);
assert_eq!(
ipt.exists(FILTER_TABLE, NETINJECT_OUTPUT_CHAIN, &ident2_rule)
.unwrap(),
true
);
n.delete_all().unwrap();
assert_eq!(
ipt.exists(FILTER_TABLE, NETINJECT_INPUT_CHAIN, &ident1_rule)
.unwrap(),
false
);
assert_eq!(
ipt.exists(FILTER_TABLE, NETINJECT_OUTPUT_CHAIN, &ident2_rule)
.unwrap(),
false
);
n.cleanup().unwrap();
assert_exists(&ipt, false);
}
fn assert_exists(ipt: &IPTables, exists: bool) {
assert_eq!(
ipt.exists(
FILTER_TABLE,
FILTER_INPUT_CHAIN,
&format!("-j {}", NETINJECT_INPUT_CHAIN)
)
.unwrap(),
exists
);
assert_eq!(
ipt.chain_exists(FILTER_TABLE, NETINJECT_INPUT_CHAIN)
.unwrap(),
exists
);
assert_eq!(
ipt.exists(
FILTER_TABLE,
FILTER_OUTPUT_CHAIN,
&format!("-j {}", NETINJECT_OUTPUT_CHAIN)
)
.unwrap(),
exists
);
assert_eq!(
ipt.chain_exists(FILTER_TABLE, NETINJECT_OUTPUT_CHAIN)
.unwrap(),
exists
);
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Media_AppBroadcasting")]
pub mod AppBroadcasting;
#[cfg(feature = "Media_AppRecording")]
pub mod AppRecording;
#[cfg(feature = "Media_Audio")]
pub mod Audio;
#[cfg(feature = "Media_Capture")]
pub mod Capture;
#[cfg(feature = "Media_Casting")]
pub mod Casting;
#[cfg(feature = "Media_ClosedCaptioning")]
pub mod ClosedCaptioning;
#[cfg(feature = "Media_ContentRestrictions")]
pub mod ContentRestrictions;
#[cfg(feature = "Media_Control")]
pub mod Control;
#[cfg(feature = "Media_Core")]
pub mod Core;
#[cfg(feature = "Media_Devices")]
pub mod Devices;
#[cfg(feature = "Media_DialProtocol")]
pub mod DialProtocol;
#[cfg(feature = "Media_Editing")]
pub mod Editing;
#[cfg(feature = "Media_Effects")]
pub mod Effects;
#[cfg(feature = "Media_FaceAnalysis")]
pub mod FaceAnalysis;
#[cfg(feature = "Media_Import")]
pub mod Import;
#[cfg(feature = "Media_MediaProperties")]
pub mod MediaProperties;
#[cfg(feature = "Media_Miracast")]
pub mod Miracast;
#[cfg(feature = "Media_Ocr")]
pub mod Ocr;
#[cfg(feature = "Media_PlayTo")]
pub mod PlayTo;
#[cfg(feature = "Media_Playback")]
pub mod Playback;
#[cfg(feature = "Media_Playlists")]
pub mod Playlists;
#[cfg(feature = "Media_Protection")]
pub mod Protection;
#[cfg(feature = "Media_Render")]
pub mod Render;
#[cfg(feature = "Media_SpeechRecognition")]
pub mod SpeechRecognition;
#[cfg(feature = "Media_SpeechSynthesis")]
pub mod SpeechSynthesis;
#[cfg(feature = "Media_Streaming")]
pub mod Streaming;
#[cfg(feature = "Media_Transcoding")]
pub mod Transcoding;
#[link(name = "windows")]
extern "system" {}
pub type AudioBuffer = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AudioBufferAccessMode(pub i32);
impl AudioBufferAccessMode {
pub const Read: Self = Self(0i32);
pub const ReadWrite: Self = Self(1i32);
pub const Write: Self = Self(2i32);
}
impl ::core::marker::Copy for AudioBufferAccessMode {}
impl ::core::clone::Clone for AudioBufferAccessMode {
fn clone(&self) -> Self {
*self
}
}
pub type AudioFrame = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AudioProcessing(pub i32);
impl AudioProcessing {
pub const Default: Self = Self(0i32);
pub const Raw: Self = Self(1i32);
}
impl ::core::marker::Copy for AudioProcessing {}
impl ::core::clone::Clone for AudioProcessing {
fn clone(&self) -> Self {
*self
}
}
pub type AutoRepeatModeChangeRequestedEventArgs = *mut ::core::ffi::c_void;
pub type IMediaExtension = *mut ::core::ffi::c_void;
pub type IMediaFrame = *mut ::core::ffi::c_void;
pub type IMediaMarker = *mut ::core::ffi::c_void;
pub type IMediaMarkers = *mut ::core::ffi::c_void;
pub type ImageDisplayProperties = *mut ::core::ffi::c_void;
pub type MediaExtensionManager = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct MediaPlaybackAutoRepeatMode(pub i32);
impl MediaPlaybackAutoRepeatMode {
pub const None: Self = Self(0i32);
pub const Track: Self = Self(1i32);
pub const List: Self = Self(2i32);
}
impl ::core::marker::Copy for MediaPlaybackAutoRepeatMode {}
impl ::core::clone::Clone for MediaPlaybackAutoRepeatMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct MediaPlaybackStatus(pub i32);
impl MediaPlaybackStatus {
pub const Closed: Self = Self(0i32);
pub const Changing: Self = Self(1i32);
pub const Stopped: Self = Self(2i32);
pub const Playing: Self = Self(3i32);
pub const Paused: Self = Self(4i32);
}
impl ::core::marker::Copy for MediaPlaybackStatus {}
impl ::core::clone::Clone for MediaPlaybackStatus {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct MediaPlaybackType(pub i32);
impl MediaPlaybackType {
pub const Unknown: Self = Self(0i32);
pub const Music: Self = Self(1i32);
pub const Video: Self = Self(2i32);
pub const Image: Self = Self(3i32);
}
impl ::core::marker::Copy for MediaPlaybackType {}
impl ::core::clone::Clone for MediaPlaybackType {
fn clone(&self) -> Self {
*self
}
}
pub type MediaProcessingTriggerDetails = *mut ::core::ffi::c_void;
#[repr(C)]
#[cfg(feature = "Foundation")]
pub struct MediaTimeRange {
pub Start: super::Foundation::TimeSpan,
pub End: super::Foundation::TimeSpan,
}
#[cfg(feature = "Foundation")]
impl ::core::marker::Copy for MediaTimeRange {}
#[cfg(feature = "Foundation")]
impl ::core::clone::Clone for MediaTimeRange {
fn clone(&self) -> Self {
*self
}
}
pub type MediaTimelineController = *mut ::core::ffi::c_void;
pub type MediaTimelineControllerFailedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct MediaTimelineControllerState(pub i32);
impl MediaTimelineControllerState {
pub const Paused: Self = Self(0i32);
pub const Running: Self = Self(1i32);
pub const Stalled: Self = Self(2i32);
pub const Error: Self = Self(3i32);
}
impl ::core::marker::Copy for MediaTimelineControllerState {}
impl ::core::clone::Clone for MediaTimelineControllerState {
fn clone(&self) -> Self {
*self
}
}
pub type MusicDisplayProperties = *mut ::core::ffi::c_void;
pub type PlaybackPositionChangeRequestedEventArgs = *mut ::core::ffi::c_void;
pub type PlaybackRateChangeRequestedEventArgs = *mut ::core::ffi::c_void;
pub type ShuffleEnabledChangeRequestedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SoundLevel(pub i32);
impl SoundLevel {
pub const Muted: Self = Self(0i32);
pub const Low: Self = Self(1i32);
pub const Full: Self = Self(2i32);
}
impl ::core::marker::Copy for SoundLevel {}
impl ::core::clone::Clone for SoundLevel {
fn clone(&self) -> Self {
*self
}
}
pub type SystemMediaTransportControls = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SystemMediaTransportControlsButton(pub i32);
impl SystemMediaTransportControlsButton {
pub const Play: Self = Self(0i32);
pub const Pause: Self = Self(1i32);
pub const Stop: Self = Self(2i32);
pub const Record: Self = Self(3i32);
pub const FastForward: Self = Self(4i32);
pub const Rewind: Self = Self(5i32);
pub const Next: Self = Self(6i32);
pub const Previous: Self = Self(7i32);
pub const ChannelUp: Self = Self(8i32);
pub const ChannelDown: Self = Self(9i32);
}
impl ::core::marker::Copy for SystemMediaTransportControlsButton {}
impl ::core::clone::Clone for SystemMediaTransportControlsButton {
fn clone(&self) -> Self {
*self
}
}
pub type SystemMediaTransportControlsButtonPressedEventArgs = *mut ::core::ffi::c_void;
pub type SystemMediaTransportControlsDisplayUpdater = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SystemMediaTransportControlsProperty(pub i32);
impl SystemMediaTransportControlsProperty {
pub const SoundLevel: Self = Self(0i32);
}
impl ::core::marker::Copy for SystemMediaTransportControlsProperty {}
impl ::core::clone::Clone for SystemMediaTransportControlsProperty {
fn clone(&self) -> Self {
*self
}
}
pub type SystemMediaTransportControlsPropertyChangedEventArgs = *mut ::core::ffi::c_void;
pub type SystemMediaTransportControlsTimelineProperties = *mut ::core::ffi::c_void;
pub type VideoDisplayProperties = *mut ::core::ffi::c_void;
pub type VideoFrame = *mut ::core::ffi::c_void;
|
use std::{collections::HashMap, fmt};
use crate::*;
/// Represents Player of given team
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#Environment>
#[derive(Clone, fmt::Debug, Default)]
pub struct Player {
/// Researched points of [`Player`]
pub research_points: ResearchPointAmount,
/// [`Player`]'s team
pub team: TeamId,
/// List of [`Unit`] owned by current [`Player`]
pub units: Vec<Unit>,
/// Map of [`City`] by [`City`]'s id
pub cities: HashMap<String, City>,
/// Count of city tiles
pub city_tile_count: u32,
}
impl Player {
/// Creates new [`Player`]
///
/// # Parameters
///
/// - `team` - [`Player`]'s team id
///
/// # Returns
///
/// Created [`Player`] with zero research points and none cities and units
///
/// # See also:
///
/// Check <https://www.lux-ai.org/specs-2021#Environment>
pub fn new(team: TeamId) -> Self {
Self {
team,
..Self::default()
}
}
/// Check if [`Player`] has enough research points to collect resources with
/// [`ResourceType`]
///
/// # Parameters
///
/// - `self` - Self reference
/// - `resource_type` - resource type to check
///
/// # Returns
///
/// `bool` value
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#Resources>
pub fn is_researched(&self, resource_type: ResourceType) -> bool {
self.research_points >= resource_type.required_research_points()
}
/// Clear all units and cities for [`Player`]
///
/// # Parameters
///
/// - `self` - mutable Self reference
///
/// # Returns
///
/// Nothing
pub fn reset_state(&mut self) {
self.units = vec![];
self.cities = Default::default();
self.city_tile_count = 0;
}
/// Whether or not [`Player`] has enough research points to mine coal
///
/// # Parameters
///
/// - `self` - Self reference
///
/// # Returns
///
/// `bool` value
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#Resources>
pub fn researched_coal(&self) -> bool { self.is_researched(ResourceType::Coal) }
/// Whether or not [`Player`] has enough research points to mine uranium
///
/// # Parameters
///
/// - `self` - Self reference
///
/// # Returns
///
/// `bool` value
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#Resources>
pub fn researched_uranium(&self) -> bool { self.is_researched(ResourceType::Uranium) }
}
|
pub mod rasterizationorderamd;
pub mod prelude;
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct IMdmAllowPolicyStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMdmAllowPolicyStatics {
type Vtable = IMdmAllowPolicyStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc39709e7_741c_41f2_a4b6_314c31502586);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMdmAllowPolicyStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMdmPolicyStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMdmPolicyStatics2 {
type Vtable = IMdmPolicyStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc99c7526_03d4_49f9_a993_43efccd265c4);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMdmPolicyStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut MessagingSyncPolicy) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IWorkplaceSettingsStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IWorkplaceSettingsStatics {
type Vtable = IWorkplaceSettingsStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe4676ffd_2d92_4c08_bad4_f6590b54a6d3);
}
#[repr(C)]
#[doc(hidden)]
pub struct IWorkplaceSettingsStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
pub struct MdmPolicy {}
impl MdmPolicy {
pub fn IsBrowserAllowed() -> ::windows::core::Result<bool> {
Self::IMdmAllowPolicyStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IsCameraAllowed() -> ::windows::core::Result<bool> {
Self::IMdmAllowPolicyStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IsMicrosoftAccountAllowed() -> ::windows::core::Result<bool> {
Self::IMdmAllowPolicyStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IsStoreAllowed() -> ::windows::core::Result<bool> {
Self::IMdmAllowPolicyStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn GetMessagingSyncPolicy() -> ::windows::core::Result<MessagingSyncPolicy> {
Self::IMdmPolicyStatics2(|this| unsafe {
let mut result__: MessagingSyncPolicy = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MessagingSyncPolicy>(result__)
})
}
pub fn IMdmAllowPolicyStatics<R, F: FnOnce(&IMdmAllowPolicyStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MdmPolicy, IMdmAllowPolicyStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IMdmPolicyStatics2<R, F: FnOnce(&IMdmPolicyStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MdmPolicy, IMdmPolicyStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for MdmPolicy {
const NAME: &'static str = "Windows.Management.Workplace.MdmPolicy";
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct MessagingSyncPolicy(pub i32);
impl MessagingSyncPolicy {
pub const Disallowed: MessagingSyncPolicy = MessagingSyncPolicy(0i32);
pub const Allowed: MessagingSyncPolicy = MessagingSyncPolicy(1i32);
pub const Required: MessagingSyncPolicy = MessagingSyncPolicy(2i32);
}
impl ::core::convert::From<i32> for MessagingSyncPolicy {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for MessagingSyncPolicy {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for MessagingSyncPolicy {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Management.Workplace.MessagingSyncPolicy;i4)");
}
impl ::windows::core::DefaultType for MessagingSyncPolicy {
type DefaultType = Self;
}
pub struct WorkplaceSettings {}
impl WorkplaceSettings {
pub fn IsMicrosoftAccountOptional() -> ::windows::core::Result<bool> {
Self::IWorkplaceSettingsStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IWorkplaceSettingsStatics<R, F: FnOnce(&IWorkplaceSettingsStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<WorkplaceSettings, IWorkplaceSettingsStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for WorkplaceSettings {
const NAME: &'static str = "Windows.Management.Workplace.WorkplaceSettings";
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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::u64;
use super::ipc::*;
use super::time::*;
// shmat(2) flags. Source: include/uapi/linux/shm.h
pub const SHM_RDONLY: u16 = 0o010000; // Read-only access.
pub const SHM_RND: u16 = 0o020000; // Round attach address to SHMLBA boundary.
pub const SHM_REMAP: u16 = 0o040000; // Take-over region on attach.
pub const SHM_EXEC: u16 = 0o0100000; // Execution access.
// IPCPerm.Mode upper byte flags. Source: include/linux/shm.h
pub const SHM_DEST: u16 = 0o01000; // Segment will be destroyed on last detach.
pub const SHM_LOCKED: u16 = 0o02000; // Segment will not be swapped.
pub const SHM_HUGETLB: u16 = 0o04000; // Segment will use huge TLB pages.
pub const SHM_NORESERVE: u16 = 0o010000; // Don't check for reservations.
// Additional Linux-only flags for shmctl(2). Source: include/uapi/linux/shm.h
pub const SHM_LOCK: u16 = 11;
pub const SHM_UNLOCK: u16 = 12;
pub const SHM_STAT: u16 = 13;
pub const SHM_INFO: u16 = 14;
// SHM defaults as specified by linux. Source: include/uapi/linux/shm.h
pub const SHMMIN: u64 = 1;
pub const SHMMNI: u64 = 4096;
pub const SHMMAX: u64 = u64::MAX - 1 << 24;
pub const SHMALL: u64 = u64::MAX - 1 << 24;
pub const SHMSEG: u64 = 4096;
// ShmidDS is equivalent to struct shmid64_ds. Source:
// include/uapi/asm-generic/shmbuf.h
#[repr(C)]
#[derive(Clone, Debug, Default)]
pub struct ShmidDS {
pub ShmPerm: IPCPerm,
pub ShmSegsz: u64,
pub ShmAtime: TimeT,
pub ShmDtime: TimeT,
pub ShmCtime: TimeT,
pub ShmCpid: i32,
pub ShmLpid: i32,
pub ShmNattach: i64,
pub Unused4: i64,
pub Unused5: i64,
}
// ShmParams is equivalent to struct shminfo. Source: include/uapi/linux/shm.h
#[repr(C)]
#[derive(Clone, Debug, Default)]
pub struct ShmParams {
pub ShmMax: u64,
pub ShmMin: u64,
pub ShmMni: u64,
pub ShmSeg: u64,
pub ShmAll: u64,
}
// ShmInfo is equivalent to struct shm_info. Source: include/uapi/linux/shm.h
#[repr(C)]
#[derive(Clone, Debug, Default)]
pub struct ShmInfo {
pub UsedIDs: i32,
// Number of currently existing segments.
//pad : i32,
pub ShmTot: u64,
// Total number of shared memory pages.
pub ShmRss: u64,
// Number of resident shared memory pages.
pub ShmSwp: u64,
// Number of swapped shared memory pages.
pub SwapAttempts: u64,
// Unused since Linux 2.4.
pub SwapSuccesses: u64,
// Unused since Linux 2.4.
}
|
#[path = "with_function/with_arity_zero.rs"]
mod with_arity_zero;
test_stdout!(without_arity_zero_returns_pid_to_parent_and_child_process_exits_badarity_which_exits_linked_parent, "{parent, badarity}\n");
|
use proptest::strategy::Just;
use crate::erlang::binary_to_list_1::result;
use crate::test::strategy;
#[test]
fn without_binary_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_not_binary(arc_process.clone()),
)
},
|(arc_process, binary)| {
prop_assert_badarg!(result(&arc_process, binary), format!("binary ({})", binary));
Ok(())
},
);
}
// `with_binary_returns_list_of_bytes` in integration tests
|
use super::{Server, TasksLayer};
use std::{
net::{SocketAddr, ToSocketAddrs},
path::PathBuf,
time::Duration,
};
/// Builder for configuring [`TasksLayer`]s.
#[derive(Clone, Debug)]
pub struct Builder {
/// The maximum capacity for the channel of events from the subscriber to
/// the aggregator task.
pub(super) event_buffer_capacity: usize,
/// The maximum number of updates to buffer per-client before the client is
/// dropped.
pub(super) client_buffer_capacity: usize,
/// The interval between publishing updates to clients.
pub(crate) publish_interval: Duration,
/// How long to retain data for completed events.
pub(crate) retention: Duration,
/// The address on which to serve the RPC server.
pub(super) server_addr: SocketAddr,
/// If and where to save a recording of the events.
pub(super) recording_path: Option<PathBuf>,
}
impl Default for Builder {
fn default() -> Self {
Self {
event_buffer_capacity: TasksLayer::DEFAULT_EVENT_BUFFER_CAPACITY,
client_buffer_capacity: TasksLayer::DEFAULT_CLIENT_BUFFER_CAPACITY,
publish_interval: TasksLayer::DEFAULT_PUBLISH_INTERVAL,
retention: TasksLayer::DEFAULT_RETENTION,
server_addr: SocketAddr::new(Server::DEFAULT_IP, Server::DEFAULT_PORT),
recording_path: None,
}
}
}
impl Builder {
/// Sets the maximum capacity for the channel of events sent from subscriber
/// layers to the aggregator task.
///
/// When this channel is at capacity, additional events will be dropped.
///
/// By default, this is [`TasksLayer::DEFAULT_EVENT_BUFFER_CAPACITY`].
pub fn event_buffer_capacity(self, event_buffer_capacity: usize) -> Self {
Self {
event_buffer_capacity,
..self
}
}
/// Sets the maximum capacity of updates to buffer for each subscribed
/// client, if that client is not reading from the RPC stream.
///
/// When this channel is at capacity, the client may be disconnected.
///
/// By default, this is [`TasksLayer::DEFAULT_CLIENT_BUFFER_CAPACITY`].
pub fn client_buffer_capacity(self, client_buffer_capacity: usize) -> Self {
Self {
client_buffer_capacity,
..self
}
}
/// Sets how frequently updates are published to clients.
///
/// A shorter duration will allow clients to update more frequently, but may
/// result in the program spending more time preparing task data updates.
///
/// By default, this is [`TasksLayer::DEFAULT_PUBLISH_INTERVAL`].
pub fn publish_interval(self, publish_interval: Duration) -> Self {
Self {
publish_interval,
..self
}
}
/// Sets how long data is retained for completed tasks.
///
/// A longer duration will allow more historical data to be replayed by
/// clients, but will result in increased memory usage. A shorter duration
/// will reduce memory usage, but less historical data from completed tasks
/// will be retained.
///
/// By default, this is [`TasksLayer::DEFAULT_RETENTION`].
pub fn retention(self, retention: Duration) -> Self {
Self { retention, ..self }
}
/// Sets the socket address on which to serve the RPC server.
///
/// By default, the server is bound on the IP address [`Server::DEFAULT_IP`]
/// on port [`Server::DEFAULT_PORT`].
pub fn server_addr(self, server_addr: impl Into<SocketAddr>) -> Self {
Self {
server_addr: server_addr.into(),
..self
}
}
/// Sets the path to record the events to the file system.
pub fn recording_path(self, path: impl Into<PathBuf>) -> Self {
Self {
recording_path: Some(path.into()),
..self
}
}
/// Completes the builder, returning a [`TasksLayer`] and [`Server`] task.
pub fn build(self) -> (TasksLayer, Server) {
TasksLayer::build(self)
}
/// Configures this builder from a standard set of environment variables:
///
/// | **Environment Variable** | **Purpose** | **Default Value** |
/// |----------------------------------|--------------------------------------------------------------|-------------------|
/// | `TOKIO_CONSOLE_RETENTION` | The duration of seconds to accumulate completed tracing data | 3600s (1h) |
/// | `TOKIO_CONSOLE_BIND` | a HOST:PORT description, such as `localhost:1234` | `127.0.0.1:6669` |
/// | `TOKIO_CONSOLE_PUBLISH_INTERVAL` | The duration to wait between sending updates to the console | 1000ms (1s) |
/// | `TOKIO_CONSOLE_RECORD_PATH` | The file path to save a recording | None |
pub fn with_default_env(mut self) -> Self {
if let Some(retention) = duration_from_env("TOKIO_CONSOLE_RETENTION") {
self.retention = retention;
}
if let Ok(bind) = std::env::var("TOKIO_CONSOLE_BIND") {
self.server_addr = bind
.to_socket_addrs()
.expect("TOKIO_CONSOLE_BIND must be formatted as HOST:PORT, such as localhost:4321")
.next()
.expect("tokio console could not resolve TOKIO_CONSOLE_BIND");
}
if let Some(interval) = duration_from_env("TOKIO_CONSOLE_PUBLISH_INTERVAL") {
self.publish_interval = interval;
}
if let Ok(path) = std::env::var("TOKIO_CONSOLE_RECORD_PATH") {
self.recording_path = Some(path.into());
}
self
}
}
fn duration_from_env(var_name: &str) -> Option<Duration> {
let var = std::env::var(var_name).ok()?;
match parse_duration(&var) {
Ok(dur) => Some(dur),
Err(e) => panic!(
"failed to parse a duration from `{}={:?}`: {}",
var_name, var, e
),
}
}
fn parse_duration(s: &str) -> Result<Duration, Box<dyn std::error::Error>> {
let s = s.trim();
if let Some(s) = s
.strip_suffix('h')
.or_else(|| s.strip_suffix("hour"))
.or_else(|| s.strip_suffix("hours"))
{
let s = s.trim();
return Ok(s
.parse::<u64>()
.map(|hours| Duration::from_secs(hours * 60 * 60))
.or_else(|_| {
s.parse::<f64>()
.map(|hours| Duration::from_secs_f64(hours * 60.0 * 60.0))
})?);
}
if let Some(s) = s
.strip_suffix('m')
.or_else(|| s.strip_suffix("min"))
.or_else(|| s.strip_suffix("mins"))
.or_else(|| s.strip_suffix("minute"))
.or_else(|| s.strip_suffix("minutes"))
{
let s = s.trim();
return Ok(s
.parse::<u64>()
.map(|mins| Duration::from_secs(mins * 60))
.or_else(|_| {
s.parse::<f64>()
.map(|mins| Duration::from_secs_f64(mins * 60.0))
})?);
}
if let Some(s) = s.strip_suffix("ms") {
return Ok(Duration::from_millis(s.trim().parse()?));
}
if let Some(s) = s.strip_suffix("us") {
return Ok(Duration::from_micros(s.trim().parse()?));
}
// Order matters here -- we have to try `ns` for nanoseconds after we try
// minutes, because `mins` ends in `ns`.
if let Some(s) = s.strip_suffix("ns") {
return Ok(Duration::from_nanos(s.trim().parse()?));
}
if let Some(s) = s
.strip_suffix("sec")
.or_else(|| s.strip_suffix("secs"))
.or_else(|| s.strip_suffix("seconds"))
// Order matters here -- we have to try `s` for seconds _last_, because
// every other plural and subsecond unit also ends in `s`...
.or_else(|| s.strip_suffix('s'))
{
let s = s.trim();
return Ok(s
.parse::<u64>()
.map(Duration::from_secs)
.or_else(|_| s.parse::<f64>().map(Duration::from_secs_f64))?);
}
Err("expected an integer followed by one of {`ns`, `us`, `ms`, `s`, `sec`, `m`, `min`, `h`, `hours`}".into())
}
#[cfg(test)]
mod tests {
use super::*;
fn test_parse_durations(expected: Duration, inputs: &[&str]) {
for input in inputs {
println!("trying: parse_duration({:?}) -> {:?}", input, expected);
match parse_duration(input) {
Err(e) => panic!(
"parse_duration({:?}) -> {} (expected {:?})",
input, e, expected
),
Ok(dur) => assert_eq!(
dur, expected,
"parse_duration({:?}) -> {:?} (expected {:?})",
input, dur, expected
),
}
}
}
#[test]
fn parse_hours() {
test_parse_durations(
Duration::from_secs(3 * 60 * 60),
&["3h", "3 h", " 3 h", "3 hours", "3hours"],
)
}
#[test]
fn parse_mins() {
test_parse_durations(
Duration::from_secs(10 * 60),
&[
"10m",
"10 m",
"10 m",
"10 minutes",
"10minutes",
" 10 minutes",
"10 min",
" 10 min",
"10min",
],
)
}
#[test]
fn parse_secs() {
test_parse_durations(
Duration::from_secs(10),
&[
"10s",
"10 s",
"10 s",
"10 seconds",
"10seconds",
" 10 seconds",
"10 sec",
" 10 sec",
"10sec",
],
)
}
#[test]
fn parse_fractional_hours() {
test_parse_durations(
Duration::from_millis(1500 * 60 * 60),
&["1.5h", "1.5 h", " 1.5 h", "1.5 hours", "1.5hours"],
)
}
#[test]
fn parse_fractional_mins() {
test_parse_durations(
Duration::from_millis(1500 * 60),
&[
"1.5m",
"1.5 m",
"1.5 m",
"1.5 minutes",
"1.5 minutes",
" 1.5 minutes",
"1.5 min",
" 1.5 min",
"1.5min",
],
)
}
#[test]
fn parse_fractional_secs() {
test_parse_durations(
Duration::from_millis(1500),
&[
"1.5s",
"1.5 s",
"1.5 s",
"1.5 seconds",
"1.5 seconds",
" 1.5 seconds",
"1.5 sec",
" 1.5 sec",
"1.5sec",
],
)
}
}
|
#![doc = "Peripheral access API for FOMU microcontrollers (generated using svd2rust v0.16.1)\n\nYou can find an overview of the API [here].\n\n[here]: https://docs.rs/svd2rust/0.16.1/svd2rust/#peripheral-api"]
#![deny(missing_docs)]
#![deny(warnings)]
#![allow(non_camel_case_types)]
#![no_std]
extern crate bare_metal;
extern crate riscv;
#[cfg(feature = "rt")]
extern crate fomu_rt as riscv_rt;
extern crate vcell;
use core::marker::PhantomData;
use core::ops::Deref;
#[doc(hidden)]
pub mod interrupt;
pub use self::interrupt::Interrupt;
#[allow(unused_imports)]
use generic::*;
#[doc = r"Common register and bit access and modify traits"]
pub mod generic;
#[doc = "CTRL"]
pub struct CTRL {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for CTRL {}
impl CTRL {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const ctrl::RegisterBlock {
0xe000_0000 as *const _
}
}
impl Deref for CTRL {
type Target = ctrl::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*CTRL::ptr() }
}
}
#[doc = "CTRL"]
pub mod ctrl;
#[doc = "LXSPI"]
pub struct LXSPI {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for LXSPI {}
impl LXSPI {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const lxspi::RegisterBlock {
0xe000_7800 as *const _
}
}
impl Deref for LXSPI {
type Target = lxspi::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*LXSPI::ptr() }
}
}
#[doc = "LXSPI"]
pub mod lxspi;
#[doc = "MESSIBLE"]
pub struct MESSIBLE {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for MESSIBLE {}
impl MESSIBLE {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const messible::RegisterBlock {
0xe000_8000 as *const _
}
}
impl Deref for MESSIBLE {
type Target = messible::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*MESSIBLE::ptr() }
}
}
#[doc = "MESSIBLE"]
pub mod messible;
#[doc = "REBOOT"]
pub struct REBOOT {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for REBOOT {}
impl REBOOT {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const reboot::RegisterBlock {
0xe000_6000 as *const _
}
}
impl Deref for REBOOT {
type Target = reboot::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*REBOOT::ptr() }
}
}
#[doc = "REBOOT"]
pub mod reboot;
#[doc = "RGB"]
pub struct RGB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for RGB {}
impl RGB {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const rgb::RegisterBlock {
0xe000_6800 as *const _
}
}
impl Deref for RGB {
type Target = rgb::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*RGB::ptr() }
}
}
#[doc = "RGB"]
pub mod rgb;
#[doc = "TIMER0"]
pub struct TIMER0 {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TIMER0 {}
impl TIMER0 {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const timer0::RegisterBlock {
0xe000_2800 as *const _
}
}
impl Deref for TIMER0 {
type Target = timer0::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*TIMER0::ptr() }
}
}
#[doc = "TIMER0"]
pub mod timer0;
#[doc = "TOUCH"]
pub struct TOUCH {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for TOUCH {}
impl TOUCH {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const touch::RegisterBlock {
0xe000_5800 as *const _
}
}
impl Deref for TOUCH {
type Target = touch::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*TOUCH::ptr() }
}
}
#[doc = "TOUCH"]
pub mod touch;
#[doc = "USB"]
pub struct USB {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for USB {}
impl USB {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const usb::RegisterBlock {
0xe000_4800 as *const _
}
}
impl Deref for USB {
type Target = usb::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*USB::ptr() }
}
}
#[doc = "USB"]
pub mod usb;
#[doc = "VERSION"]
pub struct VERSION {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for VERSION {}
impl VERSION {
#[doc = r"Returns a pointer to the register block"]
#[inline(always)]
pub const fn ptr() -> *const version::RegisterBlock {
0xe000_7000 as *const _
}
}
impl Deref for VERSION {
type Target = version::RegisterBlock;
fn deref(&self) -> &Self::Target {
unsafe { &*VERSION::ptr() }
}
}
#[doc = "VERSION"]
pub mod version;
#[no_mangle]
static mut DEVICE_PERIPHERALS: bool = false;
#[doc = r"All the peripherals"]
#[allow(non_snake_case)]
pub struct Peripherals {
#[doc = "CTRL"]
pub CTRL: CTRL,
#[doc = "LXSPI"]
pub LXSPI: LXSPI,
#[doc = "MESSIBLE"]
pub MESSIBLE: MESSIBLE,
#[doc = "REBOOT"]
pub REBOOT: REBOOT,
#[doc = "RGB"]
pub RGB: RGB,
#[doc = "TIMER0"]
pub TIMER0: TIMER0,
#[doc = "TOUCH"]
pub TOUCH: TOUCH,
#[doc = "USB"]
pub USB: USB,
#[doc = "VERSION"]
pub VERSION: VERSION,
}
impl Peripherals {
#[doc = r"Returns all the peripherals *once*"]
#[inline]
pub fn take() -> Option<Self> {
riscv::interrupt::free(|_| {
if unsafe { DEVICE_PERIPHERALS } {
None
} else {
Some(unsafe { Peripherals::steal() })
}
})
}
#[doc = r"Unchecked version of `Peripherals::take`"]
pub unsafe fn steal() -> Self {
DEVICE_PERIPHERALS = true;
Peripherals {
CTRL: CTRL {
_marker: PhantomData,
},
LXSPI: LXSPI {
_marker: PhantomData,
},
MESSIBLE: MESSIBLE {
_marker: PhantomData,
},
REBOOT: REBOOT {
_marker: PhantomData,
},
RGB: RGB {
_marker: PhantomData,
},
TIMER0: TIMER0 {
_marker: PhantomData,
},
TOUCH: TOUCH {
_marker: PhantomData,
},
USB: USB {
_marker: PhantomData,
},
VERSION: VERSION {
_marker: PhantomData,
},
}
}
}
|
// Copyright 2022 Datafuse Labs.
//
// 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.
//! Defines meta-store errors and meta-store application errors.
//!
//! ## Error relations
//!
//! The overall relations between errors defined in meta-store components are:
//!
//! ```text
//!
//! MetaError
//! |
//! +- MetaStorageError
//! |
//! +- MetaClientError
//! | |
//! | +- MetaNetworkError
//! | +- HandshakeError
//! |
//! +- MetaNetworkError
//! |
//! `- MetaApiError
//! |
//! +- ForwardToLeader -.
//! +- CanNotForward |
//! | |
//! +- MetaNetworkError |
//! | |
//! +- MetaDataError ---|-----------.
//! | | |
//! `- RemoteError ---|-----------+
//! | |
//! | |
//! | | MetaOperationError
//! | .---------|----------' |
//! | | | .----------'
//! v v v v
//! ForwardToLeader MetaDataError
//! | |
//! .---------------' '---------.
//! v v
//! MetaDataReadError Raft*Error
//! | |
//! +- MetaStorageError +- MetaStorageError
//! ```
//!
//! ## Bottom level errors:
//!
//! Bottom level errors are derived from non-meta-store layers.
//!
//! - `MetaStorageError`
//! - `MetaNetworkError`
//! - `MetaBytesError`
//!
//! ```text
//! MetaNetworkError
//! |
//! +- Connection errors
//! +- DNS errors
//! `- Payload codec error
//!
//! MetaStorageError
//! |
//! +- Sled errors
//! +- Txn conflict
//! `- Codec error:--.
//! |
//! v
//! MetaBytesError
//! ```
//!
//! ## Application level errors
//!
//! ## `MetaError`
//!
//! `MetaError` defines every error could occur inside a meta-store implementation(an embedded meta-store
//! or a client-server meta-store service).
//! The sub errors are about both a local implementation and a remote meta-store implementation:
//!
//! For a remote meta-store service:
//!
//! - `MetaClientError`: is only returned with remote meta-store service: when creating a client to
//! meta-store service. Since a client will send a handshake request, `MetaClientError` also
//! includes a network sub error: `MetaNetworkError`.
//!
//! - `MetaNetworkError` is only returned with remote meta-store service: when sending a request to
//! a remote meta-store service.
//!
//! - `MetaApiError` is only returned with remote meta-store service: it is all of the errors that
//! could occur when a meta-store service handling a request.
//!
//! For a local meta-store:
//!
//! - `MetaStorageError`: meta-store is implemented directly upon storage layer.
//!
//! ## `MetaApiError`
//!
//! `MetaApiError` is defined for meta-store service RPC API handler:
//! It includes Raft related errors and errors that occurs when forwarding a request between
//! meta-store servers:
//!
//! - Errors informing request forwarding state:: `ForwardToLeader` or `CanNotForward`.
//! - Errors occurs when forwarding a request: `MetaNetworkError`.
//! - Errors occurs when reading/writing: `MetaDataError`. Because a request may be dealt with
//! locally or dealt with remotely, via request forwarding, there are two variants for
//! `MetaDataError`:
//! - `MetaApiError::MetaDataError(MetaDataError)` is returned when a request is dealt with locally.
//! - `MetaApiError::RemoteError(MetaDataError)` is returned when a request is dealt with on a
//! remote noMetaDataError.
//!
//! ## `MetaDataError`
//!
//! It is the error that could occur when dealing with read/write request.
//!
//! In meta-store, data is written through Raft protocol, thus part of its sub errors are Raft
//! related: `RaftWriteError` or `RaftChangeMembershipError`.
//!
//! In meta-store reading data does not depend on Raft protocol, thus read errors is defined as
//! `MetaDataReadError` and is derived directly from MetaStorageError.
//!
//!
//! ## Other errors:
//!
//! - `MetaOperationError` is a intermediate error and a subset error of `MetaApiError` and is
//! defined for a local request handler without forwarding. It is finally converted to `MetaApiError`.
//!
//! - `ForwardRPCError` is another intermediate error to wrap a result of a forwarded request.
pub mod meta_api_errors;
pub mod meta_client_errors;
pub mod meta_errors;
pub mod meta_handshake_errors;
pub mod meta_management_error;
pub mod meta_network_errors;
pub mod meta_raft_errors;
pub mod meta_startup_errors;
pub mod rpc_errors;
|
use front::stdlib::value::{Value, ResultValue, to_value, from_value};
use front::stdlib::function::Function;
use std::io::stderr;
use time::{now, strftime};
/// Print a javascript value to the standard output stream
pub fn log(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let args : Vec<String> = args.iter().map(|x|from_value::<String>(*x).unwrap()).collect();
println!("{}: {}", strftime("%X", &now()), args.connect(" "));
Ok(Value::undefined())
}
/// Print a javascript value to the standard error stream
pub fn error(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let args : Vec<String> = args.iter().map(|x|from_value::<String>(*x).unwrap()).collect();
match writeln!(&mut stderr().unwrap(), "{}: {}", strftime("%X", &now()), args.connect(" ")) {
Ok(_) => Ok(Value::undefined()),
Err(io_error) => Err(to_value(io_error.to_string()))
}
}
/// Create a new `console` object
pub fn _create(global : Value) -> Value {
js!(global, {
"log": Function::make(log, ["object"]),
"error": Function::make(error, ["error"]),
"exception": Function::make(error, ["error"])
})
}
/// Initialise the global object with the `console` object
pub fn init(global:Value) {
js_extend!(global, {
"console": _create(global)
});
}
|
use serde_json::json;
use get_if_addrs::get_if_addrs;
use toml::Value;
use toml::map::Map;
use crate::reporters::Report;
pub fn ip_addrs_reporter(_: &Map<String, Value>) -> Report {
let mut ips = vec![];
for iface in get_if_addrs().unwrap() {
let ip = (iface.name, iface.addr.ip());
ips.push(ip);
}
return Report::new("ip_addrs".to_string(), json!(ips).to_string());
}
|
mod colorblindness;
mod glaucoma;
mod macular_degeneration;
mod nyctalopia;
mod osterberg;
mod receptor_density;
use crate::pipeline::*;
pub fn generate_retina_map(resolution: (u32, u32), params: &ValueMap) -> Box<[u8]> {
let mut maps: Vec<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>> = Vec::new();
// glaucoma
if let Some(Value::Bool(true)) = params.get("glaucoma_onoff") {
let severity = params.get("glaucoma_fov").unwrap().as_f64().unwrap() as u8;
//let glaucoma_scotomasize = params.get("glaucoma_scotomasize"].as_u64().unwrap();
let glaucoma = glaucoma::generate_simple(resolution, severity);
maps.push(glaucoma);
}
// achromatopsia
if let Some(Value::Bool(true)) = params.get("achromatopsia_onoff") {
let severity = params.get("achromatopsia_int").unwrap().as_f64().unwrap() as u64;
let achromatopsia = colorblindness::generate_achromatopsia(resolution, severity);
maps.push(achromatopsia);
}
// nyctalopia
if let Some(Value::Bool(true)) = params.get("nyctalopia_onoff") {
let severity = params.get("nyctalopia_int").unwrap().as_f64().unwrap() as u64;
let nyctalopia = nyctalopia::generate(resolution, severity);
maps.push(nyctalopia);
}
// colorblindness
if let Some(Value::Bool(true)) = params.get("colorblindness_onoff") {
let ctype = params.get("colorblindness_type").unwrap().as_f64().unwrap() as u64;
let severity = params.get("colorblindness_int").unwrap().as_f64().unwrap() as u64;
let colorblindness = colorblindness::generate_colorblindness(resolution, ctype, severity);
maps.push(colorblindness);
}
// macular degeneration
if let Some(Value::Bool(true)) = params.get("maculardegeneration_onoff") {
if let Some(Value::Bool(true)) = params.get("maculardegeneration_veasy") {
// parameters set in easy easy mode
let severity = params
.get("maculardegeneration_inteasy")
.unwrap()
.as_f64()
.unwrap() as u8;
let macular_degeneration = macular_degeneration::generate_simple(resolution, severity);
maps.push(macular_degeneration);
} else if let Some(Value::Bool(true)) = params.get("maculardegeneration_vadvanced") {
// parameters set in advanced mode
let radius = params
.get("maculardegeneration_radius")
.unwrap()
.as_f64()
.unwrap();
let severity = params
.get("maculardegeneration_intadvanced")
.unwrap()
.as_f64()
.unwrap();
// interpret parameters
let radius = radius * (resolution.0 as f64) / 300.0;
let severity = 1.0 - 0.5 * (1.0 - severity / 100.0).powi(2);
let macular_degeneration = macular_degeneration::generate(resolution, radius, severity);
maps.push(macular_degeneration);
}
}
// receptor density
if let Some(Value::Bool(true)) = params.get("receptordensity_onoff") {
let receptor_density = receptor_density::generate(resolution);
maps.push(receptor_density);
}
merge_maps(maps, resolution)
}
fn merge_maps(
maps: Vec<image::ImageBuffer<image::Rgba<u8>, Vec<u8>>>,
resolution: (u32, u32),
) -> Box<[u8]> {
// generate white retina map as starting point
let mut merged = image::ImageBuffer::new(resolution.0, resolution.1);
for (_, _, pixel) in merged.enumerate_pixels_mut() {
*pixel = image::Rgba([255 as u8, 255 as u8, 255 as u8, 255 as u8]);
}
// for each pixel and each channel, take the minimum of all maps at this pixel and channel
for map in maps {
for (x, y, pixel) in merged.enumerate_pixels_mut() {
let new_pixel = map.get_pixel(x, y);
let r = new_pixel[0].min(pixel[0]);
let g = new_pixel[1].min(pixel[1]);
let b = new_pixel[2].min(pixel[2]);
let a = new_pixel[3].min(pixel[3]);
*pixel = image::Rgba([r as u8, g as u8, b as u8, a as u8]);
}
}
merged.into_raw().into_boxed_slice()
}
|
// Standard library
use std::collections::{hash_map, HashMap};
use std::str::FromStr;
use std::sync::{Arc, Mutex};
// This crate
use crate::actions::{Action, ActionAnswer, ActionContext};
use crate::exts::LockIt;
use crate::nlu::{EntityData, EntityDef, IntentData, OrderKind, SlotData};
use crate::signals::collections::Hook;
use crate::skills::{register_skill, SkillLoader};
// Other crates
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use maplit::hashmap;
use rmp_serde::to_vec_named;
use unic_langid::{subtags, LanguageIdentifier};
use vap_common_skill::structures::msg_query_response::QueryDataCapability;
use vap_common_skill::structures::msg_register_intents::NluData;
use vap_common_skill::structures::msg_skill_request::{
ClientData, RequestData, RequestDataKind, RequestSlot,
};
use vap_common_skill::structures::{
msg_notification_response, msg_query_response, AssociativeMap, Language, MsgConnectResponse,
MsgNotificationResponse, MsgQueryResponse, MsgRegisterIntentsResponse, MsgSkillRequest,
};
use vap_skill_register::{
RequestResponse, Response, ResponseType, SkillRegister, SkillRegisterMessage, SkillRegisterOut,
SkillRegisterStream, SYSTEM_SELF_ID,
};
pub struct VapLoader {
out: Arc<Mutex<SkillRegisterOut>>,
stream_reg: Option<(SkillRegisterStream, SkillRegister)>,
langs: Vec<Language>,
// Dicts containing the system capabilities
notifies: HashMap<String, Box<dyn CanBeNotified>>,
queries: HashMap<String, Box<dyn CanBeQueried>>,
}
impl VapLoader {
pub fn new(port: u16, langs: Vec<LanguageIdentifier>) -> Self {
let (reg, stream, out) = SkillRegister::new(port).unwrap();
let langs = langs.into_iter().map(|l| l.into()).collect();
VapLoader {
out: Arc::new(Mutex::new(out)),
stream_reg: Some((stream, reg)),
langs,
notifies: HashMap::new(),
queries: HashMap::new(),
}
}
pub fn register_notify(&mut self, name: String, caller: Box<dyn CanBeNotified>) -> Result<()> {
if let hash_map::Entry::Vacant(e) = self.notifies.entry(name) {
e.insert(caller);
Ok(())
} else {
Err(anyhow!("Notify already exists"))
}
}
pub fn register_query(&mut self, name: String, caller: Box<dyn CanBeQueried>) -> Result<()> {
if let hash_map::Entry::Vacant(e) = self.queries.entry(name) {
e.insert(caller);
Ok(())
} else {
Err(anyhow!("Query already exists"))
}
}
async fn on_msg(
&mut self,
mut stream: SkillRegisterStream,
) -> Result<(), vap_skill_register::Error> {
loop {
let (msg, responder) = stream.recv().await?;
let response = match msg {
SkillRegisterMessage::Connect(_) => {
// SkillRegister already makes sure that the skill name is
// not one known and the vap version is compatible, there's
// nothing more to do
Response {
status: ResponseType::Valid,
payload: to_vec_named(&MsgConnectResponse {
langs: self.langs.clone(),
unique_authentication_token: Some("".into()), // TODO: Finish security
})
.unwrap(),
}
}
SkillRegisterMessage::RegisterIntents(msg) => {
let (actions, entities) = self.transform(msg.nlu_data);
match register_skill(&msg.skill_id, actions, vec![], vec![], entities) {
Ok(()) => Response {
status: ResponseType::Valid,
payload: to_vec_named(&MsgRegisterIntentsResponse {}).unwrap(),
},
Err(_) => {
Response {
status: ResponseType::RequestEntityIncomplete,
// TODO! Add why
payload: vec![],
}
}
}
}
SkillRegisterMessage::Close(_) => {
// TODO! We should unregister the skill from the NLU
Response {
status: ResponseType::Valid,
payload: Vec::new(),
}
}
SkillRegisterMessage::Notification(msg) => {
let data = msg
.data
.into_iter()
.map(|n| {
// TODO! Should we send an answer per capability?
let code = if n.client_id == SYSTEM_SELF_ID {
n.capabilities
.into_iter()
.map(|c| {
if self.notifies.contains_key(&c.name) {
match self
.notifies
.get_mut(&c.name)
.unwrap()
.notify(c.cap_data)
{
NotificationResult::Valid => 200,
}
} else {
404
}
})
.max()
.unwrap_or(200)
}
// else if ... // TODO! Notification need to be sent to clients
else {
404
};
msg_notification_response::Data::StandAlone {
client_id: n.client_id,
code,
}
})
.collect::<Vec<_>>();
Response {
status: ResponseType::Valid,
payload: to_vec_named(&MsgNotificationResponse { data }).unwrap(),
}
}
SkillRegisterMessage::Query(msg) => {
let data = msg.data.into_iter().map(
|q| {
let client_id = q.client_id;
let capabilities = if client_id == SYSTEM_SELF_ID {
q.capabilities.into_iter().map(|c|{
if let hash_map::Entry::Occupied(mut e) = self.queries.entry(c.name.clone()) {
let (code, data) = e.get_mut().query(c.cap_data).unwrap();
QueryDataCapability {name: c.name, code, data}
}
else {
QueryDataCapability {
name: c.name.clone(),
code: 404,
data: hashmap!{"object".into() => c.name.into()}
}
}
}).collect()
}
// else if ... // TODO! Queries need to be sent to clients
else {
q.capabilities.into_iter().map(|c|{
QueryDataCapability { name: c.name, code: 404, data: hashmap!{"object".into() => client_id.clone().into()}}
}).collect()
};
msg_query_response::QueryData {client_id, capabilities}
}
).collect();
Response {
status: ResponseType::Valid,
payload: to_vec_named(&MsgQueryResponse { data }).unwrap(),
}
}
};
responder
.send(response)
.map_err(|_| vap_skill_register::Error::ClosedChannel)?;
}
}
fn transform(
&self,
nlu_data: Vec<NluData>,
) -> (
Vec<(
String,
HashMap<LanguageIdentifier, IntentData>,
Arc<Mutex<dyn Action + Send>>,
)>,
Vec<(String, HashMap<LanguageIdentifier, EntityDef>)>,
) {
let mut new_intents: HashMap<String, HashMap<LanguageIdentifier, IntentData>> =
HashMap::new();
let mut entities: HashMap<String, HashMap<LanguageIdentifier, EntityDef>> = HashMap::new();
fn fmt_name(name: &str) -> String {
format!("vap_action_{}", name)
}
fn fmt_lang(lang: Language) -> LanguageIdentifier {
LanguageIdentifier::from_parts(
subtags::Language::from_str(&lang.language).unwrap(),
Option::None,
lang.country
.and_then(|r| subtags::Region::from_str(&r).ok()),
&lang
.extra
.and_then(|e| subtags::Variant::from_str(&e).ok())
.map(|v| vec![v])
.unwrap_or_else(Vec::new),
)
}
for lang_set in nlu_data.into_iter() {
for intent in lang_set.intents {
let internal_intent = IntentData {
slots: intent
.slots
.into_iter()
.map(|s| {
(
s.name.clone(),
SlotData {
slot_type: OrderKind::Ref(s.entity),
required: false,
prompt: None,
reprompt: None,
},
)
})
.collect(),
utts: intent.utterances.into_iter().map(|d| d.text).collect(), // TODO! Utterances might need some conversion of slot format
hook: Hook::Action(fmt_name(&intent.name)),
};
if let hash_map::Entry::Vacant(e) = new_intents.entry(intent.name.clone()) {
e.insert(HashMap::new());
}
assert!(new_intents
.get_mut(&intent.name)
.unwrap()
.insert(fmt_lang(lang_set.language.clone()), internal_intent)
.is_none());
}
for entity in lang_set.entities {
let def = EntityDef {
data: entity
.data
.into_iter()
.map(|d| EntityData {
value: d.value,
synonyms: d.synonyms,
})
.collect(),
automatically_extensible: !entity.strict,
};
if !entities.contains_key(&entity.name) {
entities.insert(entity.name.clone(), HashMap::new());
}
assert!(entities
.get_mut(&entity.name)
.unwrap()
.insert(fmt_lang(lang_set.language.clone()), def)
.is_none())
// TODO! Need a way of passing entities
}
}
(
new_intents
.into_iter()
.map(|(intent, utts)| {
let action: Arc<Mutex<dyn Action + Send>> =
Arc::new(Mutex::new(VapAction::new(
fmt_name(&intent),
"TODO!Figure ip".to_string(),
self.out.clone(),
)));
(intent, utts, action)
})
.collect(),
entities.into_iter().collect(),
)
}
}
#[async_trait(?Send)]
impl SkillLoader for VapLoader {
fn load_skills(&mut self, _langs: &[LanguageIdentifier]) -> Result<()> {
Ok(())
}
async fn run_loader(&mut self) -> Result<()> {
let (stream, reg) = self.stream_reg.take().unwrap();
tokio::select!(
_= reg.run() => {},
_= self.on_msg(stream) => {}
);
Ok(())
}
}
struct VapAction {
name: String,
ip: String,
next_request_id: u64,
shared_out: Arc<Mutex<SkillRegisterOut>>,
}
impl VapAction {
pub fn new(name: String, ip: String, shared_out: Arc<Mutex<SkillRegisterOut>>) -> Self {
VapAction {
name,
ip,
next_request_id: 0,
shared_out,
}
}
}
#[async_trait(?Send)]
impl Action for VapAction {
async fn call(&mut self, context: &ActionContext) -> Result<ActionAnswer> {
// TODO! Also map events!!!
let slots = context
.data
.as_intent()
.unwrap()
.slots
.iter()
.map(|(n, v)| RequestSlot {
name: n.clone(),
value: Some(v.clone()),
})
.collect();
let (capabilities, sender) = self
.shared_out
.lock_it()
.activate_skill(
self.ip.clone(),
MsgSkillRequest {
request_id: self.next_request_id,
client: ClientData {
system_id: context
.satellite
.as_ref()
.map(|s| s.uuid.clone())
.expect("No satellite"),
capabilities: vec![], // TODO! Figure out capabilities
},
request: RequestData {
type_: RequestDataKind::Intent,
intent: context.data.as_intent().unwrap().name.clone(),
locale: context.locale.clone(),
slots,
},
},
)
.await?;
sender.send(RequestResponse { code: 205 }).unwrap();
let data = if capabilities[0].name == "voice" {
capabilities[0].cap_data[&"text".into()].clone().to_string()
} else {
"NO VOICE CAPABILITY IN RESPONSE".to_string()
};
ActionAnswer::send_text(data, true)
}
fn get_name(&self) -> String {
self.name.clone()
}
}
// Capabilities /**************************************************************/
pub trait CanBeQueried {
fn query(&mut self, caps: AssociativeMap) -> Result<(u16, AssociativeMap)>;
}
pub enum NotificationResult {
Valid,
}
pub trait CanBeNotified {
fn notify(&mut self, caps: AssociativeMap) -> NotificationResult;
}
|
use spatialos_sdk::worker::internal::schema::*;
use spatialos_sdk::worker::component::*;
use std::collections::BTreeMap;
use <#= vec!["super".to_string(); self.depth() + 1].join("::") #>::generated as generated;
/* Enums. */<# for enum_name in &self.enums {
let enum_def = self.get_enum_definition(enum_name);
let enum_rust_name = self.rust_name(&enum_def.qualified_name);
#>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum <#= enum_rust_name #> {
<# for enum_value in &enum_def.values { #>
<#= enum_value.name #>,<# } #>
}
impl From<u32> for <#= enum_rust_name #> {
fn from(value: u32) -> Self {
match value {
<# for enum_value in &enum_def.values { #>
<#= enum_value.value #> => <#= enum_rust_name #>::<#= enum_value.name #>, <# } #>
_ => panic!(format!("Could not convert {} to enum <#= enum_rust_name #>.", value))
}
}
}
impl <#= enum_rust_name #> {
pub(crate) fn as_u32(self) -> u32 {
match self {
<# for enum_value in &enum_def.values { #>
<#= enum_rust_name #>::<#= enum_value.name #> => <#= enum_value.value #>, <# } #>
}
}
}
<# } #>
/* Types. */<# for type_name in &self.types { let type_def = self.get_type_definition(type_name); #>
#[derive(Debug, Clone)]
pub struct <#= self.rust_name(&type_def.qualified_name) #> {<#
for field in &type_def.fields {
#>
pub <#= field.name #>: <#= self.generate_field_type(field) #>,<# } #>
}
impl TypeConversion for <#= self.rust_name(&type_def.qualified_name) #> {
fn from_type(input: &SchemaObject) -> Result<Self, String> {
Ok(Self {<#
for field in &type_def.fields {
let field_expr = format!("input.field::<{}>({})", get_field_schema_type(field), field.field_id);
#>
<#= field.name #>: <#= self.deserialize_field(field, &field_expr) #>,<# } #>
})
}
fn to_type(input: &Self, output: &mut SchemaObject) -> Result<(), String> {<#
for field in &type_def.fields {
let borrow = if self.field_needs_borrow(field) {
"&"
} else {
""
};
#>
<#= self.serialize_field(field, &format!("{}input.{}", borrow, field.name), "output") #>;<# } #>
Ok(())
}
}
<# } #>
/* Components. */ <# for component_name in &self.components {
let component = self.get_component_definition(component_name);
let component_fields = self.get_component_fields(&component); #>
#[derive(Debug, Clone)]
pub struct <#= self.rust_name(&component.qualified_name) #> {<#
for field in &component_fields {
#>
pub <#= field.name #>: <#= self.generate_field_type(field) #>,<# } #>
}
impl TypeConversion for <#= self.rust_name(&component.qualified_name) #> {
fn from_type(input: &SchemaObject) -> Result<Self, String> {
Ok(Self {<#
for field in &component_fields {
let field_expr = format!("input.field::<{}>({})", get_field_schema_type(field), field.field_id);
#>
<#= field.name #>: <#= self.deserialize_field(field, &field_expr) #>,<# } #>
})
}
fn to_type(input: &Self, output: &mut SchemaObject) -> Result<(), String> {<#
for field in &component_fields {
let borrow = if self.field_needs_borrow(field) {
"&"
} else {
""
};
#>
<#= self.serialize_field(field, &format!("{}input.{}", borrow, field.name), "output") #>;<# } #>
Ok(())
}
}
impl ComponentData<<#= self.rust_name(&component.qualified_name) #>> for <#= self.rust_name(&component.qualified_name) #> {
fn merge(&mut self, update: <#= self.rust_name(&component.qualified_name) #>Update) {<#
for field in &component_fields {
#>
if let Some(value) = update.<#= field.name #> { self.<#= field.name #> = value; }<# } #>
}
}
#[derive(Debug, Clone, Default)]
pub struct <#= self.rust_name(&component.qualified_name) #>Update {<#
for field in &component_fields {
#>
pub <#= field.name #>: Option<<#= self.generate_field_type(field) #>>,<# } #>
}
impl TypeConversion for <#= self.rust_name(&component.qualified_name) #>Update {
fn from_type(input: &SchemaObject) -> Result<Self, String> {
let mut output = Self {<#
for field in &component_fields {
#>
<#= field.name #>: None,<# } #>
};<#
for field in &component_fields {
#>
let _field_<#= field.name #> = input.field::<<#= get_field_schema_type(field) #>>(<#= field.field_id #>);
if _field_<#= field.name #>.count() > 0 {
let field = &_field_<#= field.name #>;
output.<#= field.name #> = Some(<#= self.deserialize_field(field, "field") #>);
}<# } #>
Ok(output)
}
fn to_type(input: &Self, output: &mut SchemaObject) -> Result<(), String> {<#
for field in &component_fields {
let ref_decorator = if self.field_needs_borrow(field) {
"ref "
} else {
""
};
#>
if let Some(<#= ref_decorator #>value) = input.<#= field.name #> {
<#= self.serialize_field(field, "value", "output") #>;
}<# } #>
Ok(())
}
}
impl ComponentUpdate<<#= self.rust_name(&component.qualified_name) #>> for <#= self.rust_name(&component.qualified_name) #>Update {
fn merge(&mut self, update: <#= self.rust_name(&component.qualified_name) #>Update) {<#
for field in &self.get_component_fields(&component) {
#>
if update.<#= field.name #>.is_some() { self.<#= field.name #> = update.<#= field.name #>; }<# } #>
}
}
#[derive(Debug, Clone)]
pub enum <#= self.rust_name(&component.qualified_name) #>CommandRequest {<#
for command in &component.commands {
#>
<#= command.name.to_camel_case() #>(<#= self.rust_fqname(&command.request_type) #>),<# } #>
}
#[derive(Debug, Clone)]
pub enum <#= self.rust_name(&component.qualified_name) #>CommandResponse {<#
for command in &component.commands {
#>
<#= command.name.to_camel_case() #>(<#= self.rust_fqname(&command.response_type) #>),<# } #>
}
impl Component for <#= self.rust_name(&component.qualified_name) #> {
type Update = <#= self.rust_fqname(&component.qualified_name) #>Update;
type CommandRequest = <#= self.rust_fqname(&component.qualified_name) #>CommandRequest;
type CommandResponse = <#= self.rust_fqname(&component.qualified_name) #>CommandResponse;
const ID: ComponentId = <#= component.component_id #>;
fn from_data(data: &SchemaComponentData) -> Result<<#= self.rust_fqname(&component.qualified_name) #>, String> {
<<#= self.rust_fqname(&component.qualified_name) #> as TypeConversion>::from_type(&data.fields())
}
fn from_update(update: &SchemaComponentUpdate) -> Result<<#= self.rust_fqname(&component.qualified_name) #>Update, String> {
<<#= self.rust_fqname(&component.qualified_name) #>Update as TypeConversion>::from_type(&update.fields())
}
fn from_request(command_index: CommandIndex, request: &SchemaCommandRequest) -> Result<<#= self.rust_fqname(&component.qualified_name) #>CommandRequest, String> {
match command_index {<#
for command in &component.commands {
#>
<#= command.command_index #> => {
let result = <<#= self.rust_fqname(&command.request_type) #> as TypeConversion>::from_type(&request.object());
result.and_then(|deserialized| Ok(<#= self.rust_name(&component.qualified_name) #>CommandRequest::<#= command.name.to_camel_case() #>(deserialized)))
},<# } #>
_ => Err(format!("Attempted to deserialize an unrecognised command request with index {} in component <#= self.rust_name(&component.qualified_name) #>.", command_index))
}
}
fn from_response(command_index: CommandIndex, response: &SchemaCommandResponse) -> Result<<#= self.rust_fqname(&component.qualified_name) #>CommandResponse, String> {
match command_index {<#
for command in &component.commands {
#>
<#= command.command_index #> => {
let result = <<#= self.rust_fqname(&command.response_type) #> as TypeConversion>::from_type(&response.object());
result.and_then(|deserialized| Ok(<#= self.rust_name(&component.qualified_name) #>CommandResponse::<#= command.name.to_camel_case() #>(deserialized)))
},<# } #>
_ => Err(format!("Attempted to deserialize an unrecognised command response with index {} in component <#= self.rust_name(&component.qualified_name) #>.", command_index))
}
}
fn to_data(data: &<#= self.rust_fqname(&component.qualified_name) #>) -> Result<SchemaComponentData, String> {
let mut serialized_data = SchemaComponentData::new();
<<#= self.rust_fqname(&component.qualified_name) #> as TypeConversion>::to_type(data, &mut serialized_data.fields_mut())?;
Ok(serialized_data)
}
fn to_update(update: &<#= self.rust_fqname(&component.qualified_name) #>Update) -> Result<SchemaComponentUpdate, String> {
let mut serialized_update = SchemaComponentUpdate::new();
<<#= self.rust_fqname(&component.qualified_name) #>Update as TypeConversion>::to_type(update, &mut serialized_update.fields_mut())?;
Ok(serialized_update)
}
fn to_request(request: &<#= self.rust_fqname(&component.qualified_name) #>CommandRequest) -> Result<SchemaCommandRequest, String> {
let mut serialized_request = SchemaCommandRequest::new();
match request {<#
for command in &component.commands {
#>
<#= self.rust_name(&component.qualified_name) #>CommandRequest::<#= command.name.to_camel_case() #>(ref data) => {
<<#= self.rust_fqname(&command.request_type) #> as TypeConversion>::to_type(data, &mut serialized_request.object_mut())?;
},<# } #>
_ => unreachable!()
}
Ok(serialized_request)
}
fn to_response(response: &<#= self.rust_fqname(&component.qualified_name) #>CommandResponse) -> Result<SchemaCommandResponse, String> {
let mut serialized_response = SchemaCommandResponse::new();
match response {<#
for command in &component.commands {
#>
<#= self.rust_name(&component.qualified_name) #>CommandResponse::<#= command.name.to_camel_case() #>(ref data) => {
<<#= self.rust_fqname(&command.response_type) #> as TypeConversion>::to_type(data, &mut serialized_response.object_mut())?;
},<# } #>
_ => unreachable!()
}
Ok(serialized_response)
}
fn get_request_command_index(request: &<#= self.rust_fqname(&component.qualified_name) #>CommandRequest) -> u32 {
match request {<#
for command in &component.commands {
#>
<#= self.rust_name(&component.qualified_name) #>CommandRequest::<#= command.name.to_camel_case() #>(_) => <#= command.command_index #>,<# } #>
_ => unreachable!(),
}
}
fn get_response_command_index(response: &<#= self.rust_fqname(&component.qualified_name) #>CommandResponse) -> u32 {
match response {<#
for command in &component.commands {
#>
<#= self.rust_name(&component.qualified_name) #>CommandResponse::<#= command.name.to_camel_case() #>(_) => <#= command.command_index #>,<# } #>
_ => unreachable!(),
}
}
}
inventory::submit!(VTable::new::<<#= self.rust_name(&component.qualified_name) #>>());
<# } #>
|
extern crate rustc_serialize;
extern crate uuid;
extern crate chrono;
#[macro_use] mod macros;
pub mod parse;
pub mod method;
pub mod record;
pub mod types;
pub use self::mailbox::Mailbox;
pub use self::message::Message;
pub use self::calendar::Calendar;
pub use self::calendar_event::CalendarEvent;
pub use self::contact::Contact;
pub use self::contact_group::ContactGroup;
pub mod mailbox;
pub mod message;
pub mod message_list;
pub mod message_import;
pub mod message_copy;
pub mod message_report;
pub mod calendar;
pub mod calendar_event;
pub mod contact;
pub mod contact_group;
|
//! This module provides useful **type operators** that are not defined in `core`.
//!
//!
/// A **type operator** that ensures that `Rhs` is the same as `Self`, it is mainly useful
/// for writing macros that can take arbitrary binary or unary operators.
///
/// `Same` is implemented generically for all types; it should never need to be implemented
/// for anything else.
///
/// Note that Rust lazily evaluates types, so this will only fail for two different types if
/// the `Output` is used.
///
/// # Example
/// ```rust
/// use typenum::{Same, U4, U5, Unsigned};
///
/// assert_eq!(<U5 as Same<U5>>::Output::to_u32(), 5);
///
/// // Only an error if we use it:
/// type Undefined = <U5 as Same<U4>>::Output;
/// // Compiler error:
/// // Undefined::to_u32();
/// ```
pub trait Same<Rhs = Self> {
/// Should always be `Self`
type Output;
}
impl<T> Same<T> for T {
type Output = T;
}
/// A **type operator** that provides exponentiation by repeated squaring.
///
/// # Example
/// ```rust
/// use typenum::{Pow, N3, P3, Integer};
///
/// assert_eq!(<N3 as Pow<P3>>::Output::to_i32(), -27);
/// ```
pub trait Pow<Rhs = Self> {
/// The result of the exponentiation.
type Output;
}
/// A **type operator** for comparing `Self` and `Rhs`. It provides a similar functionality to
/// the function
/// [`core::cmp::Ord::cmp`](https://doc.rust-lang.org/nightly/core/cmp/trait.Ord.html#tymethod.cmp)
/// but for types.
///
/// # Example
/// ```rust
/// use typenum::{Cmp, Ord, Greater, Less, Equal, N3, P2, P5};
/// use std::cmp::Ordering;
///
/// assert_eq!(<P2 as Cmp<N3>>::Output::to_ordering(), Ordering::Greater);
/// assert_eq!(<P2 as Cmp<P2>>::Output::to_ordering(), Ordering::Equal);
/// assert_eq!(<P2 as Cmp<P5>>::Output::to_ordering(), Ordering::Less);
pub trait Cmp<Rhs = Self> {
/// The result of the comparison. It should only ever be one of `Greater`, `Less`, or `Equal`.
type Output;
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type IPerceptionFrameProvider = *mut ::core::ffi::c_void;
pub type IPerceptionFrameProviderManager = *mut ::core::ffi::c_void;
pub type PerceptionControlGroup = *mut ::core::ffi::c_void;
pub type PerceptionCorrelation = *mut ::core::ffi::c_void;
pub type PerceptionCorrelationGroup = *mut ::core::ffi::c_void;
pub type PerceptionFaceAuthenticationGroup = *mut ::core::ffi::c_void;
pub type PerceptionFrame = *mut ::core::ffi::c_void;
pub type PerceptionFrameProviderInfo = *mut ::core::ffi::c_void;
pub type PerceptionPropertyChangeRequest = *mut ::core::ffi::c_void;
pub type PerceptionStartFaceAuthenticationHandler = *mut ::core::ffi::c_void;
pub type PerceptionStopFaceAuthenticationHandler = *mut ::core::ffi::c_void;
pub type PerceptionVideoFrameAllocator = *mut ::core::ffi::c_void;
|
pub mod grid;
use std::fmt::Debug;
use std::time::Instant;
pub fn create_chunks(input: &str) -> Vec<&str> {
input.trim().split("\n\n").collect()
}
pub fn run_timed<T, X>(f: fn(T) -> X, argument: T, description: &str)
where
X: Debug,
{
let now = Instant::now();
let answer = f(argument);
println!(
"{}: {:?}, result found in {} ms",
description,
answer,
now.elapsed().as_millis()
);
}
pub fn run_matrix<T: ?Sized, X>(part1: fn(&T) -> X, part2: fn(&T) -> X, example: &T, input: &T)
where
X: Debug,
{
run_timed(part1, example, "part 1 example");
run_timed(part1, input, "part 1 input");
run_timed(part2, example, "part 2 example");
run_timed(part2, input, "part 2 input");
}
|
// Ideas for interaction:
// player 2 -> switch to player 2's turn
// set ! 42 -> set Yahtzee row to 42 (forced result)
// r 113456 -> roll and suggest actions
// S -> choose action 'S'
//
// Initial roll: "I would keep 56 to go for two pairs"
// Final roll: "I would take the obvious choice: ..." (i.e. the non-Chance one with highest score)
// List other actions and their expectations rounded to integers (or a couple decimals if some are close)
use std::io;
use std::io::BufRead;
extern crate yahtzeevalue;
use yahtzeevalue::*;
use yahtzeevalue::constants::*;
fn parse_outcome(line: &str) -> Option<Outcome> {
if line.len() != DICE_COUNT {
return None;
}
let mut outcome = Outcome::empty();
for c in line.chars() {
if c < '1' {
return None;
}
let v = c as usize - '1' as usize;
if v >= SIDES {
return None;
}
outcome.histogram[v] += 1;
}
Some(outcome)
}
struct Tokenizer<R: io::Read> {
reader: io::BufReader<R>,
line: String,
word: usize,
}
impl <R: io::Read> Tokenizer<R> {
fn new(inner: R) -> Self {
Tokenizer {
reader: io::BufReader::new(inner),
line: String::new(),
word: 0,
}
}
fn peek_word(&self) -> Option<&str> {
self.line.split_whitespace().nth(self.word)
}
fn next_word(&mut self) -> Option<&str> {
let res = self.line.split_whitespace().nth(self.word);
self.word += 1;
res
}
fn next<O, F: FnMut(&str) -> Option<O>>(&mut self, prompt: &str, mut parser: F) -> O {
let mut p = prompt;
loop {
while None == self.peek_word() {
println!("{}", p);
p = "I did not understand that.";
self.line.clear();
self.reader.read_line(&mut self.line).unwrap();
self.word = 0;
}
let r = self.next_word().unwrap();
match parser(r) {
Some(o) => return o,
None => (),
};
}
}
}
struct Player {
state: u32,
points: u32,
}
impl Player {
fn new() -> Self {
Player {
state: 0,
points: 0,
}
}
}
enum CommandWord {
Roll(Outcome),
Players,
Player,
Action(usize),
Help,
Score,
Bonus,
}
fn parse_command_word(w: &str, game: &Game) -> Option<CommandWord> {
match parse_outcome(w) {
Some(o) => return Some(CommandWord::Roll(o)),
None => (),
};
if w == "players" {
return Some(CommandWord::Players);
}
if w == "player" {
return Some(CommandWord::Player);
}
if w == "score" {
return Some(CommandWord::Score);
}
if w == "bonus" {
return Some(CommandWord::Bonus);
}
for (i, (_value, action, _state, _points)) in game.choices.iter().enumerate() {
if w == action.shorthand() {
return Some(CommandWord::Action(i));
}
}
if w == "help" {
return Some(CommandWord::Help);
}
return None
}
enum Command {
Roll(Outcome),
Players(usize),
Player(usize),
Action(u32, u32),
Help,
Score(i32),
Bonus(i32),
}
struct Game {
players: Vec<Player>,
player_count: usize,
player_index: usize,
choices: Vec<(f64, Action, u32, u32)>,
roll_index: usize,
prompt: String,
}
fn parse_command<R: io::Read>(reader: &mut Tokenizer<R>, game: &mut Game) -> Command {
match reader.next(&game.prompt, |w| parse_command_word(w, game)) {
CommandWord::Players => Command::Players(reader.next("New player count:", |w| w.parse::<usize>().ok())),
CommandWord::Player => Command::Player(reader.next("Whose turn is it?", |w| w.parse::<usize>().ok())),
CommandWord::Roll(o) => Command::Roll(o),
CommandWord::Action(i) => {
let (_value, _action, state, points) = &game.choices[i];
Command::Action(*state, *points)
},
CommandWord::Help => Command::Help,
CommandWord::Score => Command::Score(reader.next("Points to add/subtract:", |w| w.parse::<i32>().ok())),
CommandWord::Bonus => Command::Bonus(reader.next("Points to add/subtract:", |w| w.parse::<i32>().ok())),
}
}
const HELP: &'static str = "\
Commands:
<dice> input roll, e.g. 113666
<row> put roll on given row, e.g. D for Two Pairs
help this help text
players N set number of players to N
player N switch current turn to player N
bonus N add N to score, counting towards bonus
score N add N to score without counting towards bonus
";
fn main() {
let state_value = Store::new("state_value.bin").expect("Failed to read state value");
let stdin = io::stdin();
let mut reader = Tokenizer::new(stdin.lock());
let mut outcome_value = vec![0.0; max_outcome_encoding() + 1];
let mut reroll_value = vec![0.0; outcome_value.len()];
let mut game = Game {
players: vec![Player::new()],
player_count: 1,
player_index: 0,
choices: Vec::new(),
roll_index: 0,
prompt: String::new(),
};
loop {
let state = State::decode(game.players[game.player_index].state);
let points = game.players[game.player_index].points;
if game.roll_index == 0 {
let player_prompt = if game.player_count > 1 { format!("P{} ", game.player_index + 1) } else { String::new() };
game.prompt = format!("{}{:3} {} Input roll or command or 'help':", player_prompt, state.display_score(points), state);
}
match parse_command(&mut reader, &mut game) {
Command::Roll(mut outcome) => {
if game.roll_index == 0 {
compute_outcome_values(state, &mut |i| state_value.get(i), &mut outcome_value);
compute_subset_expectations(&mut outcome_value);
compute_reroll_value(&outcome_value, &mut reroll_value);
compute_subset_expectations(&mut reroll_value);
choose_reroll(&mut outcome, &reroll_value);
game.prompt = format!("I would keep {}. Input roll:", outcome);
game.roll_index += 1;
} else if game.roll_index == 1 {
compute_outcome_values(state, &mut |i| state_value.get(i), &mut outcome_value);
compute_subset_expectations(&mut outcome_value);
choose_reroll(&mut outcome, &outcome_value);
game.prompt = format!("I would keep {}. Input roll:", outcome);
game.roll_index += 1;
game.choices.clear();
} else if game.roll_index == 2 {
game.choices.clear();
actions(state, outcome, |action, next_state, action_points| {
let i = next_state.encode();
let value = state_value.get(i) + points as f64 + action_points as f64 - BONUS_LIMIT as f64;
game.choices.push((value, action, i, action_points));
});
game.choices.sort_by(|x, y| x.0.partial_cmp(&y.0).unwrap());
game.choices.reverse();
for (i, (value, action, _state, points)) in game.choices.iter().enumerate() {
if i == 0 {
println!("I would choose '{}' {} for {} points (E={:.1}). All possibilities:", action.shorthand(), action.name(), points, value);
}
println!(" {} {:25} {:3} pts (E={:.1})", action.shorthand(), action.name(), points, value);
}
game.prompt = "Which action do you choose?".to_owned();
}
},
Command::Players(n) => {
game.player_count = n;
while game.players.len() < game.player_count {
game.players.push(Player::new());
}
game.choices.clear();
},
Command::Player(i) => {
if i >= 1 && i <= game.player_count {
game.player_index = i - 1;
}
game.choices.clear();
},
Command::Action(s, p) => {
game.players[game.player_index].state = s;
game.players[game.player_index].points += p;
game.player_index = (game.player_index + 1) % game.player_count;
game.choices.clear();
game.roll_index = 0;
},
Command::Help => {
println!("{}", HELP);
},
Command::Score(n) => {
let p = &mut game.players[game.player_index].points;
if n < 0 {
*p = p.saturating_sub((-n) as u32);
} else {
*p = p.saturating_add(n as u32);
}
},
Command::Bonus(n) => {
let p = &mut game.players[game.player_index];
let mut s = State::decode(p.state);
if n < 0 {
p.points = p.points.saturating_sub((-n) as u32);
s.score = s.score.saturating_sub((-n) as u32);
} else {
p.points = p.points.saturating_add(n as u32);
s.score = s.score.saturating_add(n as u32).min(BONUS_LIMIT);
}
p.state = s.encode();
},
}
}
}
|
use crate::ir::eval::prelude::*;
impl IrEval for ir::IrCondition {
type Output = bool;
fn eval(
&self,
interp: &mut IrInterpreter<'_>,
used: Used,
) -> Result<Self::Output, IrEvalOutcome> {
match self {
ir::IrCondition::Ir(ir) => Ok(ir.as_bool(interp, used)?),
ir::IrCondition::Let(ir_let) => {
let value = ir_let.ir.eval(interp, used)?;
Ok(ir_let.pat.matches(interp, value, used, self)?)
}
}
}
}
|
use std::mem;
use curses;
bitflags! {
flags Buttons: curses::mmask_t {
const BUTTON_RELEASED = curses::BUTTON_RELEASED,
const BUTTON_PRESSED = curses::BUTTON_PRESSED,
const BUTTON_CLICKED = curses::BUTTON_CLICKED,
const DOUBLE_CLICKED = curses::DOUBLE_CLICKED,
const TRIPLE_CLICKED = curses::TRIPLE_CLICKED,
const BUTTON1_RELEASED = curses::BUTTON1_RELEASED,
const BUTTON1_PRESSED = curses::BUTTON1_PRESSED,
const BUTTON1_CLICKED = curses::BUTTON1_CLICKED,
const BUTTON1_DOUBLE_CLICKED = curses::BUTTON1_DOUBLE_CLICKED,
const BUTTON1_TRIPLE_CLICKED = curses::BUTTON1_TRIPLE_CLICKED,
const BUTTON2_RELEASED = curses::BUTTON2_RELEASED,
const BUTTON2_PRESSED = curses::BUTTON2_PRESSED,
const BUTTON2_CLICKED = curses::BUTTON2_CLICKED,
const BUTTON2_DOUBLE_CLICKED = curses::BUTTON2_DOUBLE_CLICKED,
const BUTTON2_TRIPLE_CLICKED = curses::BUTTON2_TRIPLE_CLICKED,
const BUTTON3_RELEASED = curses::BUTTON3_RELEASED,
const BUTTON3_PRESSED = curses::BUTTON3_PRESSED,
const BUTTON3_CLICKED = curses::BUTTON3_CLICKED,
const BUTTON3_DOUBLE_CLICKED = curses::BUTTON3_DOUBLE_CLICKED,
const BUTTON3_TRIPLE_CLICKED = curses::BUTTON3_TRIPLE_CLICKED,
const BUTTON4_RELEASED = curses::BUTTON4_RELEASED,
const BUTTON4_PRESSED = curses::BUTTON4_PRESSED,
const BUTTON4_CLICKED = curses::BUTTON4_CLICKED,
const BUTTON4_DOUBLE_CLICKED = curses::BUTTON4_DOUBLE_CLICKED,
const BUTTON4_TRIPLE_CLICKED = curses::BUTTON4_TRIPLE_CLICKED,
const BUTTON5_RELEASED = curses::BUTTON5_RELEASED,
const BUTTON5_PRESSED = curses::BUTTON5_PRESSED,
const BUTTON5_CLICKED = curses::BUTTON5_CLICKED,
const BUTTON5_DOUBLE_CLICKED = curses::BUTTON5_DOUBLE_CLICKED,
const BUTTON5_TRIPLE_CLICKED = curses::BUTTON5_TRIPLE_CLICKED,
const BUTTON_CTRL = curses::BUTTON_CTRL,
const BUTTON_SHIFT = curses::BUTTON_SHIFT,
const BUTTON_ALT = curses::BUTTON_ALT,
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Mouse(curses::MEVENT);
impl Mouse {
#[inline]
pub unsafe fn new() -> Mouse {
mem::zeroed()
}
#[inline]
pub unsafe fn as_ptr(&self) -> *const curses::MEVENT {
&self.0
}
#[inline]
pub unsafe fn as_mut_ptr(&mut self) -> *mut curses::MEVENT {
&mut self.0
}
}
impl Mouse {
#[inline]
pub fn id(&self) -> i16 {
self.0.id as i16
}
#[inline]
pub fn x(&self) -> u32 {
self.0.x as u32
}
#[inline]
pub fn y(&self) -> u32 {
self.0.y as u32
}
#[inline]
pub fn z(&self) -> u32 {
self.0.z as u32
}
pub fn buttons(&self) -> Buttons {
Buttons::from_bits_truncate(self.0.bstate)
}
}
|
/*
Copyright 2020 Timo Saarinen
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 super::*;
/// GLL - geographic Position - Latitude/Longitude
#[derive(Clone, Debug, PartialEq)]
pub struct GllData {
/// Navigation system
pub source: NavigationSystem,
/// Latitude in degrees.
pub latitude: Option<f64>,
/// Longitude in degrees.
pub longitude: Option<f64>,
/// UTC of position fix
pub timestamp: Option<DateTime<Utc>>,
/// True = data valid, false = data invalid.
pub data_valid: Option<bool>,
/// FAA mode indicator (NMEA 2.3 and later).
pub faa_mode: Option<FaaMode>,
}
impl LatLon for GllData {
fn latitude(&self) -> Option<f64> {
self.latitude
}
fn longitude(&self) -> Option<f64> {
self.longitude
}
}
// -------------------------------------------------------------------------------------------------
/// xxGLL: Geographic Position, Latitude / Longitude and time.
pub(crate) fn handle(
sentence: &str,
nav_system: NavigationSystem,
) -> Result<ParsedMessage, ParseError> {
let now: DateTime<Utc> = Utc::now();
let split: Vec<&str> = sentence.split(',').collect();
Ok(ParsedMessage::Gll(GllData {
source: nav_system,
latitude: parse_latitude_ddmm_mmm(
split.get(1).unwrap_or(&""),
split.get(2).unwrap_or(&""),
)?,
longitude: parse_longitude_dddmm_mmm(
split.get(3).unwrap_or(&""),
split.get(4).unwrap_or(&""),
)?,
timestamp: parse_hhmmss(split.get(5).unwrap_or(&""), now).ok(),
data_valid: {
match *split.get(6).unwrap_or(&"") {
"A" => Some(true),
"V" => Some(false),
_ => None,
}
},
faa_mode: FaaMode::new(split.get(7).unwrap_or(&"")).ok(),
}))
}
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_gagll() {
let mut p = NmeaParser::new();
match p.parse_sentence("$GAGLL,4916.45,N,12311.12,W,225444,A,D*48") {
Ok(ps) => {
match ps {
// The expected result
ParsedMessage::Gll(gll) => {
assert_eq!(gll.source, NavigationSystem::Galileo);
assert::close(gll.latitude.unwrap_or(0.0), 49.3, 0.1);
assert::close(gll.longitude.unwrap_or(0.0), -123.2, 0.1);
assert_eq!(gll.timestamp, {
let now: DateTime<Utc> = Utc::now();
Some(
Utc.ymd(now.year(), now.month(), now.day())
.and_hms(22, 54, 44),
)
});
assert_eq!(gll.data_valid, Some(true));
assert_eq!(gll.faa_mode, Some(FaaMode::Differential));
}
_ => {
assert!(false);
}
}
}
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
}
}
|
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt;
#[derive(Deserialize, Serialize, Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub enum ClearType {
NoPlay,
Failed,
AssistEasy,
LightAssistEasy,
Easy,
Normal,
Hard,
ExHard,
FullCombo,
Perfect,
Max,
Unknown,
}
impl Default for ClearType {
fn default() -> ClearType {
ClearType::NoPlay
}
}
impl ClearType {
pub fn from_integer(int: i32) -> ClearType {
match int {
0 => ClearType::NoPlay,
1 => ClearType::Failed,
2 => ClearType::AssistEasy,
3 => ClearType::LightAssistEasy,
4 => ClearType::Easy,
5 => ClearType::Normal,
6 => ClearType::Hard,
7 => ClearType::ExHard,
8 => ClearType::FullCombo,
9 => ClearType::Perfect,
10 => ClearType::Max,
_ => ClearType::Unknown,
}
}
pub fn to_integer(&self) -> i32 {
use ClearType::*;
match self {
NoPlay => 0,
Failed => 1,
AssistEasy => 2,
LightAssistEasy => 3,
Easy => 4,
Normal => 5,
Hard => 6,
ExHard => 7,
FullCombo => 8,
Perfect => 9,
Max => 10,
_ => 0,
}
}
}
impl fmt::Display for ClearType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ClearType::NoPlay => write!(f, "NoPlay"),
ClearType::Failed => write!(f, "Failed"),
ClearType::AssistEasy => write!(f, "AssistEasy"),
ClearType::LightAssistEasy => write!(f, "LightAssistEasy"),
ClearType::Easy => write!(f, "Easy"),
ClearType::Normal => write!(f, "Normal"),
ClearType::Hard => write!(f, "Hard"),
ClearType::ExHard => write!(f, "ExHard"),
ClearType::FullCombo => write!(f, "FullCombo"),
ClearType::Perfect => write!(f, "Perfect"),
ClearType::Max => write!(f, "Max"),
ClearType::Unknown => write!(f, "Unknown"),
}
}
}
impl PartialOrd for ClearType {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.to_integer().partial_cmp(&other.to_integer())
}
}
impl Ord for ClearType {
fn cmp(&self, other: &Self) -> Ordering {
self.to_integer().cmp(&other.to_integer())
}
}
|
use std::{collections::HashMap, f32::consts::PI};
use glium::{
index, uniforms::Uniforms, Display, DrawParameters, Frame, IndexBuffer, Program, Surface,
VertexBuffer,
};
use super::Vertex;
pub struct Mesh {
vertices: VertexBuffer<Vertex>,
indices: Vec<IndexBuffer<u32>>,
}
impl Mesh {
pub fn sphere(display: &Display) -> Mesh {
let n_meridians = 24;
let n_parallels = 12;
let n_subdivisions = 10;
let mut vertices = vec![];
let mut indices = vec![];
// A vertex deduplication map. This ensures that all vertices are stored exactly once.
// Points on the sphere are defined as (lat_index, lon_index) for the purpose of
// non-duplication. lat_index is `0..=n_parallels * n_subdivisions`, lon_index is
// `0..n_meridians * n_subdivisions`. The map maps point coordinates to vertex index.
let mut result: HashMap<(u32, u32), u32> = HashMap::new();
// generate parallels
for parallel_index in 0..n_parallels + 1 {
let mut parallel_indices = vec![];
// inclusive range to append longitude 0 once more at the end of the index buffer
for lon_index in 0..=n_meridians * n_subdivisions {
let lat_index = parallel_index * n_subdivisions;
// if we're at the end of the range, this will map lon_index to 0 again
let lon_index = lon_index % (n_meridians * n_subdivisions);
let key = (lat_index, lon_index);
let entry = result.entry(key).or_insert_with(|| {
let lat = PI / ((n_parallels * n_subdivisions) as f32) * lat_index as f32;
let lon = 2.0 * PI / ((n_meridians * n_subdivisions) as f32) * lon_index as f32;
vertices.push(Vertex {
position: [lat.sin() * lon.cos(), lat.cos(), lat.sin() * lon.sin()],
});
vertices.len() as u32 - 1
});
// for poles, only insert lon_index = 0
if lat_index == 0 || lat_index == n_parallels * n_subdivisions {
break;
}
parallel_indices.push(*entry);
}
if parallel_index == 0 || parallel_index == n_parallels {
continue;
}
indices.push(
IndexBuffer::new(display, index::PrimitiveType::LineStrip, ¶llel_indices)
.unwrap(),
);
}
for meridian_index in 0..n_meridians {
let mut meridian_indices = vec![];
for lat_index in 0..=n_parallels * n_subdivisions {
let lon_index = if lat_index == 0 || lat_index == n_parallels * n_subdivisions {
0 // poles are always (lat, 0)
} else {
meridian_index * n_subdivisions
};
let key = (lat_index, lon_index);
let entry = result.entry(key).or_insert_with(|| {
let lat = PI / ((n_parallels * n_subdivisions) as f32) * lat_index as f32;
let lon = 2.0 * PI / ((n_meridians * n_subdivisions) as f32) * lon_index as f32;
vertices.push(Vertex {
position: [lat.sin() * lon.cos(), lat.cos(), lat.sin() * lon.sin()],
});
vertices.len() as u32 - 1
});
meridian_indices.push(*entry);
}
indices.push(
IndexBuffer::new(display, index::PrimitiveType::LineStrip, &meridian_indices)
.unwrap(),
);
}
let vertices = VertexBuffer::new(display, &vertices).unwrap();
Mesh { vertices, indices }
}
pub fn draw<U: Uniforms>(
&self,
target: &mut Frame,
program: &Program,
uniforms: &U,
draw_parameters: &DrawParameters,
) {
for index_buffer in &self.indices {
target
.draw(
&self.vertices,
index_buffer,
program,
uniforms,
draw_parameters,
)
.unwrap();
}
}
}
|
use {
super::{ArcNoiseFn, NoiseFn},
crate::math::Scalar,
};
#[derive(Debug, Clone)]
pub struct ScaledNoise<T: Scalar, P> {
source: ArcNoiseFn<T, P>,
scale_x: T,
scale_y: T,
scale_z: T,
scale_w: T,
}
impl<T: Scalar, P> ScaledNoise<T, P> {
pub fn new(source: ArcNoiseFn<T, P>) -> Self {
Self {
source,
scale_x: T::one(),
scale_y: T::one(),
scale_z: T::one(),
scale_w: T::one(),
}
}
pub fn scale_x(self, scale_x: T) -> Self {
Self { scale_x, ..self }
}
pub fn scale_y(self, scale_y: T) -> Self {
Self { scale_y, ..self }
}
pub fn scale_z(self, scale_z: T) -> Self {
Self { scale_z, ..self }
}
pub fn scale_w(self, scale_w: T) -> Self {
Self { scale_w, ..self }
}
}
impl<T: Scalar> NoiseFn<T, [T; 2]> for ScaledNoise<T, [T; 2]> {
fn value(&self, point: [T; 2]) -> T {
self.source
.value([point[0] * self.scale_x, point[1] * self.scale_y])
}
}
impl<T: Scalar> NoiseFn<T, [T; 3]> for ScaledNoise<T, [T; 3]> {
fn value(&self, point: [T; 3]) -> T {
self.source.value([
point[0] * self.scale_x,
point[1] * self.scale_y,
point[2] * self.scale_z,
])
}
}
impl<T: Scalar> NoiseFn<T, [T; 4]> for ScaledNoise<T, [T; 4]> {
fn value(&self, point: [T; 4]) -> T {
self.source.value([
point[0] * self.scale_x,
point[1] * self.scale_y,
point[2] * self.scale_z,
point[3] * self.scale_w,
])
}
}
|
use super::{
service::{get_user_path, update_user},
UpdateUserInput,
};
use crate::datastore::prelude::*;
use juniper::ID;
use utils::PathToRef;
pub struct PendingUser {
pub user_id: ID,
pub email: String,
}
impl PendingUser {
fn new(user: Self) -> DbProperties {
fields_to_db_values(&[
AppValue::Ref("user_id", Some(&get_user_path(&user.user_id))),
AppValue::Str("email", Some(user.email)),
])
}
}
impl From<&Entity> for PendingUser {
fn from(entity: &Entity) -> Self {
Self {
user_id: DbValue::Key("user_id", entity).into(),
email: DbValue::Str("email", entity).into(),
}
}
}
fn get_pending_user_path<'a>(id: &ID) -> PathToRef<'a> {
vec![(KeyKind("PendingUsers"), KeyId::Cuid(id.clone()))]
}
pub async fn activate_user(client: &Client, pending_id: &ID, email: &String) -> Response<()> {
let query_batch = operations::run_query(
client,
format!("SELECT * FROM PendingUsers WHERE __key__ = @1 AND email = @2 LIMIT 1"),
Default::default(),
&[
insert::to_db_key(&get_pending_user_path(pending_id)),
insert::to_db_string(email),
],
)
.await
.or(Err(ResponseError::NotFound(
"User is not waiting activation".into(),
)))?;
if let Some(entity) = &operations::extract_first_entity(&query_batch.entity_results) {
let user = PendingUser::from(entity);
update_user(
client,
&user.user_id,
UpdateUserInput {
active: Some(true),
..Default::default()
},
)
.await?;
Ok(())
} else {
Err(ResponseError::NotFound(
"User is not waiting activation".into(),
))
}
}
pub async fn prepare_user_activation(client: &Client, user: PendingUser) -> Response<ID> {
let id = gen_cuid().map_err(ResponseError::UnexpectedError)?;
operations::create_doc(client, &get_pending_user_path(&id), PendingUser::new(user)).await?;
Ok(id)
}
|
#![feature(rustc_private)]
#![warn(unused_extern_crates)]
dylint_linting::dylint_library!();
extern crate rustc_ast;
extern crate rustc_ast_pretty;
extern crate rustc_attr;
extern crate rustc_data_structures;
extern crate rustc_errors;
extern crate rustc_hir;
extern crate rustc_hir_pretty;
extern crate rustc_index;
extern crate rustc_infer;
extern crate rustc_lexer;
extern crate rustc_lint;
extern crate rustc_middle;
extern crate rustc_mir;
extern crate rustc_parse;
extern crate rustc_parse_format;
extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_target;
extern crate rustc_trait_selection;
extern crate rustc_typeck;
mod fill_me_in;
#[doc(hidden)]
#[no_mangle]
pub fn register_lints(_sess: &rustc_session::Session, lint_store: &mut rustc_lint::LintStore) {
lint_store.register_lints(&[fill_me_in::FILL_ME_IN]);
lint_store.register_late_pass(|| Box::new(fill_me_in::FillMeIn));
}
#[test]
fn ui() {
dylint_testing::ui_test(
env!("CARGO_PKG_NAME"),
&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("ui"),
);
}
|
//!
use chart_builder::charts::*;
/// Structure used for storing chart related data and the drawing of an Bar Chart.
///
/// Compare values across multiple categories.
#[derive(Clone)]
pub struct VerticalBarChart {
data_labels: Vec<String>,
data: Vec<Vec<f64>>,
pub chart_prop: ChartProp,
pub axis_prop: AxisProp,
}
impl VerticalBarChart {
/// Creates a new instance of a VerticalBarChart.
///
/// ```chart_title``` is the String to specify the name of the chart displayed at the top of the window.
///
/// ```new_data_labels``` is the string data placed on the x-axis of the chart, each for a bar (or set of bars).
///
/// ```new_data``` is the number data on the y-axis of the chart specifying the position of each bar,
/// with indexes corresponding to the same index in new_data_labels.
pub fn new(
chart_title: String,
new_data_labels: Vec<String>,
new_data: Vec<Vec<f64>>,
) -> VerticalBarChart {
let x_axis_bounds = (0.0, 0.0);
let x_axis_scale = 1.0 / (new_data_labels.len() as f64);
let y_axis_props = calc_axis_props(&new_data, true, false); // take bar
let y_axis_bounds = y_axis_props.0;
let y_axis_scale = y_axis_props.1;
let axis_type: AxisType = if y_axis_bounds.0 < 0.0 && y_axis_bounds.1 > 0.0 {
AxisType::DoubleVertical
} else {
AxisType::Single
};
VerticalBarChart {
data_labels: new_data_labels,
data: new_data,
chart_prop: ChartProp::new(chart_title, &axis_type),
axis_prop: AxisProp::new(x_axis_bounds, y_axis_bounds, x_axis_scale, y_axis_scale),
}
}
pub fn draw_chart(&self, drawing_area: &DrawingArea) {
let data_labels = self.data_labels.clone();
let data_y = self.data.clone();
let legend_values = self.chart_prop.legend_values.clone();
let chart_title = self.chart_prop.chart_title.clone();
let x_axis_title = self.axis_prop.x_axis_title.clone();
let x_axis_scale = self.axis_prop.x_axis_scale;
let y_axis_title = self.axis_prop.y_axis_title.clone();
let y_axis_scale = self.axis_prop.y_axis_scale;
let y_axis_bounds: (f64, f64) = self.axis_prop.y_axis_bounds;
let y_axis_min = y_axis_bounds.0;
let y_axis_max = y_axis_bounds.1;
// Actual size of screen generate if legend section is to be shown.
let mut screen_size = self.chart_prop.screen_size;
let show_legend = self.chart_prop.show_legend;
let legend_size = (screen_size.0 * 0.30).ceil();
screen_size.0 = if show_legend == false {
screen_size.0
} else {
screen_size.0 + legend_size
};
let mut h_scale = screen_size.1 / screen_size.0;
let mut v_scale = screen_size.0 / screen_size.1;
// Always make text and objects smaller rather than bigger as guarnteed to fit on screen
if h_scale < v_scale {
v_scale = 1.0;
} else {
h_scale = 1.0;
}
// Scaling used dependant use of a legend
let scalings: (f64, f64, f64, f64, f64, f64);
if show_legend == true {
scalings = get_legend_scale(screen_size, legend_size);
} else {
scalings = get_normal_scale();
}
let _horizontal_scaling = scalings.0;
let _vertical_scaling = scalings.1;
let _left_bound = scalings.2;
let _right_bound = scalings.3;
let _lower_bound = scalings.4;
let _upper_bound = scalings.5;
drawing_area.connect_draw(move |_, cr| {
cr.set_dash(&[3., 2., 1.], 1.);
assert_eq!(cr.get_dash(), (vec![3., 2., 1.], 1.));
set_defaults(cr, screen_size);
// Drawing Bar chart components
let intercept = calc_x_intercept(
calc_zero_intercept(y_axis_min, y_axis_max),
_vertical_scaling,
_lower_bound,
_upper_bound,
);
let x_delimiter_interval: f64 = _horizontal_scaling * x_axis_scale;
// Bar width before horizontal scaling applied
// (size of axis (before scaling) / number of sets of bars) * (space for set of bars within delimiters filled / number of series)
let bar_width = (1.0 / (data_labels.len() as f64)) * (0.7 / (data_y.len() as f64));
let mut disp = -0.5 * (data_y.len() as f64);
for j in 0..data_y.len() {
set_nth_colour(cr, j);
for i in 0..data_labels.len() {
let y_val = data_y[j][i];
cr.rectangle(
_left_bound - (x_delimiter_interval / 2.0)
+ x_delimiter_interval * ((i + 1) as f64)
+ (bar_width * disp) * _horizontal_scaling,
intercept,
bar_width * _horizontal_scaling,
_lower_bound
- (get_percentage_in_bounds(y_val, y_axis_min, y_axis_max)
* _vertical_scaling)
- intercept,
);
cr.fill();
cr.stroke();
}
disp += 1.0;
}
// Chart Title
draw_title(
cr,
_left_bound,
_upper_bound,
h_scale,
v_scale,
&chart_title,
);
// Draw Axis
draw_x_axis_cat(
cr,
scalings,
&data_labels,
x_axis_scale,
calc_zero_intercept(y_axis_min, y_axis_max),
&x_axis_title,
screen_size,
false,
);
draw_y_axis_con(
cr,
scalings,
y_axis_min,
y_axis_max,
y_axis_scale,
0.0,
&y_axis_title,
screen_size,
);
// Draw legend if chosen
if show_legend == true {
draw_legend(cr, &legend_values, screen_size, legend_size);
}
Inhibit(false)
});
}
pub(in chart_builder) fn get_chart_prop(&self) -> ChartProp {
self.chart_prop.clone()
}
}
impl Chart for VerticalBarChart {
fn draw(&self) {
build_window(ChartType::VBar(self.clone()));
}
}
|
mod message;
pub use message::ErrorMessage;
mod server;
pub use server::ServerError;
mod system;
pub use system::SystemError;
|
// Copyright 2017 Dasein Phaos aka. Luxko
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! link between the graphics API and the target surface
use comptr::ComPtr;
use winapi::IDXGISwapChain3;
use format::*;
use resource::*;
use error::WinError;
/// link between the graphics API and the target surface
#[derive(Debug)]
pub struct SwapChain {
pub(crate) ptr: ComPtr<IDXGISwapChain3>,
}
impl SwapChain {
/// gets the index of this swapchain's current back buffer
#[inline]
pub fn get_current_back_buffer_index(&mut self) -> u32 {
unsafe{
self.ptr.GetCurrentBackBufferIndex()
}
}
/// get buffer at the given index
#[inline]
pub fn get_buffer(&mut self, index: u32) -> Result<RawResource, WinError> {
unsafe {
let mut ret = ::std::mem::uninitialized();
let hr = self.ptr.GetBuffer(
index, & ::dxguid::IID_ID3D12Resource,
&mut ret as *mut *mut _ as *mut *mut _
);
WinError::from_hresult_or_ok(hr, || RawResource{
ptr: ComPtr::new(ret)
})
}
}
/// attemp to resize the back buffers with given parameters
#[inline]
pub fn resize_buffers(&mut self, params: SwapChainResizeDesc) -> Result<(), WinError> {
let hr = unsafe {
self.ptr.ResizeBuffers1(
params.buffer_count,
params.width,
params.height,
params.format,
params.flags.bits(),
::std::ptr::null(),
::std::ptr::null_mut()
)
};
WinError::from_hresult(hr)
}
// TODO: methods for color spaces
// TODO: methods for frame latency waitable object
// TODO: methods for composition swap chain
/// get the source region size for the swap chain
#[inline]
pub fn get_source_size(&mut self) -> Result<(u32, u32), WinError> {
let mut width = 0;
let mut height = 0;
let hr = unsafe {
self.ptr.GetSourceSize(&mut width, &mut height)
};
WinError::from_hresult_or_ok(hr, || (width, height))
}
/// set the source region size for the swap chain
#[inline]
pub fn set_source_size(&mut self, width: u32, height: u32) -> Result<(), WinError> {
WinError::from_hresult(unsafe {
self.ptr.SetSourceSize(width, height)
})
}
/// get the background color for the next `present` method of this swapchain
#[inline]
pub fn get_background_color(&mut self) -> Result<[f32; 4], WinError> {
unsafe {
let mut ret = ::std::mem::uninitialized();
let hr = self.ptr.GetBackgroundColor(&mut ret);
WinError::from_hresult_or_ok(hr, || {
[ret.r, ret.g, ret.b, ret.a]
})
}
}
/// change the background color for the next frame
#[inline]
pub fn set_background_color(&mut self, r: f32, g: f32, b: f32, a: f32) -> Result<(), WinError> {
let rgba = ::winapi::DXGI_RGBA{r, g, b, a};
WinError::from_hresult(unsafe {
self.ptr.SetBackgroundColor(&rgba)
})
}
// TODO: add `get_core_window`?
/// get description
#[inline]
pub fn get_desc(&mut self) -> Result<SwapChainDesc, WinError> {
unsafe {
let mut ret = ::std::mem::uninitialized();
let hr = self.ptr.GetDesc1(&mut ret);
WinError::from_hresult_or_ok(hr, || ::std::mem::transmute(ret))
}
}
/// get fullscreen description
#[inline]
pub fn get_fullscreen_desc(&mut self) -> Result<FullScreenDesc, WinError> {
unsafe {
let mut ret = ::std::mem::uninitialized();
let hr = self.ptr.GetFullscreenDesc(&mut ret);
WinError::from_hresult_or_ok(hr, || ::std::mem::transmute(ret))
}
}
/// get the underlying `HWMD` handle for the swapchain object
#[inline]
pub fn get_hwnd(&mut self) -> Result<::winapi::HWND, WinError> {
unsafe {
let mut ret = ::std::mem::uninitialized();
let hr = self.ptr.GetHwnd(&mut ret);
WinError::from_hresult_or_ok(hr, || ret)
}
}
// TODO: add method `get_restrict_to_output`
// TODO: add method `get_containing_output`, `get_fullscreen_state`
// TODO: add method to get performance statistics about the last render frame
/// get the number of times that `Present` or `Present1` has been called.
#[inline]
pub fn get_last_present_count(&mut self) -> Result<u32, WinError> {
unsafe {
let mut ret = 0;
let hr = self.ptr.GetLastPresentCount(&mut ret);
WinError::from_hresult_or_ok(hr, || ret)
}
}
/// present a rendered back buffer to the target output.
/// `sync_interval` specifies how to synchronize presentation of a frame
/// with the verticle blank. valid values include [0..4].
// TODO: support dirty rectangles
#[inline]
pub fn present(
&mut self, sync_interval: u32, flags: PresentFlags
) -> Result<(), WinError> {
debug_assert!(sync_interval<=4);
WinError::from_hresult(unsafe {
self.ptr.Present(sync_interval, flags.bits())
})
}
}
impl From<ComPtr<IDXGISwapChain3>> for SwapChain {
#[inline]
fn from(ptr: ComPtr<IDXGISwapChain3>) -> SwapChain {
SwapChain{ptr}
}
}
/// description of a swapchain
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct SwapChainDesc {
/// the resolution width, 0 to use the width of the CA of the target window
pub width: u32,
/// the resolution height, 0 to use the height of the CA of the target window
pub height: u32,
/// the display format
pub format: DxgiFormat,
/// whether the full-screen display mode or the back buffer is stereo
// TODO: note the relationship with swapchain flip mode
pub stereo: Bool,
/// multi-sampling scheme description
pub sample_desc: SampleDesc,
/// surface usage and CPU access options for the back buffer.
/// the back buffer can be used for shader input or target output.
pub buffer_usage: Usage,
/// number of buffers in the swap chain
pub buffer_count: u32,
/// scaling behavior when the back buffer is presented
pub scaling: Scaling,
/// presentation model, as well as how the back buffer would be
/// handled after calling `swapchain.present()`.
pub swap_effect: SwapEffect,
/// transparency behavior
pub alpha_mode: AlphaMode,
/// misc flags
pub flags: SwapChainFlags,
}
impl SwapChainDesc {
/// create a new `SwapChainDesc` with default parameters
#[inline]
pub fn new(format: DxgiFormat) -> SwapChainDesc {
SwapChainDesc{
width: 0,
height: 0,
format,
stereo: false.into(),
sample_desc: Default::default(),
buffer_usage: Usage::RENDER_TARGET_OUTPUT,
buffer_count: 2,
scaling: Default::default(),
swap_effect: Default::default(),
alpha_mode: Default::default(),
flags: Default::default(),
}
}
}
impl From<SwapChainDesc> for ::winapi::DXGI_SWAP_CHAIN_DESC1 {
#[inline]
fn from(desc: SwapChainDesc) -> Self {
unsafe {
::std::mem::transmute(desc)
}
}
}
/// optional description of a fullsceen swapchain
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct FullScreenDesc {
/// numerator of the refresh rate
pub refresh_numerator: u32,
/// denominator of the refresh rate
pub refresh_denominator: u32,
/// the method the raster uses to create an image on the surface
pub scanline_order: ScanlineOrder,
/// scaling mode
pub scaling: ModeScaling,
/// whether the swapchain is windowed
pub windowed: Bool,
}
impl Default for FullScreenDesc {
/// default to 60fps, unspecified order and scaling, fullscreen
#[inline]
fn default() -> FullScreenDesc {
FullScreenDesc{
refresh_numerator: 60,
refresh_denominator: 1,
scanline_order: Default::default(),
scaling: Default::default(),
windowed: false.into()
}
}
}
impl From<FullScreenDesc> for ::winapi::DXGI_SWAP_CHAIN_FULLSCREEN_DESC {
#[inline]
fn from(desc: FullScreenDesc) -> Self {
// TODO: double check
unsafe { ::std::mem::transmute(desc)}
}
}
/// parameters for swapchain resizing
#[derive(Clone, Copy, Debug)]
pub struct SwapChainResizeDesc {
/// new resolution width, 0 to use the width of the CA of the target window
pub width: u32,
/// new resolution height, 0 to use the height of the CA of the target window
pub height: u32,
/// new format, `DXGI_FORMAT_UNKNOWN` to preserve exisiting format
pub format: DxgiFormat,
/// new buffer counts, 0 to preserve existing counts
pub buffer_count: u32,
/// new flags
pub flags: SwapChainFlags,
// TODO: add nodes support
// TODO: add present queue support
}
impl SwapChainResizeDesc {
/// construct a new resize description with `flags` and default paramters
#[inline]
pub fn new(flags: SwapChainFlags) -> SwapChainResizeDesc {
SwapChainResizeDesc{
width: 0, height: 0, format: DXGI_FORMAT_UNKNOWN,
buffer_count: 0, flags
}
}
}
/// multi-sampling scheme description. Default to count 1 and quality 0,
/// representing no aa
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct SampleDesc {
/// the number of multisamples per pixel
pub count: u32,
/// the image quality level
pub quality: u32,
}
impl Default for SampleDesc {
fn default() -> SampleDesc {
SampleDesc{count: 1, quality: 0}
}
}
bitflags!{
/// scaling behavor when the back buffer got presented.
#[repr(C)]
pub struct Scaling: u32 {
/// back buffer content would be scaled to fill the presentation target
const STRETCH = 0;
/// back buffer content would appear without scaling, with top edge
/// aligned with the presentation target.
const NONE = 1;
/// back buffer content would be scaled to fit the presentation target,
/// while preserving the aspect ratio, centered with black borders
const ASPECT_RATIO_STRETCH = 2;
}
}
impl From<Scaling> for ::winapi::DXGI_SCALING {
fn from(scaling: Scaling) -> Self {
::winapi::DXGI_SCALING(scaling.bits())
}
}
impl Default for Scaling {
#[inline]
fn default() -> Scaling {
Scaling::STRETCH
}
}
bitflags!{
/// presentation model, as well as how the back buffer would be
/// handled after calling `swapchain.present()`.
/// [more info](https://msdn.microsoft.com/en-us/library/windows/desktop/bb173077%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396)
#[repr(C)]
pub struct SwapEffect: u32 {
/// bitblt, back buffer content would be discarded after presented
const DISCARD = 0;
/// bitblt, back buffer content would persist after presented,
/// cannot be used with multisampling
const SEQUENTIAL = 1;
/// flip, back buffer content would persist after presented,
/// cannot be used with multisampling
const FLIP_SEQUENTIAL = 3;
/// flip, back buffer content would be discared after presented,
/// cannot be used with multisampling and partial presentation
const FLIP_DISCARD = 4;
}
}
impl Default for SwapEffect {
fn default() -> SwapEffect {
SwapEffect::FLIP_DISCARD
}
}
bitflags!{
/// transparency behavior of a surface
#[repr(C)]
pub struct AlphaMode: u32 {
/// transparency behavior is not specified
const UNSPECIFIED = 0;
/// each color channel is premultiplied by the alpha value
const PREMULTIPLIED = 1;
/// each color channel is not premultiplied by the alpha value
const STRAIGHT = 2;
/// alpha channel would be ignored
const IGNORE = 3;
}
}
impl Default for AlphaMode {
fn default() -> AlphaMode {
AlphaMode::UNSPECIFIED
}
}
bitflags!{
/// misc flags for swapchain behavior
#[repr(C)]
pub struct SwapChainFlags: u32 {
const NONE = 0;
/// turn off fullscreen automatic rotation
const NONPREROTATED = 1;
/// allow switch between fullscreen and windowed with `resize_target`
const ALLOW_SWITCH = 2;
/// allow `get_dc` on the 0th back buffer
const GDI_COMPATIBLE = 4;
/// OS would support creation only when driver and hardware protection is used?
const RESTRICTED_CONTENT = 8;
const RESTRICT_SHARED_RESOURCE_DRIVER = 16;
/// the presented content would only be avaiable for local display
const DISPLAY_ONLY = 32;
/// ensure rendering does not begin while a frame is still being resented
const FRAME_LATENCY_WAITABLE_OBJECT = 64;
/// create a swapchain in the foreground layer for multi-plane rendering
const FOREGROUND_LAYER = 128;
const FULLSCREEN_VIDEO = 256;
const YUV_VIDEO = 512;
const HW_PROTECTED = 1024;
/// enable displays that support variable refresh rates to function
/// properly when the application presents a swapchain tied to a full
/// screen borderless window.
const ALLOW_TEARING = 2048;
}
}
impl Default for SwapChainFlags {
#[inline]
fn default() -> Self {
SwapChainFlags::NONE
}
}
bitflags!{
/// options for frame presentation
#[repr(C)]
pub struct PresentFlags: u32 {
/// present a frame from each buffer (starting from the current one)
/// to the output
const NONE = 0;
/// present a frame from current buffer to the output.
/// this flag allows vsync instead of typical sequencing
const DO_NOT_SEQUENCE = 0x2;
/// don't present to the output. intended for use only when switching from idle
const TEST = 0x1;
/// make the runtime discard outstanding queued frames
const RESTART = 0x4;
/// make the invocation fail if the calling thread would be blocked
const DO_NOT_WAIT = 0x8;
/// indicates that presentation content will be shown only on the particular output. The content will not be visible on other outputs.
const RESTRICT_TO_OUTPUT = 0x10;
/// stereo prefers right-eye viewing instead of right
const STEREO_PREFER_RIGHT = 0x20;
/// Indicates that the presentation should use the left buffer as a mono buffer.
const STEREO_TEMPORARY_MONO = 0x40;
// TODO: const PRESENT_USE_DURATION = 0x100;
/// allow tearing for variable refresh rate displays.
///
/// this flag can be used when:
/// - the swapchain was reated with the `ALLOW_TEARING` flag
/// - the `sync_interval` is `0`
/// - fullscreen borderless window, disabling automatic Alt+Enter...
const ALLOW_TEARING = 0x200;
}
}
impl Default for PresentFlags {
#[inline]
fn default() -> Self {
PresentFlags::NONE
}
}
bitflags!{
/// method the raster uses to create an image on the surface
#[repr(C)]
pub struct ScanlineOrder: u32 {
const UNSPECIFIED = 0;
/// image is created from the first scanline to the last without skipping any
const PROGRESSIVE = 1;
/// image is created beginning with the upper field
const UPPER_FIELD_FIRST = 2;
/// image is created beginning with the lower field
const LOWER_FIELD_FIRST = 3;
}
}
impl Default for ScanlineOrder {
#[inline]
fn default() -> Self {
ScanlineOrder::UNSPECIFIED
}
}
bitflags!{
/// scaling behavior for an image on a monitor
#[repr(C)]
pub struct ModeScaling: u32 {
const UNSPECIFIED = 0;
const CENTERED = 1;
const STRETCHED = 2;
}
}
impl Default for ModeScaling {
#[inline]
fn default() -> Self {
ModeScaling::UNSPECIFIED
}
}
|
use mask::*;
#[derive(Eq, Copy, Clone, Debug, Default, PartialEq)]
pub struct WhiteMask(pub Mask);
#[derive(Eq, Copy, Clone, Debug, Default, PartialEq)]
pub struct BlackMask(pub Mask);
pub mod ops_black_on_white;
pub mod ops_white_on_black;
pub mod ops_none_on_white;
pub mod ops_white_on_white;
pub mod ops_black_on_black;
pub trait SidedMask : Into<Mask>
where Self: Sized
{
fn wrap(m: Mask) -> Self;
fn mask(&self) -> Mask;
fn advance(&self) -> Self;
fn attack(&self) -> Self;
fn filter<M: Into<Mask>>(&self, f: M) -> Self {
Self::wrap(self.mask() & f.into())
}
fn and<M: Into<Mask>>(&self, f: M) -> Self {
Self::wrap(self.mask() | f.into())
}
}
impl Into<Mask> for WhiteMask {
fn into(self) -> Mask {
self.0
}
}
impl Into<Mask> for BlackMask {
fn into(self) -> Mask {
self.0
}
}
impl SidedMask for WhiteMask {
fn advance(&self) -> Self {
WhiteMask(self.0.shift_north())
}
fn attack(&self) -> Self {
WhiteMask(self.0.shift_north_east() | self.0.shift_north_west())
}
fn wrap(m: Mask) -> Self {
WhiteMask(m)
}
fn mask(&self) -> Mask {
self.0
}
}
impl SidedMask for BlackMask {
fn advance(&self) -> Self {
BlackMask(self.0.shift_south())
}
fn attack(&self) -> Self {
BlackMask(self.0.shift_south_east() | self.0.shift_south_west())
}
fn wrap(m: Mask) -> Self {
BlackMask(m)
}
fn mask(&self) -> Mask {
self.0
}
}
|
#[macro_use]
extern crate clap;
mod solve;
use std::time::Instant;
use clap::ArgMatches;
use solve::{solve, SolveStats};
fn main() {
let matches: ArgMatches = clap_app!(myapp =>
(name: "countdown-game")
(version: "0.1.0")
(author: "Mattias Buelens <mattias.buelens@gmail.com>")
(about: "Solves the Numbers round from the Countdown game show")
(@arg TARGET: -t --target +required +takes_value "Target number")
(@arg NUMBER: +required +multiple "Numbers to use")
).get_matches();
let target_str = matches.value_of("TARGET").unwrap();
let target = target_str.parse::<i32>().unwrap();
let mut numbers: Vec<i32> = Vec::new();
for number_str in matches.values_of("NUMBER").unwrap() {
numbers.push(number_str.parse::<i32>().unwrap());
}
run_solve(numbers, target);
}
fn run_solve(numbers: Vec<i32>, target: i32) {
let mut stats = SolveStats::new();
println!("Numbers: {:?}", numbers);
println!("Target: {}", target);
let start = Instant::now();
let solution = solve(numbers, target, &mut stats);
let elapsed = start.elapsed();
println!("Solution: {} = {}", &solution, solution.value());
println!("Elapsed: {} ms", (elapsed.as_secs() * 1_000) + (elapsed.subsec_nanos() / 1_000_000) as u64);
println!("Stats: {} expanded, {} visited", stats.expanded(), stats.visited());
} |
use ::std::fs;
use std::time::Instant;
pub type CoordType = f64;
//TODO @mverleg: try with and without copy
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Point {
pub x: CoordType,
pub y: CoordType,
pub z: CoordType,
}
impl Point {
pub fn dist2(&self, other: &Point) -> CoordType {
(self.x - other.x).powf(2.) +
(self.y - other.y).powf(2.) +
(self.z - other.z).powf(2.)
}
}
#[derive(Debug, Clone)]
pub struct Minimum {
pub point1: Point,
pub point2: Point,
pub dist1: CoordType,
pub dist2: CoordType,
}
impl Minimum {
pub fn new(point1: Point, point2: Point) -> Self {
let dist2 = point1.dist2(&point2);
Minimum {
point1,
point2,
dist1: dist2.sqrt(),
dist2,
}
}
}
pub type SolveFun = fn(&mut [Point]) -> (Point, Point);
pub fn read_data() -> Vec<Point> {
let mut points = Vec::with_capacity(100_000);
let csv = fs::read_to_string("test_data.csv").unwrap();
// let mut reader = csv::Reader::from_reader(csv.as_bytes());
for line in csv.lines() {
if !line.contains(";") {
break;
}
let mut coords = line.split(";");
let point = Point {
x: coords.next().unwrap().replace(",", ".").parse::<CoordType>().unwrap(),
y: coords.next().unwrap().replace(",", ".").parse::<CoordType>().unwrap(),
z: coords.next().unwrap().replace(",", ".").parse::<CoordType>().unwrap(),
};
points.push(point);
}
points
}
pub fn bench(name: &str, solve_fun: SolveFun, reps: usize) {
let mut total_ms = 0.0;
let mut now;
let expected_dist2 = 430.80863789034777;
for rep in 0..reps {
let mut points = read_data();
now = Instant::now();
let (p1, p2) = solve_fun(&mut points);
let duration = now.elapsed().as_nanos() as f64 / 1_000_000.0;
total_ms += duration;
let actual_dist1 = p1.dist2(&p2).sqrt();
println!("{3:} rep {0:}: distance {1:.3} in {2:.3} ms",
rep, actual_dist1, duration, name);
//assert!(actual_dist1 < expected_dist2 * 1.000001, "not the shortest distance");
}
println!("{2:} took {0:.3} ms for {1:} points",
total_ms / (reps as f64), read_data().len(), name)
} |
use std::ops::Deref;
use crate::ast::error::{Hint, TypeError};
use crate::ast::SetRef;
use crate::lexer::Spanned;
use fxhash::FxHashMap;
/// CheckContext is a type system.
#[derive(Debug, Default)]
pub struct CheckerContext {
/// Map Name of unique identifiant.
hash_set: FxHashMap<String, Spanned<Hint>>,
hash_choice: FxHashMap<String, Spanned<Hint>>,
}
impl CheckerContext {
/// Declares a set and ensures it is not defined twice.
pub fn declare_set(&mut self, object_name: Spanned<String>) -> Result<(), TypeError> {
if let Some(pre) = self.hash_set.insert(
object_name.data.to_owned(),
object_name.with_data(Hint::Set),
) {
Err(TypeError::Redefinition {
object_kind: pre,
object_name,
})
} else {
Ok(())
}
}
/// Declares a choice and ensures it is not defined twice.
pub fn declare_choice(
&mut self,
object_name: Spanned<String>,
object_type: Hint,
) -> Result<(), TypeError> {
if let Some(pre) = self.hash_choice.insert(
object_name.data.to_owned(),
object_name.with_data(object_type),
) {
Err(TypeError::Redefinition {
object_kind: pre,
object_name,
})
} else {
Ok(())
}
}
/// Check if the referenced set is defined.
pub fn check_set_define(&self, subset: &SetRef) -> bool {
self.hash_set.contains_key(subset.name.deref())
}
}
|
fn main(){
println!("{}", factor(600851475142));
}
fn factor(mut x: i64) -> i64{
while x%2==0{
x=x/2;
}
let mut largest: i64 =0;
let mut divisor: i64 = 3;
while divisor <=x{
if x%divisor==0{
x=x/divisor;
if divisor > largest{
largest=divisor;
}
divisor=3;
}
divisor=divisor+2;
}
return largest;
}
|
pub mod response;
use core::fmt;
use std::fmt::{Display, Formatter};
/// What Inbox you want to look at
pub enum WhereMessage {
/// Everything
Inbox,
/// unread
Unread,
/// Sent
SENT,
}
impl Display for WhereMessage {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let string = match self {
WhereMessage::Inbox => "inbox",
WhereMessage::Unread => "unread",
WhereMessage::SENT => "sent",
};
write!(f, "{}", string)
}
}
|
// src: musl/src/fenv/fenv.c
/* Dummy functions for archs lacking fenv implementation */
pub(crate) const FE_UNDERFLOW: i32 = 0;
pub(crate) const FE_INEXACT: i32 = 0;
pub(crate) const FE_TONEAREST: i32 = 0;
#[inline]
pub(crate) fn feclearexcept(_mask: i32) -> i32 {
0
}
#[inline]
pub(crate) fn feraiseexcept(_mask: i32) -> i32 {
0
}
#[inline]
pub(crate) fn fetestexcept(_mask: i32) -> i32 {
0
}
#[inline]
pub(crate) fn fegetround() -> i32 {
FE_TONEAREST
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Access control register"]
pub acr: ACR,
#[doc = "0x04 - Power down key register"]
pub pdkeyr: PDKEYR,
#[doc = "0x08 - Flash key register"]
pub keyr: KEYR,
#[doc = "0x0c - Option byte key register"]
pub optkeyr: OPTKEYR,
#[doc = "0x10 - Status register"]
pub sr: SR,
#[doc = "0x14 - Flash control register"]
pub cr: CR,
#[doc = "0x18 - Flash ECC register"]
pub eccr: ECCR,
_reserved7: [u8; 4usize],
#[doc = "0x20 - Flash option register"]
pub optr: OPTR,
#[doc = "0x24 - Flash Bank 1 PCROP Start address register"]
pub pcrop1sr: PCROP1SR,
#[doc = "0x28 - Flash Bank 1 PCROP End address register"]
pub pcrop1er: PCROP1ER,
#[doc = "0x2c - Flash Bank 1 WRP area A address register"]
pub wrp1ar: WRP1AR,
#[doc = "0x30 - Flash Bank 1 WRP area B address register"]
pub wrp1br: WRP1BR,
_reserved12: [u8; 60usize],
#[doc = "0x70 - securable area bank1 register"]
pub sec1r: SEC1R,
}
#[doc = "Access control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [acr](acr) module"]
pub type ACR = crate::Reg<u32, _ACR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ACR;
#[doc = "`read()` method returns [acr::R](acr::R) reader structure"]
impl crate::Readable for ACR {}
#[doc = "`write(|w| ..)` method takes [acr::W](acr::W) writer structure"]
impl crate::Writable for ACR {}
#[doc = "Access control register"]
pub mod acr;
#[doc = "Power down key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pdkeyr](pdkeyr) module"]
pub type PDKEYR = crate::Reg<u32, _PDKEYR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PDKEYR;
#[doc = "`write(|w| ..)` method takes [pdkeyr::W](pdkeyr::W) writer structure"]
impl crate::Writable for PDKEYR {}
#[doc = "Power down key register"]
pub mod pdkeyr;
#[doc = "Flash key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [keyr](keyr) module"]
pub type KEYR = crate::Reg<u32, _KEYR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _KEYR;
#[doc = "`write(|w| ..)` method takes [keyr::W](keyr::W) writer structure"]
impl crate::Writable for KEYR {}
#[doc = "Flash key register"]
pub mod keyr;
#[doc = "Option byte key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optkeyr](optkeyr) module"]
pub type OPTKEYR = crate::Reg<u32, _OPTKEYR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTKEYR;
#[doc = "`write(|w| ..)` method takes [optkeyr::W](optkeyr::W) writer structure"]
impl crate::Writable for OPTKEYR {}
#[doc = "Option byte key register"]
pub mod optkeyr;
#[doc = "Status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sr](sr) module"]
pub type SR = crate::Reg<u32, _SR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SR;
#[doc = "`read()` method returns [sr::R](sr::R) reader structure"]
impl crate::Readable for SR {}
#[doc = "`write(|w| ..)` method takes [sr::W](sr::W) writer structure"]
impl crate::Writable for SR {}
#[doc = "Status register"]
pub mod sr;
#[doc = "Flash control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"]
pub type CR = crate::Reg<u32, _CR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CR;
#[doc = "`read()` method returns [cr::R](cr::R) reader structure"]
impl crate::Readable for CR {}
#[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"]
impl crate::Writable for CR {}
#[doc = "Flash control register"]
pub mod cr;
#[doc = "Flash ECC register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [eccr](eccr) module"]
pub type ECCR = crate::Reg<u32, _ECCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ECCR;
#[doc = "`read()` method returns [eccr::R](eccr::R) reader structure"]
impl crate::Readable for ECCR {}
#[doc = "`write(|w| ..)` method takes [eccr::W](eccr::W) writer structure"]
impl crate::Writable for ECCR {}
#[doc = "Flash ECC register"]
pub mod eccr;
#[doc = "Flash option register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optr](optr) module"]
pub type OPTR = crate::Reg<u32, _OPTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _OPTR;
#[doc = "`read()` method returns [optr::R](optr::R) reader structure"]
impl crate::Readable for OPTR {}
#[doc = "`write(|w| ..)` method takes [optr::W](optr::W) writer structure"]
impl crate::Writable for OPTR {}
#[doc = "Flash option register"]
pub mod optr;
#[doc = "Flash Bank 1 PCROP Start address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pcrop1sr](pcrop1sr) module"]
pub type PCROP1SR = crate::Reg<u32, _PCROP1SR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PCROP1SR;
#[doc = "`read()` method returns [pcrop1sr::R](pcrop1sr::R) reader structure"]
impl crate::Readable for PCROP1SR {}
#[doc = "`write(|w| ..)` method takes [pcrop1sr::W](pcrop1sr::W) writer structure"]
impl crate::Writable for PCROP1SR {}
#[doc = "Flash Bank 1 PCROP Start address register"]
pub mod pcrop1sr;
#[doc = "Flash Bank 1 PCROP End address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pcrop1er](pcrop1er) module"]
pub type PCROP1ER = crate::Reg<u32, _PCROP1ER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PCROP1ER;
#[doc = "`read()` method returns [pcrop1er::R](pcrop1er::R) reader structure"]
impl crate::Readable for PCROP1ER {}
#[doc = "`write(|w| ..)` method takes [pcrop1er::W](pcrop1er::W) writer structure"]
impl crate::Writable for PCROP1ER {}
#[doc = "Flash Bank 1 PCROP End address register"]
pub mod pcrop1er;
#[doc = "Flash Bank 1 WRP area A address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wrp1ar](wrp1ar) module"]
pub type WRP1AR = crate::Reg<u32, _WRP1AR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WRP1AR;
#[doc = "`read()` method returns [wrp1ar::R](wrp1ar::R) reader structure"]
impl crate::Readable for WRP1AR {}
#[doc = "`write(|w| ..)` method takes [wrp1ar::W](wrp1ar::W) writer structure"]
impl crate::Writable for WRP1AR {}
#[doc = "Flash Bank 1 WRP area A address register"]
pub mod wrp1ar;
#[doc = "Flash Bank 1 WRP area B address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wrp1br](wrp1br) module"]
pub type WRP1BR = crate::Reg<u32, _WRP1BR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _WRP1BR;
#[doc = "`read()` method returns [wrp1br::R](wrp1br::R) reader structure"]
impl crate::Readable for WRP1BR {}
#[doc = "`write(|w| ..)` method takes [wrp1br::W](wrp1br::W) writer structure"]
impl crate::Writable for WRP1BR {}
#[doc = "Flash Bank 1 WRP area B address register"]
pub mod wrp1br;
#[doc = "securable area bank1 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sec1r](sec1r) module"]
pub type SEC1R = crate::Reg<u32, _SEC1R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SEC1R;
#[doc = "`read()` method returns [sec1r::R](sec1r::R) reader structure"]
impl crate::Readable for SEC1R {}
#[doc = "`write(|w| ..)` method takes [sec1r::W](sec1r::W) writer structure"]
impl crate::Writable for SEC1R {}
#[doc = "securable area bank1 register"]
pub mod sec1r;
|
use std::error::Error;
type Result<T> = std::result::Result<T, Box<dyn Error>>;
pub mod api;
pub mod applicants;
pub mod applicants_list;
pub mod documents;
pub mod documents_list;
pub mod env;
use api::*;
use applicants::*;
use applicants_list::*;
use documents::*;
use documents_list::*;
pub fn run(api_token: &str) -> Result<()> {
let created_applicant = create_applicant(api_token, Applicant::new(Some("Mnd"), Some("Yami")))?;
println!("{}", created_applicant);
let app_list = ApplicantsList::get_applicant_list(api_token)?;
println!("{}", app_list);
// app_list.clean_double_applicants(api_token)?;
// let updated_list = ApplicantsList::get_applicant_list(api_token)?;
// println!("{}", updated_list);
let doc_result = upload_doc(
api_token,
"/Users/mennad/Pictures/meyami.jpg",
&created_applicant,
)?;
println!("{}", doc_result);
let doc_list = DocumentsList::get_docs_list(api_token, &created_applicant)?;
println!("{}", doc_list);
Ok(())
}
|
pub mod bytecodegen;
mod cfg;
mod dfg;
mod function;
|
use cql_bindgen::cass_tuple_new;
use cql_bindgen::cass_tuple_new_from_data_type;
use cql_bindgen::cass_tuple_free;
use cql_bindgen::cass_tuple_data_type;
use cql_bindgen::cass_tuple_set_null;
use cql_bindgen::cass_tuple_set_int32;
use cql_bindgen::cass_tuple_set_int64;
use cql_bindgen::cass_tuple_set_float;
use cql_bindgen::cass_tuple_set_double;
use cql_bindgen::cass_tuple_set_bool;
use cql_bindgen::cass_tuple_set_string;
//use cql_bindgen::cass_tuple_set_string_n;
use cql_bindgen::cass_tuple_set_bytes;
use cql_bindgen::cass_tuple_set_uuid;
use cql_bindgen::cass_tuple_set_inet;
//use cql_bindgen::cass_tuple_set_decimal;
//use cql_bindgen::cass_tuple_set_collection;
//use cql_bindgen::cass_tuple_set_tuple;
//use cql_bindgen::cass_tuple_set_user_type;
//use cql_bindgen::cass_iterator_from_tuple;
use std::ffi::CString;
use cql_ffi::inet::AsCassInet;
use std::net::SocketAddr;
use cql_bindgen::CassTuple as _CassTuple;
use cql_ffi::uuid::CassUuid;
use cql_ffi::udt::CassDataType;
use cql_ffi::udt::CassConstDataType;
use cql_ffi::error::CassError;
pub struct CassTuple(pub *mut _CassTuple);
impl CassTuple {
pub fn new(item_count: u64) -> Self {
unsafe {
CassTuple(cass_tuple_new(item_count))
}
}
pub fn data_type(&mut self) -> CassConstDataType {
unsafe {
CassConstDataType(cass_tuple_data_type(self.0))
}
}
pub fn new_from_data_type(data_type: CassDataType) -> CassTuple {
unsafe {
CassTuple(cass_tuple_new_from_data_type(data_type.0))
}
}
pub fn set_null(&mut self, index: u64) -> Result<(), CassError> {
unsafe {
CassError::build(
cass_tuple_set_null(self.0, index)
).wrap(())
}
}
pub fn set_int32(&mut self, index: u64, value: i32) -> Result<(), CassError> {
unsafe {
CassError::build(
cass_tuple_set_int32(self.0, index, value)
).wrap(())
}
}
pub fn set_int64(&mut self, index: u64, value: i64) -> Result<(), CassError> {
unsafe {
CassError::build(
cass_tuple_set_int64(self.0, index, value)
).wrap(())
}
}
pub fn set_float(&mut self, index: u64, value: f32) -> Result<(), CassError> {
unsafe {
CassError::build(cass_tuple_set_float(self.0, index, value)).wrap(())
}
}
pub fn set_double(&mut self, index: u64, value: f64) -> Result<(), CassError> {
unsafe {
CassError::build(
cass_tuple_set_double(self.0, index, value)
).wrap(())
}
}
pub fn set_bool(&mut self, index: u64, value: bool) -> Result<(), CassError> {
unsafe {
CassError::build(
cass_tuple_set_bool(
self.0,
index,
if value {1} else {0}
)
).wrap(())
}
}
pub fn set_string<S>(&mut self, index: u64, value: S) -> Result<(), CassError>
where S: Into<String>
{
unsafe {
let value = CString::new(value.into()).unwrap();
CassError::build(
cass_tuple_set_string(self.0, index, value.as_ptr())
).wrap(())
}
}
pub fn set_inet(&mut self, index: u64, value: SocketAddr) -> Result<(), CassError> {
let inet = AsCassInet::as_cass_inet(&value);
unsafe {
CassError::build(
cass_tuple_set_inet(
self.0,
index,
inet.0,
)
).wrap(())
}
}
pub fn set_bytes(&mut self, index: u64, value: Vec<u8>) -> Result<(), CassError> {
unsafe {
CassError::build(
cass_tuple_set_bytes(
self.0,
index,
value.as_ptr(),
value.len() as u64
)
).wrap(())
}
}
pub fn set_uuid<S>(&mut self, index: u64, value: S) -> Result<(), CassError>
where S: Into<CassUuid>
{
unsafe {
CassError::build(
cass_tuple_set_uuid(self.0, index, value.into().0)
).wrap(())
}
}
}
impl Drop for CassTuple {
fn drop(&mut self) {
unsafe {
cass_tuple_free(self.0)
}
}
}
|
extern crate openssl;
use algorithm_problem_client::AtCoderClient;
use atcoder_problems_backend::crawler;
use diesel::pg::PgConnection;
use diesel::Connection;
use log::info;
use std::env;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
simple_logger::init_with_level(log::Level::Info).unwrap();
info!("Started");
let url = env::var("SQL_URL").expect("SQL_URL must be set.");
let args: Vec<_> = env::args().collect();
let client = AtCoderClient::default();
match args[1].as_str() {
"naive" => loop {
let conn = PgConnection::establish(&url).expect("Failed to connect PostgreSQL.");
crawler::crawl_from_new_contests(&conn, &client)?;
},
"new" => loop {
let conn = PgConnection::establish(&url).expect("Failed to connect PostgreSQL.");
crawler::crawl_new_submissions(&conn, &client)?;
},
"all" => loop {
let conn = PgConnection::establish(&url).expect("Failed to connect PostgreSQL.");
crawler::crawl_all_submissions(&conn, &client)?;
},
"contest" => {
let conn = PgConnection::establish(&url).expect("Failed to connect PostgreSQL.");
crawler::crawl_contest_and_problems(&conn, &client)?;
}
_ => {
unimplemented!("Unsupported: {}", args[0]);
}
}
Ok(())
}
|
use std::sync::{Mutex, Condvar, Arc, MutexGuard};
use async_channel::{Receiver, Sender, unbounded};
use sourcerenderer_core::Platform;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{DedicatedWorkerGlobalScope, WorkerGlobalScope, Response};
use js_sys::{ArrayBuffer, Uint8Array};
use wasm_bindgen_futures::JsFuture;
use crate::WorkerPool;
use crate::platform::WebPlatform;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AsyncIOTaskError {
InProgress,
Error(String)
}
pub(crate) struct AsyncIOTask {
pub path: String,
pub cond_var: Condvar,
pub result: Mutex<Result<Box<[u8]>, AsyncIOTaskError>>
}
impl AsyncIOTask {
pub fn new(path: &str) -> Arc<Self> {
Arc::new(Self {
path: path.to_string(),
cond_var: Condvar::new(),
result: Mutex::new(Err(AsyncIOTaskError::InProgress))
})
}
pub fn wait_for_result(&self) -> MutexGuard<Result<Box<[u8]>, AsyncIOTaskError>> {
let mut guard = self.result.lock().unwrap();
while guard.as_ref().err() == Some(&AsyncIOTaskError::InProgress) {
guard = self.cond_var.wait(guard).unwrap();
}
guard
}
}
pub(crate) fn start_worker(worker_pool: &WorkerPool) -> Sender<Arc<AsyncIOTask>> {
crate::console_log!("Starting async worker");
let (task_sender, task_receiver) = unbounded::<Arc<AsyncIOTask>>();
worker_pool.run_permanent(move || {
crate::console_log!("Starting async worker thread");
let future = process(task_receiver);
wasm_bindgen_futures::spawn_local(future);
}, Some("Async worker")).unwrap();
task_sender
}
async fn process(task_receiver: Receiver<Arc<AsyncIOTask>>) {
crate::console_log!("Started async worker");
loop {
let task = task_receiver.recv().await.unwrap();
let result = handle_fetch_task(task.path.clone()).await;
let mut result_guard = task.result.lock().unwrap();
if let Ok(result) = result {
*result_guard = Ok(result);
} else {
*result_guard = Err(AsyncIOTaskError::Error(format!("{:?}", result.err().unwrap())));
}
task.cond_var.notify_all();
}
}
async fn handle_fetch_task(url: String) -> Result<Box<[u8]>, JsValue> {
let global = js_sys::global();
let worker_global = global.dyn_into::<DedicatedWorkerGlobalScope>().unwrap();
let response_js_obj = JsFuture::from(worker_global.fetch_with_str(&url)).await?;
let response: Response = response_js_obj.dyn_into()?;
if !response.ok() {
return Err(JsValue::from_str(&response.status_text()));
}
let buffer_js_obj = JsFuture::from(response.array_buffer()?).await?;
let typed_array: Uint8Array = Uint8Array::new(&buffer_js_obj);
let mut buffer = Vec::<u8>::with_capacity(typed_array.length() as usize);
assert!(buffer.capacity() >= typed_array.length() as usize);
unsafe {
typed_array.raw_copy_to_ptr(buffer.as_mut_ptr());
buffer.set_len(typed_array.length() as usize);
}
Ok(Vec::into_boxed_slice(buffer))
} |
fn main() {
#[allow(clippy::unusual_byte_groupings)]
if let Ok(v) = std::env::var("DEP_OPENSSL_VERSION_NUMBER") {
println!("cargo:rustc-env=OPENSSL_API_VERSION={v}");
// cfg setup from openssl crate's build script
let version = u64::from_str_radix(&v, 16).unwrap();
if version >= 0x1_00_01_00_0 {
println!("cargo:rustc-cfg=ossl101");
}
if version >= 0x1_00_02_00_0 {
println!("cargo:rustc-cfg=ossl102");
}
if version >= 0x1_01_00_00_0 {
println!("cargo:rustc-cfg=ossl110");
}
if version >= 0x1_01_00_07_0 {
println!("cargo:rustc-cfg=ossl110g");
}
if version >= 0x1_01_01_00_0 {
println!("cargo:rustc-cfg=ossl111");
}
}
if let Ok(v) = std::env::var("DEP_OPENSSL_CONF") {
for conf in v.split(',') {
println!("cargo:rustc-cfg=osslconf=\"{conf}\"");
}
}
}
|
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use sfxr::Sample;
fn criterion_benchmark(c: &mut Criterion) {
// Default samples
c.bench_function("pickup", |b| {
b.iter(|| {
black_box(Sample::pickup(None));
});
});
c.bench_function("laser", |b| {
b.iter(|| {
black_box(Sample::laser(None));
});
});
c.bench_function("explosion", |b| {
b.iter(|| {
black_box(Sample::explosion(None));
});
});
c.bench_function("powerup", |b| {
b.iter(|| {
black_box(Sample::powerup(None));
});
});
c.bench_function("hit", |b| {
b.iter(|| {
black_box(Sample::hit(None));
});
});
c.bench_function("jump", |b| {
b.iter(|| {
black_box(Sample::jump(None));
});
});
c.bench_function("blip", |b| {
b.iter(|| {
black_box(Sample::blip(None));
});
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
use std::fmt;
use std::ops::{Deref, DerefMut};
use serde::{Deserialize, Serialize};
use super::cartridge::Cartridge;
use super::gpu::VIDEO_RAM_SIZE;
use super::iodev::{IoDevices, WaitControl};
use super::{Addr, Bus};
pub mod consts {
pub const WORK_RAM_SIZE: usize = 256 * 1024;
pub const INTERNAL_RAM_SIZE: usize = 32 * 1024;
pub const BIOS_ADDR: u32 = 0x0000_0000;
pub const EWRAM_ADDR: u32 = 0x0200_0000;
pub const IWRAM_ADDR: u32 = 0x0300_0000;
pub const IOMEM_ADDR: u32 = 0x0400_0000;
pub const PALRAM_ADDR: u32 = 0x0500_0000;
pub const VRAM_ADDR: u32 = 0x0600_0000;
pub const OAM_ADDR: u32 = 0x0700_0000;
pub const GAMEPAK_WS0_LO: u32 = 0x0800_0000;
pub const GAMEPAK_WS0_HI: u32 = 0x0900_0000;
pub const GAMEPAK_WS1_LO: u32 = 0x0A00_0000;
pub const GAMEPAK_WS1_HI: u32 = 0x0B00_0000;
pub const GAMEPAK_WS2_LO: u32 = 0x0C00_0000;
pub const GAMEPAK_WS2_HI: u32 = 0x0D00_0000;
pub const SRAM_LO: u32 = 0x0E00_0000;
pub const SRAM_HI: u32 = 0x0F00_0000;
pub const PAGE_BIOS: usize = (BIOS_ADDR >> 24) as usize;
pub const PAGE_EWRAM: usize = (EWRAM_ADDR >> 24) as usize;
pub const PAGE_IWRAM: usize = (IWRAM_ADDR >> 24) as usize;
pub const PAGE_IOMEM: usize = (IOMEM_ADDR >> 24) as usize;
pub const PAGE_PALRAM: usize = (PALRAM_ADDR >> 24) as usize;
pub const PAGE_VRAM: usize = (VRAM_ADDR >> 24) as usize;
pub const PAGE_OAM: usize = (OAM_ADDR >> 24) as usize;
pub const PAGE_GAMEPAK_WS0: usize = (GAMEPAK_WS0_LO >> 24) as usize;
pub const PAGE_GAMEPAK_WS1: usize = (GAMEPAK_WS1_LO >> 24) as usize;
pub const PAGE_GAMEPAK_WS2: usize = (GAMEPAK_WS2_LO >> 24) as usize;
pub const PAGE_SRAM_LO: usize = (SRAM_LO >> 24) as usize;
pub const PAGE_SRAM_HI: usize = (SRAM_HI >> 24) as usize;
}
use consts::*;
#[derive(Debug, Copy, Clone)]
pub enum MemoryAccessType {
NonSeq,
Seq,
}
impl fmt::Display for MemoryAccessType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
MemoryAccessType::NonSeq => "N",
MemoryAccessType::Seq => "S",
}
)
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum MemoryAccessWidth {
MemoryAccess8,
MemoryAccess16,
MemoryAccess32,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[repr(transparent)]
pub struct BoxedMemory {
pub mem: Box<[u8]>,
}
impl BoxedMemory {
pub fn new(boxed_slice: Box<[u8]>) -> BoxedMemory {
BoxedMemory { mem: boxed_slice }
}
}
impl Bus for BoxedMemory {
fn read_8(&self, addr: Addr) -> u8 {
unsafe { *self.mem.get_unchecked(addr as usize) }
}
fn write_8(&mut self, addr: Addr, value: u8) {
unsafe {
*self.mem.get_unchecked_mut(addr as usize) = value;
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
struct DummyBus([u8; 4]);
impl Bus for DummyBus {
fn read_8(&self, _addr: Addr) -> u8 {
0
}
fn write_8(&mut self, _addr: Addr, _value: u8) {}
}
const CYCLE_LUT_SIZE: usize = 0x10;
#[derive(Serialize, Deserialize, Clone)]
struct CycleLookupTables {
n_cycles32: [usize; CYCLE_LUT_SIZE],
s_cycles32: [usize; CYCLE_LUT_SIZE],
n_cycles16: [usize; CYCLE_LUT_SIZE],
s_cycles16: [usize; CYCLE_LUT_SIZE],
}
impl Default for CycleLookupTables {
fn default() -> CycleLookupTables {
CycleLookupTables {
n_cycles32: [1; CYCLE_LUT_SIZE],
s_cycles32: [1; CYCLE_LUT_SIZE],
n_cycles16: [1; CYCLE_LUT_SIZE],
s_cycles16: [1; CYCLE_LUT_SIZE],
}
}
}
impl CycleLookupTables {
pub fn init(&mut self) {
self.n_cycles32[PAGE_EWRAM] = 6;
self.s_cycles32[PAGE_EWRAM] = 6;
self.n_cycles16[PAGE_EWRAM] = 3;
self.s_cycles16[PAGE_EWRAM] = 3;
self.n_cycles32[PAGE_OAM] = 2;
self.s_cycles32[PAGE_OAM] = 2;
self.n_cycles16[PAGE_OAM] = 1;
self.s_cycles16[PAGE_OAM] = 1;
self.n_cycles32[PAGE_VRAM] = 2;
self.s_cycles32[PAGE_VRAM] = 2;
self.n_cycles16[PAGE_VRAM] = 1;
self.s_cycles16[PAGE_VRAM] = 1;
self.n_cycles32[PAGE_PALRAM] = 2;
self.s_cycles32[PAGE_PALRAM] = 2;
self.n_cycles16[PAGE_PALRAM] = 1;
self.s_cycles16[PAGE_PALRAM] = 1;
}
pub fn update_gamepak_waitstates(&mut self, waitcnt: WaitControl) {
static S_GAMEPAK_NSEQ_CYCLES: [usize; 4] = [4, 3, 2, 8];
static S_GAMEPAK_WS0_SEQ_CYCLES: [usize; 2] = [2, 1];
static S_GAMEPAK_WS1_SEQ_CYCLES: [usize; 2] = [4, 1];
static S_GAMEPAK_WS2_SEQ_CYCLES: [usize; 2] = [8, 1];
let ws0_first_access = waitcnt.ws0_first_access() as usize;
let ws1_first_access = waitcnt.ws1_first_access() as usize;
let ws2_first_access = waitcnt.ws2_first_access() as usize;
let ws0_second_access = waitcnt.ws0_second_access() as usize;
let ws1_second_access = waitcnt.ws1_second_access() as usize;
let ws2_second_access = waitcnt.ws2_second_access() as usize;
// update SRAM access
let sram_wait_cycles = 1 + S_GAMEPAK_NSEQ_CYCLES[waitcnt.sram_wait_control() as usize];
self.n_cycles32[PAGE_SRAM_LO] = sram_wait_cycles;
self.n_cycles32[PAGE_SRAM_LO] = sram_wait_cycles;
self.n_cycles16[PAGE_SRAM_HI] = sram_wait_cycles;
self.n_cycles16[PAGE_SRAM_HI] = sram_wait_cycles;
self.s_cycles32[PAGE_SRAM_LO] = sram_wait_cycles;
self.s_cycles32[PAGE_SRAM_LO] = sram_wait_cycles;
self.s_cycles16[PAGE_SRAM_HI] = sram_wait_cycles;
self.s_cycles16[PAGE_SRAM_HI] = sram_wait_cycles;
// update both pages of each waitstate
for i in 0..2 {
self.n_cycles16[PAGE_GAMEPAK_WS0 + i] = 1 + S_GAMEPAK_NSEQ_CYCLES[ws0_first_access];
self.s_cycles16[PAGE_GAMEPAK_WS0 + i] = 1 + S_GAMEPAK_WS0_SEQ_CYCLES[ws0_second_access];
self.n_cycles16[PAGE_GAMEPAK_WS1 + i] = 1 + S_GAMEPAK_NSEQ_CYCLES[ws1_first_access];
self.s_cycles16[PAGE_GAMEPAK_WS1 + i] = 1 + S_GAMEPAK_WS1_SEQ_CYCLES[ws1_second_access];
self.n_cycles16[PAGE_GAMEPAK_WS2 + i] = 1 + S_GAMEPAK_NSEQ_CYCLES[ws2_first_access];
self.s_cycles16[PAGE_GAMEPAK_WS2 + i] = 1 + S_GAMEPAK_WS2_SEQ_CYCLES[ws2_second_access];
// ROM 32bit accesses are split into two 16bit accesses 1N+1S
self.n_cycles32[PAGE_GAMEPAK_WS0 + i] =
self.n_cycles16[PAGE_GAMEPAK_WS0 + i] + self.s_cycles16[PAGE_GAMEPAK_WS0 + i];
self.n_cycles32[PAGE_GAMEPAK_WS1 + i] =
self.n_cycles16[PAGE_GAMEPAK_WS1 + i] + self.s_cycles16[PAGE_GAMEPAK_WS1 + i];
self.n_cycles32[PAGE_GAMEPAK_WS2 + i] =
self.n_cycles16[PAGE_GAMEPAK_WS2 + i] + self.s_cycles16[PAGE_GAMEPAK_WS2 + i];
self.s_cycles32[PAGE_GAMEPAK_WS0 + i] = 2 * self.s_cycles16[PAGE_GAMEPAK_WS0 + i];
self.s_cycles32[PAGE_GAMEPAK_WS1 + i] = 2 * self.s_cycles16[PAGE_GAMEPAK_WS1 + i];
self.s_cycles32[PAGE_GAMEPAK_WS2 + i] = 2 * self.s_cycles16[PAGE_GAMEPAK_WS2 + i];
}
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct SysBus {
pub io: IoDevices,
bios: BoxedMemory,
onboard_work_ram: BoxedMemory,
internal_work_ram: BoxedMemory,
pub cartridge: Cartridge,
dummy: DummyBus,
cycle_luts: CycleLookupTables,
pub trace_access: bool,
}
#[repr(transparent)]
#[derive(Clone)]
pub struct SysBusPtr {
ptr: *mut SysBus,
}
impl Default for SysBusPtr {
fn default() -> SysBusPtr {
SysBusPtr {
ptr: std::ptr::null_mut::<SysBus>(),
}
}
}
impl SysBusPtr {
pub fn new(ptr: *mut SysBus) -> SysBusPtr {
SysBusPtr { ptr: ptr }
}
}
impl Deref for SysBusPtr {
type Target = SysBus;
fn deref(&self) -> &Self::Target {
unsafe { &*self.ptr }
}
}
impl DerefMut for SysBusPtr {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.ptr }
}
}
macro_rules! memory_map {
(read($sb:ident, $read_fn:ident, $addr:expr)) => {
match $addr & 0xff000000 {
BIOS_ADDR => {
if $addr >= 0x4000 {
0
} else {
$sb.bios.$read_fn($addr)
}
}
EWRAM_ADDR => $sb.onboard_work_ram.$read_fn($addr & 0x3_ffff),
IWRAM_ADDR => $sb.internal_work_ram.$read_fn($addr & 0x7fff),
IOMEM_ADDR => {
let addr = if $addr & 0xffff == 0x8000 {
0x800
} else {
$addr & 0x7ff
};
$sb.io.$read_fn(addr)
}
PALRAM_ADDR => $sb.io.gpu.palette_ram.$read_fn($addr & 0x3ff),
VRAM_ADDR => {
let mut ofs = $addr & ((VIDEO_RAM_SIZE as u32) - 1);
if ofs > 0x18000 {
ofs -= 0x8000;
}
$sb.io.gpu.vram.$read_fn(ofs)
}
OAM_ADDR => $sb.io.gpu.oam.$read_fn($addr & 0x3ff),
GAMEPAK_WS0_LO | GAMEPAK_WS0_HI | GAMEPAK_WS1_LO | GAMEPAK_WS1_HI | GAMEPAK_WS2_LO => {
$sb.cartridge.$read_fn($addr)
}
GAMEPAK_WS2_HI => $sb.cartridge.$read_fn($addr),
SRAM_LO | SRAM_HI => $sb.cartridge.$read_fn($addr),
_ => {
// warn!("trying to read invalid address {:#x}", $addr);
// TODO open bus
0
}
}
};
(write($sb:ident, $write_fn:ident, $addr:expr, $value:expr)) => {
match $addr & 0xff000000 {
BIOS_ADDR => {}
EWRAM_ADDR => $sb.onboard_work_ram.$write_fn($addr & 0x3_ffff, $value),
IWRAM_ADDR => $sb.internal_work_ram.$write_fn($addr & 0x7fff, $value),
IOMEM_ADDR => {
let addr = if $addr & 0xffff == 0x8000 {
0x800
} else {
$addr & 0x7ff
};
$sb.io.$write_fn(addr, $value)
}
PALRAM_ADDR => $sb.io.gpu.palette_ram.$write_fn($addr & 0x3ff, $value),
VRAM_ADDR => {
let mut ofs = $addr & ((VIDEO_RAM_SIZE as u32) - 1);
if ofs > 0x18000 {
ofs -= 0x8000;
}
$sb.io.gpu.vram.$write_fn(ofs, $value)
}
OAM_ADDR => $sb.io.gpu.oam.$write_fn($addr & 0x3ff, $value),
GAMEPAK_WS0_LO | GAMEPAK_WS0_HI => {}
GAMEPAK_WS2_HI => $sb.cartridge.$write_fn($addr, $value),
SRAM_LO | SRAM_HI => $sb.cartridge.$write_fn($addr, $value),
_ => {
// warn!("trying to write invalid address {:#x}", $addr);
// TODO open bus
}
}
};
}
impl SysBus {
pub fn new(io: IoDevices, bios_rom: Box<[u8]>, cartridge: Cartridge) -> SysBus {
let mut luts = CycleLookupTables::default();
luts.init();
luts.update_gamepak_waitstates(io.waitcnt);
SysBus {
io: io,
bios: BoxedMemory::new(bios_rom),
onboard_work_ram: BoxedMemory::new(vec![0; WORK_RAM_SIZE].into_boxed_slice()),
internal_work_ram: BoxedMemory::new(vec![0; INTERNAL_RAM_SIZE].into_boxed_slice()),
cartridge: cartridge,
dummy: DummyBus([0; 4]),
cycle_luts: luts,
trace_access: false,
}
}
/// must be called whenever this object is instanciated
pub fn created(&mut self) {
let ptr = SysBusPtr::new(self as *mut SysBus);
// HACK
self.io.set_sysbus_ptr(ptr.clone());
}
pub fn on_waitcnt_written(&mut self, waitcnt: WaitControl) {
self.cycle_luts.update_gamepak_waitstates(waitcnt);
}
#[inline(always)]
pub fn get_cycles(
&self,
addr: Addr,
access: MemoryAccessType,
width: MemoryAccessWidth,
) -> usize {
use MemoryAccessType::*;
use MemoryAccessWidth::*;
let page = (addr >> 24) as usize;
// TODO optimize out by making the LUTs have 0x100 entries for each possible page ?
if page > 0xF {
// open bus
return 1;
}
match width {
MemoryAccess8 | MemoryAccess16 => match access {
NonSeq => self.cycle_luts.n_cycles16[page],
Seq => self.cycle_luts.s_cycles16[page],
},
MemoryAccess32 => match access {
NonSeq => self.cycle_luts.n_cycles32[page],
Seq => self.cycle_luts.s_cycles32[page],
},
}
}
}
impl Bus for SysBus {
fn read_32(&self, addr: Addr) -> u32 {
memory_map!(read(self, read_32, addr & !3))
}
fn read_16(&self, addr: Addr) -> u16 {
memory_map!(read(self, read_16, addr & !1))
}
fn read_8(&self, addr: Addr) -> u8 {
memory_map!(read(self, read_8, addr))
}
fn write_32(&mut self, addr: Addr, value: u32) {
memory_map!(write(self, write_32, addr & !3, value));
}
fn write_16(&mut self, addr: Addr, value: u16) {
memory_map!(write(self, write_16, addr & !1, value));
}
fn write_8(&mut self, addr: Addr, value: u8) {
memory_map!(write(self, write_8, addr, value));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.